1#[doc(hidden)]
39pub mod wheel_glide;
40
41use std::f32::consts::PI;
42
43use crate::{
44 Bounds, Command, EventKind, EventPayload, NodeId, Point, Points, ScrollBehavior, Size,
45 StickyCell,
46 geometry::{Axis, Percentage, Radians, point},
47};
48
49const MIN_GLIDE: f32 = 0.05;
51const STOP: f32 = 0.01;
53const WHEEL_IDLE: f64 = 150.0;
55const INDICATOR_HOLD: f64 = 700.0;
57const INDICATOR_FADE: f64 = 300.0;
59const ANIMATION: f64 = 300.0;
61const WHEEL_SNAP: f32 = 0.6;
64const INDICATOR_MARGIN: f32 = 2.0;
66pub const INDICATOR_THICK: Points = Points(3.0);
68const THUMB_GRAB: f32 = 12.0;
71const THUMB_SLOP: f32 = 4.0;
73
74#[derive(Debug, Default, Clone, Copy, PartialEq)]
78struct Offset {
79 x: f32,
80 y: f32,
81}
82
83impl Offset {
84 const fn new(x: f32, y: f32) -> Self {
85 Self { x, y }
86 }
87
88 fn along(self, horizontal: bool) -> f32 {
89 if horizontal { self.x } else { self.y }
90 }
91
92 fn with(self, horizontal: bool, v: f32) -> Self {
94 if horizontal {
95 Self::new(v, self.y)
96 } else {
97 Self::new(self.x, v)
98 }
99 }
100
101 fn lerp(self, to: Self, k: f32) -> Self {
102 Self::new(self.x + (to.x - self.x) * k, self.y + (to.y - self.y) * k)
103 }
104
105 fn distance(self, to: Self) -> f32 {
107 (to.x - self.x).abs().max((to.y - self.y).abs())
108 }
109
110 fn clamp(self, (min, max): (Self, Self)) -> Self {
112 Self::new(
113 self.x.clamp(min.x, max.x.max(min.x)),
114 self.y.clamp(min.y, max.y.max(min.y)),
115 )
116 }
117}
118
119impl std::ops::Add for Offset {
120 type Output = Self;
121
122 fn add(self, o: Self) -> Self {
123 Self::new(self.x + o.x, self.y + o.y)
124 }
125}
126
127impl From<Offset> for Point<Points> {
128 fn from(o: Offset) -> Self {
129 point(Points(o.x), Points(o.y))
130 }
131}
132
133impl From<Point<Points>> for Offset {
134 fn from(p: Point<Points>) -> Self {
135 Offset::new(p.x.0, p.y.0)
136 }
137}
138
139#[derive(Debug, Default, Clone, Copy, PartialEq)]
141enum Phase {
142 #[default]
144 Idle,
145 Drag { start: Offset, moved: Offset },
148 Thumb { start: f32 },
151 Wheel {
156 last: f64,
157 total: f32,
158 gesture: bool,
159 raw: Offset,
160 glide: wheel_glide::Glide,
161 },
162 Glide { velocity: Offset, last: f64 },
164 Animate {
168 from: Offset,
169 to: Offset,
170 start: f64,
171 duration: f64,
172 momentum: bool,
173 end: bool,
174 },
175 Zoom {
180 from: f32,
181 to: f32,
182 from_c: Offset,
183 to_c: Offset,
184 at: Offset,
185 start: f64,
186 duration: f64,
187 },
188}
189
190#[derive(Debug, Default, Clone)]
193#[non_exhaustive]
194pub struct Live {
195 phase: Phase,
196 ticking: bool,
198 report: bool,
200 shown: f64,
202 pub alpha: f32,
204 pub refreshing: bool,
206 dismissing: bool,
210 spin_start: Option<f64>,
213 pub spin: Radians,
215 pub dark: bool,
218 pinch_from: f32,
220 reported_zoom: f32,
222 rezoomed: bool,
224}
225
226#[derive(Debug, Clone)]
228#[non_exhaustive]
229pub struct ScrollState {
230 pub x: Points,
233 pub y: Points,
235 pub content: Size<Points>,
237 pub zoom: f32,
239 pub can_zoom: bool,
242 pub horizontal: bool,
244 pub indicator: bool,
246 pub behavior: ScrollBehavior,
248 pub applied: u32,
251 pub sticky: Vec<StickyCell>,
253 pub mirrored: bool,
256 pub live: Live,
258}
259
260impl Default for ScrollState {
261 fn default() -> Self {
262 Self {
263 x: Points::ZERO,
264 y: Points::ZERO,
265 content: Size::default(),
266 zoom: 1.0,
267 can_zoom: false,
268 horizontal: false,
269 indicator: false,
270 behavior: ScrollBehavior::default(),
271 applied: 0,
272 sticky: Vec::new(),
273 mirrored: false,
274 live: Live::default(),
275 }
276 }
277}
278
279pub trait ScrollHost {
282 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R>;
285 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R>;
287 fn now(&self) -> f64;
289 fn listens(&self, kind: EventKind) -> bool;
291 fn event(&self, kind: EventKind, payload: EventPayload);
293 fn report(&self, offset: Point<Points>, applied: u32);
296 fn report_zoom(&self, scale: f32) {
299 let _ = scale;
300 }
301 fn key_scrolled(&self, key_move: KeyMove) {
305 let _ = key_move;
306 }
307 fn moved(&self, offset: Point<Points>);
311 fn pulled(&self, distance: Points);
314 fn relayout(&self);
316 fn redraw(&self);
318 fn attached(&self) -> bool;
320 fn start_ticking(&self);
322 fn settled(&self) {}
326 fn dark(&self) -> bool {
329 false
330 }
331}
332
333fn rubber(over: f32, dim: f32) -> f32 {
338 let dim = dim.max(1.0);
339 (1.0 - 1.0 / (over * 0.55 / dim + 1.0)) * dim
340}
341
342pub fn dragged(raw: Points, min: Points, max: Points, dim: Points, bounces: bool) -> Points {
345 Points(drag_position(raw.0, min.0, max.0, dim.0, bounces))
346}
347
348fn drag_position(raw: f32, min: f32, max: f32, dim: f32, bounces: bool) -> f32 {
349 if raw < min {
350 if bounces {
351 min - rubber(min - raw, dim)
352 } else {
353 min
354 }
355 } else if raw > max {
356 if bounces {
357 max + rubber(raw - max, dim)
358 } else {
359 max
360 }
361 } else {
362 raw
363 }
364}
365
366pub fn rate(behavior: &ScrollBehavior) -> f32 {
368 if behavior.deceleration > 0.0 && behavior.deceleration < 1.0 {
369 behavior.deceleration
370 } else if behavior.snaps() || behavior.paging {
371 0.99
372 } else {
373 0.998
374 }
375}
376
377fn glide_step(v: f32, rate: f32, dt: f32) -> (f32, f32) {
380 let k = rate.powf(dt);
381 (v * (k - 1.0) / rate.ln(), v * k)
382}
383
384pub fn projected(offset: Points, velocity: f32, rate: f32) -> Points {
387 Points(offset.0 - velocity / rate.ln())
388}
389
390pub fn sticky_shift(offset: Points, start: Points, end: Points) -> Points {
394 let travel = end.0 - start.0;
395 Points((offset.0 - start.0).clamp(travel.min(0.0), travel.max(0.0)))
396}
397
398pub fn ease_out(t: f64) -> f32 {
400 let t = t.clamp(0.0, 1.0);
401 (1.0 - (1.0 - t).powi(3)) as f32
402}
403
404pub fn snap_duration(distance: Points, velocity: f32) -> f64 {
408 let (distance, v) = (distance.0, velocity);
409 if distance.abs() < 0.5 {
410 return 0.0;
411 }
412 if v * distance > 0.0 {
413 (3.0 * distance.abs() / v.abs()).clamp(180.0, 600.0) as f64
414 } else {
415 ANIMATION
416 }
417}
418
419pub fn indicator_alpha(since: f64) -> f32 {
421 if since < INDICATOR_HOLD {
422 1.0
423 } else {
424 (1.0 - (since - INDICATOR_HOLD) / INDICATOR_FADE).max(0.0) as f32
425 }
426}
427
428pub fn indicator_span(viewport: Points, total: Points, offset: Points) -> Option<(Points, Points)> {
432 indicator_span_within(viewport, total, offset, Points::ZERO, Points::ZERO)
433}
434
435pub fn indicator_span_within(
441 viewport: Points,
442 total: Points,
443 offset: Points,
444 before: Points,
445 after: Points,
446) -> Option<(Points, Points)> {
447 span(viewport.0, total.0, offset.0, before.0, after.0)
448 .map(|(start, len)| (Points(start), Points(len)))
449}
450
451fn span(viewport: f32, total: f32, offset: f32, before: f32, after: f32) -> Option<(f32, f32)> {
452 const MIN_LENGTH: f32 = 32.0;
454 let (before, after) = (before.max(0.0), after.max(0.0));
455 let room = viewport - before - after;
456 if total <= viewport + 0.5 || room <= 4.0 * INDICATOR_MARGIN {
457 return None;
458 }
459 let track = room - 2.0 * INDICATOR_MARGIN;
460 let max = total - viewport;
461 let over = if offset < 0.0 {
463 -offset
464 } else {
465 (offset - max).max(0.0)
466 };
467 let len = (track * viewport / total - over).max(MIN_LENGTH).min(track);
468 let t = (offset / max).clamp(0.0, 1.0);
469 Some((before + INDICATOR_MARGIN + (track - len) * t, len))
470}
471
472pub fn thumb_scroll(d: Points, range: Points, travel: Points) -> Points {
475 if travel.0 > 0.0 {
476 Points(d.0 * range.0 / travel.0)
477 } else {
478 Points(0.0)
479 }
480}
481
482fn shifted(phase: Phase, d: Offset, horizontal: bool) -> Phase {
486 match phase {
487 Phase::Drag { start, moved } => Phase::Drag {
488 start: start + d,
489 moved,
490 },
491 Phase::Thumb { start } => Phase::Thumb {
492 start: start + d.along(horizontal),
493 },
494 Phase::Animate {
495 from,
496 to,
497 start,
498 duration,
499 momentum,
500 end,
501 } => Phase::Animate {
502 from: from + d,
503 to: to + d,
504 start,
505 duration,
506 momentum,
507 end,
508 },
509 Phase::Wheel {
510 last,
511 total,
512 gesture,
513 raw,
514 glide,
515 } => Phase::Wheel {
516 last,
517 total,
518 gesture,
519 raw: raw + d,
520 glide: glide.shifted(d.into()),
521 },
522 other => other,
523 }
524}
525
526fn spin_angle(elapsed: f64) -> Radians {
530 let frac = elapsed.max(0.0).rem_euclid(1000.0) / 1000.0;
531 Radians(frac as f32 * 2.0 * PI)
532}
533
534pub fn spokes(progress: Percentage, spin: Radians) -> impl Iterator<Item = (Radians, f32)> {
539 const SPOKES: usize = 8;
540 let (progress, spin) = (progress.0, spin.0);
541 let shown = ((progress * SPOKES as f32).ceil() as usize).min(SPOKES);
542 let step = 2.0 * PI / SPOKES as f32;
543 let lead = (spin / step) as usize % SPOKES;
544 (0..shown).map(move |i| {
545 let fade = if progress < 1.0 {
546 0.8
547 } else {
548 1.0 - ((lead + SPOKES - i) % SPOKES) as f32 / SPOKES as f32 * 0.85
549 };
550 (Radians(i as f32 * step), fade)
551 })
552}
553
554pub fn reading_order<T>(axis: Axis, children: &mut [T], origin: impl Fn(&T) -> Point<Points>) {
563 if children.len() < 2 {
564 return;
565 }
566 let key = |child: &T| {
567 let at = origin(child);
568 match axis {
569 Axis::Horizontal => (at.x.0, at.y.0),
570 Axis::Vertical => (at.y.0, at.x.0),
571 }
572 };
573 children.sort_by(|a, b| {
574 let (a, b) = (key(a), key(b));
575 a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
576 });
577}
578
579impl ScrollState {
582 pub fn max(&self, size: Size<Points>) -> Point<Points> {
584 let (x, y) = self.max_f(size);
585 point(Points(x), Points(y))
586 }
587
588 fn max_f(&self, size: Size<Points>) -> (f32, f32) {
589 let inset = self.behavior.content_inset;
590 let z = self.zoom;
591 (
592 (self.content.width.0 * z + inset.left.0 + inset.right.0 - size.width.0).max(0.0),
593 (self.content.height.0 * z + inset.top.0 + inset.bottom.0 - size.height.0).max(0.0),
594 )
595 }
596
597 pub fn origin(&self) -> Point<Points> {
601 let inset = self.behavior.content_inset;
602 point(self.x - inset.left, self.y - inset.top)
603 }
604
605 pub fn zooms(&self) -> bool {
609 self.can_zoom && self.behavior.zooms()
610 }
611
612 pub fn centered(&self, size: Size<Points>) -> Point<Points> {
616 if !self.zooms() || !self.behavior.center_content {
617 return Point::default();
618 }
619 let inset = self.behavior.content_inset;
620 let free = |viewport: f32, content: f32| ((viewport - content * self.zoom) / 2.0).max(0.0);
621 point(
622 Points(free(
623 size.width.0 - inset.left.0 - inset.right.0,
624 self.content.width.0,
625 )),
626 Points(free(
627 size.height.0 - inset.top.0 - inset.bottom.0,
628 self.content.height.0,
629 )),
630 )
631 }
632
633 pub fn to_viewport(&self, size: Size<Points>, content: Point<Points>) -> Point<Points> {
636 let (o, room) = (self.origin(), self.centered(size));
637 point(
638 Points(content.x.0 * self.zoom - o.x.0 + room.x.0),
639 Points(content.y.0 * self.zoom - o.y.0 + room.y.0),
640 )
641 }
642
643 pub fn to_content(&self, size: Size<Points>, at: Point<Points>) -> Point<Points> {
646 let (o, room) = (self.origin(), self.centered(size));
647 point(
648 Points((at.x.0 + o.x.0 - room.x.0) / self.zoom),
649 Points((at.y.0 + o.y.0 - room.y.0) / self.zoom),
650 )
651 }
652
653 fn offset(&self) -> f32 {
655 if self.horizontal { self.x.0 } else { self.y.0 }
656 }
657
658 fn pos(&self) -> Offset {
660 Offset::new(self.x.0, self.y.0)
661 }
662
663 fn range(&self, size: Size<Points>) -> (Offset, Offset) {
667 let (min, max) = self.limits(size);
668 if self.zooms() {
669 let (mx, my) = self.max_f(size);
670 let top = if self.horizontal { 0.0 } else { min };
672 (Offset::new(0.0, top), Offset::new(mx, my))
673 } else {
674 let zero = Offset::default();
675 (
676 zero.with(self.horizontal, min),
677 zero.with(self.horizontal, max),
678 )
679 }
680 }
681
682 fn content_at(&self, size: Size<Points>, at: Offset) -> Offset {
684 let c = self.to_content(size, point(Points(at.x), Points(at.y)));
685 Offset::new(c.x.0, c.y.0)
686 }
687
688 fn showing(&self, size: Size<Points>, c: Offset, at: Offset) -> Offset {
691 let inset = self.behavior.content_inset;
692 let room = self.centered(size);
693 Offset::new(
694 c.x * self.zoom + room.x.0 - at.x + inset.left.0,
695 c.y * self.zoom + room.y.0 - at.y + inset.top.0,
696 )
697 .clamp(self.range(size))
698 }
699
700 fn goal(&self) -> f32 {
703 match self.live.phase {
704 Phase::Animate { to, .. } => to.along(self.horizontal),
705 _ => self.offset(),
706 }
707 }
708
709 fn viewport(&self, size: Size<Points>) -> f32 {
711 if self.horizontal {
712 size.width.0
713 } else {
714 size.height.0
715 }
716 }
717
718 fn lead(&self) -> f32 {
720 if self.horizontal {
721 self.behavior.content_inset.left.0
722 } else {
723 self.behavior.content_inset.top.0
724 }
725 }
726
727 fn limits(&self, size: Size<Points>) -> (f32, f32) {
730 let max = self.max_f(size);
731 let min = if !self.horizontal && self.live.refreshing {
732 -self.behavior.refresh_inset().0
733 } else {
734 0.0
735 };
736 (min, if self.horizontal { max.0 } else { max.1 })
737 }
738
739 pub fn reported(&self, size: Size<Points>) -> Point<Points> {
742 let (mx, my) = self.max_f(size);
743 let inset = self.behavior.content_inset;
744 point(
745 Points(self.x.0.clamp(0.0, mx) - inset.left.0),
746 Points(self.y.0.clamp(0.0, my) - inset.top.0),
747 )
748 }
749
750 pub fn can_scroll(&self, size: Size<Points>, delta: Point<Points>) -> bool {
755 let (dx, dy) = (delta.x.0, delta.y.0);
756 if !self.behavior.enabled {
757 return false;
758 }
759 if self.zooms() {
760 let ((min, max), p) = (self.range(size), self.pos());
761 let can = |d: f32, p: f32, min: f32, max: f32| {
762 (d > 0.0 && p < max - 0.5) || (d < 0.0 && p > min + 0.5)
763 };
764 return can(dx, p.x, min.x, max.x) || can(dy, p.y, min.y, max.y);
765 }
766 let (min, max) = self.limits(size);
767 if max <= min {
768 return false;
769 }
770 let d = if self.horizontal {
771 let d = if dx != 0.0 { dx } else { dy };
772 if self.mirrored && dx != 0.0 { -d } else { d }
773 } else {
774 dy
775 };
776 let pos = self.offset();
777 (d > 0.0 && pos < max - 0.5) || (d < 0.0 && pos > min + 0.5)
778 }
779
780 pub fn thumb(&self, size: Size<Points>) -> Option<(Bounds<Points>, Points)> {
783 self.thumb_within(
784 size,
785 Bounds {
786 origin: Point::default(),
787 size,
788 },
789 )
790 }
791
792 pub fn thumb_within(
799 &self,
800 size: Size<Points>,
801 visible: Bounds<Points>,
802 ) -> Option<(Bounds<Points>, Points)> {
803 let (rect, travel) = self.thumb_f(size, visible)?;
804 Some((rect, Points(travel)))
805 }
806
807 fn visible_edges(size: Size<Points>, visible: Bounds<Points>) -> Option<(f32, f32)> {
810 let (w, h) = (size.width.0, size.height.0);
811 let left = visible.origin.x.0.max(0.0);
812 let top = visible.origin.y.0.max(0.0);
813 let right = (visible.origin.x.0 + visible.size.width.0).min(w);
814 let bottom = (visible.origin.y.0 + visible.size.height.0).min(h);
815 (right > left && bottom > top).then_some((right, bottom))
816 }
817
818 fn thumb_f(
819 &self,
820 size: Size<Points>,
821 visible: Bounds<Points>,
822 ) -> Option<(Bounds<Points>, f32)> {
823 const EDGE: f32 = 2.0;
824 if self.zooms() {
826 return None;
827 }
828 let thick = INDICATOR_THICK.0;
829 let (w, h) = (size.width.0, size.height.0);
830 let (right, bottom) = Self::visible_edges(size, visible)?;
831 let inset = self.behavior.content_inset;
832 let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
833 let (dim, total, offset, before, after) = if self.horizontal {
836 let (before, after) = if self.mirrored {
837 (bar.right, bar.left)
838 } else {
839 (bar.left, bar.right)
840 };
841 (
842 w,
843 self.content.width.0 + inset.left.0 + inset.right.0,
844 self.x.0,
845 before,
846 after,
847 )
848 } else {
849 (
850 h,
851 self.content.height.0 + inset.top.0 + inset.bottom.0,
852 self.y.0,
853 bar.top,
854 bar.bottom,
855 )
856 };
857 let (start, len) = span(dim, total, offset, before, after)?;
858 let (x, y, rw, rh) = if self.horizontal {
859 let x = if self.mirrored {
860 w - start - len
861 } else {
862 start
863 };
864 (x, bottom - bar.bottom - thick - EDGE, len, thick)
865 } else {
866 (right - bar.right - thick - EDGE, start, thick, len)
867 };
868 let rect = Bounds {
869 origin: point(Points(x), Points(y)),
870 size: Size {
871 width: Points(rw),
872 height: Points(rh),
873 },
874 };
875 Some((rect, dim - before - after - 2.0 * INDICATOR_MARGIN - len))
876 }
877
878 pub fn grabs_thumb(&self, size: Size<Points>, at: Point<Points>) -> bool {
882 self.grabs_thumb_within(
883 size,
884 Bounds {
885 origin: Point::default(),
886 size,
887 },
888 at,
889 )
890 }
891
892 pub fn grabs_thumb_within(
896 &self,
897 size: Size<Points>,
898 visible: Bounds<Points>,
899 at: Point<Points>,
900 ) -> bool {
901 let (x, y) = (at.x.0, at.y.0);
902 if !self.indicator || !self.behavior.enabled {
903 return false;
904 }
905 let Some((rect, _)) = self.thumb_f(size, visible) else {
906 return false;
907 };
908 let Some((right, bottom)) = Self::visible_edges(size, visible) else {
909 return false;
910 };
911 let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
913 let (along, across, start, len, edge) = if self.horizontal {
914 (
915 x,
916 y,
917 rect.origin.x.0,
918 rect.size.width.0,
919 bottom - bar.bottom,
920 )
921 } else {
922 (y, x, rect.origin.y.0, rect.size.height.0, right - bar.right)
923 };
924 (edge - THUMB_GRAB..=edge).contains(&across)
925 && (start - THUMB_SLOP..=start + len + THUMB_SLOP).contains(&along)
926 }
927
928 pub fn indicates(&self) -> bool {
931 (self.indicator && self.live.alpha > 0.0) || self.y.0 < 0.0
932 }
933
934 pub fn spinner(&self, width: Points, refresh: bool) -> Option<(Point<Points>, Percentage)> {
939 let y = self.y.0;
940 let b = &self.behavior;
941 let active = self.live.refreshing || self.live.dismissing;
942 if self.horizontal || y >= 0.0 || b.refresh_indicator.is_some() || !(active || refresh) {
943 return None;
944 }
945 let progress = if active {
946 1.0
947 } else {
948 (-y / b.refresh_threshold().0).min(1.0)
949 };
950 let cy = b.content_inset.top.0 - y - b.refresh_inset().0 / 2.0;
951 Some((point(width / 2.0, Points(cy)), Percentage(progress)))
952 }
953
954 pub fn spinner_opacity(&self) -> f32 {
957 if self.live.dismissing {
958 let inset = self.behavior.refresh_inset().0;
959 if inset > 0.0 {
960 (-self.y.0 / inset).clamp(0.0, 1.0)
961 } else {
962 0.0
963 }
964 } else {
965 1.0
966 }
967 }
968
969 pub fn sticky_shifts(&self) -> impl Iterator<Item = (NodeId, Point<Points>)> + '_ {
971 self.sticky_shifts_with(|_| 0.0)
972 }
973
974 pub fn sticky_shifts_with<'a>(
977 &'a self,
978 value: impl Fn(crate::animation::NodeId) -> f32 + 'a,
979 ) -> impl Iterator<Item = (NodeId, Point<Points>)> + 'a {
980 let offset = Points(self.offset() - self.lead());
981 self.sticky.iter().map(move |c| {
982 let extra = c.offset.map_or(0.0, &value);
983 let t = sticky_shift(Points(offset.0 + extra), c.start, c.end);
984 let zero = Points(0.0);
985 (
986 c.cell,
987 if self.horizontal {
988 point(t, zero)
989 } else {
990 point(zero, t)
991 },
992 )
993 })
994 }
995}
996
997fn phase(host: &impl ScrollHost) -> Phase {
1000 host.scroll(|s, _| s.live.phase).unwrap_or(Phase::Idle)
1001}
1002
1003fn set_phase(host: &impl ScrollHost, phase: Phase) {
1004 host.scroll_mut(|s, _| s.live.phase = phase);
1005}
1006
1007fn enabled(host: &impl ScrollHost) -> bool {
1009 host.scroll(|s, _| s.behavior.enabled).unwrap_or(false)
1010}
1011
1012fn emit(host: &impl ScrollHost, kind: EventKind) {
1014 if kind == EventKind::ScrollEnd {
1015 host.settled();
1016 }
1017 if !host.listens(kind) {
1018 return;
1019 }
1020 let offset = host.scroll(|s, size| s.reported(size)).unwrap_or_default();
1021 host.event(kind, EventPayload::Scroll(offset));
1022}
1023
1024fn interrupt(host: &impl ScrollHost) {
1027 let momentum = matches!(
1028 phase(host),
1029 Phase::Glide { .. } | Phase::Animate { momentum: true, .. }
1030 );
1031 set_phase(host, Phase::Idle);
1032 if momentum {
1033 emit(host, EventKind::MomentumEnd);
1034 }
1035}
1036
1037fn moved_to(host: &impl ScrollHost, to: Offset) {
1042 let moved = host.scroll_mut(|s, size| {
1043 let rezoomed = std::mem::take(&mut s.live.rezoomed);
1044 if s.pos() == to && !rezoomed {
1045 return None;
1046 }
1047 let pulled =
1049 (!s.horizontal && (s.y.0 < 0.0 || to.y < 0.0)).then(|| Points((-to.y).max(0.0)));
1050 (s.x, s.y) = (Points(to.x), Points(to.y));
1051 if !s.horizontal && to.y >= 0.0 {
1052 s.live.dismissing = false;
1053 if !s.live.refreshing {
1054 s.live.spin_start = None;
1055 s.live.spin = Radians(0.0);
1056 }
1057 }
1058 if s.indicator {
1059 s.live.shown = host.now();
1060 s.live.alpha = 1.0;
1061 s.live.dark = host.dark();
1062 }
1063 s.live.report = true;
1064 Some((s.reported(size), pulled))
1065 });
1066 let Some(Some((offset, pulled))) = moved else {
1067 return;
1068 };
1069 host.moved(offset);
1070 if let Some(distance) = pulled {
1071 host.pulled(distance);
1072 }
1073 if host.attached() {
1074 ensure_ticking(host);
1075 } else {
1076 report(host);
1078 }
1079}
1080
1081fn moved_along(host: &impl ScrollHost, pos: f32) {
1083 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, pos)) {
1084 moved_to(host, to);
1085 }
1086}
1087
1088fn report(host: &impl ScrollHost) {
1089 let pending = host.scroll_mut(|s, size| {
1090 if !std::mem::take(&mut s.live.report) {
1091 return None;
1092 }
1093 let known = s.zooms() || s.live.reported_zoom != 0.0;
1096 let zoom = (known && s.zoom != s.live.reported_zoom).then(|| {
1097 s.live.reported_zoom = s.zoom;
1098 s.zoom
1099 });
1100 Some((s.reported(size), s.applied, zoom))
1101 });
1102 if let Some(Some((offset, applied, zoom))) = pending {
1103 if let Some(zoom) = zoom {
1104 host.report_zoom(zoom);
1105 }
1106 host.report(offset, applied);
1107 }
1108}
1109
1110fn animate_to(host: &impl ScrollHost, to: Offset, duration: f64, momentum: bool, end: bool) {
1112 let Some((from, to)) = host.scroll(|s, size| (s.pos(), to.clamp(s.range(size)))) else {
1113 return;
1114 };
1115 if from.distance(to) < 0.5 || duration <= 0.0 {
1116 set_phase(host, Phase::Idle);
1117 moved_to(host, to);
1118 if momentum {
1119 emit(host, EventKind::MomentumEnd);
1120 }
1121 if end {
1122 emit(host, EventKind::ScrollEnd);
1123 }
1124 return;
1125 }
1126 set_phase(
1127 host,
1128 Phase::Animate {
1129 from,
1130 to,
1131 start: host.now(),
1132 duration,
1133 momentum,
1134 end,
1135 },
1136 );
1137 ensure_ticking(host);
1138}
1139
1140fn animate_along(host: &impl ScrollHost, to: f32, duration: f64, momentum: bool, end: bool) {
1142 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, to)) {
1143 animate_to(host, to, duration, momentum, end);
1144 }
1145}
1146
1147fn release(host: &impl ScrollHost, v: Offset, snap_velocity: f32) {
1151 let Some((pos, (min, max), main, target)) = host.scroll(|s, size| {
1152 let range = s.range(size);
1153 let pos = s.pos();
1154 let main = v.along(s.horizontal);
1155 let lead = s.lead();
1156 let dim = s.viewport(size);
1157 let snap_velocity = if snap_velocity == 0.0 {
1158 main
1159 } else {
1160 snap_velocity
1161 };
1162 let max = range.1.along(s.horizontal);
1163 let target = s
1166 .behavior
1167 .snap_target(
1168 Points(s.offset() - lead),
1169 projected(Points(s.offset()), main, rate(&s.behavior)) - Points(lead),
1170 snap_velocity,
1171 Points(dim),
1172 Points(max + dim - lead),
1173 )
1174 .filter(|_| !s.zooms())
1175 .map(|t| (pos.with(s.horizontal, t.0 + lead), t.0 + lead - s.offset()));
1176 (pos, range, main, target)
1177 }) else {
1178 return;
1179 };
1180 let past = |p: f32, min: f32, max: f32| p < min - 0.5 || p > max + 0.5;
1181 let room = |v: f32, p: f32, min: f32, max: f32| v > 0.0 && p < max || v < 0.0 && p > min;
1182 if past(pos.x, min.x, max.x) || past(pos.y, min.y, max.y) || (min.y == 0.0 && pos.y < 0.0) {
1183 animate_to(host, pos.clamp((min, max)), ANIMATION, false, true);
1184 } else if let Some((target, distance)) = target {
1185 let duration = snap_duration(Points(distance), main);
1186 if duration > 0.0 {
1187 emit(host, EventKind::MomentumStart);
1188 }
1189 animate_to(host, target, duration, duration > 0.0, true);
1190 } else if v.x.abs().max(v.y.abs()) > MIN_GLIDE
1191 && (room(v.x, pos.x, min.x, max.x) || room(v.y, pos.y, min.y, max.y))
1192 {
1193 set_phase(
1194 host,
1195 Phase::Glide {
1196 velocity: v,
1197 last: host.now(),
1198 },
1199 );
1200 emit(host, EventKind::MomentumStart);
1201 ensure_ticking(host);
1202 } else {
1203 set_phase(host, Phase::Idle);
1204 emit(host, EventKind::ScrollEnd);
1205 }
1206}
1207
1208fn ensure_ticking(host: &impl ScrollHost) {
1211 let start = host.scroll_mut(|s, _| !std::mem::replace(&mut s.live.ticking, true));
1212 if start == Some(true) {
1213 host.start_ticking();
1214 }
1215}
1216
1217pub fn frame(host: &impl ScrollHost, now: f64) -> bool {
1220 let busy = tick(host, now);
1221 if !busy {
1222 host.scroll_mut(|s, _| s.live.ticking = false);
1223 }
1224 busy
1225}
1226
1227pub fn deadline(host: &impl ScrollHost, now: f64) -> Option<f64> {
1234 let (phase, rate) = host.scroll(|s, _| (s.live.phase, rate(&s.behavior)))?;
1235 let end = match phase {
1236 Phase::Glide { velocity, last } => {
1237 let speed = velocity.x.abs().max(velocity.y.abs());
1239 if speed < STOP || !(0.0..1.0).contains(&rate) {
1240 last
1241 } else {
1242 last + ((STOP / speed).ln() / rate.ln()).max(0.0) as f64
1243 }
1244 }
1245 Phase::Animate {
1246 start, duration, ..
1247 }
1248 | Phase::Zoom {
1249 start, duration, ..
1250 } => start + duration,
1251 Phase::Wheel {
1252 last,
1253 gesture: false,
1254 glide,
1255 ..
1256 } => (last + WHEEL_IDLE).max(glide.end()),
1257 _ => return None,
1258 };
1259 Some(end.max(now) + 1.0)
1262}
1263
1264pub fn detached(host: &impl ScrollHost) {
1267 set_phase(host, Phase::Idle);
1268 report(host);
1269 host.scroll_mut(|s, _| {
1270 s.live.ticking = false;
1271 s.live.dismissing = false;
1272 if !s.live.refreshing {
1273 s.live.spin_start = None;
1274 s.live.spin = Radians(0.0);
1275 }
1276 });
1277}
1278
1279fn tick(host: &impl ScrollHost, now: f64) -> bool {
1280 let Some((phase, pos, rate, (min, max))) =
1281 host.scroll(|s, size| (s.live.phase, s.pos(), rate(&s.behavior), s.range(size)))
1282 else {
1283 return false;
1284 };
1285 match phase {
1286 Phase::Glide { velocity, last } => {
1287 let dt = (now - last).max(0.0) as f32;
1288 let axis = |v: f32, p: f32, min: f32, max: f32| {
1291 let (d, v) = glide_step(v, rate, dt);
1292 let next = p + d;
1293 let stopped = v.abs() < STOP || next <= min || next >= max;
1294 (next, if stopped { 0.0 } else { v }, stopped)
1295 };
1296 let (x, vx, stop_x) = axis(velocity.x, pos.x, min.x, max.x);
1297 let (y, vy, stop_y) = axis(velocity.y, pos.y, min.y, max.y);
1298 moved_to(host, Offset::new(x, y).clamp((min, max)));
1299 if stop_x && stop_y {
1300 set_phase(host, Phase::Idle);
1301 emit(host, EventKind::MomentumEnd);
1302 emit(host, EventKind::ScrollEnd);
1303 } else {
1304 set_phase(
1305 host,
1306 Phase::Glide {
1307 velocity: Offset::new(vx, vy),
1308 last: now,
1309 },
1310 );
1311 }
1312 }
1313 Phase::Animate {
1314 from,
1315 to,
1316 start,
1317 duration,
1318 momentum,
1319 end,
1320 } => {
1321 let t = (now - start) / duration;
1322 moved_to(host, from.lerp(to, ease_out(t)));
1323 if t >= 1.0 {
1324 set_phase(host, Phase::Idle);
1325 if momentum {
1326 emit(host, EventKind::MomentumEnd);
1327 }
1328 if end {
1329 emit(host, EventKind::ScrollEnd);
1330 }
1331 }
1332 }
1333 Phase::Zoom {
1334 from,
1335 to,
1336 from_c,
1337 to_c,
1338 at,
1339 start,
1340 duration,
1341 } => {
1342 let t = (now - start) / duration;
1343 let k = ease_out(t);
1344 zoom_at(host, from + (to - from) * k, from_c.lerp(to_c, k), at);
1345 if t >= 1.0 {
1346 set_phase(host, Phase::Idle);
1347 }
1348 }
1349 Phase::Wheel {
1350 gesture: false,
1351 raw,
1352 glide,
1353 ..
1354 } if now < glide.end() => {
1355 moved_to(host, glide.value(raw.into(), now).into());
1356 }
1357 Phase::Wheel {
1358 last,
1359 total,
1360 gesture: false,
1361 raw,
1362 glide,
1363 } if now - last > WHEEL_IDLE => {
1364 if glide != wheel_glide::Glide::default() {
1368 moved_to(host, raw);
1369 }
1370 set_phase(host, Phase::Idle);
1371 let snaps = host
1372 .scroll(|s, _| s.behavior.snaps() || s.behavior.paging)
1373 .unwrap_or(false);
1374 let v = if snaps && total.abs() >= 1.0 {
1375 total.signum() * WHEEL_SNAP
1376 } else {
1377 0.0
1378 };
1379 release(host, Offset::default(), v);
1380 }
1381 Phase::Idle
1382 if pos.x < min.x - 0.5
1383 || pos.x > max.x.max(min.x) + 0.5
1384 || pos.y < min.y - 0.5
1385 || pos.y > max.y.max(min.y) + 0.5
1386 || (min.y == 0.0 && pos.y < 0.0) =>
1387 {
1388 moved_to(host, pos.clamp((min, max)))
1389 }
1390 _ => {}
1391 }
1392 report(host);
1393 let Some((busy, redraw)) = host.scroll_mut(|s, _| {
1394 let mut redraw = false;
1395 let mut busy = !matches!(
1396 s.live.phase,
1397 Phase::Idle
1398 | Phase::Drag { .. }
1399 | Phase::Thumb { .. }
1400 | Phase::Wheel { gesture: true, .. }
1401 );
1402 if matches!(s.live.phase, Phase::Thumb { .. }) {
1403 s.live.shown = now;
1405 } else if s.live.alpha > 0.0 {
1406 let alpha = indicator_alpha(now - s.live.shown);
1407 if alpha != s.live.alpha {
1408 s.live.alpha = alpha;
1409 redraw = true;
1410 }
1411 busy |= alpha > 0.0;
1412 }
1413 if matches!(s.live.phase, Phase::Idle) && s.live.dismissing {
1414 s.live.dismissing = false;
1415 if !s.live.refreshing {
1416 s.live.spin_start = None;
1417 s.live.spin = Radians(0.0);
1418 }
1419 redraw = true;
1420 }
1421 if !s.horizontal
1422 && s.offset() < 0.0
1423 && (s.live.refreshing || s.live.dismissing)
1424 && s.behavior.refresh_indicator.is_none()
1425 {
1426 let start = *s.live.spin_start.get_or_insert(now);
1427 s.live.spin = spin_angle(now - start);
1428 redraw = true;
1429 busy = true;
1430 }
1431 (busy, redraw)
1432 }) else {
1433 return false;
1434 };
1435 if redraw {
1436 host.redraw();
1437 }
1438 busy
1439}
1440
1441pub fn config(
1445 host: &impl ScrollHost,
1446 horizontal: bool,
1447 indicator: bool,
1448 replaced: bool,
1449 mirrored: bool,
1450) {
1451 let changed = host.scroll_mut(|s, _| {
1452 s.horizontal = horizontal;
1453 s.indicator = indicator && !replaced;
1459 if !indicator {
1460 s.live.alpha = 0.0;
1461 }
1462 let mirrored = mirrored && horizontal;
1463 std::mem::replace(&mut s.mirrored, mirrored) != mirrored
1464 });
1465 if changed == Some(true) {
1466 host.relayout();
1467 }
1468}
1469
1470pub fn content(host: &impl ScrollHost, content: Size<Points>) {
1474 let Some((past, zooms)) = host.scroll_mut(|s, size| {
1475 s.content = content;
1476 let (p, (min, max)) = (s.pos(), s.range(size));
1477 (
1478 p.x > max.x.max(min.x) + 0.5 || p.y > max.y.max(min.y) + 0.5,
1479 s.zooms(),
1480 )
1481 }) else {
1482 return;
1483 };
1484 if zooms {
1485 host.relayout();
1487 }
1488 if past {
1489 ensure_ticking(host);
1490 }
1491 host.redraw();
1492}
1493
1494pub fn scroll_by(host: &impl ScrollHost, delta: Point<Points>) {
1497 let (dx, dy) = (delta.x.0, delta.y.0);
1498 let Some((pos, d)) = host.scroll_mut(|s, _| {
1499 s.applied = s.applied.wrapping_add(1);
1500 let d = if s.zooms() {
1503 Offset::new(dx, dy)
1504 } else {
1505 Offset::default().with(s.horizontal, if s.horizontal { dx } else { dy })
1506 };
1507 s.live.phase = shifted(s.live.phase, d, s.horizontal);
1508 s.live.report = true;
1509 (s.pos(), d)
1510 }) else {
1511 return;
1512 };
1513 if d != Offset::default() {
1514 moved_to(host, pos + d);
1515 }
1516 report(host);
1517}
1518
1519pub fn behavior(host: &impl ScrollHost, behavior: &ScrollBehavior) {
1521 let Some((inset, refresh, held, zoom)) = host.scroll_mut(|s, _| {
1522 let inset = s.behavior.content_inset != behavior.content_inset
1524 || s.can_zoom
1525 && (s.behavior.zooms() != behavior.zooms()
1526 || s.behavior.center_content != behavior.center_content);
1527 let refresh = s.behavior.refresh_indicator != behavior.refresh_indicator;
1528 s.behavior = behavior.clone();
1529 let zoom = if s.zooms() {
1531 limit_zoom(behavior, s.zoom, false)
1532 } else {
1533 1.0
1534 };
1535 if !behavior.enabled
1536 && matches!(
1537 s.live.phase,
1538 Phase::Drag { .. } | Phase::Thumb { .. } | Phase::Wheel { .. }
1539 )
1540 {
1541 s.live.phase = Phase::Idle;
1542 }
1543 let held = (refresh
1545 && !s.horizontal
1546 && s.live.refreshing
1547 && s.offset() < 0.0
1548 && !matches!(s.live.phase, Phase::Drag { .. }))
1549 .then(|| behavior.refresh_inset().0);
1550 (inset, refresh, held, (zoom != s.zoom).then_some(zoom))
1551 }) else {
1552 return;
1553 };
1554 if let Some(zoom) = zoom {
1555 zoom_to(host, zoom, None, false);
1556 }
1557 if inset {
1558 host.relayout();
1559 }
1560 if refresh {
1561 host.redraw();
1562 }
1563 if let Some(room) = held {
1564 animate_along(host, -room, ANIMATION, false, false);
1565 }
1566}
1567
1568pub fn refreshing(host: &impl ScrollHost, refreshing: bool) {
1571 let Some(Some((pos, dragging, inset))) = host.scroll_mut(|s, _| {
1572 if s.horizontal || s.live.refreshing == refreshing {
1573 return None;
1574 }
1575 s.live.refreshing = refreshing;
1576 if refreshing {
1577 s.live.dismissing = false;
1578 } else if s.offset() < 0.0 {
1579 s.live.dismissing = true;
1580 } else {
1581 s.live.dismissing = false;
1582 s.live.spin_start = None;
1583 s.live.spin = Radians(0.0);
1584 }
1585 Some((
1586 s.offset(),
1587 matches!(s.live.phase, Phase::Drag { .. }),
1588 s.behavior.refresh_inset().0,
1589 ))
1590 }) else {
1591 return;
1592 };
1593 host.redraw();
1594 if dragging {
1595 return;
1596 }
1597 if refreshing && pos <= 0.5 {
1598 animate_along(host, -inset, ANIMATION, false, false);
1599 } else if !refreshing && pos < 0.0 {
1600 animate_along(host, 0.0, ANIMATION, false, false);
1601 }
1602}
1603
1604pub fn command(host: &impl ScrollHost, command: &Command) {
1607 if let Command::ZoomTo {
1608 scale,
1609 center,
1610 animated,
1611 } = *command
1612 {
1613 let center = center.map(|c| Offset::new(c.x.0, c.y.0));
1614 return zoom_to(host, scale, center, animated);
1615 }
1616 let Some(Some((target, animated))) = host.scroll_mut(|s, size| {
1617 let range = s.range(size);
1618 let inset = s.behavior.content_inset;
1619 let (target, animated) = match *command {
1620 Command::ScrollTo { x, y, animated } => (
1622 if s.zooms() {
1623 Offset::new(x.0 + inset.left.0, y.0 + inset.top.0)
1624 } else if s.horizontal {
1625 s.pos().with(true, x.0 + inset.left.0)
1626 } else {
1627 s.pos().with(false, y.0 + inset.top.0)
1628 },
1629 animated,
1630 ),
1631 Command::ScrollToEnd { animated } => (
1632 s.pos().with(s.horizontal, range.1.along(s.horizontal)),
1633 animated,
1634 ),
1635 Command::ScrollToIndex { .. } => {
1636 log::debug!("scroll: {command:?} is not supported");
1637 return None;
1638 }
1639 _ => return None,
1640 };
1641 s.applied = s.applied.wrapping_add(1);
1642 s.live.report = true;
1643 Some((target.clamp(range), animated))
1644 }) else {
1645 return;
1646 };
1647 interrupt(host);
1648 if animated {
1649 animate_to(host, target, ANIMATION, false, true);
1650 } else {
1651 moved_to(host, target);
1652 }
1653 report(host);
1654}
1655
1656fn limit_zoom(b: &ScrollBehavior, scale: f32, rubber: bool) -> f32 {
1661 let (min, max) = (b.min_zoom, b.max_zoom.max(b.min_zoom));
1662 let band = |limit: f32| limit * (scale / limit).powf(0.3);
1663 if scale > max {
1664 if rubber && b.bounces_zoom {
1665 band(max)
1666 } else {
1667 max
1668 }
1669 } else if scale < min {
1670 if rubber && b.bounces_zoom {
1671 band(min)
1672 } else {
1673 min
1674 }
1675 } else {
1676 scale
1677 }
1678}
1679
1680fn zoom_at(host: &impl ScrollHost, scale: f32, c: Offset, at: Offset) {
1683 let to = host.scroll_mut(|s, size| {
1684 if s.zoom != scale {
1685 s.zoom = scale;
1686 s.live.rezoomed = true;
1687 }
1688 s.showing(size, c, at)
1689 });
1690 if let Some(to) = to {
1691 moved_to(host, to);
1692 }
1693}
1694
1695fn zoom_to(host: &impl ScrollHost, scale: f32, center: Option<Offset>, animated: bool) {
1698 let Some(Some((from, to, at, now_c))) = host.scroll(|s, size| {
1699 if !s.zooms() && s.zoom == 1.0 {
1701 log::debug!("scroll: zoomTo on a scroll view that does not zoom");
1702 return None;
1703 }
1704 let to = if s.zooms() {
1705 limit_zoom(&s.behavior, scale, false)
1706 } else {
1707 1.0
1708 };
1709 let at = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
1710 Some((s.zoom, to, at, s.content_at(size, at)))
1711 }) else {
1712 return;
1713 };
1714 interrupt(host);
1715 let c = center.unwrap_or(now_c);
1716 if animated && host.attached() && (to - from).abs() > 1e-4 {
1717 zoom_eased(host, from, to, now_c, c, at);
1718 } else {
1719 zoom_at(host, to, c, at);
1720 report(host);
1721 }
1722}
1723
1724fn zoom_eased(
1727 host: &impl ScrollHost,
1728 from: f32,
1729 to: f32,
1730 from_c: Offset,
1731 to_c: Offset,
1732 at: Offset,
1733) {
1734 set_phase(
1735 host,
1736 Phase::Zoom {
1737 from,
1738 to,
1739 from_c,
1740 to_c,
1741 at,
1742 start: host.now(),
1743 duration: ANIMATION,
1744 },
1745 );
1746 ensure_ticking(host);
1747}
1748
1749pub fn pinches(host: &impl ScrollHost) -> bool {
1751 host.scroll(|s, _| s.zooms() && s.behavior.pinch)
1752 .unwrap_or(false)
1753}
1754
1755pub fn pinch_begin(host: &impl ScrollHost) {
1758 interrupt(host);
1759 host.scroll_mut(|s, _| s.live.pinch_from = s.zoom);
1760}
1761
1762pub fn pinch(host: &impl ScrollHost, scale: f32, at: Point<Points>) {
1766 let at = Offset::new(at.x.0, at.y.0);
1767 let Some((to, c)) = host.scroll_mut(|s, size| {
1768 let raw = s.live.pinch_from * scale;
1769 let to = limit_zoom(&s.behavior, raw, true);
1770 (to, s.content_at(size, at))
1771 }) else {
1772 return;
1773 };
1774 zoom_at(host, to, c, at);
1775}
1776
1777pub fn pinch_end(host: &impl ScrollHost, at: Point<Points>) {
1779 let at = Offset::new(at.x.0, at.y.0);
1780 let Some((from, to, c)) = host.scroll(|s, size| {
1781 (
1782 s.zoom,
1783 limit_zoom(&s.behavior, s.zoom, false),
1784 s.content_at(size, at),
1785 )
1786 }) else {
1787 return;
1788 };
1789 if (to - from).abs() > 1e-4 {
1790 zoom_eased(host, from, to, c, c, at);
1791 }
1792}
1793
1794pub fn drag_begin(host: &impl ScrollHost) {
1799 if !enabled(host) {
1800 return;
1801 }
1802 interrupt(host);
1803 let (start, cleared) = host
1804 .scroll_mut(|s, _| {
1805 let cleared = !s.live.refreshing && std::mem::take(&mut s.live.dismissing);
1806 if cleared {
1807 s.live.spin_start = None;
1808 s.live.spin = Radians(0.0);
1809 }
1810 (s.pos(), cleared)
1811 })
1812 .unwrap_or_default();
1813 if cleared {
1814 host.redraw();
1815 }
1816 set_phase(
1817 host,
1818 Phase::Drag {
1819 start,
1820 moved: Offset::default(),
1821 },
1822 );
1823 emit(host, EventKind::ScrollDragStart);
1824}
1825
1826pub fn drag_move(host: &impl ScrollHost, delta: Point<Points>) {
1829 drag(host, delta.x.0, delta.y.0, false);
1830}
1831
1832pub fn drag_to(host: &impl ScrollHost, moved: Point<Points>) {
1834 drag(host, moved.x.0, moved.y.0, true);
1835}
1836
1837fn drag(host: &impl ScrollHost, dx: f32, dy: f32, since_begin: bool) {
1838 let Phase::Drag { start, moved } = phase(host) else {
1839 return;
1840 };
1841 let Some((pos, moved)) = host.scroll(|s, size| {
1842 let (min, max) = s.range(size);
1843 let d = if s.zooms() {
1844 Offset::new(-dx, -dy)
1845 } else if !s.horizontal {
1846 Offset::new(0.0, -dy)
1847 } else if s.mirrored {
1848 Offset::new(dx, 0.0)
1849 } else {
1850 Offset::new(-dx, 0.0)
1851 };
1852 let moved = if since_begin { d } else { moved + d };
1855 let raw = start + moved;
1856 let bounces = s.behavior.bounces;
1857 let pos = Offset::new(
1858 drag_position(raw.x, min.x, max.x.max(min.x), size.width.0, bounces),
1859 drag_position(raw.y, min.y, max.y.max(min.y), size.height.0, bounces),
1860 );
1861 (pos, moved)
1862 }) else {
1863 return;
1864 };
1865 set_phase(host, Phase::Drag { start, moved });
1866 moved_to(host, pos);
1867}
1868
1869pub fn drag_end(host: &impl ScrollHost, vx: f32, vy: f32) {
1872 if !matches!(phase(host), Phase::Drag { .. }) {
1873 return;
1874 }
1875 let listens = host.listens(EventKind::Refresh);
1876 let Some((v, refresh)) = host.scroll(|s, _| {
1877 let v = if s.zooms() {
1878 Offset::new(-vx / 1000.0, -vy / 1000.0)
1879 } else {
1880 let v = if !s.horizontal {
1881 -vy
1882 } else if s.mirrored {
1883 vx
1884 } else {
1885 -vx
1886 } / 1000.0;
1887 Offset::default().with(s.horizontal, v)
1888 };
1889 let refresh = !s.horizontal
1890 && !s.live.refreshing
1891 && listens
1892 && s.behavior.refreshes(Points(s.offset()));
1893 (v, refresh)
1894 }) else {
1895 return;
1896 };
1897 set_phase(host, Phase::Idle);
1898 emit(host, EventKind::ScrollDragEnd);
1899 if refresh {
1900 host.scroll_mut(|s, _| {
1902 s.live.refreshing = true;
1903 s.live.dismissing = false;
1904 });
1905 host.event(EventKind::Refresh, EventPayload::None);
1906 }
1907 release(host, v, 0.0);
1908}
1909
1910pub fn hovered(host: &impl ScrollHost) {
1916 let shown = host.scroll_mut(|s, size| {
1917 if s.thumb(size).is_none() || !s.indicator || !s.behavior.enabled {
1918 return false;
1919 }
1920 s.live.shown = host.now();
1921 if s.live.alpha == 1.0 {
1922 return false;
1923 }
1924 s.live.alpha = 1.0;
1925 s.live.dark = host.dark();
1926 true
1927 });
1928 if shown != Some(true) {
1929 return;
1930 }
1931 host.redraw();
1932 ensure_ticking(host);
1933}
1934
1935pub fn thumb_begin(host: &impl ScrollHost) {
1937 interrupt(host);
1938 let grabbed = host.scroll_mut(|s, _| {
1939 s.live.phase = Phase::Thumb { start: s.offset() };
1940 s.live.shown = host.now();
1941 s.live.alpha = 1.0;
1942 s.live.dark = host.dark();
1943 });
1944 if grabbed.is_none() {
1945 return;
1946 }
1947 host.redraw();
1948 emit(host, EventKind::ScrollDragStart);
1949}
1950
1951pub fn thumb_move(host: &impl ScrollHost, moved: Point<Points>) {
1955 let (dx, dy) = (moved.x.0, moved.y.0);
1956 let Phase::Thumb { start } = phase(host) else {
1957 return;
1958 };
1959 let Some(Some(pos)) = host.scroll(|s, size| {
1960 let (_, travel) = s.thumb(size)?;
1961 let (min, max) = s.limits(size);
1962 let d = if !s.horizontal {
1963 dy
1964 } else if s.mirrored {
1965 -dx
1966 } else {
1967 dx
1968 };
1969 let d = thumb_scroll(Points(d), Points(max), travel).0;
1970 Some((start + d).clamp(min, max.max(min)))
1971 }) else {
1972 return;
1973 };
1974 moved_along(host, pos);
1975}
1976
1977pub fn thumb_end(host: &impl ScrollHost) {
1980 if !matches!(phase(host), Phase::Thumb { .. }) {
1981 return;
1982 }
1983 set_phase(host, Phase::Idle);
1984 host.scroll_mut(|s, _| s.live.shown = host.now());
1985 ensure_ticking(host);
1986 emit(host, EventKind::ScrollDragEnd);
1987 release(host, Offset::default(), 0.0);
1988}
1989
1990pub fn wheel_begin(host: &impl ScrollHost) {
1995 if !enabled(host) {
1996 return;
1997 }
1998 interrupt(host);
1999 set_phase(
2000 host,
2001 Phase::Wheel {
2002 last: host.now(),
2003 total: 0.0,
2004 gesture: true,
2005 raw: Offset::default(),
2006 glide: wheel_glide::Glide::default(),
2007 },
2008 );
2009 emit(host, EventKind::ScrollDragStart);
2010}
2011
2012pub fn wheel(host: &impl ScrollHost, delta: Point<Points>) {
2015 wheel_by(host, delta, false);
2016}
2017
2018#[doc(hidden)]
2024pub fn wheel_smooth(host: &impl ScrollHost, delta: Point<Points>) {
2025 wheel_by(host, delta, true);
2026}
2027
2028#[doc(hidden)]
2031pub fn smooth_wheel(host: &impl ScrollHost) -> bool {
2032 host.scroll(|s, _| {
2033 s.behavior.smooth_wheel && !s.zooms() && !s.behavior.snaps() && !s.behavior.paging
2034 })
2035 .unwrap_or(false)
2036}
2037
2038#[doc(hidden)]
2042pub fn wheel_line(
2043 host: &impl ScrollHost,
2044 delta: Point<Points>,
2045 line: Point<Points>,
2046) -> Point<Points> {
2047 let height = host
2048 .scroll(|s, _| s.behavior.wheel_line_height)
2049 .unwrap_or(Points::ZERO)
2050 .0;
2051 let axis = |d: Points, line: Points| {
2052 if height > 0.0 && line.0 > 0.0 {
2053 Points(d.0 * height / line.0)
2054 } else {
2055 d
2056 }
2057 };
2058 point(axis(delta.x, line.x), axis(delta.y, line.y))
2059}
2060
2061fn wheel_by(host: &impl ScrollHost, delta: Point<Points>, smooth: bool) {
2062 let (dx, dy) = (delta.x.0, delta.y.0);
2063 if !enabled(host) {
2064 return;
2065 }
2066 let (gesture, total, last) = match phase(host) {
2067 Phase::Wheel {
2068 gesture,
2069 total,
2070 raw,
2071 glide,
2072 ..
2073 } => (gesture, total, (!gesture).then_some((raw, glide))),
2074 _ => {
2075 interrupt(host);
2076 (false, 0.0, None)
2077 }
2078 };
2079 let smooth = smooth && !gesture;
2080 let now = host.now();
2081 let Some((pos, to, total)) = host.scroll(|s, size| {
2082 let (min, max) = s.range(size);
2083 let d = if s.zooms() {
2084 Offset::new(dx, dy)
2085 } else if !s.horizontal {
2086 Offset::new(0.0, dy)
2087 } else if dx != 0.0 {
2088 Offset::new(if s.mirrored { -dx } else { dx }, 0.0)
2089 } else {
2090 Offset::new(dy, 0.0)
2092 };
2093 let pos = s.pos();
2094 let from = match last {
2097 Some((raw, _)) if smooth => raw,
2098 _ => pos,
2099 };
2100 let one =
2102 |p: f32, d: f32, min: f32, max: f32| (p + d).clamp(min.min(p), max.max(min).max(p));
2103 (
2104 pos,
2105 Offset::new(
2106 one(from.x, d.x, min.x, max.x),
2107 one(from.y, d.y, min.y, max.y),
2108 ),
2109 total + d.along(s.horizontal),
2110 )
2111 }) else {
2112 return;
2113 };
2114 let glide = match last {
2115 _ if !smooth => wheel_glide::Glide::default(),
2116 Some((raw, g)) if now < g.end() => g.retargeted(raw.into(), to.into(), now),
2117 _ => wheel_glide::Glide::new(pos.into(), to.into(), now),
2118 };
2119 set_phase(
2120 host,
2121 Phase::Wheel {
2122 last: now,
2123 total,
2124 gesture,
2125 raw: to,
2126 glide,
2127 },
2128 );
2129 if !smooth {
2130 moved_to(host, to);
2131 }
2132 ensure_ticking(host);
2133}
2134
2135pub fn wheel_end(host: &impl ScrollHost, vx: f32, vy: f32) {
2138 end_wheel(host, vx, vy, true);
2139}
2140
2141pub fn wheel_settle(host: &impl ScrollHost) {
2147 end_wheel(host, 0.0, 0.0, false);
2148}
2149
2150fn end_wheel(host: &impl ScrollHost, vx: f32, vy: f32, onward: bool) {
2151 let Phase::Wheel { gesture, total, .. } = phase(host) else {
2152 return;
2153 };
2154 let Some(v) = host.scroll(|s, _| {
2155 let v = if s.zooms() {
2156 return Offset::new(vx / 1000.0, vy / 1000.0);
2157 } else if !s.horizontal {
2158 vy
2159 } else if vx != 0.0 {
2160 if s.mirrored { -vx } else { vx }
2161 } else {
2162 vy
2163 };
2164 Offset::default().with(s.horizontal, v / 1000.0)
2165 }) else {
2166 return;
2167 };
2168 set_phase(host, Phase::Idle);
2169 if gesture {
2170 emit(host, EventKind::ScrollDragEnd);
2171 }
2172 let snap = if onward && v == Offset::default() && total.abs() >= 1.0 {
2173 total.signum() * WHEEL_SNAP
2174 } else {
2175 0.0
2176 };
2177 release(host, v, snap);
2178}
2179
2180const WHEEL_STEP_ANIMATION: f64 = 150.0;
2183
2184pub fn wheel_step(host: &impl ScrollHost, delta: Point<Points>) {
2190 if !enabled(host) {
2191 return;
2192 }
2193 let Some(target) = host.scroll(|s, size| {
2194 if s.zooms() || s.behavior.snaps() || s.behavior.paging {
2195 return None;
2196 }
2197 let (min, max) = s.limits(size);
2198 let max = max.max(min);
2199 let (dx, dy) = (delta.x.0, delta.y.0);
2200 let d = if !s.horizontal {
2201 dy
2202 } else if dx != 0.0 {
2203 if s.mirrored { -dx } else { dx }
2204 } else {
2205 dy
2207 };
2208 let pos = s.offset();
2209 if pos < min - 0.5 || pos > max + 0.5 {
2210 return None;
2211 }
2212 Some((s.goal() + d).clamp(min, max))
2213 }) else {
2214 return;
2215 };
2216 let Some(to) = target else {
2217 wheel(host, delta);
2218 return;
2219 };
2220 if matches!(phase(host), Phase::Wheel { gesture: true, .. }) {
2221 return;
2223 }
2224 let goal = host.scroll(|s, _| s.goal()).unwrap_or(to);
2225 if (to - goal).abs() < 0.5 {
2226 return;
2228 }
2229 interrupt(host);
2230 animate_along(host, to, WHEEL_STEP_ANIMATION, false, true);
2231}
2232
2233pub const KEY_LINE: Points = Points(40.0);
2237const KEY_PAGE: f32 = 0.875;
2239const KEY_ANIMATION: f64 = 200.0;
2241
2242#[derive(Debug, Clone, Copy, PartialEq)]
2244pub enum KeyMove {
2245 Points(Points),
2247 Pages(f32),
2249 Start,
2251 End,
2253}
2254
2255impl KeyMove {
2256 pub fn sign(self) -> f32 {
2258 match self {
2259 KeyMove::Points(d) => d.0.signum(),
2260 KeyMove::Pages(n) => n.signum(),
2261 KeyMove::Start => -1.0,
2262 KeyMove::End => 1.0,
2263 }
2264 }
2265}
2266
2267pub fn vk_key_move(vk: u16, shift: bool, ctrl: bool) -> Option<(bool, KeyMove)> {
2272 const VK_SPACE: u16 = 0x20;
2273 const VK_PRIOR: u16 = 0x21;
2274 const VK_NEXT: u16 = 0x22;
2275 const VK_END: u16 = 0x23;
2276 const VK_HOME: u16 = 0x24;
2277 const VK_LEFT: u16 = 0x25;
2278 const VK_UP: u16 = 0x26;
2279 const VK_RIGHT: u16 = 0x27;
2280 const VK_DOWN: u16 = 0x28;
2281 if ctrl {
2282 return match vk {
2283 VK_HOME => Some((false, KeyMove::Start)),
2284 VK_END => Some((false, KeyMove::End)),
2285 _ => None,
2286 };
2287 }
2288 Some(match vk {
2289 VK_UP => (false, KeyMove::Points(-KEY_LINE)),
2290 VK_DOWN => (false, KeyMove::Points(KEY_LINE)),
2291 VK_LEFT => (true, KeyMove::Points(-KEY_LINE)),
2292 VK_RIGHT => (true, KeyMove::Points(KEY_LINE)),
2293 VK_PRIOR => (false, KeyMove::Pages(-1.0)),
2294 VK_NEXT => (false, KeyMove::Pages(1.0)),
2295 VK_SPACE if shift => (false, KeyMove::Pages(-1.0)),
2296 VK_SPACE => (false, KeyMove::Pages(1.0)),
2297 VK_HOME => (false, KeyMove::Start),
2298 VK_END => (false, KeyMove::End),
2299 _ => return None,
2300 })
2301}
2302
2303fn key_target(m: KeyMove, base: f32, viewport: f32, min: f32, max: f32) -> f32 {
2305 let max = max.max(min);
2306 match m {
2307 KeyMove::Points(d) => base + d.0,
2308 KeyMove::Pages(n) => base + n * (viewport * KEY_PAGE).max(KEY_LINE.0),
2309 KeyMove::Start => min,
2310 KeyMove::End => max,
2311 }
2312 .clamp(min, max)
2313}
2314
2315pub fn key_scroll(host: &impl ScrollHost, m: KeyMove, flip: bool) {
2321 let Some((base, viewport, min, max, flip)) = host.scroll(|s, size| {
2322 let (min, max) = s.limits(size);
2323 (s.goal(), s.viewport(size), min, max, flip && s.mirrored)
2324 }) else {
2325 return;
2326 };
2327 let moved = match m {
2328 KeyMove::Points(d) if flip => KeyMove::Points(-d),
2329 m => m,
2330 };
2331 let to = key_target(moved, base, viewport, min, max);
2332 interrupt(host);
2333 animate_along(host, to, KEY_ANIMATION, false, true);
2334 host.key_scrolled(m);
2338}
2339
2340const REVEAL_MARGIN: f32 = 16.0;
2342
2343pub fn reveal_delta(start: Points, end: Points, viewport: Points) -> Points {
2347 Points(reveal_by(start.0, end.0, viewport.0))
2348}
2349
2350pub fn reveal_focus_delta(start: Points, end: Points, viewport: Points) -> Points {
2356 Points(reveal_focus_by(start.0, end.0, viewport.0))
2357}
2358
2359fn reveal_by(start: f32, end: f32, viewport: f32) -> f32 {
2360 let margin = REVEAL_MARGIN.min(viewport / 4.0);
2361 if start < margin {
2362 start - margin
2363 } else if end > viewport - margin {
2364 (end - (viewport - margin)).min(start - margin)
2365 } else {
2366 0.0
2367 }
2368}
2369
2370fn reveal_focus_by(start: f32, end: f32, viewport: f32) -> f32 {
2371 if end - start > viewport && end > 0.0 && start < viewport {
2372 0.0
2373 } else {
2374 reveal_by(start, end, viewport)
2375 }
2376}
2377
2378pub fn reveal(host: &impl ScrollHost, start: Points, len: Points) -> Points {
2384 let (start, len) = (start.0, len.0);
2385 let Some((base, pos, dim, min, max)) = host.scroll(|s, size| {
2386 let (min, max) = s.limits(size);
2387 (s.goal(), s.offset(), s.viewport(size), min, max)
2388 }) else {
2389 return Points(0.0);
2390 };
2391 let start = start - (base - pos);
2393 let delta = reveal_focus_by(start, start + len, dim);
2394 let to = (base + delta).clamp(min, max.max(min));
2395 if (to - base).abs() < 0.5 {
2396 return Points(0.0);
2397 }
2398 interrupt(host);
2399 animate_along(host, to, ANIMATION, false, true);
2400 Points(to - base)
2401}
2402
2403#[cfg(test)]
2404mod tests {
2405 use super::*;
2406 use crate::EdgeInsets;
2407
2408 #[test]
2409 fn content_is_read_in_the_order_it_is_on_screen() {
2410 let cells = [(0, 160.0), (1, 200.0), (2, 80.0), (3, 120.0)];
2413 let mut vertical = cells;
2414 reading_order(Axis::Vertical, &mut vertical, |c| {
2415 point(Points(0.0), Points(c.1))
2416 });
2417 assert_eq!(vertical.map(|c| c.0), [2, 3, 0, 1]);
2418 let grid = [
2420 (0, (50.0, 0.0)),
2421 (1, (0.0, 40.0)),
2422 (2, (0.0, 0.0)),
2423 (3, (50.0, 40.0)),
2424 ];
2425 let at = |c: &(i32, (f32, f32))| point(Points(c.1.0), Points(c.1.1));
2426 let mut rows = grid;
2427 reading_order(Axis::Vertical, &mut rows, at);
2428 assert_eq!(rows.map(|c| c.0), [2, 0, 1, 3]);
2429 let mut columns = grid;
2430 reading_order(Axis::Horizontal, &mut columns, at);
2431 assert_eq!(columns.map(|c| c.0), [2, 1, 0, 3]);
2432 }
2433
2434 fn scroll_state(content: (f32, f32), horizontal: bool) -> ScrollState {
2435 ScrollState {
2436 content: sz(content.0, content.1),
2437 horizontal,
2438 ..Default::default()
2439 }
2440 }
2441
2442 fn sz(w: f32, h: f32) -> Size<Points> {
2443 crate::geometry::size(Points(w), Points(h))
2444 }
2445
2446 fn pt(x: f32, y: f32) -> Point<Points> {
2447 point(Points(x), Points(y))
2448 }
2449
2450 #[test]
2451 fn rubber_band_resists() {
2452 assert_eq!(drag_position(50.0, 0.0, 100.0, 400.0, true), 50.0);
2453 let over = drag_position(-100.0, 0.0, 100.0, 400.0, true);
2454 assert!(over < 0.0 && over > -100.0, "{over}");
2455 let more = drag_position(-400.0, 0.0, 100.0, 400.0, true);
2456 assert!(more < over && more > -400.0 * 0.55);
2457 assert_eq!(drag_position(-100.0, 0.0, 100.0, 400.0, false), 0.0);
2458 assert_eq!(drag_position(300.0, 0.0, 100.0, 400.0, false), 100.0);
2459 assert!(drag_position(150.0, 0.0, 100.0, 400.0, true) > 100.0);
2460 let p = Points;
2461 assert_eq!(dragged(p(50.0), p(0.0), p(100.0), p(400.0), true), p(50.0));
2462 assert!(rubber(1e6, 400.0) < 400.0);
2464 }
2465
2466 #[test]
2467 fn glide_integrates_to_projection() {
2468 let rate = 0.998;
2469 let (mut pos, mut v) = (0.0f32, 2.0f32);
2470 for _ in 0..2000 {
2471 let (d, nv) = glide_step(v, rate, 16.0);
2472 pos += d;
2473 v = nv;
2474 }
2475 let end = projected(Points(0.0), 2.0, rate).0;
2476 assert!((pos - end).abs() < 1.0, "{pos} vs {end}");
2477 let (a, _) = glide_step(2.0, rate, 32.0);
2479 let (b1, v1) = glide_step(2.0, rate, 16.0);
2480 let (b2, _) = glide_step(v1, rate, 16.0);
2481 assert!((a - (b1 + b2)).abs() < 1e-3);
2482 }
2483
2484 #[test]
2485 fn animated_sticky_offsets_stick_further_in() {
2486 let mut s = scroll_state((320.0, 2000.0), false);
2487 s.y = Points(150.0);
2488 s.sticky = vec![
2489 crate::StickyCell {
2490 cell: 1,
2491 start: Points(100.0),
2492 end: Points(300.0),
2493 offset: None,
2494 },
2495 crate::StickyCell {
2496 cell: 2,
2497 start: Points(100.0),
2498 end: Points(300.0),
2499 offset: Some(7),
2500 },
2501 ];
2502 let shifts: Vec<_> = s
2504 .sticky_shifts_with(|n| if n == 7 { 56.0 } else { 0.0 })
2505 .map(|(c, p)| (c, p.y.0))
2506 .collect();
2507 assert_eq!(shifts, [(1, 50.0), (2, 106.0)]);
2508 }
2509
2510 #[test]
2511 fn sticky_shift_clamps() {
2512 let p = Points;
2513 assert_eq!(sticky_shift(p(0.0), p(100.0), p(300.0)), p(0.0));
2514 assert_eq!(sticky_shift(p(150.0), p(100.0), p(300.0)), p(50.0));
2515 assert_eq!(sticky_shift(p(500.0), p(100.0), p(300.0)), p(200.0));
2516 assert_eq!(sticky_shift(p(500.0), p(100.0), p(f32::INFINITY)), p(400.0));
2517 assert_eq!(sticky_shift(p(0.0), p(300.0), p(100.0)), p(-200.0));
2520 assert_eq!(sticky_shift(p(150.0), p(300.0), p(100.0)), p(-150.0));
2521 assert_eq!(sticky_shift(p(300.0), p(300.0), p(100.0)), p(0.0));
2522 assert_eq!(sticky_shift(p(500.0), p(300.0), p(100.0)), p(0.0));
2523 }
2524
2525 #[test]
2526 fn rates_follow_behavior() {
2527 let mut b = ScrollBehavior::default();
2528 assert_eq!(rate(&b), 0.998);
2529 b.paging = true;
2530 assert_eq!(rate(&b), 0.99);
2531 b.deceleration = 0.95;
2532 assert_eq!(rate(&b), 0.95);
2533 }
2534
2535 #[test]
2536 fn snapping_and_paging_targets() {
2537 let b = ScrollBehavior {
2540 paging: true,
2541 ..Default::default()
2542 };
2543 let r = rate(&b);
2544 let pt = Points;
2545 let t = b.snap_target(
2546 pt(250.0),
2547 projected(pt(250.0), 0.0, r),
2548 0.0,
2549 pt(400.0),
2550 pt(1600.0),
2551 );
2552 assert_eq!(t, Some(pt(400.0)));
2553 let t = b.snap_target(
2554 pt(100.0),
2555 projected(pt(100.0), 1.0, r),
2556 1.0,
2557 pt(400.0),
2558 pt(1600.0),
2559 );
2560 assert_eq!(t, Some(pt(400.0)));
2561 let t = b.snap_target(
2562 pt(300.0),
2563 projected(pt(300.0), -1.0, r),
2564 -1.0,
2565 pt(400.0),
2566 pt(1600.0),
2567 );
2568 assert_eq!(t, Some(pt(0.0)));
2569 let b = ScrollBehavior {
2570 snap_interval: pt(100.0),
2571 ..Default::default()
2572 };
2573 let t = b.snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0));
2574 assert_eq!(t, Some(pt(100.0)));
2575 assert_eq!(
2576 ScrollBehavior::default().snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0)),
2577 None
2578 );
2579 }
2580
2581 #[test]
2582 fn indicator_geometry() {
2583 assert_eq!(span(400.0, 400.0, 0.0, 0.0, 0.0), None);
2584 let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2585 assert_eq!(s0, 2.0);
2586 assert!((l0 - 99.0).abs() < 0.01);
2587 let (s1, l1) = span(400.0, 1600.0, 1200.0, 0.0, 0.0).unwrap();
2588 assert!((s1 + l1 - 398.0).abs() < 0.01);
2589 let (_, l2) = span(400.0, 1600.0, -50.0, 0.0, 0.0).unwrap();
2590 assert!(l2 < l0);
2591 assert_eq!(
2592 indicator_span(Points(400.0), Points(1600.0), Points(0.0)),
2593 Some((Points(s0), Points(l0)))
2594 );
2595 assert_eq!(indicator_alpha(0.0), 1.0);
2596 assert_eq!(indicator_alpha(INDICATOR_HOLD + INDICATOR_FADE), 0.0);
2597 }
2598
2599 #[test]
2600 fn snap_durations() {
2601 let p = Points;
2602 assert_eq!(snap_duration(p(0.2), 1.0), 0.0);
2603 assert_eq!(snap_duration(p(100.0), -1.0), ANIMATION);
2604 assert_eq!(snap_duration(p(300.0), 1.0), 600.0);
2605 assert_eq!(snap_duration(p(300.0), 3.0), 300.0);
2606 assert_eq!(ease_out(1.0), 1.0);
2607 assert_eq!(ease_out(2.0), 1.0);
2608 }
2609
2610 #[test]
2611 fn insets_clamp_and_report() {
2612 let mut s = scroll_state((300.0, 1000.0), false);
2613 let size = sz(300.0, 400.0);
2614 s.behavior.content_inset = EdgeInsets {
2615 top: Points(50.0),
2616 bottom: Points(20.0),
2617 ..Default::default()
2618 };
2619 assert_eq!(s.limits(size), (0.0, 670.0));
2620 assert_eq!(s.max(size), pt(0.0, 670.0));
2621 assert_eq!(s.reported(size), pt(0.0, -50.0));
2623 s.y = Points(900.0);
2624 assert_eq!(s.reported(size), pt(0.0, 620.0));
2625 assert_eq!(s.origin(), pt(0.0, 850.0));
2627 s.live.refreshing = true;
2629 assert_eq!(s.limits(size).0, -56.0);
2630 s.behavior.refresh_indicator = Some(Points(80.0));
2631 assert_eq!(s.limits(size).0, -80.0);
2632 }
2633
2634 #[test]
2635 fn can_scroll_follows_edges_and_mirroring() {
2636 let size = sz(300.0, 400.0);
2637 let mut s = scroll_state((300.0, 1000.0), false);
2638 s.behavior.enabled = true;
2639 assert!(s.can_scroll(size, pt(0.0, 10.0)));
2640 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2641 s.y = Points(600.0);
2642 assert!(!s.can_scroll(size, pt(0.0, 10.0)));
2643 s.behavior.enabled = false;
2644 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2645
2646 let size = sz(300.0, 100.0);
2647 let mut row = scroll_state((1000.0, 100.0), true);
2648 row.behavior.enabled = true;
2649 row.mirrored = true;
2650 assert!(row.can_scroll(size, pt(-10.0, 0.0)));
2652 assert!(!row.can_scroll(size, pt(10.0, 0.0)));
2653 assert!(row.can_scroll(size, pt(0.0, 10.0)));
2655 }
2656
2657 #[test]
2658 fn scroll_by_moves_gestures_along() {
2659 let y = |v: f32| Offset::new(0.0, v);
2660 let drag = shifted(
2661 Phase::Drag {
2662 start: y(10.0),
2663 moved: y(5.0),
2664 },
2665 y(30.0),
2666 false,
2667 );
2668 assert_eq!(
2669 drag,
2670 Phase::Drag {
2671 start: y(40.0),
2672 moved: y(5.0)
2673 }
2674 );
2675 let anim = Phase::Animate {
2676 from: y(0.0),
2677 to: y(100.0),
2678 start: 1.0,
2679 duration: 300.0,
2680 momentum: false,
2681 end: true,
2682 };
2683 let Phase::Animate { from, to, .. } = shifted(anim, y(-20.0), false) else {
2684 panic!()
2685 };
2686 assert_eq!((from, to), (y(-20.0), y(80.0)));
2687 assert_eq!(shifted(Phase::Idle, y(5.0), false), Phase::Idle);
2688 assert_eq!(
2689 shifted(Phase::Thumb { start: 10.0 }, y(30.0), false),
2690 Phase::Thumb { start: 40.0 }
2691 );
2692 }
2693
2694 #[test]
2695 fn thumb_follows_the_pointer() {
2696 let p = Points;
2699 let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2700 let travel = 400.0 - 2.0 * INDICATOR_MARGIN - l0;
2701 let end = thumb_scroll(p(travel), p(1200.0), p(travel)).0;
2702 assert!((end - 1200.0).abs() < 0.01);
2703 let (s1, _) = span(400.0, 1600.0, end, 0.0, 0.0).unwrap();
2704 assert!((s1 - s0 - travel).abs() < 0.01);
2705 assert!(thumb_scroll(p(-10.0), p(1200.0), p(travel)).0 < 0.0);
2706 assert_eq!(thumb_scroll(p(10.0), p(1200.0), p(0.0)), p(0.0));
2707 }
2708
2709 #[test]
2710 fn thumb_is_grabbed_at_the_edge() {
2711 let mut s = scroll_state((300.0, 1600.0), false);
2712 s.indicator = true;
2713 s.behavior.enabled = true;
2714 let size = sz(300.0, 400.0);
2715 let (rect, _) = s.thumb(size).unwrap();
2716 assert_eq!(rect.origin.x.0, 300.0 - INDICATOR_THICK.0 - 2.0);
2717 assert!(s.grabs_thumb(size, pt(295.0, 10.0)));
2718 assert!(!s.grabs_thumb(size, pt(200.0, 10.0)));
2719 assert!(!s.grabs_thumb(size, pt(295.0, 300.0)));
2720 }
2721
2722 #[test]
2723 fn thumb_keeps_clear_of_the_scrollbar_inset() {
2724 let (s0, l0) = span(400.0, 1600.0, 0.0, 50.0, 100.0).unwrap();
2727 assert_eq!(s0, 50.0 + INDICATOR_MARGIN);
2728 let (s1, l1) = span(400.0, 1600.0, 1200.0, 50.0, 100.0).unwrap();
2729 assert!((s1 + l1 - (300.0 - INDICATOR_MARGIN)).abs() < 0.01);
2730 let (_, full) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2732 assert!(l0 < full && (l0 - 246.0 / 4.0).abs() < 0.01, "{l0}");
2733 assert_eq!(span(400.0, 1600.0, 0.0, 200.0, 195.0), None);
2735 assert_eq!(
2737 span(400.0, 1600.0, 0.0, -10.0, 0.0),
2738 span(400.0, 1600.0, 0.0, 0.0, 0.0)
2739 );
2740 assert_eq!(
2741 indicator_span_within(
2742 Points(400.0),
2743 Points(1600.0),
2744 Points(0.0),
2745 Points(50.0),
2746 Points(100.0)
2747 ),
2748 Some((Points(s0), Points(l0)))
2749 );
2750
2751 let mut s = scroll_state((300.0, 1600.0), false);
2753 s.indicator = true;
2754 s.behavior.enabled = true;
2755 s.behavior.scrollbar_inset = EdgeInsets {
2756 top: Points(50.0),
2757 right: Points(8.0),
2758 bottom: Points(100.0),
2759 left: Points::ZERO,
2760 };
2761 let size = sz(300.0, 400.0);
2762 let (rect, travel) = s.thumb(size).unwrap();
2763 assert_eq!(rect.origin.x.0, 300.0 - 8.0 - INDICATOR_THICK.0 - 2.0);
2764 assert_eq!(rect.origin.y.0, s0);
2765 assert!((travel.0 - (400.0 - 150.0 - 2.0 * INDICATOR_MARGIN - l0)).abs() < 0.01);
2766 assert!(s.grabs_thumb(size, pt(287.0, 60.0)));
2767 assert!(!s.grabs_thumb(size, pt(295.0, 60.0)), "past its edge");
2768 assert!(!s.grabs_thumb(size, pt(287.0, 20.0)), "above its track");
2769
2770 let mut s = scroll_state((900.0, 2000.0), true);
2773 s.behavior.scrollbar_inset = EdgeInsets {
2774 top: Points::ZERO,
2775 right: Points(30.0),
2776 bottom: Points(20.0),
2777 left: Points(10.0),
2778 };
2779 let size = sz(300.0, 400.0);
2780 let (rect, _) = s.thumb(size).unwrap();
2781 assert_eq!(rect.origin.y.0, 400.0 - 20.0 - INDICATOR_THICK.0 - 2.0);
2782 assert_eq!(rect.origin.x.0, 10.0 + INDICATOR_MARGIN);
2783 s.mirrored = true;
2784 let (rect, _) = s.thumb(size).unwrap();
2785 assert_eq!(
2786 rect.origin.x.0 + rect.size.width.0,
2787 300.0 - 30.0 - INDICATOR_MARGIN
2788 );
2789 }
2790
2791 #[test]
2792 fn thumb_stays_in_the_visible_part() {
2793 let mut s = scroll_state((900.0, 2000.0), true);
2797 s.indicator = true;
2798 s.behavior.enabled = true;
2799 let size = sz(300.0, 2000.0);
2800 let visible = Bounds::new(pt(0.0, 600.0), sz(300.0, 400.0));
2801 let (rect, _) = s.thumb_within(size, visible).unwrap();
2802 assert_eq!(rect.origin.y.0, 1000.0 - INDICATOR_THICK.0 - 2.0);
2803 assert!(s.grabs_thumb_within(size, visible, pt(20.0, 997.0)));
2804 assert!(!s.grabs_thumb_within(size, visible, pt(20.0, 1997.0)));
2805 let (rect, _) = s.thumb(size).unwrap();
2807 assert_eq!(rect.origin.y.0, 2000.0 - INDICATOR_THICK.0 - 2.0);
2808 let hidden = Bounds::new(pt(0.0, 2100.0), sz(300.0, 400.0));
2810 assert!(s.thumb_within(size, hidden).is_none());
2811 }
2812
2813 #[test]
2814 fn scroll_keys() {
2815 assert_eq!(
2816 vk_key_move(0x28, false, false),
2817 Some((false, KeyMove::Points(KEY_LINE)))
2818 );
2819 assert_eq!(
2820 vk_key_move(0x25, false, false),
2821 Some((true, KeyMove::Points(-KEY_LINE)))
2822 );
2823 assert_eq!(
2824 vk_key_move(0x20, true, false),
2825 Some((false, KeyMove::Pages(-1.0)))
2826 );
2827 assert_eq!(
2828 vk_key_move(0x24, false, true),
2829 Some((false, KeyMove::Start))
2830 );
2831 assert_eq!(vk_key_move(0x28, false, true), None);
2832 assert_eq!(vk_key_move(b'A' as u16, false, false), None);
2833 assert_eq!(KeyMove::Start.sign(), -1.0);
2834 assert_eq!(KeyMove::Pages(1.0).sign(), 1.0);
2835 assert_eq!(
2836 key_target(KeyMove::Points(Points(40.0)), 10.0, 400.0, 0.0, 1000.0),
2837 50.0
2838 );
2839 assert_eq!(
2840 key_target(KeyMove::Pages(1.0), 0.0, 400.0, 0.0, 1000.0),
2841 350.0
2842 );
2843 assert_eq!(
2844 key_target(KeyMove::Pages(-1.0), 100.0, 400.0, 0.0, 1000.0),
2845 0.0
2846 );
2847 assert_eq!(key_target(KeyMove::End, 0.0, 400.0, 0.0, 1000.0), 1000.0);
2848 assert_eq!(
2849 key_target(KeyMove::Start, 500.0, 400.0, -56.0, 1000.0),
2850 -56.0
2851 );
2852 }
2853
2854 #[test]
2855 fn reveal_deltas() {
2856 assert_eq!(reveal_by(100.0, 140.0, 400.0), 0.0);
2857 assert_eq!(reveal_by(-30.0, 10.0, 400.0), -46.0);
2858 assert_eq!(reveal_by(380.0, 420.0, 400.0), 36.0);
2859 assert_eq!(reveal_by(200.0, 900.0, 400.0), 184.0);
2861 assert_eq!(reveal_focus_by(500.0, 1200.0, 400.0), 484.0);
2864 assert_eq!(reveal_focus_by(-1200.0, -500.0, 400.0), -1216.0);
2865 assert_eq!(reveal_focus_by(200.0, 900.0, 400.0), 0.0);
2866 assert_eq!(reveal_focus_by(-2000.0, 300.0, 400.0), 0.0);
2867 assert_eq!(reveal_focus_by(-2000.0, 900.0, 400.0), 0.0);
2868 assert_eq!(reveal_focus_by(-100.0, 290.0, 400.0), -116.0);
2871 assert_eq!(
2872 reveal_focus_delta(Points(200.0), Points(900.0), Points(400.0)),
2873 Points(0.0)
2874 );
2875 assert_eq!(
2876 reveal_delta(Points(-30.0), Points(10.0), Points(400.0)),
2877 Points(-46.0)
2878 );
2879 }
2880
2881 #[test]
2882 fn spinner_spokes() {
2883 assert_eq!(spokes(Percentage(0.3), Radians(0.0)).count(), 3);
2884 assert!(spokes(Percentage(0.3), Radians(0.0)).all(|(_, a)| a == 0.8));
2885 let all: Vec<_> = spokes(Percentage(1.0), Radians(0.0)).collect();
2886 assert_eq!(all.len(), 8);
2887 assert_eq!(all[0].1, 1.0);
2889 assert_eq!(all[1].0, Radians(PI / 4.0));
2890 }
2891
2892 #[test]
2893 fn refresh_follows_its_props() {
2894 let mut s = scroll_state((300.0, 1000.0), false);
2895 assert!(!s.behavior.refreshes(Points(-63.0)));
2896 assert!(s.behavior.refreshes(Points(-64.0)));
2897 s.y = Points(-32.0);
2899 assert_eq!(
2900 s.spinner(Points(300.0), true),
2901 Some((pt(150.0, 4.0), Percentage(0.5)))
2902 );
2903 s.behavior.refresh_indicator = Some(Points(100.0));
2906 assert!(!s.behavior.refreshes(Points(-64.0)));
2907 assert!(s.behavior.refreshes(Points(-100.0)));
2908 assert_eq!(s.behavior.refresh_inset(), Points(100.0));
2909 assert_eq!(s.spinner(Points(300.0), true), None);
2910 }
2911
2912 #[test]
2913 fn refresh_dismissal_keeps_spinning_and_large_clocks_stay_precise() {
2914 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
2915 refreshing(&host, true);
2916 assert!(host.tick(ANIMATION));
2918 assert_eq!(host.state.borrow().y, Points(-56.0));
2919 assert!(host.tick(ANIMATION + 125.0));
2920 let before = host.state.borrow().live.spin;
2921 assert!((before.0 - PI / 4.0).abs() < 1e-5, "{before:?}");
2922
2923 refreshing(&host, false);
2926 assert_eq!(
2927 host.state
2928 .borrow()
2929 .spinner(Points(300.0), true)
2930 .map(|s| s.1),
2931 Some(Percentage(1.0))
2932 );
2933 assert_eq!(
2934 host.state
2935 .borrow()
2936 .spinner(Points(300.0), false)
2937 .map(|s| s.1),
2938 Some(Percentage(1.0))
2939 );
2940 assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
2941
2942 assert!(host.tick(ANIMATION + 125.0 + 150.0));
2946 let mid_y = host.state.borrow().y.0;
2947 assert!(mid_y < 0.0 && mid_y > -56.0, "{mid_y}");
2948 assert_eq!(
2949 host.state
2950 .borrow()
2951 .spinner(Points(300.0), true)
2952 .map(|s| s.1),
2953 Some(Percentage(1.0))
2954 );
2955 let mid_opacity = host.state.borrow().spinner_opacity();
2956 assert!(
2957 (mid_opacity - (-mid_y / 56.0)).abs() < 1e-5 && mid_opacity > 0.0 && mid_opacity < 1.0,
2958 "{mid_opacity}"
2959 );
2960 let mid_spin = host.state.borrow().live.spin;
2961 assert!(
2962 mid_spin.0 > before.0 && (mid_spin.0 - spin_angle(275.0).0).abs() < 1e-5,
2963 "before={before:?} mid={mid_spin:?}"
2964 );
2965
2966 host.tick(ANIMATION + 125.0 + ANIMATION);
2969 assert_eq!(host.state.borrow().y, Points(0.0));
2970 assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
2971 assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
2972 assert!(!host.tick(ANIMATION + 125.0 + ANIMATION + 16.0));
2973 host.state.borrow_mut().y = Points(-32.0);
2974 assert_eq!(
2975 host.state
2976 .borrow()
2977 .spinner(Points(300.0), true)
2978 .map(|s| s.1),
2979 Some(Percentage(0.5))
2980 );
2981 assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
2982
2983 let mut inset_state = scroll_state((300.0, 1000.0), false);
2987 inset_state.behavior.content_inset.top = Points(48.0);
2988 let host = TestHost::new(inset_state);
2989 refreshing(&host, true);
2990 assert!(host.tick(ANIMATION));
2991 assert_eq!(
2992 host.state
2993 .borrow()
2994 .spinner(Points(300.0), true)
2995 .map(|(c, p)| (c.y.0, p)),
2996 Some((76.0, Percentage(1.0)))
2997 );
2998 refreshing(&host, false);
2999 assert!(host.tick(ANIMATION + 250.0));
3000 let (center, progress) = host.state.borrow().spinner(Points(300.0), true).unwrap();
3001 let near_end_opacity = host.state.borrow().spinner_opacity();
3002 assert!(center.y.0 > 20.0, "center stays in viewport: {center:?}");
3003 assert_eq!(progress, Percentage(1.0));
3004 assert!(
3005 near_end_opacity > 0.0 && near_end_opacity < 0.1,
3006 "{near_end_opacity}"
3007 );
3008 host.tick(ANIMATION + ANIMATION);
3009 assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3010
3011 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3014 refreshing(&host, true);
3015 assert!(host.tick(ANIMATION));
3016 refreshing(&host, false);
3017 wheel(&host, pt(0.0, 10.0));
3018 assert_eq!(host.state.borrow().y, Points(-46.0));
3019 let settled_wheel = ANIMATION + WHEEL_IDLE + 1.0;
3020 assert!(host.tick(settled_wheel));
3021 assert!(matches!(
3022 host.state.borrow().live.phase,
3023 Phase::Animate { to, .. } if to.y == 0.0
3024 ));
3025 assert!(host.tick(settled_wheel + 150.0));
3026 let bounce_y = host.state.borrow().y.0;
3027 assert!(bounce_y < 0.0 && bounce_y > -46.0, "{bounce_y}");
3028 host.tick(settled_wheel + ANIMATION);
3029 assert_eq!(host.state.borrow().y, Points(0.0));
3030 assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3031 assert!(!host.tick(10_000.0));
3032
3033 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3036 refreshing(&host, true);
3037 assert!(host.tick(ANIMATION));
3038 refreshing(&host, false);
3039 wheel(&host, pt(0.0, 55.7));
3040 assert!((host.state.borrow().y.0 - -0.3).abs() < 1e-4);
3041 assert!(!host.tick(ANIMATION + WHEEL_IDLE + 1.0));
3042 assert_eq!(host.state.borrow().y, Points(0.0));
3043 assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3044
3045 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3047 refreshing(&host, true);
3048 assert!(host.tick(ANIMATION));
3049 refreshing(&host, false);
3050 drag_begin(&host);
3051 assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
3052 assert_eq!(
3053 host.state
3054 .borrow()
3055 .spinner(Points(300.0), true)
3056 .map(|s| s.1),
3057 Some(Percentage(56.0 / 64.0))
3058 );
3059 drag_end(&host, 0.0, 0.0);
3060 host.tick(ANIMATION + ANIMATION);
3061 assert_eq!(host.state.borrow().y, Points(0.0));
3062
3063 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3064 refreshing(&host, true);
3065 assert!(host.tick(ANIMATION));
3066 refreshing(&host, false);
3067 detached(&host);
3068 assert!(!host.state.borrow().live.dismissing);
3069
3070 let mut s = scroll_state((300.0, 1000.0), false);
3073 s.y = Points(-56.0);
3074 s.live.refreshing = true;
3075 let host = TestHost::new(s);
3076 let base = 10_000_000_000.0;
3077 for step in 0..8 {
3078 assert!(host.tick(base + step as f64 * 125.0));
3079 let spin = host.state.borrow().live.spin;
3080 let brightest = spokes(Percentage(1.0), spin)
3081 .enumerate()
3082 .max_by(|a, b| a.1.1.total_cmp(&b.1.1))
3083 .map(|(i, _)| i);
3084 assert_eq!(brightest, Some(step));
3085 }
3086 }
3087
3088 struct TestHost {
3091 state: std::cell::RefCell<ScrollState>,
3092 clock: std::cell::Cell<f64>,
3093 redraws: std::cell::Cell<u32>,
3094 reports: std::cell::RefCell<Vec<String>>,
3096 key_moves: std::cell::RefCell<Vec<KeyMove>>,
3098 }
3099
3100 impl TestHost {
3101 fn new(state: ScrollState) -> Self {
3102 Self {
3103 state: std::cell::RefCell::new(state),
3104 clock: std::cell::Cell::new(0.0),
3105 redraws: std::cell::Cell::new(0),
3106 reports: Default::default(),
3107 key_moves: Default::default(),
3108 }
3109 }
3110
3111 fn tick(&self, now: f64) -> bool {
3112 self.clock.set(now);
3113 frame(self, now)
3114 }
3115 }
3116
3117 impl ScrollHost for TestHost {
3118 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R> {
3119 Some(f(&self.state.borrow(), sz(300.0, 500.0)))
3120 }
3121 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R> {
3122 Some(f(&mut self.state.borrow_mut(), sz(300.0, 500.0)))
3123 }
3124 fn now(&self) -> f64 {
3125 self.clock.get()
3126 }
3127 fn listens(&self, _: EventKind) -> bool {
3128 true
3129 }
3130 fn event(&self, _: EventKind, _: EventPayload) {}
3131 fn report(&self, offset: Point<Points>, _: u32) {
3132 let line = format!("scroll {} {}", offset.x.0, offset.y.0);
3133 self.reports.borrow_mut().push(line);
3134 }
3135 fn report_zoom(&self, scale: f32) {
3136 self.reports.borrow_mut().push(format!("zoom {scale}"));
3137 }
3138 fn key_scrolled(&self, key_move: KeyMove) {
3139 self.key_moves.borrow_mut().push(key_move);
3140 }
3141 fn moved(&self, _: Point<Points>) {}
3142 fn pulled(&self, _: Points) {}
3143 fn relayout(&self) {}
3144 fn redraw(&self) {
3145 self.redraws.set(self.redraws.get() + 1);
3146 }
3147 fn attached(&self) -> bool {
3148 true
3149 }
3150 fn start_ticking(&self) {}
3151 }
3152
3153 #[test]
3154 fn a_key_scroll_tells_the_host_every_key_move() {
3155 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
3156 key_scroll(&host, KeyMove::End, false);
3157 key_scroll(&host, KeyMove::Pages(-1.0), false);
3158 assert_eq!(
3159 *host.key_moves.borrow(),
3160 [KeyMove::End, KeyMove::Pages(-1.0)]
3161 );
3162 assert!(matches!(
3163 host.state.borrow().live.phase,
3164 Phase::Animate { .. }
3165 ));
3166
3167 let mut row = scroll_state((100_000.0, 500.0), true);
3170 row.mirrored = true;
3171 row.x = Points(1000.0);
3172 let host = TestHost::new(row);
3173 key_scroll(&host, KeyMove::Points(KEY_LINE), true);
3174 assert_eq!(host.state.borrow().goal(), 1000.0 - KEY_LINE.0);
3175 assert_eq!(*host.key_moves.borrow(), [KeyMove::Points(KEY_LINE)]);
3176 }
3177
3178 #[test]
3179 fn wheel_notches_glide_and_add_up_where_the_scroll_is_headed() {
3180 let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
3181 let notch = |dy: f32| wheel_step(&host, pt(0.0, dy));
3182 notch(48.0);
3183 assert_eq!(host.state.borrow().y.0, 0.0);
3185 assert_eq!(host.state.borrow().goal(), 48.0);
3186 notch(48.0);
3188 assert_eq!(host.state.borrow().goal(), 96.0);
3189 frame(&host, WHEEL_STEP_ANIMATION);
3190 assert_eq!(host.state.borrow().y.0, 96.0);
3191 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3192 notch(-1000.0);
3194 assert_eq!(host.state.borrow().goal(), 0.0);
3195 frame(&host, WHEEL_STEP_ANIMATION);
3196 notch(-48.0);
3197 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3198
3199 let mut paging = scroll_state((300.0, 10_000.0), false);
3202 paging.behavior.paging = true;
3203 let host = TestHost::new(paging);
3204 wheel_step(&host, pt(0.0, 48.0));
3205 assert_eq!(host.state.borrow().y.0, 48.0);
3206 assert!(matches!(
3207 host.state.borrow().live.phase,
3208 Phase::Wheel { gesture: false, .. }
3209 ));
3210 }
3211
3212 #[test]
3213 fn smooth_wheel_notches_glide_on_chromiums_curve() {
3214 let mut smooth = scroll_state((300.0, 10_000.0), false);
3215 smooth.behavior.smooth_wheel = true;
3216 let host = TestHost::new(smooth);
3217 assert!(smooth_wheel(&host));
3218 wheel_smooth(&host, pt(0.0, 40.0));
3219 assert_eq!(host.state.borrow().y.0, 0.0);
3221 frame(&host, 60.0);
3222 let y = host.state.borrow().y.0;
3223 assert!(y > 0.0 && y < 40.0, "{y}");
3224 wheel_smooth(&host, pt(0.0, 40.0));
3226 assert!(matches!(
3227 host.state.borrow().live.phase,
3228 Phase::Wheel { gesture: false, raw, .. } if raw.y == 80.0
3229 ));
3230 let mut now = 60.0;
3232 while let Some(next) = deadline(&host, now) {
3233 now = next;
3234 frame(&host, now);
3235 }
3236 assert_eq!(host.state.borrow().y.0, 80.0);
3237 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3238
3239 let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
3242 assert!(!smooth_wheel(&host));
3243 let mut paging = scroll_state((300.0, 10_000.0), false);
3244 paging.behavior.smooth_wheel = true;
3245 paging.behavior.paging = true;
3246 assert!(!smooth_wheel(&TestHost::new(paging)));
3247 }
3248
3249 #[test]
3250 fn wheel_line_height_rescales_a_notch() {
3251 let mut lines = scroll_state((300.0, 10_000.0), false);
3252 let host = TestHost::new(lines.clone());
3253 assert_eq!(
3255 wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
3256 pt(0.0, 30.0)
3257 );
3258 lines.behavior.wheel_line_height = Points(40.0);
3259 let host = TestHost::new(lines);
3260 assert_eq!(
3262 wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
3263 pt(0.0, 120.0)
3264 );
3265 assert_eq!(
3267 wheel_line(&host, pt(25.0, 30.0), pt(25.0, 15.0)),
3268 pt(40.0, 80.0)
3269 );
3270 }
3271
3272 #[test]
3273 fn a_settled_touchpad_scroll_snaps_to_the_nearest_page() {
3274 let paged = || {
3276 let mut s = scroll_state((300.0, 5000.0), false);
3277 s.behavior.paging = true;
3278 s.y = Points(500.0);
3279 let host = TestHost::new(s);
3280 wheel_begin(&host);
3281 wheel(&host, pt(0.0, -60.0));
3283 host
3284 };
3285 let settle = |host: &TestHost| {
3286 let mut now = 0.0;
3287 while let Some(next) = deadline(host, now) {
3288 now = next;
3289 frame(host, now);
3290 }
3291 host.state.borrow().y.0
3292 };
3293 let host = paged();
3295 wheel_settle(&host);
3296 assert_eq!(settle(&host), 500.0);
3297 let host = paged();
3299 wheel_end(&host, 0.0, 0.0);
3300 assert_eq!(settle(&host), 0.0);
3301 }
3302
3303 #[test]
3304 fn a_glide_and_an_eased_move_end_at_their_deadlines() {
3305 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
3306 assert_eq!(deadline(&host, 0.0), None);
3307 for phase in [
3308 Phase::Glide {
3309 velocity: Offset::new(0.0, 2.0),
3310 last: 0.0,
3311 },
3312 Phase::Animate {
3313 from: Offset::default(),
3314 to: Offset::new(0.0, 400.0),
3315 start: 0.0,
3316 duration: ANIMATION,
3317 momentum: false,
3318 end: true,
3319 },
3320 ] {
3321 host.state.borrow_mut().y = Points(0.0);
3322 host.state.borrow_mut().live.phase = phase;
3323 let mut now = 0.0;
3324 let mut frames = 0;
3325 while let Some(next) = deadline(&host, now) {
3326 now = next;
3327 frame(&host, now);
3328 frames += 1;
3329 assert!(frames < 5, "{:?}", host.state.borrow().live.phase);
3330 }
3331 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3332 let y = host.state.borrow().y.0;
3333 match phase {
3334 Phase::Glide { .. } => assert!(
3336 (y - projected(Points(0.0), 2.0, 0.998).0).abs() < 6.0,
3337 "{y}"
3338 ),
3339 _ => assert_eq!(y, 400.0),
3340 }
3341 }
3342 }
3343
3344 #[test]
3345 fn indicator_follows_the_view_on_either_axis() {
3346 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3347 for horizontal in [false, true] {
3348 config(&host, horizontal, true, false, false);
3349 assert!(host.state.borrow().indicator);
3350 config(&host, horizontal, false, false, false);
3352 assert!(!host.state.borrow().indicator);
3353 config(&host, horizontal, true, true, false);
3355 assert!(!host.state.borrow().indicator);
3356 }
3357 }
3358
3359 #[test]
3360 fn switching_indicators_while_refreshing_keeps_the_new_room() {
3361 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3362 let own = ScrollBehavior {
3363 refresh_indicator: Some(Points(72.0)),
3364 ..Default::default()
3365 };
3366 behavior(&host, &own);
3367 refreshing(&host, true);
3368 frame(&host, 1000.0);
3369 assert_eq!(host.state.borrow().y, Points(-72.0));
3370 let redraws = host.redraws.get();
3372 behavior(&host, &ScrollBehavior::default());
3373 assert!(host.redraws.get() > redraws);
3374 frame(&host, 1000.0);
3375 assert_eq!(host.state.borrow().y, Points(-56.0));
3376 behavior(&host, &ScrollBehavior::default());
3378 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3379 }
3380
3381 fn zooming(content: (f32, f32)) -> TestHost {
3384 let mut s = scroll_state(content, false);
3385 s.can_zoom = true;
3386 s.behavior.min_zoom = 0.5;
3387 s.behavior.max_zoom = 4.0;
3388 TestHost::new(s)
3389 }
3390
3391 fn zoom_and_offset(host: &TestHost) -> (f32, f32, f32) {
3392 let s = host.state.borrow();
3393 (s.zoom, s.x.0, s.y.0)
3394 }
3395
3396 fn zoom_to(scale: f32, center: Option<Point<Points>>, animated: bool) -> Command {
3397 Command::ZoomTo {
3398 scale,
3399 center,
3400 animated,
3401 }
3402 }
3403
3404 #[test]
3405 fn only_a_backend_that_draws_zoomed_content_zooms() {
3406 let host = zooming((300.0, 500.0));
3407 host.state.borrow_mut().can_zoom = false;
3408 command(&host, &zoom_to(2.0, None, false));
3409 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3410 assert!(host.reports.borrow().is_empty());
3411 host.state.borrow_mut().can_zoom = true;
3413 command(&host, &zoom_to(2.0, None, false));
3414 assert_eq!(zoom_and_offset(&host), (2.0, 150.0, 250.0));
3415 assert_eq!(*host.reports.borrow(), ["zoom 2", "scroll 150 250"]);
3416 }
3417
3418 #[test]
3419 fn a_pinch_keeps_the_content_under_the_pointer_and_springs_back() {
3420 let host = zooming((300.0, 500.0));
3421 let size = sz(300.0, 500.0);
3422 let at = pt(100.0, 120.0);
3423 pinch_begin(&host);
3424 pinch(&host, 2.0, at);
3425 assert_eq!(zoom_and_offset(&host), (2.0, 100.0, 120.0));
3426 {
3427 let s = host.state.borrow();
3428 assert_eq!(s.to_viewport(size, at), at);
3429 assert_eq!(s.to_content(size, at), at);
3430 }
3431 pinch(&host, 6.0, at);
3433 let banded = host.state.borrow().zoom;
3434 assert!(banded > 4.0 && banded < 6.0, "{banded}");
3435 pinch_end(&host, at);
3436 frame(&host, ANIMATION);
3437 assert_eq!(zoom_and_offset(&host), (4.0, 300.0, 360.0));
3439 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3440 }
3441
3442 #[test]
3443 fn zoomed_content_pans_both_ways_without_a_bar() {
3444 let host = zooming((300.0, 500.0));
3445 host.state.borrow_mut().indicator = true;
3446 let size = sz(300.0, 500.0);
3447 assert!(!host.state.borrow().can_scroll(size, pt(10.0, 10.0)));
3448 command(&host, &zoom_to(2.0, Some(pt(0.0, 0.0)), false));
3449 assert_eq!(zoom_and_offset(&host), (2.0, 0.0, 0.0));
3451 let s = host.state.borrow().clone();
3452 assert!(s.can_scroll(size, pt(10.0, 0.0)) && s.can_scroll(size, pt(0.0, 10.0)));
3453 assert!(!s.can_scroll(size, pt(-10.0, -10.0)));
3454 assert!(s.thumb(size).is_none());
3455 wheel(&host, pt(30.0, 40.0));
3456 assert_eq!(zoom_and_offset(&host), (2.0, 30.0, 40.0));
3457 wheel(&host, pt(1000.0, 1000.0));
3459 assert_eq!(zoom_and_offset(&host), (2.0, 300.0, 500.0));
3460 wheel_begin(&host);
3462 wheel(&host, pt(-10.0, -10.0));
3463 wheel_end(&host, -1000.0, -500.0);
3464 let mut now = 0.0;
3465 while let Some(next) = deadline(&host, now) {
3466 now = next;
3467 frame(&host, now);
3468 }
3469 let (_, x, y) = zoom_and_offset(&host);
3470 assert!(x < 280.0 && y < 480.0 && x < y, "{x} {y}");
3471 }
3472
3473 #[test]
3474 fn zoom_to_eases_to_the_point_it_centers() {
3475 let host = zooming((300.0, 500.0));
3476 command(&host, &zoom_to(2.0, Some(pt(100.0, 200.0)), true));
3477 assert!(matches!(host.state.borrow().live.phase, Phase::Zoom { .. }));
3478 assert_eq!(deadline(&host, 0.0), Some(ANIMATION + 1.0));
3479 frame(&host, ANIMATION / 2.0);
3480 let half = host.state.borrow().zoom;
3481 assert!(half > 1.0 && half < 2.0, "{half}");
3482 frame(&host, ANIMATION);
3483 assert_eq!(zoom_and_offset(&host), (2.0, 50.0, 150.0));
3485 command(&host, &zoom_to(10.0, None, false));
3487 assert_eq!(host.state.borrow().zoom, 4.0);
3488 }
3489
3490 #[test]
3491 fn small_content_is_centered() {
3492 let host = zooming((300.0, 500.0));
3493 host.state.borrow_mut().behavior.center_content = true;
3494 command(&host, &zoom_to(0.5, None, false));
3495 let s = host.state.borrow();
3496 let size = sz(300.0, 500.0);
3497 assert_eq!(s.centered(size), pt(75.0, 125.0));
3498 assert_eq!(s.to_viewport(size, pt(0.0, 0.0)), pt(75.0, 125.0));
3499 assert_eq!(s.to_content(size, pt(75.0, 125.0)), pt(0.0, 0.0));
3500 assert_eq!((s.x.0, s.y.0), (0.0, 0.0));
3501 }
3502
3503 #[test]
3504 fn new_limits_clamp_the_zoom_and_a_view_that_zooms_no_more_is_back_at_1() {
3505 let host = zooming((300.0, 500.0));
3506 command(&host, &zoom_to(3.0, None, false));
3507 let mut b = host.state.borrow().behavior.clone();
3508 b.max_zoom = 2.0;
3509 behavior(&host, &b);
3510 assert_eq!(host.state.borrow().zoom, 2.0);
3511 b.max_zoom = 0.5;
3512 behavior(&host, &b);
3513 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3514 frame(&host, 0.0);
3515 let reports = host.reports.borrow();
3516 assert_eq!(reports[reports.len() - 2..], ["zoom 1", "scroll 0 0"]);
3517 }
3518}