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 pub spin: Radians,
208 pub dark: bool,
211 pinch_from: f32,
213 reported_zoom: f32,
215 rezoomed: bool,
217}
218
219#[derive(Debug, Clone)]
221#[non_exhaustive]
222pub struct ScrollState {
223 pub x: Points,
226 pub y: Points,
228 pub content: Size<Points>,
230 pub zoom: f32,
232 pub can_zoom: bool,
235 pub horizontal: bool,
237 pub indicator: bool,
239 pub behavior: ScrollBehavior,
241 pub applied: u32,
244 pub sticky: Vec<StickyCell>,
246 pub mirrored: bool,
249 pub live: Live,
251}
252
253impl Default for ScrollState {
254 fn default() -> Self {
255 Self {
256 x: Points::ZERO,
257 y: Points::ZERO,
258 content: Size::default(),
259 zoom: 1.0,
260 can_zoom: false,
261 horizontal: false,
262 indicator: false,
263 behavior: ScrollBehavior::default(),
264 applied: 0,
265 sticky: Vec::new(),
266 mirrored: false,
267 live: Live::default(),
268 }
269 }
270}
271
272pub trait ScrollHost {
275 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R>;
278 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R>;
280 fn now(&self) -> f64;
282 fn listens(&self, kind: EventKind) -> bool;
284 fn event(&self, kind: EventKind, payload: EventPayload);
286 fn report(&self, offset: Point<Points>, applied: u32);
289 fn report_zoom(&self, scale: f32) {
292 let _ = scale;
293 }
294 fn key_scrolled(&self, key_move: KeyMove) {
298 let _ = key_move;
299 }
300 fn moved(&self, offset: Point<Points>);
304 fn pulled(&self, distance: Points);
307 fn relayout(&self);
309 fn redraw(&self);
311 fn attached(&self) -> bool;
313 fn start_ticking(&self);
315 fn settled(&self) {}
319 fn dark(&self) -> bool {
322 false
323 }
324}
325
326fn rubber(over: f32, dim: f32) -> f32 {
331 let dim = dim.max(1.0);
332 (1.0 - 1.0 / (over * 0.55 / dim + 1.0)) * dim
333}
334
335pub fn dragged(raw: Points, min: Points, max: Points, dim: Points, bounces: bool) -> Points {
338 Points(drag_position(raw.0, min.0, max.0, dim.0, bounces))
339}
340
341fn drag_position(raw: f32, min: f32, max: f32, dim: f32, bounces: bool) -> f32 {
342 if raw < min {
343 if bounces {
344 min - rubber(min - raw, dim)
345 } else {
346 min
347 }
348 } else if raw > max {
349 if bounces {
350 max + rubber(raw - max, dim)
351 } else {
352 max
353 }
354 } else {
355 raw
356 }
357}
358
359pub fn rate(behavior: &ScrollBehavior) -> f32 {
361 if behavior.deceleration > 0.0 && behavior.deceleration < 1.0 {
362 behavior.deceleration
363 } else if behavior.snaps() || behavior.paging {
364 0.99
365 } else {
366 0.998
367 }
368}
369
370fn glide_step(v: f32, rate: f32, dt: f32) -> (f32, f32) {
373 let k = rate.powf(dt);
374 (v * (k - 1.0) / rate.ln(), v * k)
375}
376
377pub fn projected(offset: Points, velocity: f32, rate: f32) -> Points {
380 Points(offset.0 - velocity / rate.ln())
381}
382
383pub fn sticky_shift(offset: Points, start: Points, end: Points) -> Points {
386 Points((offset.0 - start.0).clamp(0.0, (end.0 - start.0).max(0.0)))
387}
388
389pub fn ease_out(t: f64) -> f32 {
391 let t = t.clamp(0.0, 1.0);
392 (1.0 - (1.0 - t).powi(3)) as f32
393}
394
395pub fn snap_duration(distance: Points, velocity: f32) -> f64 {
399 let (distance, v) = (distance.0, velocity);
400 if distance.abs() < 0.5 {
401 return 0.0;
402 }
403 if v * distance > 0.0 {
404 (3.0 * distance.abs() / v.abs()).clamp(180.0, 600.0) as f64
405 } else {
406 ANIMATION
407 }
408}
409
410pub fn indicator_alpha(since: f64) -> f32 {
412 if since < INDICATOR_HOLD {
413 1.0
414 } else {
415 (1.0 - (since - INDICATOR_HOLD) / INDICATOR_FADE).max(0.0) as f32
416 }
417}
418
419pub fn indicator_span(viewport: Points, total: Points, offset: Points) -> Option<(Points, Points)> {
423 indicator_span_within(viewport, total, offset, Points::ZERO, Points::ZERO)
424}
425
426pub fn indicator_span_within(
432 viewport: Points,
433 total: Points,
434 offset: Points,
435 before: Points,
436 after: Points,
437) -> Option<(Points, Points)> {
438 span(viewport.0, total.0, offset.0, before.0, after.0)
439 .map(|(start, len)| (Points(start), Points(len)))
440}
441
442fn span(viewport: f32, total: f32, offset: f32, before: f32, after: f32) -> Option<(f32, f32)> {
443 const MIN_LENGTH: f32 = 32.0;
445 let (before, after) = (before.max(0.0), after.max(0.0));
446 let room = viewport - before - after;
447 if total <= viewport + 0.5 || room <= 4.0 * INDICATOR_MARGIN {
448 return None;
449 }
450 let track = room - 2.0 * INDICATOR_MARGIN;
451 let max = total - viewport;
452 let over = if offset < 0.0 {
454 -offset
455 } else {
456 (offset - max).max(0.0)
457 };
458 let len = (track * viewport / total - over).max(MIN_LENGTH).min(track);
459 let t = (offset / max).clamp(0.0, 1.0);
460 Some((before + INDICATOR_MARGIN + (track - len) * t, len))
461}
462
463pub fn thumb_scroll(d: Points, range: Points, travel: Points) -> Points {
466 if travel.0 > 0.0 {
467 Points(d.0 * range.0 / travel.0)
468 } else {
469 Points(0.0)
470 }
471}
472
473fn shifted(phase: Phase, d: Offset, horizontal: bool) -> Phase {
477 match phase {
478 Phase::Drag { start, moved } => Phase::Drag {
479 start: start + d,
480 moved,
481 },
482 Phase::Thumb { start } => Phase::Thumb {
483 start: start + d.along(horizontal),
484 },
485 Phase::Animate {
486 from,
487 to,
488 start,
489 duration,
490 momentum,
491 end,
492 } => Phase::Animate {
493 from: from + d,
494 to: to + d,
495 start,
496 duration,
497 momentum,
498 end,
499 },
500 Phase::Wheel {
501 last,
502 total,
503 gesture,
504 raw,
505 glide,
506 } => Phase::Wheel {
507 last,
508 total,
509 gesture,
510 raw: raw + d,
511 glide: glide.shifted(d.into()),
512 },
513 other => other,
514 }
515}
516
517pub fn spokes(progress: Percentage, spin: Radians) -> impl Iterator<Item = (Radians, f32)> {
522 const SPOKES: usize = 8;
523 let (progress, spin) = (progress.0, spin.0);
524 let shown = ((progress * SPOKES as f32).ceil() as usize).min(SPOKES);
525 let step = 2.0 * PI / SPOKES as f32;
526 let lead = (spin / step) as usize % SPOKES;
527 (0..shown).map(move |i| {
528 let fade = if progress < 1.0 {
529 0.8
530 } else {
531 1.0 - ((lead + SPOKES - i) % SPOKES) as f32 / SPOKES as f32 * 0.85
532 };
533 (Radians(i as f32 * step), fade)
534 })
535}
536
537pub fn reading_order<T>(axis: Axis, children: &mut [T], origin: impl Fn(&T) -> Point<Points>) {
546 if children.len() < 2 {
547 return;
548 }
549 let key = |child: &T| {
550 let at = origin(child);
551 match axis {
552 Axis::Horizontal => (at.x.0, at.y.0),
553 Axis::Vertical => (at.y.0, at.x.0),
554 }
555 };
556 children.sort_by(|a, b| {
557 let (a, b) = (key(a), key(b));
558 a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
559 });
560}
561
562impl ScrollState {
565 pub fn max(&self, size: Size<Points>) -> Point<Points> {
567 let (x, y) = self.max_f(size);
568 point(Points(x), Points(y))
569 }
570
571 fn max_f(&self, size: Size<Points>) -> (f32, f32) {
572 let inset = self.behavior.content_inset;
573 let z = self.zoom;
574 (
575 (self.content.width.0 * z + inset.left.0 + inset.right.0 - size.width.0).max(0.0),
576 (self.content.height.0 * z + inset.top.0 + inset.bottom.0 - size.height.0).max(0.0),
577 )
578 }
579
580 pub fn origin(&self) -> Point<Points> {
584 let inset = self.behavior.content_inset;
585 point(self.x - inset.left, self.y - inset.top)
586 }
587
588 pub fn zooms(&self) -> bool {
592 self.can_zoom && self.behavior.zooms()
593 }
594
595 pub fn centered(&self, size: Size<Points>) -> Point<Points> {
599 if !self.zooms() || !self.behavior.center_content {
600 return Point::default();
601 }
602 let inset = self.behavior.content_inset;
603 let free = |viewport: f32, content: f32| ((viewport - content * self.zoom) / 2.0).max(0.0);
604 point(
605 Points(free(
606 size.width.0 - inset.left.0 - inset.right.0,
607 self.content.width.0,
608 )),
609 Points(free(
610 size.height.0 - inset.top.0 - inset.bottom.0,
611 self.content.height.0,
612 )),
613 )
614 }
615
616 pub fn to_viewport(&self, size: Size<Points>, content: Point<Points>) -> Point<Points> {
619 let (o, room) = (self.origin(), self.centered(size));
620 point(
621 Points(content.x.0 * self.zoom - o.x.0 + room.x.0),
622 Points(content.y.0 * self.zoom - o.y.0 + room.y.0),
623 )
624 }
625
626 pub fn to_content(&self, size: Size<Points>, at: Point<Points>) -> Point<Points> {
629 let (o, room) = (self.origin(), self.centered(size));
630 point(
631 Points((at.x.0 + o.x.0 - room.x.0) / self.zoom),
632 Points((at.y.0 + o.y.0 - room.y.0) / self.zoom),
633 )
634 }
635
636 fn offset(&self) -> f32 {
638 if self.horizontal { self.x.0 } else { self.y.0 }
639 }
640
641 fn pos(&self) -> Offset {
643 Offset::new(self.x.0, self.y.0)
644 }
645
646 fn range(&self, size: Size<Points>) -> (Offset, Offset) {
650 let (min, max) = self.limits(size);
651 if self.zooms() {
652 let (mx, my) = self.max_f(size);
653 let top = if self.horizontal { 0.0 } else { min };
655 (Offset::new(0.0, top), Offset::new(mx, my))
656 } else {
657 let zero = Offset::default();
658 (
659 zero.with(self.horizontal, min),
660 zero.with(self.horizontal, max),
661 )
662 }
663 }
664
665 fn content_at(&self, size: Size<Points>, at: Offset) -> Offset {
667 let c = self.to_content(size, point(Points(at.x), Points(at.y)));
668 Offset::new(c.x.0, c.y.0)
669 }
670
671 fn showing(&self, size: Size<Points>, c: Offset, at: Offset) -> Offset {
674 let inset = self.behavior.content_inset;
675 let room = self.centered(size);
676 Offset::new(
677 c.x * self.zoom + room.x.0 - at.x + inset.left.0,
678 c.y * self.zoom + room.y.0 - at.y + inset.top.0,
679 )
680 .clamp(self.range(size))
681 }
682
683 fn goal(&self) -> f32 {
686 match self.live.phase {
687 Phase::Animate { to, .. } => to.along(self.horizontal),
688 _ => self.offset(),
689 }
690 }
691
692 fn viewport(&self, size: Size<Points>) -> f32 {
694 if self.horizontal {
695 size.width.0
696 } else {
697 size.height.0
698 }
699 }
700
701 fn lead(&self) -> f32 {
703 if self.horizontal {
704 self.behavior.content_inset.left.0
705 } else {
706 self.behavior.content_inset.top.0
707 }
708 }
709
710 fn limits(&self, size: Size<Points>) -> (f32, f32) {
713 let max = self.max_f(size);
714 let min = if !self.horizontal && self.live.refreshing {
715 -self.behavior.refresh_inset().0
716 } else {
717 0.0
718 };
719 (min, if self.horizontal { max.0 } else { max.1 })
720 }
721
722 pub fn reported(&self, size: Size<Points>) -> Point<Points> {
725 let (mx, my) = self.max_f(size);
726 let inset = self.behavior.content_inset;
727 point(
728 Points(self.x.0.clamp(0.0, mx) - inset.left.0),
729 Points(self.y.0.clamp(0.0, my) - inset.top.0),
730 )
731 }
732
733 pub fn can_scroll(&self, size: Size<Points>, delta: Point<Points>) -> bool {
738 let (dx, dy) = (delta.x.0, delta.y.0);
739 if !self.behavior.enabled {
740 return false;
741 }
742 if self.zooms() {
743 let ((min, max), p) = (self.range(size), self.pos());
744 let can = |d: f32, p: f32, min: f32, max: f32| {
745 (d > 0.0 && p < max - 0.5) || (d < 0.0 && p > min + 0.5)
746 };
747 return can(dx, p.x, min.x, max.x) || can(dy, p.y, min.y, max.y);
748 }
749 let (min, max) = self.limits(size);
750 if max <= min {
751 return false;
752 }
753 let d = if self.horizontal {
754 let d = if dx != 0.0 { dx } else { dy };
755 if self.mirrored && dx != 0.0 { -d } else { d }
756 } else {
757 dy
758 };
759 let pos = self.offset();
760 (d > 0.0 && pos < max - 0.5) || (d < 0.0 && pos > min + 0.5)
761 }
762
763 pub fn thumb(&self, size: Size<Points>) -> Option<(Bounds<Points>, Points)> {
766 self.thumb_within(
767 size,
768 Bounds {
769 origin: Point::default(),
770 size,
771 },
772 )
773 }
774
775 pub fn thumb_within(
782 &self,
783 size: Size<Points>,
784 visible: Bounds<Points>,
785 ) -> Option<(Bounds<Points>, Points)> {
786 let (rect, travel) = self.thumb_f(size, visible)?;
787 Some((rect, Points(travel)))
788 }
789
790 fn visible_edges(size: Size<Points>, visible: Bounds<Points>) -> Option<(f32, f32)> {
793 let (w, h) = (size.width.0, size.height.0);
794 let left = visible.origin.x.0.max(0.0);
795 let top = visible.origin.y.0.max(0.0);
796 let right = (visible.origin.x.0 + visible.size.width.0).min(w);
797 let bottom = (visible.origin.y.0 + visible.size.height.0).min(h);
798 (right > left && bottom > top).then_some((right, bottom))
799 }
800
801 fn thumb_f(
802 &self,
803 size: Size<Points>,
804 visible: Bounds<Points>,
805 ) -> Option<(Bounds<Points>, f32)> {
806 const EDGE: f32 = 2.0;
807 if self.zooms() {
809 return None;
810 }
811 let thick = INDICATOR_THICK.0;
812 let (w, h) = (size.width.0, size.height.0);
813 let (right, bottom) = Self::visible_edges(size, visible)?;
814 let inset = self.behavior.content_inset;
815 let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
816 let (dim, total, offset, before, after) = if self.horizontal {
819 let (before, after) = if self.mirrored {
820 (bar.right, bar.left)
821 } else {
822 (bar.left, bar.right)
823 };
824 (
825 w,
826 self.content.width.0 + inset.left.0 + inset.right.0,
827 self.x.0,
828 before,
829 after,
830 )
831 } else {
832 (
833 h,
834 self.content.height.0 + inset.top.0 + inset.bottom.0,
835 self.y.0,
836 bar.top,
837 bar.bottom,
838 )
839 };
840 let (start, len) = span(dim, total, offset, before, after)?;
841 let (x, y, rw, rh) = if self.horizontal {
842 let x = if self.mirrored {
843 w - start - len
844 } else {
845 start
846 };
847 (x, bottom - bar.bottom - thick - EDGE, len, thick)
848 } else {
849 (right - bar.right - thick - EDGE, start, thick, len)
850 };
851 let rect = Bounds {
852 origin: point(Points(x), Points(y)),
853 size: Size {
854 width: Points(rw),
855 height: Points(rh),
856 },
857 };
858 Some((rect, dim - before - after - 2.0 * INDICATOR_MARGIN - len))
859 }
860
861 pub fn grabs_thumb(&self, size: Size<Points>, at: Point<Points>) -> bool {
865 self.grabs_thumb_within(
866 size,
867 Bounds {
868 origin: Point::default(),
869 size,
870 },
871 at,
872 )
873 }
874
875 pub fn grabs_thumb_within(
879 &self,
880 size: Size<Points>,
881 visible: Bounds<Points>,
882 at: Point<Points>,
883 ) -> bool {
884 let (x, y) = (at.x.0, at.y.0);
885 if !self.indicator || !self.behavior.enabled {
886 return false;
887 }
888 let Some((rect, _)) = self.thumb_f(size, visible) else {
889 return false;
890 };
891 let Some((right, bottom)) = Self::visible_edges(size, visible) else {
892 return false;
893 };
894 let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
896 let (along, across, start, len, edge) = if self.horizontal {
897 (
898 x,
899 y,
900 rect.origin.x.0,
901 rect.size.width.0,
902 bottom - bar.bottom,
903 )
904 } else {
905 (y, x, rect.origin.y.0, rect.size.height.0, right - bar.right)
906 };
907 (edge - THUMB_GRAB..=edge).contains(&across)
908 && (start - THUMB_SLOP..=start + len + THUMB_SLOP).contains(&along)
909 }
910
911 pub fn indicates(&self) -> bool {
914 (self.indicator && self.live.alpha > 0.0) || self.y.0 < 0.0
915 }
916
917 pub fn spinner(&self, width: Points, refresh: bool) -> Option<(Point<Points>, Percentage)> {
922 let y = self.y.0;
923 let b = &self.behavior;
924 if self.horizontal
925 || y >= 0.0
926 || b.refresh_indicator.is_some()
927 || !(self.live.refreshing || refresh)
928 {
929 return None;
930 }
931 let progress = if self.live.refreshing {
932 1.0
933 } else {
934 (-y / b.refresh_threshold().0).min(1.0)
935 };
936 let cy = b.content_inset.top.0 - y - b.refresh_inset().0 / 2.0;
937 Some((point(width / 2.0, Points(cy)), Percentage(progress)))
938 }
939
940 pub fn sticky_shifts(&self) -> impl Iterator<Item = (NodeId, Point<Points>)> + '_ {
942 self.sticky_shifts_with(|_| 0.0)
943 }
944
945 pub fn sticky_shifts_with<'a>(
948 &'a self,
949 value: impl Fn(crate::animation::NodeId) -> f32 + 'a,
950 ) -> impl Iterator<Item = (NodeId, Point<Points>)> + 'a {
951 let offset = Points(self.offset() - self.lead());
952 self.sticky.iter().map(move |c| {
953 let extra = c.offset.map_or(0.0, &value);
954 let t = sticky_shift(Points(offset.0 + extra), c.start, c.end);
955 let zero = Points(0.0);
956 (
957 c.cell,
958 if self.horizontal {
959 point(t, zero)
960 } else {
961 point(zero, t)
962 },
963 )
964 })
965 }
966}
967
968fn phase(host: &impl ScrollHost) -> Phase {
971 host.scroll(|s, _| s.live.phase).unwrap_or(Phase::Idle)
972}
973
974fn set_phase(host: &impl ScrollHost, phase: Phase) {
975 host.scroll_mut(|s, _| s.live.phase = phase);
976}
977
978fn enabled(host: &impl ScrollHost) -> bool {
980 host.scroll(|s, _| s.behavior.enabled).unwrap_or(false)
981}
982
983fn emit(host: &impl ScrollHost, kind: EventKind) {
985 if kind == EventKind::ScrollEnd {
986 host.settled();
987 }
988 if !host.listens(kind) {
989 return;
990 }
991 let offset = host.scroll(|s, size| s.reported(size)).unwrap_or_default();
992 host.event(kind, EventPayload::Scroll(offset));
993}
994
995fn interrupt(host: &impl ScrollHost) {
998 let momentum = matches!(
999 phase(host),
1000 Phase::Glide { .. } | Phase::Animate { momentum: true, .. }
1001 );
1002 set_phase(host, Phase::Idle);
1003 if momentum {
1004 emit(host, EventKind::MomentumEnd);
1005 }
1006}
1007
1008fn moved_to(host: &impl ScrollHost, to: Offset) {
1013 let moved = host.scroll_mut(|s, size| {
1014 let rezoomed = std::mem::take(&mut s.live.rezoomed);
1015 if s.pos() == to && !rezoomed {
1016 return None;
1017 }
1018 let pulled =
1020 (!s.horizontal && (s.y.0 < 0.0 || to.y < 0.0)).then(|| Points((-to.y).max(0.0)));
1021 (s.x, s.y) = (Points(to.x), Points(to.y));
1022 if s.indicator {
1023 s.live.shown = host.now();
1024 s.live.alpha = 1.0;
1025 s.live.dark = host.dark();
1026 }
1027 s.live.report = true;
1028 Some((s.reported(size), pulled))
1029 });
1030 let Some(Some((offset, pulled))) = moved else {
1031 return;
1032 };
1033 host.moved(offset);
1034 if let Some(distance) = pulled {
1035 host.pulled(distance);
1036 }
1037 if host.attached() {
1038 ensure_ticking(host);
1039 } else {
1040 report(host);
1042 }
1043}
1044
1045fn moved_along(host: &impl ScrollHost, pos: f32) {
1047 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, pos)) {
1048 moved_to(host, to);
1049 }
1050}
1051
1052fn report(host: &impl ScrollHost) {
1053 let pending = host.scroll_mut(|s, size| {
1054 if !std::mem::take(&mut s.live.report) {
1055 return None;
1056 }
1057 let known = s.zooms() || s.live.reported_zoom != 0.0;
1060 let zoom = (known && s.zoom != s.live.reported_zoom).then(|| {
1061 s.live.reported_zoom = s.zoom;
1062 s.zoom
1063 });
1064 Some((s.reported(size), s.applied, zoom))
1065 });
1066 if let Some(Some((offset, applied, zoom))) = pending {
1067 if let Some(zoom) = zoom {
1068 host.report_zoom(zoom);
1069 }
1070 host.report(offset, applied);
1071 }
1072}
1073
1074fn animate_to(host: &impl ScrollHost, to: Offset, duration: f64, momentum: bool, end: bool) {
1076 let Some((from, to)) = host.scroll(|s, size| (s.pos(), to.clamp(s.range(size)))) else {
1077 return;
1078 };
1079 if from.distance(to) < 0.5 || duration <= 0.0 {
1080 set_phase(host, Phase::Idle);
1081 moved_to(host, to);
1082 if momentum {
1083 emit(host, EventKind::MomentumEnd);
1084 }
1085 if end {
1086 emit(host, EventKind::ScrollEnd);
1087 }
1088 return;
1089 }
1090 set_phase(
1091 host,
1092 Phase::Animate {
1093 from,
1094 to,
1095 start: host.now(),
1096 duration,
1097 momentum,
1098 end,
1099 },
1100 );
1101 ensure_ticking(host);
1102}
1103
1104fn animate_along(host: &impl ScrollHost, to: f32, duration: f64, momentum: bool, end: bool) {
1106 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, to)) {
1107 animate_to(host, to, duration, momentum, end);
1108 }
1109}
1110
1111fn release(host: &impl ScrollHost, v: Offset, snap_velocity: f32) {
1115 let Some((pos, (min, max), main, target)) = host.scroll(|s, size| {
1116 let range = s.range(size);
1117 let pos = s.pos();
1118 let main = v.along(s.horizontal);
1119 let lead = s.lead();
1120 let dim = s.viewport(size);
1121 let snap_velocity = if snap_velocity == 0.0 {
1122 main
1123 } else {
1124 snap_velocity
1125 };
1126 let max = range.1.along(s.horizontal);
1127 let target = s
1130 .behavior
1131 .snap_target(
1132 Points(s.offset() - lead),
1133 projected(Points(s.offset()), main, rate(&s.behavior)) - Points(lead),
1134 snap_velocity,
1135 Points(dim),
1136 Points(max + dim - lead),
1137 )
1138 .filter(|_| !s.zooms())
1139 .map(|t| (pos.with(s.horizontal, t.0 + lead), t.0 + lead - s.offset()));
1140 (pos, range, main, target)
1141 }) else {
1142 return;
1143 };
1144 let past = |p: f32, min: f32, max: f32| p < min - 0.5 || p > max + 0.5;
1145 let room = |v: f32, p: f32, min: f32, max: f32| v > 0.0 && p < max || v < 0.0 && p > min;
1146 if past(pos.x, min.x, max.x) || past(pos.y, min.y, max.y) {
1147 animate_to(host, pos.clamp((min, max)), ANIMATION, false, true);
1148 } else if let Some((target, distance)) = target {
1149 let duration = snap_duration(Points(distance), main);
1150 if duration > 0.0 {
1151 emit(host, EventKind::MomentumStart);
1152 }
1153 animate_to(host, target, duration, duration > 0.0, true);
1154 } else if v.x.abs().max(v.y.abs()) > MIN_GLIDE
1155 && (room(v.x, pos.x, min.x, max.x) || room(v.y, pos.y, min.y, max.y))
1156 {
1157 set_phase(
1158 host,
1159 Phase::Glide {
1160 velocity: v,
1161 last: host.now(),
1162 },
1163 );
1164 emit(host, EventKind::MomentumStart);
1165 ensure_ticking(host);
1166 } else {
1167 set_phase(host, Phase::Idle);
1168 emit(host, EventKind::ScrollEnd);
1169 }
1170}
1171
1172fn ensure_ticking(host: &impl ScrollHost) {
1175 let start = host.scroll_mut(|s, _| !std::mem::replace(&mut s.live.ticking, true));
1176 if start == Some(true) {
1177 host.start_ticking();
1178 }
1179}
1180
1181pub fn frame(host: &impl ScrollHost, now: f64) -> bool {
1184 let busy = tick(host, now);
1185 if !busy {
1186 host.scroll_mut(|s, _| s.live.ticking = false);
1187 }
1188 busy
1189}
1190
1191pub fn deadline(host: &impl ScrollHost, now: f64) -> Option<f64> {
1198 let (phase, rate) = host.scroll(|s, _| (s.live.phase, rate(&s.behavior)))?;
1199 let end = match phase {
1200 Phase::Glide { velocity, last } => {
1201 let speed = velocity.x.abs().max(velocity.y.abs());
1203 if speed < STOP || !(0.0..1.0).contains(&rate) {
1204 last
1205 } else {
1206 last + ((STOP / speed).ln() / rate.ln()).max(0.0) as f64
1207 }
1208 }
1209 Phase::Animate {
1210 start, duration, ..
1211 }
1212 | Phase::Zoom {
1213 start, duration, ..
1214 } => start + duration,
1215 Phase::Wheel {
1216 last,
1217 gesture: false,
1218 glide,
1219 ..
1220 } => (last + WHEEL_IDLE).max(glide.end()),
1221 _ => return None,
1222 };
1223 Some(end.max(now) + 1.0)
1226}
1227
1228pub fn detached(host: &impl ScrollHost) {
1231 set_phase(host, Phase::Idle);
1232 report(host);
1233 host.scroll_mut(|s, _| s.live.ticking = false);
1234}
1235
1236fn tick(host: &impl ScrollHost, now: f64) -> bool {
1237 let Some((phase, pos, rate, (min, max))) =
1238 host.scroll(|s, size| (s.live.phase, s.pos(), rate(&s.behavior), s.range(size)))
1239 else {
1240 return false;
1241 };
1242 match phase {
1243 Phase::Glide { velocity, last } => {
1244 let dt = (now - last).max(0.0) as f32;
1245 let axis = |v: f32, p: f32, min: f32, max: f32| {
1248 let (d, v) = glide_step(v, rate, dt);
1249 let next = p + d;
1250 let stopped = v.abs() < STOP || next <= min || next >= max;
1251 (next, if stopped { 0.0 } else { v }, stopped)
1252 };
1253 let (x, vx, stop_x) = axis(velocity.x, pos.x, min.x, max.x);
1254 let (y, vy, stop_y) = axis(velocity.y, pos.y, min.y, max.y);
1255 moved_to(host, Offset::new(x, y).clamp((min, max)));
1256 if stop_x && stop_y {
1257 set_phase(host, Phase::Idle);
1258 emit(host, EventKind::MomentumEnd);
1259 emit(host, EventKind::ScrollEnd);
1260 } else {
1261 set_phase(
1262 host,
1263 Phase::Glide {
1264 velocity: Offset::new(vx, vy),
1265 last: now,
1266 },
1267 );
1268 }
1269 }
1270 Phase::Animate {
1271 from,
1272 to,
1273 start,
1274 duration,
1275 momentum,
1276 end,
1277 } => {
1278 let t = (now - start) / duration;
1279 moved_to(host, from.lerp(to, ease_out(t)));
1280 if t >= 1.0 {
1281 set_phase(host, Phase::Idle);
1282 if momentum {
1283 emit(host, EventKind::MomentumEnd);
1284 }
1285 if end {
1286 emit(host, EventKind::ScrollEnd);
1287 }
1288 }
1289 }
1290 Phase::Zoom {
1291 from,
1292 to,
1293 from_c,
1294 to_c,
1295 at,
1296 start,
1297 duration,
1298 } => {
1299 let t = (now - start) / duration;
1300 let k = ease_out(t);
1301 zoom_at(host, from + (to - from) * k, from_c.lerp(to_c, k), at);
1302 if t >= 1.0 {
1303 set_phase(host, Phase::Idle);
1304 }
1305 }
1306 Phase::Wheel {
1307 gesture: false,
1308 raw,
1309 glide,
1310 ..
1311 } if now < glide.end() => {
1312 moved_to(host, glide.value(raw.into(), now).into());
1313 }
1314 Phase::Wheel {
1315 last,
1316 total,
1317 gesture: false,
1318 raw,
1319 glide,
1320 } if now - last > WHEEL_IDLE => {
1321 if glide != wheel_glide::Glide::default() {
1325 moved_to(host, raw);
1326 }
1327 set_phase(host, Phase::Idle);
1328 let snaps = host
1329 .scroll(|s, _| s.behavior.snaps() || s.behavior.paging)
1330 .unwrap_or(false);
1331 if snaps {
1332 let v = if total.abs() >= 1.0 {
1333 total.signum() * WHEEL_SNAP
1334 } else {
1335 0.0
1336 };
1337 release(host, Offset::default(), v);
1338 } else {
1339 emit(host, EventKind::ScrollEnd);
1340 }
1341 }
1342 Phase::Idle if pos.x > max.x.max(min.x) + 0.5 || pos.y > max.y.max(min.y) + 0.5 => {
1343 moved_to(
1344 host,
1345 Offset::new(pos.x.min(max.x.max(min.x)), pos.y.min(max.y.max(min.y))),
1346 )
1347 }
1348 _ => {}
1349 }
1350 report(host);
1351 let Some((busy, redraw)) = host.scroll_mut(|s, _| {
1352 let mut redraw = false;
1353 let mut busy = !matches!(
1354 s.live.phase,
1355 Phase::Idle
1356 | Phase::Drag { .. }
1357 | Phase::Thumb { .. }
1358 | Phase::Wheel { gesture: true, .. }
1359 );
1360 if matches!(s.live.phase, Phase::Thumb { .. }) {
1361 s.live.shown = now;
1363 } else if s.live.alpha > 0.0 {
1364 let alpha = indicator_alpha(now - s.live.shown);
1365 if alpha != s.live.alpha {
1366 s.live.alpha = alpha;
1367 redraw = true;
1368 }
1369 busy |= alpha > 0.0;
1370 }
1371 if !s.horizontal
1372 && s.offset() < 0.0
1373 && s.live.refreshing
1374 && s.behavior.refresh_indicator.is_none()
1375 {
1376 s.live.spin = Radians(((now / 1000.0) as f32 * 2.0 * PI) % (2.0 * PI));
1377 redraw = true;
1378 busy = true;
1379 }
1380 (busy, redraw)
1381 }) else {
1382 return false;
1383 };
1384 if redraw {
1385 host.redraw();
1386 }
1387 busy
1388}
1389
1390pub fn config(
1394 host: &impl ScrollHost,
1395 horizontal: bool,
1396 indicator: bool,
1397 replaced: bool,
1398 mirrored: bool,
1399) {
1400 let changed = host.scroll_mut(|s, _| {
1401 s.horizontal = horizontal;
1402 s.indicator = indicator && !replaced;
1408 if !indicator {
1409 s.live.alpha = 0.0;
1410 }
1411 let mirrored = mirrored && horizontal;
1412 std::mem::replace(&mut s.mirrored, mirrored) != mirrored
1413 });
1414 if changed == Some(true) {
1415 host.relayout();
1416 }
1417}
1418
1419pub fn content(host: &impl ScrollHost, content: Size<Points>) {
1423 let Some((past, zooms)) = host.scroll_mut(|s, size| {
1424 s.content = content;
1425 let (p, (min, max)) = (s.pos(), s.range(size));
1426 (
1427 p.x > max.x.max(min.x) + 0.5 || p.y > max.y.max(min.y) + 0.5,
1428 s.zooms(),
1429 )
1430 }) else {
1431 return;
1432 };
1433 if zooms {
1434 host.relayout();
1436 }
1437 if past {
1438 ensure_ticking(host);
1439 }
1440 host.redraw();
1441}
1442
1443pub fn scroll_by(host: &impl ScrollHost, delta: Point<Points>) {
1446 let (dx, dy) = (delta.x.0, delta.y.0);
1447 let Some((pos, d)) = host.scroll_mut(|s, _| {
1448 s.applied = s.applied.wrapping_add(1);
1449 let d = if s.zooms() {
1452 Offset::new(dx, dy)
1453 } else {
1454 Offset::default().with(s.horizontal, if s.horizontal { dx } else { dy })
1455 };
1456 s.live.phase = shifted(s.live.phase, d, s.horizontal);
1457 s.live.report = true;
1458 (s.pos(), d)
1459 }) else {
1460 return;
1461 };
1462 if d != Offset::default() {
1463 moved_to(host, pos + d);
1464 }
1465 report(host);
1466}
1467
1468pub fn behavior(host: &impl ScrollHost, behavior: &ScrollBehavior) {
1470 let Some((inset, refresh, held, zoom)) = host.scroll_mut(|s, _| {
1471 let inset = s.behavior.content_inset != behavior.content_inset
1473 || s.can_zoom
1474 && (s.behavior.zooms() != behavior.zooms()
1475 || s.behavior.center_content != behavior.center_content);
1476 let refresh = s.behavior.refresh_indicator != behavior.refresh_indicator;
1477 s.behavior = behavior.clone();
1478 let zoom = if s.zooms() {
1480 limit_zoom(behavior, s.zoom, false)
1481 } else {
1482 1.0
1483 };
1484 if !behavior.enabled
1485 && matches!(
1486 s.live.phase,
1487 Phase::Drag { .. } | Phase::Thumb { .. } | Phase::Wheel { .. }
1488 )
1489 {
1490 s.live.phase = Phase::Idle;
1491 }
1492 let held = (refresh
1494 && !s.horizontal
1495 && s.live.refreshing
1496 && s.offset() < 0.0
1497 && !matches!(s.live.phase, Phase::Drag { .. }))
1498 .then(|| behavior.refresh_inset().0);
1499 (inset, refresh, held, (zoom != s.zoom).then_some(zoom))
1500 }) else {
1501 return;
1502 };
1503 if let Some(zoom) = zoom {
1504 zoom_to(host, zoom, None, false);
1505 }
1506 if inset {
1507 host.relayout();
1508 }
1509 if refresh {
1510 host.redraw();
1511 }
1512 if let Some(room) = held {
1513 animate_along(host, -room, ANIMATION, false, false);
1514 }
1515}
1516
1517pub fn refreshing(host: &impl ScrollHost, refreshing: bool) {
1520 let Some(Some((pos, dragging, inset))) = host.scroll_mut(|s, _| {
1521 if s.horizontal || s.live.refreshing == refreshing {
1522 return None;
1523 }
1524 s.live.refreshing = refreshing;
1525 Some((
1526 s.offset(),
1527 matches!(s.live.phase, Phase::Drag { .. }),
1528 s.behavior.refresh_inset().0,
1529 ))
1530 }) else {
1531 return;
1532 };
1533 host.redraw();
1534 if dragging {
1535 return;
1536 }
1537 if refreshing && pos <= 0.5 {
1538 animate_along(host, -inset, ANIMATION, false, false);
1539 } else if !refreshing && pos < 0.0 {
1540 animate_along(host, 0.0, ANIMATION, false, false);
1541 }
1542}
1543
1544pub fn command(host: &impl ScrollHost, command: &Command) {
1547 if let Command::ZoomTo {
1548 scale,
1549 center,
1550 animated,
1551 } = *command
1552 {
1553 let center = center.map(|c| Offset::new(c.x.0, c.y.0));
1554 return zoom_to(host, scale, center, animated);
1555 }
1556 let Some(Some((target, animated))) = host.scroll_mut(|s, size| {
1557 let range = s.range(size);
1558 let inset = s.behavior.content_inset;
1559 let (target, animated) = match *command {
1560 Command::ScrollTo { x, y, animated } => (
1562 if s.zooms() {
1563 Offset::new(x.0 + inset.left.0, y.0 + inset.top.0)
1564 } else if s.horizontal {
1565 s.pos().with(true, x.0 + inset.left.0)
1566 } else {
1567 s.pos().with(false, y.0 + inset.top.0)
1568 },
1569 animated,
1570 ),
1571 Command::ScrollToEnd { animated } => (
1572 s.pos().with(s.horizontal, range.1.along(s.horizontal)),
1573 animated,
1574 ),
1575 Command::ScrollToIndex { .. } => {
1576 log::debug!("scroll: {command:?} is not supported");
1577 return None;
1578 }
1579 _ => return None,
1580 };
1581 s.applied = s.applied.wrapping_add(1);
1582 s.live.report = true;
1583 Some((target.clamp(range), animated))
1584 }) else {
1585 return;
1586 };
1587 interrupt(host);
1588 if animated {
1589 animate_to(host, target, ANIMATION, false, true);
1590 } else {
1591 moved_to(host, target);
1592 }
1593 report(host);
1594}
1595
1596fn limit_zoom(b: &ScrollBehavior, scale: f32, rubber: bool) -> f32 {
1601 let (min, max) = (b.min_zoom, b.max_zoom.max(b.min_zoom));
1602 let band = |limit: f32| limit * (scale / limit).powf(0.3);
1603 if scale > max {
1604 if rubber && b.bounces_zoom {
1605 band(max)
1606 } else {
1607 max
1608 }
1609 } else if scale < min {
1610 if rubber && b.bounces_zoom {
1611 band(min)
1612 } else {
1613 min
1614 }
1615 } else {
1616 scale
1617 }
1618}
1619
1620fn zoom_at(host: &impl ScrollHost, scale: f32, c: Offset, at: Offset) {
1623 let to = host.scroll_mut(|s, size| {
1624 if s.zoom != scale {
1625 s.zoom = scale;
1626 s.live.rezoomed = true;
1627 }
1628 s.showing(size, c, at)
1629 });
1630 if let Some(to) = to {
1631 moved_to(host, to);
1632 }
1633}
1634
1635fn zoom_to(host: &impl ScrollHost, scale: f32, center: Option<Offset>, animated: bool) {
1638 let Some(Some((from, to, at, now_c))) = host.scroll(|s, size| {
1639 if !s.zooms() && s.zoom == 1.0 {
1641 log::debug!("scroll: zoomTo on a scroll view that does not zoom");
1642 return None;
1643 }
1644 let to = if s.zooms() {
1645 limit_zoom(&s.behavior, scale, false)
1646 } else {
1647 1.0
1648 };
1649 let at = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
1650 Some((s.zoom, to, at, s.content_at(size, at)))
1651 }) else {
1652 return;
1653 };
1654 interrupt(host);
1655 let c = center.unwrap_or(now_c);
1656 if animated && host.attached() && (to - from).abs() > 1e-4 {
1657 zoom_eased(host, from, to, now_c, c, at);
1658 } else {
1659 zoom_at(host, to, c, at);
1660 report(host);
1661 }
1662}
1663
1664fn zoom_eased(
1667 host: &impl ScrollHost,
1668 from: f32,
1669 to: f32,
1670 from_c: Offset,
1671 to_c: Offset,
1672 at: Offset,
1673) {
1674 set_phase(
1675 host,
1676 Phase::Zoom {
1677 from,
1678 to,
1679 from_c,
1680 to_c,
1681 at,
1682 start: host.now(),
1683 duration: ANIMATION,
1684 },
1685 );
1686 ensure_ticking(host);
1687}
1688
1689pub fn pinches(host: &impl ScrollHost) -> bool {
1691 host.scroll(|s, _| s.zooms() && s.behavior.pinch)
1692 .unwrap_or(false)
1693}
1694
1695pub fn pinch_begin(host: &impl ScrollHost) {
1698 interrupt(host);
1699 host.scroll_mut(|s, _| s.live.pinch_from = s.zoom);
1700}
1701
1702pub fn pinch(host: &impl ScrollHost, scale: f32, at: Point<Points>) {
1706 let at = Offset::new(at.x.0, at.y.0);
1707 let Some((to, c)) = host.scroll_mut(|s, size| {
1708 let raw = s.live.pinch_from * scale;
1709 let to = limit_zoom(&s.behavior, raw, true);
1710 (to, s.content_at(size, at))
1711 }) else {
1712 return;
1713 };
1714 zoom_at(host, to, c, at);
1715}
1716
1717pub fn pinch_end(host: &impl ScrollHost, at: Point<Points>) {
1719 let at = Offset::new(at.x.0, at.y.0);
1720 let Some((from, to, c)) = host.scroll(|s, size| {
1721 (
1722 s.zoom,
1723 limit_zoom(&s.behavior, s.zoom, false),
1724 s.content_at(size, at),
1725 )
1726 }) else {
1727 return;
1728 };
1729 if (to - from).abs() > 1e-4 {
1730 zoom_eased(host, from, to, c, c, at);
1731 }
1732}
1733
1734pub fn drag_begin(host: &impl ScrollHost) {
1739 if !enabled(host) {
1740 return;
1741 }
1742 interrupt(host);
1743 let start = host.scroll(|s, _| s.pos()).unwrap_or_default();
1744 set_phase(
1745 host,
1746 Phase::Drag {
1747 start,
1748 moved: Offset::default(),
1749 },
1750 );
1751 emit(host, EventKind::ScrollDragStart);
1752}
1753
1754pub fn drag_move(host: &impl ScrollHost, delta: Point<Points>) {
1757 drag(host, delta.x.0, delta.y.0, false);
1758}
1759
1760pub fn drag_to(host: &impl ScrollHost, moved: Point<Points>) {
1762 drag(host, moved.x.0, moved.y.0, true);
1763}
1764
1765fn drag(host: &impl ScrollHost, dx: f32, dy: f32, since_begin: bool) {
1766 let Phase::Drag { start, moved } = phase(host) else {
1767 return;
1768 };
1769 let Some((pos, moved)) = host.scroll(|s, size| {
1770 let (min, max) = s.range(size);
1771 let d = if s.zooms() {
1772 Offset::new(-dx, -dy)
1773 } else if !s.horizontal {
1774 Offset::new(0.0, -dy)
1775 } else if s.mirrored {
1776 Offset::new(dx, 0.0)
1777 } else {
1778 Offset::new(-dx, 0.0)
1779 };
1780 let moved = if since_begin { d } else { moved + d };
1783 let raw = start + moved;
1784 let bounces = s.behavior.bounces;
1785 let pos = Offset::new(
1786 drag_position(raw.x, min.x, max.x.max(min.x), size.width.0, bounces),
1787 drag_position(raw.y, min.y, max.y.max(min.y), size.height.0, bounces),
1788 );
1789 (pos, moved)
1790 }) else {
1791 return;
1792 };
1793 set_phase(host, Phase::Drag { start, moved });
1794 moved_to(host, pos);
1795}
1796
1797pub fn drag_end(host: &impl ScrollHost, vx: f32, vy: f32) {
1800 if !matches!(phase(host), Phase::Drag { .. }) {
1801 return;
1802 }
1803 let listens = host.listens(EventKind::Refresh);
1804 let Some((v, refresh)) = host.scroll(|s, _| {
1805 let v = if s.zooms() {
1806 Offset::new(-vx / 1000.0, -vy / 1000.0)
1807 } else {
1808 let v = if !s.horizontal {
1809 -vy
1810 } else if s.mirrored {
1811 vx
1812 } else {
1813 -vx
1814 } / 1000.0;
1815 Offset::default().with(s.horizontal, v)
1816 };
1817 let refresh = !s.horizontal
1818 && !s.live.refreshing
1819 && listens
1820 && s.behavior.refreshes(Points(s.offset()));
1821 (v, refresh)
1822 }) else {
1823 return;
1824 };
1825 set_phase(host, Phase::Idle);
1826 emit(host, EventKind::ScrollDragEnd);
1827 if refresh {
1828 host.scroll_mut(|s, _| s.live.refreshing = true);
1830 host.event(EventKind::Refresh, EventPayload::None);
1831 }
1832 release(host, v, 0.0);
1833}
1834
1835pub fn hovered(host: &impl ScrollHost) {
1841 let shown = host.scroll_mut(|s, size| {
1842 if s.thumb(size).is_none() || !s.indicator || !s.behavior.enabled {
1843 return false;
1844 }
1845 s.live.shown = host.now();
1846 if s.live.alpha == 1.0 {
1847 return false;
1848 }
1849 s.live.alpha = 1.0;
1850 s.live.dark = host.dark();
1851 true
1852 });
1853 if shown != Some(true) {
1854 return;
1855 }
1856 host.redraw();
1857 ensure_ticking(host);
1858}
1859
1860pub fn thumb_begin(host: &impl ScrollHost) {
1862 interrupt(host);
1863 let grabbed = host.scroll_mut(|s, _| {
1864 s.live.phase = Phase::Thumb { start: s.offset() };
1865 s.live.shown = host.now();
1866 s.live.alpha = 1.0;
1867 s.live.dark = host.dark();
1868 });
1869 if grabbed.is_none() {
1870 return;
1871 }
1872 host.redraw();
1873 emit(host, EventKind::ScrollDragStart);
1874}
1875
1876pub fn thumb_move(host: &impl ScrollHost, moved: Point<Points>) {
1880 let (dx, dy) = (moved.x.0, moved.y.0);
1881 let Phase::Thumb { start } = phase(host) else {
1882 return;
1883 };
1884 let Some(Some(pos)) = host.scroll(|s, size| {
1885 let (_, travel) = s.thumb(size)?;
1886 let (min, max) = s.limits(size);
1887 let d = if !s.horizontal {
1888 dy
1889 } else if s.mirrored {
1890 -dx
1891 } else {
1892 dx
1893 };
1894 let d = thumb_scroll(Points(d), Points(max), travel).0;
1895 Some((start + d).clamp(min, max.max(min)))
1896 }) else {
1897 return;
1898 };
1899 moved_along(host, pos);
1900}
1901
1902pub fn thumb_end(host: &impl ScrollHost) {
1905 if !matches!(phase(host), Phase::Thumb { .. }) {
1906 return;
1907 }
1908 set_phase(host, Phase::Idle);
1909 host.scroll_mut(|s, _| s.live.shown = host.now());
1910 ensure_ticking(host);
1911 emit(host, EventKind::ScrollDragEnd);
1912 release(host, Offset::default(), 0.0);
1913}
1914
1915pub fn wheel_begin(host: &impl ScrollHost) {
1920 if !enabled(host) {
1921 return;
1922 }
1923 interrupt(host);
1924 set_phase(
1925 host,
1926 Phase::Wheel {
1927 last: host.now(),
1928 total: 0.0,
1929 gesture: true,
1930 raw: Offset::default(),
1931 glide: wheel_glide::Glide::default(),
1932 },
1933 );
1934 emit(host, EventKind::ScrollDragStart);
1935}
1936
1937pub fn wheel(host: &impl ScrollHost, delta: Point<Points>) {
1940 wheel_by(host, delta, false);
1941}
1942
1943#[doc(hidden)]
1949pub fn wheel_smooth(host: &impl ScrollHost, delta: Point<Points>) {
1950 wheel_by(host, delta, true);
1951}
1952
1953#[doc(hidden)]
1956pub fn smooth_wheel(host: &impl ScrollHost) -> bool {
1957 host.scroll(|s, _| {
1958 s.behavior.smooth_wheel && !s.zooms() && !s.behavior.snaps() && !s.behavior.paging
1959 })
1960 .unwrap_or(false)
1961}
1962
1963#[doc(hidden)]
1967pub fn wheel_line(
1968 host: &impl ScrollHost,
1969 delta: Point<Points>,
1970 line: Point<Points>,
1971) -> Point<Points> {
1972 let height = host
1973 .scroll(|s, _| s.behavior.wheel_line_height)
1974 .unwrap_or(Points::ZERO)
1975 .0;
1976 let axis = |d: Points, line: Points| {
1977 if height > 0.0 && line.0 > 0.0 {
1978 Points(d.0 * height / line.0)
1979 } else {
1980 d
1981 }
1982 };
1983 point(axis(delta.x, line.x), axis(delta.y, line.y))
1984}
1985
1986fn wheel_by(host: &impl ScrollHost, delta: Point<Points>, smooth: bool) {
1987 let (dx, dy) = (delta.x.0, delta.y.0);
1988 if !enabled(host) {
1989 return;
1990 }
1991 let (gesture, total, last) = match phase(host) {
1992 Phase::Wheel {
1993 gesture,
1994 total,
1995 raw,
1996 glide,
1997 ..
1998 } => (gesture, total, (!gesture).then_some((raw, glide))),
1999 _ => {
2000 interrupt(host);
2001 (false, 0.0, None)
2002 }
2003 };
2004 let smooth = smooth && !gesture;
2005 let now = host.now();
2006 let Some((pos, to, total)) = host.scroll(|s, size| {
2007 let (min, max) = s.range(size);
2008 let d = if s.zooms() {
2009 Offset::new(dx, dy)
2010 } else if !s.horizontal {
2011 Offset::new(0.0, dy)
2012 } else if dx != 0.0 {
2013 Offset::new(if s.mirrored { -dx } else { dx }, 0.0)
2014 } else {
2015 Offset::new(dy, 0.0)
2017 };
2018 let pos = s.pos();
2019 let from = match last {
2022 Some((raw, _)) if smooth => raw,
2023 _ => pos,
2024 };
2025 let one =
2027 |p: f32, d: f32, min: f32, max: f32| (p + d).clamp(min.min(p), max.max(min).max(p));
2028 (
2029 pos,
2030 Offset::new(
2031 one(from.x, d.x, min.x, max.x),
2032 one(from.y, d.y, min.y, max.y),
2033 ),
2034 total + d.along(s.horizontal),
2035 )
2036 }) else {
2037 return;
2038 };
2039 let glide = match last {
2040 _ if !smooth => wheel_glide::Glide::default(),
2041 Some((raw, g)) if now < g.end() => g.retargeted(raw.into(), to.into(), now),
2042 _ => wheel_glide::Glide::new(pos.into(), to.into(), now),
2043 };
2044 set_phase(
2045 host,
2046 Phase::Wheel {
2047 last: now,
2048 total,
2049 gesture,
2050 raw: to,
2051 glide,
2052 },
2053 );
2054 if !smooth {
2055 moved_to(host, to);
2056 }
2057 ensure_ticking(host);
2058}
2059
2060pub fn wheel_end(host: &impl ScrollHost, vx: f32, vy: f32) {
2063 end_wheel(host, vx, vy, true);
2064}
2065
2066pub fn wheel_settle(host: &impl ScrollHost) {
2072 end_wheel(host, 0.0, 0.0, false);
2073}
2074
2075fn end_wheel(host: &impl ScrollHost, vx: f32, vy: f32, onward: bool) {
2076 let Phase::Wheel { gesture, total, .. } = phase(host) else {
2077 return;
2078 };
2079 let Some(v) = host.scroll(|s, _| {
2080 let v = if s.zooms() {
2081 return Offset::new(vx / 1000.0, vy / 1000.0);
2082 } else if !s.horizontal {
2083 vy
2084 } else if vx != 0.0 {
2085 if s.mirrored { -vx } else { vx }
2086 } else {
2087 vy
2088 };
2089 Offset::default().with(s.horizontal, v / 1000.0)
2090 }) else {
2091 return;
2092 };
2093 set_phase(host, Phase::Idle);
2094 if gesture {
2095 emit(host, EventKind::ScrollDragEnd);
2096 }
2097 let snap = if onward && v == Offset::default() && total.abs() >= 1.0 {
2098 total.signum() * WHEEL_SNAP
2099 } else {
2100 0.0
2101 };
2102 release(host, v, snap);
2103}
2104
2105const WHEEL_STEP_ANIMATION: f64 = 150.0;
2108
2109pub fn wheel_step(host: &impl ScrollHost, delta: Point<Points>) {
2115 if !enabled(host) {
2116 return;
2117 }
2118 let Some(target) = host.scroll(|s, size| {
2119 if s.zooms() || s.behavior.snaps() || s.behavior.paging {
2120 return None;
2121 }
2122 let (min, max) = s.limits(size);
2123 let max = max.max(min);
2124 let (dx, dy) = (delta.x.0, delta.y.0);
2125 let d = if !s.horizontal {
2126 dy
2127 } else if dx != 0.0 {
2128 if s.mirrored { -dx } else { dx }
2129 } else {
2130 dy
2132 };
2133 let pos = s.offset();
2134 if pos < min - 0.5 || pos > max + 0.5 {
2135 return None;
2136 }
2137 Some((s.goal() + d).clamp(min, max))
2138 }) else {
2139 return;
2140 };
2141 let Some(to) = target else {
2142 wheel(host, delta);
2143 return;
2144 };
2145 if matches!(phase(host), Phase::Wheel { gesture: true, .. }) {
2146 return;
2148 }
2149 let goal = host.scroll(|s, _| s.goal()).unwrap_or(to);
2150 if (to - goal).abs() < 0.5 {
2151 return;
2153 }
2154 interrupt(host);
2155 animate_along(host, to, WHEEL_STEP_ANIMATION, false, true);
2156}
2157
2158pub const KEY_LINE: Points = Points(40.0);
2162const KEY_PAGE: f32 = 0.875;
2164const KEY_ANIMATION: f64 = 200.0;
2166
2167#[derive(Debug, Clone, Copy, PartialEq)]
2169pub enum KeyMove {
2170 Points(Points),
2172 Pages(f32),
2174 Start,
2176 End,
2178}
2179
2180impl KeyMove {
2181 pub fn sign(self) -> f32 {
2183 match self {
2184 KeyMove::Points(d) => d.0.signum(),
2185 KeyMove::Pages(n) => n.signum(),
2186 KeyMove::Start => -1.0,
2187 KeyMove::End => 1.0,
2188 }
2189 }
2190}
2191
2192pub fn vk_key_move(vk: u16, shift: bool, ctrl: bool) -> Option<(bool, KeyMove)> {
2197 const VK_SPACE: u16 = 0x20;
2198 const VK_PRIOR: u16 = 0x21;
2199 const VK_NEXT: u16 = 0x22;
2200 const VK_END: u16 = 0x23;
2201 const VK_HOME: u16 = 0x24;
2202 const VK_LEFT: u16 = 0x25;
2203 const VK_UP: u16 = 0x26;
2204 const VK_RIGHT: u16 = 0x27;
2205 const VK_DOWN: u16 = 0x28;
2206 if ctrl {
2207 return match vk {
2208 VK_HOME => Some((false, KeyMove::Start)),
2209 VK_END => Some((false, KeyMove::End)),
2210 _ => None,
2211 };
2212 }
2213 Some(match vk {
2214 VK_UP => (false, KeyMove::Points(-KEY_LINE)),
2215 VK_DOWN => (false, KeyMove::Points(KEY_LINE)),
2216 VK_LEFT => (true, KeyMove::Points(-KEY_LINE)),
2217 VK_RIGHT => (true, KeyMove::Points(KEY_LINE)),
2218 VK_PRIOR => (false, KeyMove::Pages(-1.0)),
2219 VK_NEXT => (false, KeyMove::Pages(1.0)),
2220 VK_SPACE if shift => (false, KeyMove::Pages(-1.0)),
2221 VK_SPACE => (false, KeyMove::Pages(1.0)),
2222 VK_HOME => (false, KeyMove::Start),
2223 VK_END => (false, KeyMove::End),
2224 _ => return None,
2225 })
2226}
2227
2228fn key_target(m: KeyMove, base: f32, viewport: f32, min: f32, max: f32) -> f32 {
2230 let max = max.max(min);
2231 match m {
2232 KeyMove::Points(d) => base + d.0,
2233 KeyMove::Pages(n) => base + n * (viewport * KEY_PAGE).max(KEY_LINE.0),
2234 KeyMove::Start => min,
2235 KeyMove::End => max,
2236 }
2237 .clamp(min, max)
2238}
2239
2240pub fn key_scroll(host: &impl ScrollHost, m: KeyMove, flip: bool) {
2246 let Some((base, viewport, min, max, flip)) = host.scroll(|s, size| {
2247 let (min, max) = s.limits(size);
2248 (s.goal(), s.viewport(size), min, max, flip && s.mirrored)
2249 }) else {
2250 return;
2251 };
2252 let moved = match m {
2253 KeyMove::Points(d) if flip => KeyMove::Points(-d),
2254 m => m,
2255 };
2256 let to = key_target(moved, base, viewport, min, max);
2257 interrupt(host);
2258 animate_along(host, to, KEY_ANIMATION, false, true);
2259 host.key_scrolled(m);
2263}
2264
2265const REVEAL_MARGIN: f32 = 16.0;
2267
2268pub fn reveal_delta(start: Points, end: Points, viewport: Points) -> Points {
2272 Points(reveal_by(start.0, end.0, viewport.0))
2273}
2274
2275pub fn reveal_focus_delta(start: Points, end: Points, viewport: Points) -> Points {
2281 Points(reveal_focus_by(start.0, end.0, viewport.0))
2282}
2283
2284fn reveal_by(start: f32, end: f32, viewport: f32) -> f32 {
2285 let margin = REVEAL_MARGIN.min(viewport / 4.0);
2286 if start < margin {
2287 start - margin
2288 } else if end > viewport - margin {
2289 (end - (viewport - margin)).min(start - margin)
2290 } else {
2291 0.0
2292 }
2293}
2294
2295fn reveal_focus_by(start: f32, end: f32, viewport: f32) -> f32 {
2296 if end - start > viewport && end > 0.0 && start < viewport {
2297 0.0
2298 } else {
2299 reveal_by(start, end, viewport)
2300 }
2301}
2302
2303pub fn reveal(host: &impl ScrollHost, start: Points, len: Points) -> Points {
2309 let (start, len) = (start.0, len.0);
2310 let Some((base, pos, dim, min, max)) = host.scroll(|s, size| {
2311 let (min, max) = s.limits(size);
2312 (s.goal(), s.offset(), s.viewport(size), min, max)
2313 }) else {
2314 return Points(0.0);
2315 };
2316 let start = start - (base - pos);
2318 let delta = reveal_focus_by(start, start + len, dim);
2319 let to = (base + delta).clamp(min, max.max(min));
2320 if (to - base).abs() < 0.5 {
2321 return Points(0.0);
2322 }
2323 interrupt(host);
2324 animate_along(host, to, ANIMATION, false, true);
2325 Points(to - base)
2326}
2327
2328#[cfg(test)]
2329mod tests {
2330 use super::*;
2331 use crate::EdgeInsets;
2332
2333 #[test]
2334 fn content_is_read_in_the_order_it_is_on_screen() {
2335 let cells = [(0, 160.0), (1, 200.0), (2, 80.0), (3, 120.0)];
2338 let mut vertical = cells;
2339 reading_order(Axis::Vertical, &mut vertical, |c| {
2340 point(Points(0.0), Points(c.1))
2341 });
2342 assert_eq!(vertical.map(|c| c.0), [2, 3, 0, 1]);
2343 let grid = [
2345 (0, (50.0, 0.0)),
2346 (1, (0.0, 40.0)),
2347 (2, (0.0, 0.0)),
2348 (3, (50.0, 40.0)),
2349 ];
2350 let at = |c: &(i32, (f32, f32))| point(Points(c.1.0), Points(c.1.1));
2351 let mut rows = grid;
2352 reading_order(Axis::Vertical, &mut rows, at);
2353 assert_eq!(rows.map(|c| c.0), [2, 0, 1, 3]);
2354 let mut columns = grid;
2355 reading_order(Axis::Horizontal, &mut columns, at);
2356 assert_eq!(columns.map(|c| c.0), [2, 1, 0, 3]);
2357 }
2358
2359 fn scroll_state(content: (f32, f32), horizontal: bool) -> ScrollState {
2360 ScrollState {
2361 content: sz(content.0, content.1),
2362 horizontal,
2363 ..Default::default()
2364 }
2365 }
2366
2367 fn sz(w: f32, h: f32) -> Size<Points> {
2368 crate::geometry::size(Points(w), Points(h))
2369 }
2370
2371 fn pt(x: f32, y: f32) -> Point<Points> {
2372 point(Points(x), Points(y))
2373 }
2374
2375 #[test]
2376 fn rubber_band_resists() {
2377 assert_eq!(drag_position(50.0, 0.0, 100.0, 400.0, true), 50.0);
2378 let over = drag_position(-100.0, 0.0, 100.0, 400.0, true);
2379 assert!(over < 0.0 && over > -100.0, "{over}");
2380 let more = drag_position(-400.0, 0.0, 100.0, 400.0, true);
2381 assert!(more < over && more > -400.0 * 0.55);
2382 assert_eq!(drag_position(-100.0, 0.0, 100.0, 400.0, false), 0.0);
2383 assert_eq!(drag_position(300.0, 0.0, 100.0, 400.0, false), 100.0);
2384 assert!(drag_position(150.0, 0.0, 100.0, 400.0, true) > 100.0);
2385 let p = Points;
2386 assert_eq!(dragged(p(50.0), p(0.0), p(100.0), p(400.0), true), p(50.0));
2387 assert!(rubber(1e6, 400.0) < 400.0);
2389 }
2390
2391 #[test]
2392 fn glide_integrates_to_projection() {
2393 let rate = 0.998;
2394 let (mut pos, mut v) = (0.0f32, 2.0f32);
2395 for _ in 0..2000 {
2396 let (d, nv) = glide_step(v, rate, 16.0);
2397 pos += d;
2398 v = nv;
2399 }
2400 let end = projected(Points(0.0), 2.0, rate).0;
2401 assert!((pos - end).abs() < 1.0, "{pos} vs {end}");
2402 let (a, _) = glide_step(2.0, rate, 32.0);
2404 let (b1, v1) = glide_step(2.0, rate, 16.0);
2405 let (b2, _) = glide_step(v1, rate, 16.0);
2406 assert!((a - (b1 + b2)).abs() < 1e-3);
2407 }
2408
2409 #[test]
2410 fn animated_sticky_offsets_stick_further_in() {
2411 let mut s = scroll_state((320.0, 2000.0), false);
2412 s.y = Points(150.0);
2413 s.sticky = vec![
2414 crate::StickyCell {
2415 cell: 1,
2416 start: Points(100.0),
2417 end: Points(300.0),
2418 offset: None,
2419 },
2420 crate::StickyCell {
2421 cell: 2,
2422 start: Points(100.0),
2423 end: Points(300.0),
2424 offset: Some(7),
2425 },
2426 ];
2427 let shifts: Vec<_> = s
2429 .sticky_shifts_with(|n| if n == 7 { 56.0 } else { 0.0 })
2430 .map(|(c, p)| (c, p.y.0))
2431 .collect();
2432 assert_eq!(shifts, [(1, 50.0), (2, 106.0)]);
2433 }
2434
2435 #[test]
2436 fn sticky_shift_clamps() {
2437 let p = Points;
2438 assert_eq!(sticky_shift(p(0.0), p(100.0), p(300.0)), p(0.0));
2439 assert_eq!(sticky_shift(p(150.0), p(100.0), p(300.0)), p(50.0));
2440 assert_eq!(sticky_shift(p(500.0), p(100.0), p(300.0)), p(200.0));
2441 assert_eq!(sticky_shift(p(500.0), p(100.0), p(f32::INFINITY)), p(400.0));
2442 }
2443
2444 #[test]
2445 fn rates_follow_behavior() {
2446 let mut b = ScrollBehavior::default();
2447 assert_eq!(rate(&b), 0.998);
2448 b.paging = true;
2449 assert_eq!(rate(&b), 0.99);
2450 b.deceleration = 0.95;
2451 assert_eq!(rate(&b), 0.95);
2452 }
2453
2454 #[test]
2455 fn snapping_and_paging_targets() {
2456 let b = ScrollBehavior {
2459 paging: true,
2460 ..Default::default()
2461 };
2462 let r = rate(&b);
2463 let pt = Points;
2464 let t = b.snap_target(
2465 pt(250.0),
2466 projected(pt(250.0), 0.0, r),
2467 0.0,
2468 pt(400.0),
2469 pt(1600.0),
2470 );
2471 assert_eq!(t, Some(pt(400.0)));
2472 let t = b.snap_target(
2473 pt(100.0),
2474 projected(pt(100.0), 1.0, r),
2475 1.0,
2476 pt(400.0),
2477 pt(1600.0),
2478 );
2479 assert_eq!(t, Some(pt(400.0)));
2480 let t = b.snap_target(
2481 pt(300.0),
2482 projected(pt(300.0), -1.0, r),
2483 -1.0,
2484 pt(400.0),
2485 pt(1600.0),
2486 );
2487 assert_eq!(t, Some(pt(0.0)));
2488 let b = ScrollBehavior {
2489 snap_interval: pt(100.0),
2490 ..Default::default()
2491 };
2492 let t = b.snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0));
2493 assert_eq!(t, Some(pt(100.0)));
2494 assert_eq!(
2495 ScrollBehavior::default().snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0)),
2496 None
2497 );
2498 }
2499
2500 #[test]
2501 fn indicator_geometry() {
2502 assert_eq!(span(400.0, 400.0, 0.0, 0.0, 0.0), None);
2503 let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2504 assert_eq!(s0, 2.0);
2505 assert!((l0 - 99.0).abs() < 0.01);
2506 let (s1, l1) = span(400.0, 1600.0, 1200.0, 0.0, 0.0).unwrap();
2507 assert!((s1 + l1 - 398.0).abs() < 0.01);
2508 let (_, l2) = span(400.0, 1600.0, -50.0, 0.0, 0.0).unwrap();
2509 assert!(l2 < l0);
2510 assert_eq!(
2511 indicator_span(Points(400.0), Points(1600.0), Points(0.0)),
2512 Some((Points(s0), Points(l0)))
2513 );
2514 assert_eq!(indicator_alpha(0.0), 1.0);
2515 assert_eq!(indicator_alpha(INDICATOR_HOLD + INDICATOR_FADE), 0.0);
2516 }
2517
2518 #[test]
2519 fn snap_durations() {
2520 let p = Points;
2521 assert_eq!(snap_duration(p(0.2), 1.0), 0.0);
2522 assert_eq!(snap_duration(p(100.0), -1.0), ANIMATION);
2523 assert_eq!(snap_duration(p(300.0), 1.0), 600.0);
2524 assert_eq!(snap_duration(p(300.0), 3.0), 300.0);
2525 assert_eq!(ease_out(1.0), 1.0);
2526 assert_eq!(ease_out(2.0), 1.0);
2527 }
2528
2529 #[test]
2530 fn insets_clamp_and_report() {
2531 let mut s = scroll_state((300.0, 1000.0), false);
2532 let size = sz(300.0, 400.0);
2533 s.behavior.content_inset = EdgeInsets {
2534 top: Points(50.0),
2535 bottom: Points(20.0),
2536 ..Default::default()
2537 };
2538 assert_eq!(s.limits(size), (0.0, 670.0));
2539 assert_eq!(s.max(size), pt(0.0, 670.0));
2540 assert_eq!(s.reported(size), pt(0.0, -50.0));
2542 s.y = Points(900.0);
2543 assert_eq!(s.reported(size), pt(0.0, 620.0));
2544 assert_eq!(s.origin(), pt(0.0, 850.0));
2546 s.live.refreshing = true;
2548 assert_eq!(s.limits(size).0, -56.0);
2549 s.behavior.refresh_indicator = Some(Points(80.0));
2550 assert_eq!(s.limits(size).0, -80.0);
2551 }
2552
2553 #[test]
2554 fn can_scroll_follows_edges_and_mirroring() {
2555 let size = sz(300.0, 400.0);
2556 let mut s = scroll_state((300.0, 1000.0), false);
2557 s.behavior.enabled = true;
2558 assert!(s.can_scroll(size, pt(0.0, 10.0)));
2559 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2560 s.y = Points(600.0);
2561 assert!(!s.can_scroll(size, pt(0.0, 10.0)));
2562 s.behavior.enabled = false;
2563 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2564
2565 let size = sz(300.0, 100.0);
2566 let mut row = scroll_state((1000.0, 100.0), true);
2567 row.behavior.enabled = true;
2568 row.mirrored = true;
2569 assert!(row.can_scroll(size, pt(-10.0, 0.0)));
2571 assert!(!row.can_scroll(size, pt(10.0, 0.0)));
2572 assert!(row.can_scroll(size, pt(0.0, 10.0)));
2574 }
2575
2576 #[test]
2577 fn scroll_by_moves_gestures_along() {
2578 let y = |v: f32| Offset::new(0.0, v);
2579 let drag = shifted(
2580 Phase::Drag {
2581 start: y(10.0),
2582 moved: y(5.0),
2583 },
2584 y(30.0),
2585 false,
2586 );
2587 assert_eq!(
2588 drag,
2589 Phase::Drag {
2590 start: y(40.0),
2591 moved: y(5.0)
2592 }
2593 );
2594 let anim = Phase::Animate {
2595 from: y(0.0),
2596 to: y(100.0),
2597 start: 1.0,
2598 duration: 300.0,
2599 momentum: false,
2600 end: true,
2601 };
2602 let Phase::Animate { from, to, .. } = shifted(anim, y(-20.0), false) else {
2603 panic!()
2604 };
2605 assert_eq!((from, to), (y(-20.0), y(80.0)));
2606 assert_eq!(shifted(Phase::Idle, y(5.0), false), Phase::Idle);
2607 assert_eq!(
2608 shifted(Phase::Thumb { start: 10.0 }, y(30.0), false),
2609 Phase::Thumb { start: 40.0 }
2610 );
2611 }
2612
2613 #[test]
2614 fn thumb_follows_the_pointer() {
2615 let p = Points;
2618 let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2619 let travel = 400.0 - 2.0 * INDICATOR_MARGIN - l0;
2620 let end = thumb_scroll(p(travel), p(1200.0), p(travel)).0;
2621 assert!((end - 1200.0).abs() < 0.01);
2622 let (s1, _) = span(400.0, 1600.0, end, 0.0, 0.0).unwrap();
2623 assert!((s1 - s0 - travel).abs() < 0.01);
2624 assert!(thumb_scroll(p(-10.0), p(1200.0), p(travel)).0 < 0.0);
2625 assert_eq!(thumb_scroll(p(10.0), p(1200.0), p(0.0)), p(0.0));
2626 }
2627
2628 #[test]
2629 fn thumb_is_grabbed_at_the_edge() {
2630 let mut s = scroll_state((300.0, 1600.0), false);
2631 s.indicator = true;
2632 s.behavior.enabled = true;
2633 let size = sz(300.0, 400.0);
2634 let (rect, _) = s.thumb(size).unwrap();
2635 assert_eq!(rect.origin.x.0, 300.0 - INDICATOR_THICK.0 - 2.0);
2636 assert!(s.grabs_thumb(size, pt(295.0, 10.0)));
2637 assert!(!s.grabs_thumb(size, pt(200.0, 10.0)));
2638 assert!(!s.grabs_thumb(size, pt(295.0, 300.0)));
2639 }
2640
2641 #[test]
2642 fn thumb_keeps_clear_of_the_scrollbar_inset() {
2643 let (s0, l0) = span(400.0, 1600.0, 0.0, 50.0, 100.0).unwrap();
2646 assert_eq!(s0, 50.0 + INDICATOR_MARGIN);
2647 let (s1, l1) = span(400.0, 1600.0, 1200.0, 50.0, 100.0).unwrap();
2648 assert!((s1 + l1 - (300.0 - INDICATOR_MARGIN)).abs() < 0.01);
2649 let (_, full) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2651 assert!(l0 < full && (l0 - 246.0 / 4.0).abs() < 0.01, "{l0}");
2652 assert_eq!(span(400.0, 1600.0, 0.0, 200.0, 195.0), None);
2654 assert_eq!(
2656 span(400.0, 1600.0, 0.0, -10.0, 0.0),
2657 span(400.0, 1600.0, 0.0, 0.0, 0.0)
2658 );
2659 assert_eq!(
2660 indicator_span_within(
2661 Points(400.0),
2662 Points(1600.0),
2663 Points(0.0),
2664 Points(50.0),
2665 Points(100.0)
2666 ),
2667 Some((Points(s0), Points(l0)))
2668 );
2669
2670 let mut s = scroll_state((300.0, 1600.0), false);
2672 s.indicator = true;
2673 s.behavior.enabled = true;
2674 s.behavior.scrollbar_inset = EdgeInsets {
2675 top: Points(50.0),
2676 right: Points(8.0),
2677 bottom: Points(100.0),
2678 left: Points::ZERO,
2679 };
2680 let size = sz(300.0, 400.0);
2681 let (rect, travel) = s.thumb(size).unwrap();
2682 assert_eq!(rect.origin.x.0, 300.0 - 8.0 - INDICATOR_THICK.0 - 2.0);
2683 assert_eq!(rect.origin.y.0, s0);
2684 assert!((travel.0 - (400.0 - 150.0 - 2.0 * INDICATOR_MARGIN - l0)).abs() < 0.01);
2685 assert!(s.grabs_thumb(size, pt(287.0, 60.0)));
2686 assert!(!s.grabs_thumb(size, pt(295.0, 60.0)), "past its edge");
2687 assert!(!s.grabs_thumb(size, pt(287.0, 20.0)), "above its track");
2688
2689 let mut s = scroll_state((900.0, 2000.0), true);
2692 s.behavior.scrollbar_inset = EdgeInsets {
2693 top: Points::ZERO,
2694 right: Points(30.0),
2695 bottom: Points(20.0),
2696 left: Points(10.0),
2697 };
2698 let size = sz(300.0, 400.0);
2699 let (rect, _) = s.thumb(size).unwrap();
2700 assert_eq!(rect.origin.y.0, 400.0 - 20.0 - INDICATOR_THICK.0 - 2.0);
2701 assert_eq!(rect.origin.x.0, 10.0 + INDICATOR_MARGIN);
2702 s.mirrored = true;
2703 let (rect, _) = s.thumb(size).unwrap();
2704 assert_eq!(
2705 rect.origin.x.0 + rect.size.width.0,
2706 300.0 - 30.0 - INDICATOR_MARGIN
2707 );
2708 }
2709
2710 #[test]
2711 fn thumb_stays_in_the_visible_part() {
2712 let mut s = scroll_state((900.0, 2000.0), true);
2716 s.indicator = true;
2717 s.behavior.enabled = true;
2718 let size = sz(300.0, 2000.0);
2719 let visible = Bounds::new(pt(0.0, 600.0), sz(300.0, 400.0));
2720 let (rect, _) = s.thumb_within(size, visible).unwrap();
2721 assert_eq!(rect.origin.y.0, 1000.0 - INDICATOR_THICK.0 - 2.0);
2722 assert!(s.grabs_thumb_within(size, visible, pt(20.0, 997.0)));
2723 assert!(!s.grabs_thumb_within(size, visible, pt(20.0, 1997.0)));
2724 let (rect, _) = s.thumb(size).unwrap();
2726 assert_eq!(rect.origin.y.0, 2000.0 - INDICATOR_THICK.0 - 2.0);
2727 let hidden = Bounds::new(pt(0.0, 2100.0), sz(300.0, 400.0));
2729 assert!(s.thumb_within(size, hidden).is_none());
2730 }
2731
2732 #[test]
2733 fn scroll_keys() {
2734 assert_eq!(
2735 vk_key_move(0x28, false, false),
2736 Some((false, KeyMove::Points(KEY_LINE)))
2737 );
2738 assert_eq!(
2739 vk_key_move(0x25, false, false),
2740 Some((true, KeyMove::Points(-KEY_LINE)))
2741 );
2742 assert_eq!(
2743 vk_key_move(0x20, true, false),
2744 Some((false, KeyMove::Pages(-1.0)))
2745 );
2746 assert_eq!(
2747 vk_key_move(0x24, false, true),
2748 Some((false, KeyMove::Start))
2749 );
2750 assert_eq!(vk_key_move(0x28, false, true), None);
2751 assert_eq!(vk_key_move(b'A' as u16, false, false), None);
2752 assert_eq!(KeyMove::Start.sign(), -1.0);
2753 assert_eq!(KeyMove::Pages(1.0).sign(), 1.0);
2754 assert_eq!(
2755 key_target(KeyMove::Points(Points(40.0)), 10.0, 400.0, 0.0, 1000.0),
2756 50.0
2757 );
2758 assert_eq!(
2759 key_target(KeyMove::Pages(1.0), 0.0, 400.0, 0.0, 1000.0),
2760 350.0
2761 );
2762 assert_eq!(
2763 key_target(KeyMove::Pages(-1.0), 100.0, 400.0, 0.0, 1000.0),
2764 0.0
2765 );
2766 assert_eq!(key_target(KeyMove::End, 0.0, 400.0, 0.0, 1000.0), 1000.0);
2767 assert_eq!(
2768 key_target(KeyMove::Start, 500.0, 400.0, -56.0, 1000.0),
2769 -56.0
2770 );
2771 }
2772
2773 #[test]
2774 fn reveal_deltas() {
2775 assert_eq!(reveal_by(100.0, 140.0, 400.0), 0.0);
2776 assert_eq!(reveal_by(-30.0, 10.0, 400.0), -46.0);
2777 assert_eq!(reveal_by(380.0, 420.0, 400.0), 36.0);
2778 assert_eq!(reveal_by(200.0, 900.0, 400.0), 184.0);
2780 assert_eq!(reveal_focus_by(500.0, 1200.0, 400.0), 484.0);
2783 assert_eq!(reveal_focus_by(-1200.0, -500.0, 400.0), -1216.0);
2784 assert_eq!(reveal_focus_by(200.0, 900.0, 400.0), 0.0);
2785 assert_eq!(reveal_focus_by(-2000.0, 300.0, 400.0), 0.0);
2786 assert_eq!(reveal_focus_by(-2000.0, 900.0, 400.0), 0.0);
2787 assert_eq!(reveal_focus_by(-100.0, 290.0, 400.0), -116.0);
2790 assert_eq!(
2791 reveal_focus_delta(Points(200.0), Points(900.0), Points(400.0)),
2792 Points(0.0)
2793 );
2794 assert_eq!(
2795 reveal_delta(Points(-30.0), Points(10.0), Points(400.0)),
2796 Points(-46.0)
2797 );
2798 }
2799
2800 #[test]
2801 fn spinner_spokes() {
2802 assert_eq!(spokes(Percentage(0.3), Radians(0.0)).count(), 3);
2803 assert!(spokes(Percentage(0.3), Radians(0.0)).all(|(_, a)| a == 0.8));
2804 let all: Vec<_> = spokes(Percentage(1.0), Radians(0.0)).collect();
2805 assert_eq!(all.len(), 8);
2806 assert_eq!(all[0].1, 1.0);
2808 assert_eq!(all[1].0, Radians(PI / 4.0));
2809 }
2810
2811 #[test]
2812 fn refresh_follows_its_props() {
2813 let mut s = scroll_state((300.0, 1000.0), false);
2814 assert!(!s.behavior.refreshes(Points(-63.0)));
2815 assert!(s.behavior.refreshes(Points(-64.0)));
2816 s.y = Points(-32.0);
2818 assert_eq!(
2819 s.spinner(Points(300.0), true),
2820 Some((pt(150.0, 4.0), Percentage(0.5)))
2821 );
2822 s.behavior.refresh_indicator = Some(Points(100.0));
2825 assert!(!s.behavior.refreshes(Points(-64.0)));
2826 assert!(s.behavior.refreshes(Points(-100.0)));
2827 assert_eq!(s.behavior.refresh_inset(), Points(100.0));
2828 assert_eq!(s.spinner(Points(300.0), true), None);
2829 }
2830
2831 struct TestHost {
2834 state: std::cell::RefCell<ScrollState>,
2835 redraws: std::cell::Cell<u32>,
2836 reports: std::cell::RefCell<Vec<String>>,
2838 key_moves: std::cell::RefCell<Vec<KeyMove>>,
2840 }
2841
2842 impl TestHost {
2843 fn new(state: ScrollState) -> Self {
2844 Self {
2845 state: std::cell::RefCell::new(state),
2846 redraws: std::cell::Cell::new(0),
2847 reports: Default::default(),
2848 key_moves: Default::default(),
2849 }
2850 }
2851 }
2852
2853 impl ScrollHost for TestHost {
2854 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R> {
2855 Some(f(&self.state.borrow(), sz(300.0, 500.0)))
2856 }
2857 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R> {
2858 Some(f(&mut self.state.borrow_mut(), sz(300.0, 500.0)))
2859 }
2860 fn now(&self) -> f64 {
2861 0.0
2862 }
2863 fn listens(&self, _: EventKind) -> bool {
2864 true
2865 }
2866 fn event(&self, _: EventKind, _: EventPayload) {}
2867 fn report(&self, offset: Point<Points>, _: u32) {
2868 let line = format!("scroll {} {}", offset.x.0, offset.y.0);
2869 self.reports.borrow_mut().push(line);
2870 }
2871 fn report_zoom(&self, scale: f32) {
2872 self.reports.borrow_mut().push(format!("zoom {scale}"));
2873 }
2874 fn key_scrolled(&self, key_move: KeyMove) {
2875 self.key_moves.borrow_mut().push(key_move);
2876 }
2877 fn moved(&self, _: Point<Points>) {}
2878 fn pulled(&self, _: Points) {}
2879 fn relayout(&self) {}
2880 fn redraw(&self) {
2881 self.redraws.set(self.redraws.get() + 1);
2882 }
2883 fn attached(&self) -> bool {
2884 true
2885 }
2886 fn start_ticking(&self) {}
2887 }
2888
2889 #[test]
2890 fn a_key_scroll_tells_the_host_every_key_move() {
2891 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
2892 key_scroll(&host, KeyMove::End, false);
2893 key_scroll(&host, KeyMove::Pages(-1.0), false);
2894 assert_eq!(
2895 *host.key_moves.borrow(),
2896 [KeyMove::End, KeyMove::Pages(-1.0)]
2897 );
2898 assert!(matches!(
2899 host.state.borrow().live.phase,
2900 Phase::Animate { .. }
2901 ));
2902
2903 let mut row = scroll_state((100_000.0, 500.0), true);
2906 row.mirrored = true;
2907 row.x = Points(1000.0);
2908 let host = TestHost::new(row);
2909 key_scroll(&host, KeyMove::Points(KEY_LINE), true);
2910 assert_eq!(host.state.borrow().goal(), 1000.0 - KEY_LINE.0);
2911 assert_eq!(*host.key_moves.borrow(), [KeyMove::Points(KEY_LINE)]);
2912 }
2913
2914 #[test]
2915 fn wheel_notches_glide_and_add_up_where_the_scroll_is_headed() {
2916 let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
2917 let notch = |dy: f32| wheel_step(&host, pt(0.0, dy));
2918 notch(48.0);
2919 assert_eq!(host.state.borrow().y.0, 0.0);
2921 assert_eq!(host.state.borrow().goal(), 48.0);
2922 notch(48.0);
2924 assert_eq!(host.state.borrow().goal(), 96.0);
2925 frame(&host, WHEEL_STEP_ANIMATION);
2926 assert_eq!(host.state.borrow().y.0, 96.0);
2927 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2928 notch(-1000.0);
2930 assert_eq!(host.state.borrow().goal(), 0.0);
2931 frame(&host, WHEEL_STEP_ANIMATION);
2932 notch(-48.0);
2933 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2934
2935 let mut paging = scroll_state((300.0, 10_000.0), false);
2938 paging.behavior.paging = true;
2939 let host = TestHost::new(paging);
2940 wheel_step(&host, pt(0.0, 48.0));
2941 assert_eq!(host.state.borrow().y.0, 48.0);
2942 assert!(matches!(
2943 host.state.borrow().live.phase,
2944 Phase::Wheel { gesture: false, .. }
2945 ));
2946 }
2947
2948 #[test]
2949 fn smooth_wheel_notches_glide_on_chromiums_curve() {
2950 let mut smooth = scroll_state((300.0, 10_000.0), false);
2951 smooth.behavior.smooth_wheel = true;
2952 let host = TestHost::new(smooth);
2953 assert!(smooth_wheel(&host));
2954 wheel_smooth(&host, pt(0.0, 40.0));
2955 assert_eq!(host.state.borrow().y.0, 0.0);
2957 frame(&host, 60.0);
2958 let y = host.state.borrow().y.0;
2959 assert!(y > 0.0 && y < 40.0, "{y}");
2960 wheel_smooth(&host, pt(0.0, 40.0));
2962 assert!(matches!(
2963 host.state.borrow().live.phase,
2964 Phase::Wheel { gesture: false, raw, .. } if raw.y == 80.0
2965 ));
2966 let mut now = 60.0;
2968 while let Some(next) = deadline(&host, now) {
2969 now = next;
2970 frame(&host, now);
2971 }
2972 assert_eq!(host.state.borrow().y.0, 80.0);
2973 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2974
2975 let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
2978 assert!(!smooth_wheel(&host));
2979 let mut paging = scroll_state((300.0, 10_000.0), false);
2980 paging.behavior.smooth_wheel = true;
2981 paging.behavior.paging = true;
2982 assert!(!smooth_wheel(&TestHost::new(paging)));
2983 }
2984
2985 #[test]
2986 fn wheel_line_height_rescales_a_notch() {
2987 let mut lines = scroll_state((300.0, 10_000.0), false);
2988 let host = TestHost::new(lines.clone());
2989 assert_eq!(
2991 wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
2992 pt(0.0, 30.0)
2993 );
2994 lines.behavior.wheel_line_height = Points(40.0);
2995 let host = TestHost::new(lines);
2996 assert_eq!(
2998 wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
2999 pt(0.0, 120.0)
3000 );
3001 assert_eq!(
3003 wheel_line(&host, pt(25.0, 30.0), pt(25.0, 15.0)),
3004 pt(40.0, 80.0)
3005 );
3006 }
3007
3008 #[test]
3009 fn a_settled_touchpad_scroll_snaps_to_the_nearest_page() {
3010 let paged = || {
3012 let mut s = scroll_state((300.0, 5000.0), false);
3013 s.behavior.paging = true;
3014 s.y = Points(500.0);
3015 let host = TestHost::new(s);
3016 wheel_begin(&host);
3017 wheel(&host, pt(0.0, -60.0));
3019 host
3020 };
3021 let settle = |host: &TestHost| {
3022 let mut now = 0.0;
3023 while let Some(next) = deadline(host, now) {
3024 now = next;
3025 frame(host, now);
3026 }
3027 host.state.borrow().y.0
3028 };
3029 let host = paged();
3031 wheel_settle(&host);
3032 assert_eq!(settle(&host), 500.0);
3033 let host = paged();
3035 wheel_end(&host, 0.0, 0.0);
3036 assert_eq!(settle(&host), 0.0);
3037 }
3038
3039 #[test]
3040 fn a_glide_and_an_eased_move_end_at_their_deadlines() {
3041 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
3042 assert_eq!(deadline(&host, 0.0), None);
3043 for phase in [
3044 Phase::Glide {
3045 velocity: Offset::new(0.0, 2.0),
3046 last: 0.0,
3047 },
3048 Phase::Animate {
3049 from: Offset::default(),
3050 to: Offset::new(0.0, 400.0),
3051 start: 0.0,
3052 duration: ANIMATION,
3053 momentum: false,
3054 end: true,
3055 },
3056 ] {
3057 host.state.borrow_mut().y = Points(0.0);
3058 host.state.borrow_mut().live.phase = phase;
3059 let mut now = 0.0;
3060 let mut frames = 0;
3061 while let Some(next) = deadline(&host, now) {
3062 now = next;
3063 frame(&host, now);
3064 frames += 1;
3065 assert!(frames < 5, "{:?}", host.state.borrow().live.phase);
3066 }
3067 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3068 let y = host.state.borrow().y.0;
3069 match phase {
3070 Phase::Glide { .. } => assert!(
3072 (y - projected(Points(0.0), 2.0, 0.998).0).abs() < 6.0,
3073 "{y}"
3074 ),
3075 _ => assert_eq!(y, 400.0),
3076 }
3077 }
3078 }
3079
3080 #[test]
3081 fn indicator_follows_the_view_on_either_axis() {
3082 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3083 for horizontal in [false, true] {
3084 config(&host, horizontal, true, false, false);
3085 assert!(host.state.borrow().indicator);
3086 config(&host, horizontal, false, false, false);
3088 assert!(!host.state.borrow().indicator);
3089 config(&host, horizontal, true, true, false);
3091 assert!(!host.state.borrow().indicator);
3092 }
3093 }
3094
3095 #[test]
3096 fn switching_indicators_while_refreshing_keeps_the_new_room() {
3097 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3098 let own = ScrollBehavior {
3099 refresh_indicator: Some(Points(72.0)),
3100 ..Default::default()
3101 };
3102 behavior(&host, &own);
3103 refreshing(&host, true);
3104 frame(&host, 1000.0);
3105 assert_eq!(host.state.borrow().y, Points(-72.0));
3106 let redraws = host.redraws.get();
3108 behavior(&host, &ScrollBehavior::default());
3109 assert!(host.redraws.get() > redraws);
3110 frame(&host, 1000.0);
3111 assert_eq!(host.state.borrow().y, Points(-56.0));
3112 behavior(&host, &ScrollBehavior::default());
3114 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3115 }
3116
3117 fn zooming(content: (f32, f32)) -> TestHost {
3120 let mut s = scroll_state(content, false);
3121 s.can_zoom = true;
3122 s.behavior.min_zoom = 0.5;
3123 s.behavior.max_zoom = 4.0;
3124 TestHost::new(s)
3125 }
3126
3127 fn zoom_and_offset(host: &TestHost) -> (f32, f32, f32) {
3128 let s = host.state.borrow();
3129 (s.zoom, s.x.0, s.y.0)
3130 }
3131
3132 fn zoom_to(scale: f32, center: Option<Point<Points>>, animated: bool) -> Command {
3133 Command::ZoomTo {
3134 scale,
3135 center,
3136 animated,
3137 }
3138 }
3139
3140 #[test]
3141 fn only_a_backend_that_draws_zoomed_content_zooms() {
3142 let host = zooming((300.0, 500.0));
3143 host.state.borrow_mut().can_zoom = false;
3144 command(&host, &zoom_to(2.0, None, false));
3145 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3146 assert!(host.reports.borrow().is_empty());
3147 host.state.borrow_mut().can_zoom = true;
3149 command(&host, &zoom_to(2.0, None, false));
3150 assert_eq!(zoom_and_offset(&host), (2.0, 150.0, 250.0));
3151 assert_eq!(*host.reports.borrow(), ["zoom 2", "scroll 150 250"]);
3152 }
3153
3154 #[test]
3155 fn a_pinch_keeps_the_content_under_the_pointer_and_springs_back() {
3156 let host = zooming((300.0, 500.0));
3157 let size = sz(300.0, 500.0);
3158 let at = pt(100.0, 120.0);
3159 pinch_begin(&host);
3160 pinch(&host, 2.0, at);
3161 assert_eq!(zoom_and_offset(&host), (2.0, 100.0, 120.0));
3162 {
3163 let s = host.state.borrow();
3164 assert_eq!(s.to_viewport(size, at), at);
3165 assert_eq!(s.to_content(size, at), at);
3166 }
3167 pinch(&host, 6.0, at);
3169 let banded = host.state.borrow().zoom;
3170 assert!(banded > 4.0 && banded < 6.0, "{banded}");
3171 pinch_end(&host, at);
3172 frame(&host, ANIMATION);
3173 assert_eq!(zoom_and_offset(&host), (4.0, 300.0, 360.0));
3175 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3176 }
3177
3178 #[test]
3179 fn zoomed_content_pans_both_ways_without_a_bar() {
3180 let host = zooming((300.0, 500.0));
3181 host.state.borrow_mut().indicator = true;
3182 let size = sz(300.0, 500.0);
3183 assert!(!host.state.borrow().can_scroll(size, pt(10.0, 10.0)));
3184 command(&host, &zoom_to(2.0, Some(pt(0.0, 0.0)), false));
3185 assert_eq!(zoom_and_offset(&host), (2.0, 0.0, 0.0));
3187 let s = host.state.borrow().clone();
3188 assert!(s.can_scroll(size, pt(10.0, 0.0)) && s.can_scroll(size, pt(0.0, 10.0)));
3189 assert!(!s.can_scroll(size, pt(-10.0, -10.0)));
3190 assert!(s.thumb(size).is_none());
3191 wheel(&host, pt(30.0, 40.0));
3192 assert_eq!(zoom_and_offset(&host), (2.0, 30.0, 40.0));
3193 wheel(&host, pt(1000.0, 1000.0));
3195 assert_eq!(zoom_and_offset(&host), (2.0, 300.0, 500.0));
3196 wheel_begin(&host);
3198 wheel(&host, pt(-10.0, -10.0));
3199 wheel_end(&host, -1000.0, -500.0);
3200 let mut now = 0.0;
3201 while let Some(next) = deadline(&host, now) {
3202 now = next;
3203 frame(&host, now);
3204 }
3205 let (_, x, y) = zoom_and_offset(&host);
3206 assert!(x < 280.0 && y < 480.0 && x < y, "{x} {y}");
3207 }
3208
3209 #[test]
3210 fn zoom_to_eases_to_the_point_it_centers() {
3211 let host = zooming((300.0, 500.0));
3212 command(&host, &zoom_to(2.0, Some(pt(100.0, 200.0)), true));
3213 assert!(matches!(host.state.borrow().live.phase, Phase::Zoom { .. }));
3214 assert_eq!(deadline(&host, 0.0), Some(ANIMATION + 1.0));
3215 frame(&host, ANIMATION / 2.0);
3216 let half = host.state.borrow().zoom;
3217 assert!(half > 1.0 && half < 2.0, "{half}");
3218 frame(&host, ANIMATION);
3219 assert_eq!(zoom_and_offset(&host), (2.0, 50.0, 150.0));
3221 command(&host, &zoom_to(10.0, None, false));
3223 assert_eq!(host.state.borrow().zoom, 4.0);
3224 }
3225
3226 #[test]
3227 fn small_content_is_centered() {
3228 let host = zooming((300.0, 500.0));
3229 host.state.borrow_mut().behavior.center_content = true;
3230 command(&host, &zoom_to(0.5, None, false));
3231 let s = host.state.borrow();
3232 let size = sz(300.0, 500.0);
3233 assert_eq!(s.centered(size), pt(75.0, 125.0));
3234 assert_eq!(s.to_viewport(size, pt(0.0, 0.0)), pt(75.0, 125.0));
3235 assert_eq!(s.to_content(size, pt(75.0, 125.0)), pt(0.0, 0.0));
3236 assert_eq!((s.x.0, s.y.0), (0.0, 0.0));
3237 }
3238
3239 #[test]
3240 fn new_limits_clamp_the_zoom_and_a_view_that_zooms_no_more_is_back_at_1() {
3241 let host = zooming((300.0, 500.0));
3242 command(&host, &zoom_to(3.0, None, false));
3243 let mut b = host.state.borrow().behavior.clone();
3244 b.max_zoom = 2.0;
3245 behavior(&host, &b);
3246 assert_eq!(host.state.borrow().zoom, 2.0);
3247 b.max_zoom = 0.5;
3248 behavior(&host, &b);
3249 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3250 frame(&host, 0.0);
3251 let reports = host.reports.borrow();
3252 assert_eq!(reports[reports.len() - 2..], ["zoom 1", "scroll 0 0"]);
3253 }
3254}