1use std::f32::consts::PI;
39
40use crate::{
41 Bounds, Command, EventKind, EventPayload, NodeId, Point, Points, ScrollBehavior, Size,
42 StickyCell,
43 geometry::{Axis, Percentage, Radians, point},
44};
45
46const MIN_GLIDE: f32 = 0.05;
48const STOP: f32 = 0.01;
50const WHEEL_IDLE: f64 = 150.0;
52const INDICATOR_HOLD: f64 = 700.0;
54const INDICATOR_FADE: f64 = 300.0;
56const ANIMATION: f64 = 300.0;
58const WHEEL_SNAP: f32 = 0.6;
61const INDICATOR_MARGIN: f32 = 2.0;
63pub const INDICATOR_THICK: Points = Points(3.0);
65const THUMB_GRAB: f32 = 12.0;
68const THUMB_SLOP: f32 = 4.0;
70
71#[derive(Debug, Default, Clone, Copy, PartialEq)]
75struct Offset {
76 x: f32,
77 y: f32,
78}
79
80impl Offset {
81 const fn new(x: f32, y: f32) -> Self {
82 Self { x, y }
83 }
84
85 fn along(self, horizontal: bool) -> f32 {
86 if horizontal { self.x } else { self.y }
87 }
88
89 fn with(self, horizontal: bool, v: f32) -> Self {
91 if horizontal {
92 Self::new(v, self.y)
93 } else {
94 Self::new(self.x, v)
95 }
96 }
97
98 fn lerp(self, to: Self, k: f32) -> Self {
99 Self::new(self.x + (to.x - self.x) * k, self.y + (to.y - self.y) * k)
100 }
101
102 fn distance(self, to: Self) -> f32 {
104 (to.x - self.x).abs().max((to.y - self.y).abs())
105 }
106
107 fn clamp(self, (min, max): (Self, Self)) -> Self {
109 Self::new(
110 self.x.clamp(min.x, max.x.max(min.x)),
111 self.y.clamp(min.y, max.y.max(min.y)),
112 )
113 }
114}
115
116impl std::ops::Add for Offset {
117 type Output = Self;
118
119 fn add(self, o: Self) -> Self {
120 Self::new(self.x + o.x, self.y + o.y)
121 }
122}
123
124#[derive(Debug, Default, Clone, Copy, PartialEq)]
126enum Phase {
127 #[default]
129 Idle,
130 Drag { start: Offset, moved: Offset },
133 Thumb { start: f32 },
136 Wheel {
139 last: f64,
140 total: f32,
141 gesture: bool,
142 },
143 Glide { velocity: Offset, last: f64 },
145 Animate {
149 from: Offset,
150 to: Offset,
151 start: f64,
152 duration: f64,
153 momentum: bool,
154 end: bool,
155 },
156 Zoom {
161 from: f32,
162 to: f32,
163 from_c: Offset,
164 to_c: Offset,
165 at: Offset,
166 start: f64,
167 duration: f64,
168 },
169}
170
171#[derive(Debug, Default, Clone)]
174#[non_exhaustive]
175pub struct Live {
176 phase: Phase,
177 ticking: bool,
179 report: bool,
181 shown: f64,
183 pub alpha: f32,
185 pub refreshing: bool,
187 pub spin: Radians,
189 pub dark: bool,
192 pinch_from: f32,
194 reported_zoom: f32,
196 rezoomed: bool,
198}
199
200#[derive(Debug, Clone)]
202#[non_exhaustive]
203pub struct ScrollState {
204 pub x: Points,
207 pub y: Points,
209 pub content: Size<Points>,
211 pub zoom: f32,
213 pub can_zoom: bool,
216 pub horizontal: bool,
218 pub indicator: bool,
220 pub behavior: ScrollBehavior,
222 pub applied: u32,
225 pub sticky: Vec<StickyCell>,
227 pub mirrored: bool,
230 pub live: Live,
232}
233
234impl Default for ScrollState {
235 fn default() -> Self {
236 Self {
237 x: Points::ZERO,
238 y: Points::ZERO,
239 content: Size::default(),
240 zoom: 1.0,
241 can_zoom: false,
242 horizontal: false,
243 indicator: false,
244 behavior: ScrollBehavior::default(),
245 applied: 0,
246 sticky: Vec::new(),
247 mirrored: false,
248 live: Live::default(),
249 }
250 }
251}
252
253pub trait ScrollHost {
256 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R>;
259 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R>;
261 fn now(&self) -> f64;
263 fn listens(&self, kind: EventKind) -> bool;
265 fn event(&self, kind: EventKind, payload: EventPayload);
267 fn report(&self, offset: Point<Points>, applied: u32);
270 fn report_zoom(&self, scale: f32) {
273 let _ = scale;
274 }
275 fn key_scrolled(&self, key_move: KeyMove) {
279 let _ = key_move;
280 }
281 fn moved(&self, offset: Point<Points>);
285 fn pulled(&self, distance: Points);
288 fn relayout(&self);
290 fn redraw(&self);
292 fn attached(&self) -> bool;
294 fn start_ticking(&self);
296 fn settled(&self) {}
300 fn dark(&self) -> bool {
303 false
304 }
305}
306
307fn rubber(over: f32, dim: f32) -> f32 {
312 let dim = dim.max(1.0);
313 (1.0 - 1.0 / (over * 0.55 / dim + 1.0)) * dim
314}
315
316pub fn dragged(raw: Points, min: Points, max: Points, dim: Points, bounces: bool) -> Points {
319 Points(drag_position(raw.0, min.0, max.0, dim.0, bounces))
320}
321
322fn drag_position(raw: f32, min: f32, max: f32, dim: f32, bounces: bool) -> f32 {
323 if raw < min {
324 if bounces {
325 min - rubber(min - raw, dim)
326 } else {
327 min
328 }
329 } else if raw > max {
330 if bounces {
331 max + rubber(raw - max, dim)
332 } else {
333 max
334 }
335 } else {
336 raw
337 }
338}
339
340pub fn rate(behavior: &ScrollBehavior) -> f32 {
342 if behavior.deceleration > 0.0 && behavior.deceleration < 1.0 {
343 behavior.deceleration
344 } else if behavior.snaps() || behavior.paging {
345 0.99
346 } else {
347 0.998
348 }
349}
350
351fn glide_step(v: f32, rate: f32, dt: f32) -> (f32, f32) {
354 let k = rate.powf(dt);
355 (v * (k - 1.0) / rate.ln(), v * k)
356}
357
358pub fn projected(offset: Points, velocity: f32, rate: f32) -> Points {
361 Points(offset.0 - velocity / rate.ln())
362}
363
364pub fn sticky_shift(offset: Points, start: Points, end: Points) -> Points {
367 Points((offset.0 - start.0).clamp(0.0, (end.0 - start.0).max(0.0)))
368}
369
370pub fn ease_out(t: f64) -> f32 {
372 let t = t.clamp(0.0, 1.0);
373 (1.0 - (1.0 - t).powi(3)) as f32
374}
375
376pub fn snap_duration(distance: Points, velocity: f32) -> f64 {
380 let (distance, v) = (distance.0, velocity);
381 if distance.abs() < 0.5 {
382 return 0.0;
383 }
384 if v * distance > 0.0 {
385 (3.0 * distance.abs() / v.abs()).clamp(180.0, 600.0) as f64
386 } else {
387 ANIMATION
388 }
389}
390
391pub fn indicator_alpha(since: f64) -> f32 {
393 if since < INDICATOR_HOLD {
394 1.0
395 } else {
396 (1.0 - (since - INDICATOR_HOLD) / INDICATOR_FADE).max(0.0) as f32
397 }
398}
399
400pub fn indicator_span(viewport: Points, total: Points, offset: Points) -> Option<(Points, Points)> {
404 span(viewport.0, total.0, offset.0).map(|(start, len)| (Points(start), Points(len)))
405}
406
407fn span(viewport: f32, total: f32, offset: f32) -> Option<(f32, f32)> {
408 const MIN_LENGTH: f32 = 32.0;
410 if total <= viewport + 0.5 || viewport <= 4.0 * INDICATOR_MARGIN {
411 return None;
412 }
413 let track = viewport - 2.0 * INDICATOR_MARGIN;
414 let max = total - viewport;
415 let over = if offset < 0.0 {
417 -offset
418 } else {
419 (offset - max).max(0.0)
420 };
421 let len = (track * viewport / total - over).max(MIN_LENGTH).min(track);
422 let t = (offset / max).clamp(0.0, 1.0);
423 Some((INDICATOR_MARGIN + (track - len) * t, len))
424}
425
426pub fn thumb_scroll(d: Points, range: Points, travel: Points) -> Points {
429 if travel.0 > 0.0 {
430 Points(d.0 * range.0 / travel.0)
431 } else {
432 Points(0.0)
433 }
434}
435
436fn shifted(phase: Phase, d: Offset, horizontal: bool) -> Phase {
440 match phase {
441 Phase::Drag { start, moved } => Phase::Drag {
442 start: start + d,
443 moved,
444 },
445 Phase::Thumb { start } => Phase::Thumb {
446 start: start + d.along(horizontal),
447 },
448 Phase::Animate {
449 from,
450 to,
451 start,
452 duration,
453 momentum,
454 end,
455 } => Phase::Animate {
456 from: from + d,
457 to: to + d,
458 start,
459 duration,
460 momentum,
461 end,
462 },
463 other => other,
464 }
465}
466
467pub fn spokes(progress: Percentage, spin: Radians) -> impl Iterator<Item = (Radians, f32)> {
472 const SPOKES: usize = 8;
473 let (progress, spin) = (progress.0, spin.0);
474 let shown = ((progress * SPOKES as f32).ceil() as usize).min(SPOKES);
475 let step = 2.0 * PI / SPOKES as f32;
476 let lead = (spin / step) as usize % SPOKES;
477 (0..shown).map(move |i| {
478 let fade = if progress < 1.0 {
479 0.8
480 } else {
481 1.0 - ((lead + SPOKES - i) % SPOKES) as f32 / SPOKES as f32 * 0.85
482 };
483 (Radians(i as f32 * step), fade)
484 })
485}
486
487pub fn reading_order<T>(axis: Axis, children: &mut [T], origin: impl Fn(&T) -> Point<Points>) {
496 if children.len() < 2 {
497 return;
498 }
499 let key = |child: &T| {
500 let at = origin(child);
501 match axis {
502 Axis::Horizontal => (at.x.0, at.y.0),
503 Axis::Vertical => (at.y.0, at.x.0),
504 }
505 };
506 children.sort_by(|a, b| {
507 let (a, b) = (key(a), key(b));
508 a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
509 });
510}
511
512impl ScrollState {
515 pub fn max(&self, size: Size<Points>) -> Point<Points> {
517 let (x, y) = self.max_f(size);
518 point(Points(x), Points(y))
519 }
520
521 fn max_f(&self, size: Size<Points>) -> (f32, f32) {
522 let inset = self.behavior.content_inset;
523 let z = self.zoom;
524 (
525 (self.content.width.0 * z + inset.left.0 + inset.right.0 - size.width.0).max(0.0),
526 (self.content.height.0 * z + inset.top.0 + inset.bottom.0 - size.height.0).max(0.0),
527 )
528 }
529
530 pub fn origin(&self) -> Point<Points> {
534 let inset = self.behavior.content_inset;
535 point(self.x - inset.left, self.y - inset.top)
536 }
537
538 pub fn zooms(&self) -> bool {
542 self.can_zoom && self.behavior.zooms()
543 }
544
545 pub fn centered(&self, size: Size<Points>) -> Point<Points> {
549 if !self.zooms() || !self.behavior.center_content {
550 return Point::default();
551 }
552 let inset = self.behavior.content_inset;
553 let free = |viewport: f32, content: f32| ((viewport - content * self.zoom) / 2.0).max(0.0);
554 point(
555 Points(free(
556 size.width.0 - inset.left.0 - inset.right.0,
557 self.content.width.0,
558 )),
559 Points(free(
560 size.height.0 - inset.top.0 - inset.bottom.0,
561 self.content.height.0,
562 )),
563 )
564 }
565
566 pub fn to_viewport(&self, size: Size<Points>, content: Point<Points>) -> Point<Points> {
569 let (o, room) = (self.origin(), self.centered(size));
570 point(
571 Points(content.x.0 * self.zoom - o.x.0 + room.x.0),
572 Points(content.y.0 * self.zoom - o.y.0 + room.y.0),
573 )
574 }
575
576 pub fn to_content(&self, size: Size<Points>, at: Point<Points>) -> Point<Points> {
579 let (o, room) = (self.origin(), self.centered(size));
580 point(
581 Points((at.x.0 + o.x.0 - room.x.0) / self.zoom),
582 Points((at.y.0 + o.y.0 - room.y.0) / self.zoom),
583 )
584 }
585
586 fn offset(&self) -> f32 {
588 if self.horizontal { self.x.0 } else { self.y.0 }
589 }
590
591 fn pos(&self) -> Offset {
593 Offset::new(self.x.0, self.y.0)
594 }
595
596 fn range(&self, size: Size<Points>) -> (Offset, Offset) {
600 let (min, max) = self.limits(size);
601 if self.zooms() {
602 let (mx, my) = self.max_f(size);
603 let top = if self.horizontal { 0.0 } else { min };
605 (Offset::new(0.0, top), Offset::new(mx, my))
606 } else {
607 let zero = Offset::default();
608 (
609 zero.with(self.horizontal, min),
610 zero.with(self.horizontal, max),
611 )
612 }
613 }
614
615 fn content_at(&self, size: Size<Points>, at: Offset) -> Offset {
617 let c = self.to_content(size, point(Points(at.x), Points(at.y)));
618 Offset::new(c.x.0, c.y.0)
619 }
620
621 fn showing(&self, size: Size<Points>, c: Offset, at: Offset) -> Offset {
624 let inset = self.behavior.content_inset;
625 let room = self.centered(size);
626 Offset::new(
627 c.x * self.zoom + room.x.0 - at.x + inset.left.0,
628 c.y * self.zoom + room.y.0 - at.y + inset.top.0,
629 )
630 .clamp(self.range(size))
631 }
632
633 fn goal(&self) -> f32 {
636 match self.live.phase {
637 Phase::Animate { to, .. } => to.along(self.horizontal),
638 _ => self.offset(),
639 }
640 }
641
642 fn viewport(&self, size: Size<Points>) -> f32 {
644 if self.horizontal {
645 size.width.0
646 } else {
647 size.height.0
648 }
649 }
650
651 fn lead(&self) -> f32 {
653 if self.horizontal {
654 self.behavior.content_inset.left.0
655 } else {
656 self.behavior.content_inset.top.0
657 }
658 }
659
660 fn limits(&self, size: Size<Points>) -> (f32, f32) {
663 let max = self.max_f(size);
664 let min = if !self.horizontal && self.live.refreshing {
665 -self.behavior.refresh_inset().0
666 } else {
667 0.0
668 };
669 (min, if self.horizontal { max.0 } else { max.1 })
670 }
671
672 pub fn reported(&self, size: Size<Points>) -> Point<Points> {
675 let (mx, my) = self.max_f(size);
676 let inset = self.behavior.content_inset;
677 point(
678 Points(self.x.0.clamp(0.0, mx) - inset.left.0),
679 Points(self.y.0.clamp(0.0, my) - inset.top.0),
680 )
681 }
682
683 pub fn can_scroll(&self, size: Size<Points>, delta: Point<Points>) -> bool {
688 let (dx, dy) = (delta.x.0, delta.y.0);
689 if !self.behavior.enabled {
690 return false;
691 }
692 if self.zooms() {
693 let ((min, max), p) = (self.range(size), self.pos());
694 let can = |d: f32, p: f32, min: f32, max: f32| {
695 (d > 0.0 && p < max - 0.5) || (d < 0.0 && p > min + 0.5)
696 };
697 return can(dx, p.x, min.x, max.x) || can(dy, p.y, min.y, max.y);
698 }
699 let (min, max) = self.limits(size);
700 if max <= min {
701 return false;
702 }
703 let d = if self.horizontal {
704 let d = if dx != 0.0 { dx } else { dy };
705 if self.mirrored && dx != 0.0 { -d } else { d }
706 } else {
707 dy
708 };
709 let pos = self.offset();
710 (d > 0.0 && pos < max - 0.5) || (d < 0.0 && pos > min + 0.5)
711 }
712
713 pub fn thumb(&self, size: Size<Points>) -> Option<(Bounds<Points>, Points)> {
716 self.thumb_within(
717 size,
718 Bounds {
719 origin: Point::default(),
720 size,
721 },
722 )
723 }
724
725 pub fn thumb_within(
732 &self,
733 size: Size<Points>,
734 visible: Bounds<Points>,
735 ) -> Option<(Bounds<Points>, Points)> {
736 let (rect, travel) = self.thumb_f(size, visible)?;
737 Some((rect, Points(travel)))
738 }
739
740 fn visible_edges(size: Size<Points>, visible: Bounds<Points>) -> Option<(f32, f32)> {
743 let (w, h) = (size.width.0, size.height.0);
744 let left = visible.origin.x.0.max(0.0);
745 let top = visible.origin.y.0.max(0.0);
746 let right = (visible.origin.x.0 + visible.size.width.0).min(w);
747 let bottom = (visible.origin.y.0 + visible.size.height.0).min(h);
748 (right > left && bottom > top).then_some((right, bottom))
749 }
750
751 fn thumb_f(
752 &self,
753 size: Size<Points>,
754 visible: Bounds<Points>,
755 ) -> Option<(Bounds<Points>, f32)> {
756 const EDGE: f32 = 2.0;
757 if self.zooms() {
759 return None;
760 }
761 let thick = INDICATOR_THICK.0;
762 let (w, h) = (size.width.0, size.height.0);
763 let (right, bottom) = Self::visible_edges(size, visible)?;
764 let inset = self.behavior.content_inset;
765 let (dim, total, offset) = if self.horizontal {
766 (
767 w,
768 self.content.width.0 + inset.left.0 + inset.right.0,
769 self.x.0,
770 )
771 } else {
772 (
773 h,
774 self.content.height.0 + inset.top.0 + inset.bottom.0,
775 self.y.0,
776 )
777 };
778 let (start, len) = span(dim, total, offset)?;
779 let (x, y, rw, rh) = if self.horizontal {
780 let x = if self.mirrored {
781 w - start - len
782 } else {
783 start
784 };
785 (x, bottom - thick - EDGE, len, thick)
786 } else {
787 (right - thick - EDGE, start, thick, len)
788 };
789 let rect = Bounds {
790 origin: point(Points(x), Points(y)),
791 size: Size {
792 width: Points(rw),
793 height: Points(rh),
794 },
795 };
796 Some((rect, dim - 2.0 * INDICATOR_MARGIN - len))
797 }
798
799 pub fn grabs_thumb(&self, size: Size<Points>, at: Point<Points>) -> bool {
803 self.grabs_thumb_within(
804 size,
805 Bounds {
806 origin: Point::default(),
807 size,
808 },
809 at,
810 )
811 }
812
813 pub fn grabs_thumb_within(
817 &self,
818 size: Size<Points>,
819 visible: Bounds<Points>,
820 at: Point<Points>,
821 ) -> bool {
822 let (x, y) = (at.x.0, at.y.0);
823 if !self.indicator || !self.behavior.enabled {
824 return false;
825 }
826 let Some((rect, _)) = self.thumb_f(size, visible) else {
827 return false;
828 };
829 let Some((right, bottom)) = Self::visible_edges(size, visible) else {
830 return false;
831 };
832 let (along, across, start, len, edge) = if self.horizontal {
833 (x, y, rect.origin.x.0, rect.size.width.0, bottom)
834 } else {
835 (y, x, rect.origin.y.0, rect.size.height.0, right)
836 };
837 (edge - THUMB_GRAB..=edge).contains(&across)
838 && (start - THUMB_SLOP..=start + len + THUMB_SLOP).contains(&along)
839 }
840
841 pub fn indicates(&self) -> bool {
844 (self.indicator && self.live.alpha > 0.0) || self.y.0 < 0.0
845 }
846
847 pub fn spinner(&self, width: Points, refresh: bool) -> Option<(Point<Points>, Percentage)> {
852 let y = self.y.0;
853 let b = &self.behavior;
854 if self.horizontal
855 || y >= 0.0
856 || b.refresh_indicator.is_some()
857 || !(self.live.refreshing || refresh)
858 {
859 return None;
860 }
861 let progress = if self.live.refreshing {
862 1.0
863 } else {
864 (-y / b.refresh_threshold().0).min(1.0)
865 };
866 let cy = b.content_inset.top.0 - y - b.refresh_inset().0 / 2.0;
867 Some((point(width / 2.0, Points(cy)), Percentage(progress)))
868 }
869
870 pub fn sticky_shifts(&self) -> impl Iterator<Item = (NodeId, Point<Points>)> + '_ {
872 self.sticky_shifts_with(|_| 0.0)
873 }
874
875 pub fn sticky_shifts_with<'a>(
878 &'a self,
879 value: impl Fn(crate::animation::NodeId) -> f32 + 'a,
880 ) -> impl Iterator<Item = (NodeId, Point<Points>)> + 'a {
881 let offset = Points(self.offset() - self.lead());
882 self.sticky.iter().map(move |c| {
883 let extra = c.offset.map_or(0.0, &value);
884 let t = sticky_shift(Points(offset.0 + extra), c.start, c.end);
885 let zero = Points(0.0);
886 (
887 c.cell,
888 if self.horizontal {
889 point(t, zero)
890 } else {
891 point(zero, t)
892 },
893 )
894 })
895 }
896}
897
898fn phase(host: &impl ScrollHost) -> Phase {
901 host.scroll(|s, _| s.live.phase).unwrap_or(Phase::Idle)
902}
903
904fn set_phase(host: &impl ScrollHost, phase: Phase) {
905 host.scroll_mut(|s, _| s.live.phase = phase);
906}
907
908fn enabled(host: &impl ScrollHost) -> bool {
910 host.scroll(|s, _| s.behavior.enabled).unwrap_or(false)
911}
912
913fn emit(host: &impl ScrollHost, kind: EventKind) {
915 if kind == EventKind::ScrollEnd {
916 host.settled();
917 }
918 if !host.listens(kind) {
919 return;
920 }
921 let offset = host.scroll(|s, size| s.reported(size)).unwrap_or_default();
922 host.event(kind, EventPayload::Scroll(offset));
923}
924
925fn interrupt(host: &impl ScrollHost) {
928 let momentum = matches!(
929 phase(host),
930 Phase::Glide { .. } | Phase::Animate { momentum: true, .. }
931 );
932 set_phase(host, Phase::Idle);
933 if momentum {
934 emit(host, EventKind::MomentumEnd);
935 }
936}
937
938fn moved_to(host: &impl ScrollHost, to: Offset) {
943 let moved = host.scroll_mut(|s, size| {
944 let rezoomed = std::mem::take(&mut s.live.rezoomed);
945 if s.pos() == to && !rezoomed {
946 return None;
947 }
948 let pulled =
950 (!s.horizontal && (s.y.0 < 0.0 || to.y < 0.0)).then(|| Points((-to.y).max(0.0)));
951 (s.x, s.y) = (Points(to.x), Points(to.y));
952 if s.indicator {
953 s.live.shown = host.now();
954 s.live.alpha = 1.0;
955 s.live.dark = host.dark();
956 }
957 s.live.report = true;
958 Some((s.reported(size), pulled))
959 });
960 let Some(Some((offset, pulled))) = moved else {
961 return;
962 };
963 host.moved(offset);
964 if let Some(distance) = pulled {
965 host.pulled(distance);
966 }
967 if host.attached() {
968 ensure_ticking(host);
969 } else {
970 report(host);
972 }
973}
974
975fn moved_along(host: &impl ScrollHost, pos: f32) {
977 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, pos)) {
978 moved_to(host, to);
979 }
980}
981
982fn report(host: &impl ScrollHost) {
983 let pending = host.scroll_mut(|s, size| {
984 if !std::mem::take(&mut s.live.report) {
985 return None;
986 }
987 let known = s.zooms() || s.live.reported_zoom != 0.0;
990 let zoom = (known && s.zoom != s.live.reported_zoom).then(|| {
991 s.live.reported_zoom = s.zoom;
992 s.zoom
993 });
994 Some((s.reported(size), s.applied, zoom))
995 });
996 if let Some(Some((offset, applied, zoom))) = pending {
997 if let Some(zoom) = zoom {
998 host.report_zoom(zoom);
999 }
1000 host.report(offset, applied);
1001 }
1002}
1003
1004fn animate_to(host: &impl ScrollHost, to: Offset, duration: f64, momentum: bool, end: bool) {
1006 let Some((from, to)) = host.scroll(|s, size| (s.pos(), to.clamp(s.range(size)))) else {
1007 return;
1008 };
1009 if from.distance(to) < 0.5 || duration <= 0.0 {
1010 set_phase(host, Phase::Idle);
1011 moved_to(host, to);
1012 if momentum {
1013 emit(host, EventKind::MomentumEnd);
1014 }
1015 if end {
1016 emit(host, EventKind::ScrollEnd);
1017 }
1018 return;
1019 }
1020 set_phase(
1021 host,
1022 Phase::Animate {
1023 from,
1024 to,
1025 start: host.now(),
1026 duration,
1027 momentum,
1028 end,
1029 },
1030 );
1031 ensure_ticking(host);
1032}
1033
1034fn animate_along(host: &impl ScrollHost, to: f32, duration: f64, momentum: bool, end: bool) {
1036 if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, to)) {
1037 animate_to(host, to, duration, momentum, end);
1038 }
1039}
1040
1041fn release(host: &impl ScrollHost, v: Offset, snap_velocity: f32) {
1045 let Some((pos, (min, max), main, target)) = host.scroll(|s, size| {
1046 let range = s.range(size);
1047 let pos = s.pos();
1048 let main = v.along(s.horizontal);
1049 let lead = s.lead();
1050 let dim = s.viewport(size);
1051 let snap_velocity = if snap_velocity == 0.0 {
1052 main
1053 } else {
1054 snap_velocity
1055 };
1056 let max = range.1.along(s.horizontal);
1057 let target = s
1060 .behavior
1061 .snap_target(
1062 Points(s.offset() - lead),
1063 projected(Points(s.offset()), main, rate(&s.behavior)) - Points(lead),
1064 snap_velocity,
1065 Points(dim),
1066 Points(max + dim - lead),
1067 )
1068 .filter(|_| !s.zooms())
1069 .map(|t| (pos.with(s.horizontal, t.0 + lead), t.0 + lead - s.offset()));
1070 (pos, range, main, target)
1071 }) else {
1072 return;
1073 };
1074 let past = |p: f32, min: f32, max: f32| p < min - 0.5 || p > max + 0.5;
1075 let room = |v: f32, p: f32, min: f32, max: f32| v > 0.0 && p < max || v < 0.0 && p > min;
1076 if past(pos.x, min.x, max.x) || past(pos.y, min.y, max.y) {
1077 animate_to(host, pos.clamp((min, max)), ANIMATION, false, true);
1078 } else if let Some((target, distance)) = target {
1079 let duration = snap_duration(Points(distance), main);
1080 if duration > 0.0 {
1081 emit(host, EventKind::MomentumStart);
1082 }
1083 animate_to(host, target, duration, duration > 0.0, true);
1084 } else if v.x.abs().max(v.y.abs()) > MIN_GLIDE
1085 && (room(v.x, pos.x, min.x, max.x) || room(v.y, pos.y, min.y, max.y))
1086 {
1087 set_phase(
1088 host,
1089 Phase::Glide {
1090 velocity: v,
1091 last: host.now(),
1092 },
1093 );
1094 emit(host, EventKind::MomentumStart);
1095 ensure_ticking(host);
1096 } else {
1097 set_phase(host, Phase::Idle);
1098 emit(host, EventKind::ScrollEnd);
1099 }
1100}
1101
1102fn ensure_ticking(host: &impl ScrollHost) {
1105 let start = host.scroll_mut(|s, _| !std::mem::replace(&mut s.live.ticking, true));
1106 if start == Some(true) {
1107 host.start_ticking();
1108 }
1109}
1110
1111pub fn frame(host: &impl ScrollHost, now: f64) -> bool {
1114 let busy = tick(host, now);
1115 if !busy {
1116 host.scroll_mut(|s, _| s.live.ticking = false);
1117 }
1118 busy
1119}
1120
1121pub fn deadline(host: &impl ScrollHost, now: f64) -> Option<f64> {
1128 let (phase, rate) = host.scroll(|s, _| (s.live.phase, rate(&s.behavior)))?;
1129 let end = match phase {
1130 Phase::Glide { velocity, last } => {
1131 let speed = velocity.x.abs().max(velocity.y.abs());
1133 if speed < STOP || !(0.0..1.0).contains(&rate) {
1134 last
1135 } else {
1136 last + ((STOP / speed).ln() / rate.ln()).max(0.0) as f64
1137 }
1138 }
1139 Phase::Animate {
1140 start, duration, ..
1141 }
1142 | Phase::Zoom {
1143 start, duration, ..
1144 } => start + duration,
1145 Phase::Wheel {
1146 last,
1147 gesture: false,
1148 ..
1149 } => last + WHEEL_IDLE,
1150 _ => return None,
1151 };
1152 Some(end.max(now) + 1.0)
1155}
1156
1157pub fn detached(host: &impl ScrollHost) {
1160 set_phase(host, Phase::Idle);
1161 report(host);
1162 host.scroll_mut(|s, _| s.live.ticking = false);
1163}
1164
1165fn tick(host: &impl ScrollHost, now: f64) -> bool {
1166 let Some((phase, pos, rate, (min, max))) =
1167 host.scroll(|s, size| (s.live.phase, s.pos(), rate(&s.behavior), s.range(size)))
1168 else {
1169 return false;
1170 };
1171 match phase {
1172 Phase::Glide { velocity, last } => {
1173 let dt = (now - last).max(0.0) as f32;
1174 let axis = |v: f32, p: f32, min: f32, max: f32| {
1177 let (d, v) = glide_step(v, rate, dt);
1178 let next = p + d;
1179 let stopped = v.abs() < STOP || next <= min || next >= max;
1180 (next, if stopped { 0.0 } else { v }, stopped)
1181 };
1182 let (x, vx, stop_x) = axis(velocity.x, pos.x, min.x, max.x);
1183 let (y, vy, stop_y) = axis(velocity.y, pos.y, min.y, max.y);
1184 moved_to(host, Offset::new(x, y).clamp((min, max)));
1185 if stop_x && stop_y {
1186 set_phase(host, Phase::Idle);
1187 emit(host, EventKind::MomentumEnd);
1188 emit(host, EventKind::ScrollEnd);
1189 } else {
1190 set_phase(
1191 host,
1192 Phase::Glide {
1193 velocity: Offset::new(vx, vy),
1194 last: now,
1195 },
1196 );
1197 }
1198 }
1199 Phase::Animate {
1200 from,
1201 to,
1202 start,
1203 duration,
1204 momentum,
1205 end,
1206 } => {
1207 let t = (now - start) / duration;
1208 moved_to(host, from.lerp(to, ease_out(t)));
1209 if t >= 1.0 {
1210 set_phase(host, Phase::Idle);
1211 if momentum {
1212 emit(host, EventKind::MomentumEnd);
1213 }
1214 if end {
1215 emit(host, EventKind::ScrollEnd);
1216 }
1217 }
1218 }
1219 Phase::Zoom {
1220 from,
1221 to,
1222 from_c,
1223 to_c,
1224 at,
1225 start,
1226 duration,
1227 } => {
1228 let t = (now - start) / duration;
1229 let k = ease_out(t);
1230 zoom_at(host, from + (to - from) * k, from_c.lerp(to_c, k), at);
1231 if t >= 1.0 {
1232 set_phase(host, Phase::Idle);
1233 }
1234 }
1235 Phase::Wheel {
1236 last,
1237 total,
1238 gesture: false,
1239 } if now - last > WHEEL_IDLE => {
1240 set_phase(host, Phase::Idle);
1243 let snaps = host
1244 .scroll(|s, _| s.behavior.snaps() || s.behavior.paging)
1245 .unwrap_or(false);
1246 if snaps {
1247 let v = if total.abs() >= 1.0 {
1248 total.signum() * WHEEL_SNAP
1249 } else {
1250 0.0
1251 };
1252 release(host, Offset::default(), v);
1253 } else {
1254 emit(host, EventKind::ScrollEnd);
1255 }
1256 }
1257 Phase::Idle if pos.x > max.x.max(min.x) + 0.5 || pos.y > max.y.max(min.y) + 0.5 => {
1258 moved_to(
1259 host,
1260 Offset::new(pos.x.min(max.x.max(min.x)), pos.y.min(max.y.max(min.y))),
1261 )
1262 }
1263 _ => {}
1264 }
1265 report(host);
1266 let Some((busy, redraw)) = host.scroll_mut(|s, _| {
1267 let mut redraw = false;
1268 let mut busy = !matches!(
1269 s.live.phase,
1270 Phase::Idle
1271 | Phase::Drag { .. }
1272 | Phase::Thumb { .. }
1273 | Phase::Wheel { gesture: true, .. }
1274 );
1275 if matches!(s.live.phase, Phase::Thumb { .. }) {
1276 s.live.shown = now;
1278 } else if s.live.alpha > 0.0 {
1279 let alpha = indicator_alpha(now - s.live.shown);
1280 if alpha != s.live.alpha {
1281 s.live.alpha = alpha;
1282 redraw = true;
1283 }
1284 busy |= alpha > 0.0;
1285 }
1286 if !s.horizontal
1287 && s.offset() < 0.0
1288 && s.live.refreshing
1289 && s.behavior.refresh_indicator.is_none()
1290 {
1291 s.live.spin = Radians(((now / 1000.0) as f32 * 2.0 * PI) % (2.0 * PI));
1292 redraw = true;
1293 busy = true;
1294 }
1295 (busy, redraw)
1296 }) else {
1297 return false;
1298 };
1299 if redraw {
1300 host.redraw();
1301 }
1302 busy
1303}
1304
1305pub fn config(
1309 host: &impl ScrollHost,
1310 horizontal: bool,
1311 indicator: bool,
1312 replaced: bool,
1313 mirrored: bool,
1314) {
1315 let changed = host.scroll_mut(|s, _| {
1316 s.horizontal = horizontal;
1317 s.indicator = indicator && !replaced;
1323 if !indicator {
1324 s.live.alpha = 0.0;
1325 }
1326 let mirrored = mirrored && horizontal;
1327 std::mem::replace(&mut s.mirrored, mirrored) != mirrored
1328 });
1329 if changed == Some(true) {
1330 host.relayout();
1331 }
1332}
1333
1334pub fn content(host: &impl ScrollHost, content: Size<Points>) {
1338 let Some((past, zooms)) = host.scroll_mut(|s, size| {
1339 s.content = content;
1340 let (p, (min, max)) = (s.pos(), s.range(size));
1341 (
1342 p.x > max.x.max(min.x) + 0.5 || p.y > max.y.max(min.y) + 0.5,
1343 s.zooms(),
1344 )
1345 }) else {
1346 return;
1347 };
1348 if zooms {
1349 host.relayout();
1351 }
1352 if past {
1353 ensure_ticking(host);
1354 }
1355 host.redraw();
1356}
1357
1358pub fn scroll_by(host: &impl ScrollHost, delta: Point<Points>) {
1361 let (dx, dy) = (delta.x.0, delta.y.0);
1362 let Some((pos, d)) = host.scroll_mut(|s, _| {
1363 s.applied = s.applied.wrapping_add(1);
1364 let d = if s.zooms() {
1367 Offset::new(dx, dy)
1368 } else {
1369 Offset::default().with(s.horizontal, if s.horizontal { dx } else { dy })
1370 };
1371 s.live.phase = shifted(s.live.phase, d, s.horizontal);
1372 s.live.report = true;
1373 (s.pos(), d)
1374 }) else {
1375 return;
1376 };
1377 if d != Offset::default() {
1378 moved_to(host, pos + d);
1379 }
1380 report(host);
1381}
1382
1383pub fn behavior(host: &impl ScrollHost, behavior: &ScrollBehavior) {
1385 let Some((inset, refresh, held, zoom)) = host.scroll_mut(|s, _| {
1386 let inset = s.behavior.content_inset != behavior.content_inset
1388 || s.can_zoom
1389 && (s.behavior.zooms() != behavior.zooms()
1390 || s.behavior.center_content != behavior.center_content);
1391 let refresh = s.behavior.refresh_indicator != behavior.refresh_indicator;
1392 s.behavior = behavior.clone();
1393 let zoom = if s.zooms() {
1395 limit_zoom(behavior, s.zoom, false)
1396 } else {
1397 1.0
1398 };
1399 if !behavior.enabled
1400 && matches!(
1401 s.live.phase,
1402 Phase::Drag { .. } | Phase::Thumb { .. } | Phase::Wheel { .. }
1403 )
1404 {
1405 s.live.phase = Phase::Idle;
1406 }
1407 let held = (refresh
1409 && !s.horizontal
1410 && s.live.refreshing
1411 && s.offset() < 0.0
1412 && !matches!(s.live.phase, Phase::Drag { .. }))
1413 .then(|| behavior.refresh_inset().0);
1414 (inset, refresh, held, (zoom != s.zoom).then_some(zoom))
1415 }) else {
1416 return;
1417 };
1418 if let Some(zoom) = zoom {
1419 zoom_to(host, zoom, None, false);
1420 }
1421 if inset {
1422 host.relayout();
1423 }
1424 if refresh {
1425 host.redraw();
1426 }
1427 if let Some(room) = held {
1428 animate_along(host, -room, ANIMATION, false, false);
1429 }
1430}
1431
1432pub fn refreshing(host: &impl ScrollHost, refreshing: bool) {
1435 let Some(Some((pos, dragging, inset))) = host.scroll_mut(|s, _| {
1436 if s.horizontal || s.live.refreshing == refreshing {
1437 return None;
1438 }
1439 s.live.refreshing = refreshing;
1440 Some((
1441 s.offset(),
1442 matches!(s.live.phase, Phase::Drag { .. }),
1443 s.behavior.refresh_inset().0,
1444 ))
1445 }) else {
1446 return;
1447 };
1448 host.redraw();
1449 if dragging {
1450 return;
1451 }
1452 if refreshing && pos <= 0.5 {
1453 animate_along(host, -inset, ANIMATION, false, false);
1454 } else if !refreshing && pos < 0.0 {
1455 animate_along(host, 0.0, ANIMATION, false, false);
1456 }
1457}
1458
1459pub fn command(host: &impl ScrollHost, command: &Command) {
1462 if let Command::ZoomTo {
1463 scale,
1464 center,
1465 animated,
1466 } = *command
1467 {
1468 let center = center.map(|c| Offset::new(c.x.0, c.y.0));
1469 return zoom_to(host, scale, center, animated);
1470 }
1471 let Some(Some((target, animated))) = host.scroll_mut(|s, size| {
1472 let range = s.range(size);
1473 let inset = s.behavior.content_inset;
1474 let (target, animated) = match *command {
1475 Command::ScrollTo { x, y, animated } => (
1477 if s.zooms() {
1478 Offset::new(x.0 + inset.left.0, y.0 + inset.top.0)
1479 } else if s.horizontal {
1480 s.pos().with(true, x.0 + inset.left.0)
1481 } else {
1482 s.pos().with(false, y.0 + inset.top.0)
1483 },
1484 animated,
1485 ),
1486 Command::ScrollToEnd { animated } => (
1487 s.pos().with(s.horizontal, range.1.along(s.horizontal)),
1488 animated,
1489 ),
1490 Command::ScrollToIndex { .. } => {
1491 log::debug!("scroll: {command:?} is not supported");
1492 return None;
1493 }
1494 _ => return None,
1495 };
1496 s.applied = s.applied.wrapping_add(1);
1497 s.live.report = true;
1498 Some((target.clamp(range), animated))
1499 }) else {
1500 return;
1501 };
1502 interrupt(host);
1503 if animated {
1504 animate_to(host, target, ANIMATION, false, true);
1505 } else {
1506 moved_to(host, target);
1507 }
1508 report(host);
1509}
1510
1511fn limit_zoom(b: &ScrollBehavior, scale: f32, rubber: bool) -> f32 {
1516 let (min, max) = (b.min_zoom, b.max_zoom.max(b.min_zoom));
1517 let band = |limit: f32| limit * (scale / limit).powf(0.3);
1518 if scale > max {
1519 if rubber && b.bounces_zoom {
1520 band(max)
1521 } else {
1522 max
1523 }
1524 } else if scale < min {
1525 if rubber && b.bounces_zoom {
1526 band(min)
1527 } else {
1528 min
1529 }
1530 } else {
1531 scale
1532 }
1533}
1534
1535fn zoom_at(host: &impl ScrollHost, scale: f32, c: Offset, at: Offset) {
1538 let to = host.scroll_mut(|s, size| {
1539 if s.zoom != scale {
1540 s.zoom = scale;
1541 s.live.rezoomed = true;
1542 }
1543 s.showing(size, c, at)
1544 });
1545 if let Some(to) = to {
1546 moved_to(host, to);
1547 }
1548}
1549
1550fn zoom_to(host: &impl ScrollHost, scale: f32, center: Option<Offset>, animated: bool) {
1553 let Some(Some((from, to, at, now_c))) = host.scroll(|s, size| {
1554 if !s.zooms() && s.zoom == 1.0 {
1556 log::debug!("scroll: zoomTo on a scroll view that does not zoom");
1557 return None;
1558 }
1559 let to = if s.zooms() {
1560 limit_zoom(&s.behavior, scale, false)
1561 } else {
1562 1.0
1563 };
1564 let at = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
1565 Some((s.zoom, to, at, s.content_at(size, at)))
1566 }) else {
1567 return;
1568 };
1569 interrupt(host);
1570 let c = center.unwrap_or(now_c);
1571 if animated && host.attached() && (to - from).abs() > 1e-4 {
1572 zoom_eased(host, from, to, now_c, c, at);
1573 } else {
1574 zoom_at(host, to, c, at);
1575 report(host);
1576 }
1577}
1578
1579fn zoom_eased(
1582 host: &impl ScrollHost,
1583 from: f32,
1584 to: f32,
1585 from_c: Offset,
1586 to_c: Offset,
1587 at: Offset,
1588) {
1589 set_phase(
1590 host,
1591 Phase::Zoom {
1592 from,
1593 to,
1594 from_c,
1595 to_c,
1596 at,
1597 start: host.now(),
1598 duration: ANIMATION,
1599 },
1600 );
1601 ensure_ticking(host);
1602}
1603
1604pub fn pinches(host: &impl ScrollHost) -> bool {
1606 host.scroll(|s, _| s.zooms() && s.behavior.pinch)
1607 .unwrap_or(false)
1608}
1609
1610pub fn pinch_begin(host: &impl ScrollHost) {
1613 interrupt(host);
1614 host.scroll_mut(|s, _| s.live.pinch_from = s.zoom);
1615}
1616
1617pub fn pinch(host: &impl ScrollHost, scale: f32, at: Point<Points>) {
1621 let at = Offset::new(at.x.0, at.y.0);
1622 let Some((to, c)) = host.scroll_mut(|s, size| {
1623 let raw = s.live.pinch_from * scale;
1624 let to = limit_zoom(&s.behavior, raw, true);
1625 (to, s.content_at(size, at))
1626 }) else {
1627 return;
1628 };
1629 zoom_at(host, to, c, at);
1630}
1631
1632pub fn pinch_end(host: &impl ScrollHost, at: Point<Points>) {
1634 let at = Offset::new(at.x.0, at.y.0);
1635 let Some((from, to, c)) = host.scroll(|s, size| {
1636 (
1637 s.zoom,
1638 limit_zoom(&s.behavior, s.zoom, false),
1639 s.content_at(size, at),
1640 )
1641 }) else {
1642 return;
1643 };
1644 if (to - from).abs() > 1e-4 {
1645 zoom_eased(host, from, to, c, c, at);
1646 }
1647}
1648
1649pub fn drag_begin(host: &impl ScrollHost) {
1654 if !enabled(host) {
1655 return;
1656 }
1657 interrupt(host);
1658 let start = host.scroll(|s, _| s.pos()).unwrap_or_default();
1659 set_phase(
1660 host,
1661 Phase::Drag {
1662 start,
1663 moved: Offset::default(),
1664 },
1665 );
1666 emit(host, EventKind::ScrollDragStart);
1667}
1668
1669pub fn drag_move(host: &impl ScrollHost, delta: Point<Points>) {
1672 drag(host, delta.x.0, delta.y.0, false);
1673}
1674
1675pub fn drag_to(host: &impl ScrollHost, moved: Point<Points>) {
1677 drag(host, moved.x.0, moved.y.0, true);
1678}
1679
1680fn drag(host: &impl ScrollHost, dx: f32, dy: f32, since_begin: bool) {
1681 let Phase::Drag { start, moved } = phase(host) else {
1682 return;
1683 };
1684 let Some((pos, moved)) = host.scroll(|s, size| {
1685 let (min, max) = s.range(size);
1686 let d = if s.zooms() {
1687 Offset::new(-dx, -dy)
1688 } else if !s.horizontal {
1689 Offset::new(0.0, -dy)
1690 } else if s.mirrored {
1691 Offset::new(dx, 0.0)
1692 } else {
1693 Offset::new(-dx, 0.0)
1694 };
1695 let moved = if since_begin { d } else { moved + d };
1698 let raw = start + moved;
1699 let bounces = s.behavior.bounces;
1700 let pos = Offset::new(
1701 drag_position(raw.x, min.x, max.x.max(min.x), size.width.0, bounces),
1702 drag_position(raw.y, min.y, max.y.max(min.y), size.height.0, bounces),
1703 );
1704 (pos, moved)
1705 }) else {
1706 return;
1707 };
1708 set_phase(host, Phase::Drag { start, moved });
1709 moved_to(host, pos);
1710}
1711
1712pub fn drag_end(host: &impl ScrollHost, vx: f32, vy: f32) {
1715 if !matches!(phase(host), Phase::Drag { .. }) {
1716 return;
1717 }
1718 let listens = host.listens(EventKind::Refresh);
1719 let Some((v, refresh)) = host.scroll(|s, _| {
1720 let v = if s.zooms() {
1721 Offset::new(-vx / 1000.0, -vy / 1000.0)
1722 } else {
1723 let v = if !s.horizontal {
1724 -vy
1725 } else if s.mirrored {
1726 vx
1727 } else {
1728 -vx
1729 } / 1000.0;
1730 Offset::default().with(s.horizontal, v)
1731 };
1732 let refresh = !s.horizontal
1733 && !s.live.refreshing
1734 && listens
1735 && s.behavior.refreshes(Points(s.offset()));
1736 (v, refresh)
1737 }) else {
1738 return;
1739 };
1740 set_phase(host, Phase::Idle);
1741 emit(host, EventKind::ScrollDragEnd);
1742 if refresh {
1743 host.scroll_mut(|s, _| s.live.refreshing = true);
1745 host.event(EventKind::Refresh, EventPayload::None);
1746 }
1747 release(host, v, 0.0);
1748}
1749
1750pub fn hovered(host: &impl ScrollHost) {
1756 let shown = host.scroll_mut(|s, size| {
1757 if s.thumb(size).is_none() || !s.indicator || !s.behavior.enabled {
1758 return false;
1759 }
1760 s.live.shown = host.now();
1761 if s.live.alpha == 1.0 {
1762 return false;
1763 }
1764 s.live.alpha = 1.0;
1765 s.live.dark = host.dark();
1766 true
1767 });
1768 if shown != Some(true) {
1769 return;
1770 }
1771 host.redraw();
1772 ensure_ticking(host);
1773}
1774
1775pub fn thumb_begin(host: &impl ScrollHost) {
1777 interrupt(host);
1778 let grabbed = host.scroll_mut(|s, _| {
1779 s.live.phase = Phase::Thumb { start: s.offset() };
1780 s.live.shown = host.now();
1781 s.live.alpha = 1.0;
1782 s.live.dark = host.dark();
1783 });
1784 if grabbed.is_none() {
1785 return;
1786 }
1787 host.redraw();
1788 emit(host, EventKind::ScrollDragStart);
1789}
1790
1791pub fn thumb_move(host: &impl ScrollHost, moved: Point<Points>) {
1795 let (dx, dy) = (moved.x.0, moved.y.0);
1796 let Phase::Thumb { start } = phase(host) else {
1797 return;
1798 };
1799 let Some(Some(pos)) = host.scroll(|s, size| {
1800 let (_, travel) = s.thumb(size)?;
1801 let (min, max) = s.limits(size);
1802 let d = if !s.horizontal {
1803 dy
1804 } else if s.mirrored {
1805 -dx
1806 } else {
1807 dx
1808 };
1809 let d = thumb_scroll(Points(d), Points(max), travel).0;
1810 Some((start + d).clamp(min, max.max(min)))
1811 }) else {
1812 return;
1813 };
1814 moved_along(host, pos);
1815}
1816
1817pub fn thumb_end(host: &impl ScrollHost) {
1820 if !matches!(phase(host), Phase::Thumb { .. }) {
1821 return;
1822 }
1823 set_phase(host, Phase::Idle);
1824 host.scroll_mut(|s, _| s.live.shown = host.now());
1825 ensure_ticking(host);
1826 emit(host, EventKind::ScrollDragEnd);
1827 release(host, Offset::default(), 0.0);
1828}
1829
1830pub fn wheel_begin(host: &impl ScrollHost) {
1835 if !enabled(host) {
1836 return;
1837 }
1838 interrupt(host);
1839 set_phase(
1840 host,
1841 Phase::Wheel {
1842 last: host.now(),
1843 total: 0.0,
1844 gesture: true,
1845 },
1846 );
1847 emit(host, EventKind::ScrollDragStart);
1848}
1849
1850pub fn wheel(host: &impl ScrollHost, delta: Point<Points>) {
1853 let (dx, dy) = (delta.x.0, delta.y.0);
1854 if !enabled(host) {
1855 return;
1856 }
1857 let (gesture, total) = match phase(host) {
1858 Phase::Wheel { gesture, total, .. } => (gesture, total),
1859 _ => {
1860 interrupt(host);
1861 (false, 0.0)
1862 }
1863 };
1864 let Some((pos, total)) = host.scroll(|s, size| {
1865 let (min, max) = s.range(size);
1866 let d = if s.zooms() {
1867 Offset::new(dx, dy)
1868 } else if !s.horizontal {
1869 Offset::new(0.0, dy)
1870 } else if dx != 0.0 {
1871 Offset::new(if s.mirrored { -dx } else { dx }, 0.0)
1872 } else {
1873 Offset::new(dy, 0.0)
1875 };
1876 let pos = s.pos();
1877 let one =
1879 |p: f32, d: f32, min: f32, max: f32| (p + d).clamp(min.min(p), max.max(min).max(p));
1880 (
1881 Offset::new(one(pos.x, d.x, min.x, max.x), one(pos.y, d.y, min.y, max.y)),
1882 total + d.along(s.horizontal),
1883 )
1884 }) else {
1885 return;
1886 };
1887 set_phase(
1888 host,
1889 Phase::Wheel {
1890 last: host.now(),
1891 total,
1892 gesture,
1893 },
1894 );
1895 moved_to(host, pos);
1896 ensure_ticking(host);
1897}
1898
1899pub fn wheel_end(host: &impl ScrollHost, vx: f32, vy: f32) {
1902 let Phase::Wheel { gesture, total, .. } = phase(host) else {
1903 return;
1904 };
1905 let Some(v) = host.scroll(|s, _| {
1906 let v = if s.zooms() {
1907 return Offset::new(vx / 1000.0, vy / 1000.0);
1908 } else if !s.horizontal {
1909 vy
1910 } else if vx != 0.0 {
1911 if s.mirrored { -vx } else { vx }
1912 } else {
1913 vy
1914 };
1915 Offset::default().with(s.horizontal, v / 1000.0)
1916 }) else {
1917 return;
1918 };
1919 set_phase(host, Phase::Idle);
1920 if gesture {
1921 emit(host, EventKind::ScrollDragEnd);
1922 }
1923 let snap = if v == Offset::default() && total.abs() >= 1.0 {
1924 total.signum() * WHEEL_SNAP
1925 } else {
1926 0.0
1927 };
1928 release(host, v, snap);
1929}
1930
1931pub const KEY_LINE: Points = Points(40.0);
1935const KEY_PAGE: f32 = 0.875;
1937const KEY_ANIMATION: f64 = 200.0;
1939
1940#[derive(Debug, Clone, Copy, PartialEq)]
1942pub enum KeyMove {
1943 Points(Points),
1945 Pages(f32),
1947 Start,
1949 End,
1951}
1952
1953impl KeyMove {
1954 pub fn sign(self) -> f32 {
1956 match self {
1957 KeyMove::Points(d) => d.0.signum(),
1958 KeyMove::Pages(n) => n.signum(),
1959 KeyMove::Start => -1.0,
1960 KeyMove::End => 1.0,
1961 }
1962 }
1963}
1964
1965pub fn vk_key_move(vk: u16, shift: bool, ctrl: bool) -> Option<(bool, KeyMove)> {
1970 const VK_SPACE: u16 = 0x20;
1971 const VK_PRIOR: u16 = 0x21;
1972 const VK_NEXT: u16 = 0x22;
1973 const VK_END: u16 = 0x23;
1974 const VK_HOME: u16 = 0x24;
1975 const VK_LEFT: u16 = 0x25;
1976 const VK_UP: u16 = 0x26;
1977 const VK_RIGHT: u16 = 0x27;
1978 const VK_DOWN: u16 = 0x28;
1979 if ctrl {
1980 return match vk {
1981 VK_HOME => Some((false, KeyMove::Start)),
1982 VK_END => Some((false, KeyMove::End)),
1983 _ => None,
1984 };
1985 }
1986 Some(match vk {
1987 VK_UP => (false, KeyMove::Points(-KEY_LINE)),
1988 VK_DOWN => (false, KeyMove::Points(KEY_LINE)),
1989 VK_LEFT => (true, KeyMove::Points(-KEY_LINE)),
1990 VK_RIGHT => (true, KeyMove::Points(KEY_LINE)),
1991 VK_PRIOR => (false, KeyMove::Pages(-1.0)),
1992 VK_NEXT => (false, KeyMove::Pages(1.0)),
1993 VK_SPACE if shift => (false, KeyMove::Pages(-1.0)),
1994 VK_SPACE => (false, KeyMove::Pages(1.0)),
1995 VK_HOME => (false, KeyMove::Start),
1996 VK_END => (false, KeyMove::End),
1997 _ => return None,
1998 })
1999}
2000
2001fn key_target(m: KeyMove, base: f32, viewport: f32, min: f32, max: f32) -> f32 {
2003 let max = max.max(min);
2004 match m {
2005 KeyMove::Points(d) => base + d.0,
2006 KeyMove::Pages(n) => base + n * (viewport * KEY_PAGE).max(KEY_LINE.0),
2007 KeyMove::Start => min,
2008 KeyMove::End => max,
2009 }
2010 .clamp(min, max)
2011}
2012
2013pub fn key_scroll(host: &impl ScrollHost, m: KeyMove, flip: bool) {
2019 let Some((base, viewport, min, max, flip)) = host.scroll(|s, size| {
2020 let (min, max) = s.limits(size);
2021 (s.goal(), s.viewport(size), min, max, flip && s.mirrored)
2022 }) else {
2023 return;
2024 };
2025 let moved = match m {
2026 KeyMove::Points(d) if flip => KeyMove::Points(-d),
2027 m => m,
2028 };
2029 let to = key_target(moved, base, viewport, min, max);
2030 interrupt(host);
2031 animate_along(host, to, KEY_ANIMATION, false, true);
2032 host.key_scrolled(m);
2036}
2037
2038const REVEAL_MARGIN: f32 = 16.0;
2040
2041pub fn reveal_delta(start: Points, end: Points, viewport: Points) -> Points {
2045 Points(reveal_by(start.0, end.0, viewport.0))
2046}
2047
2048pub fn reveal_focus_delta(start: Points, end: Points, viewport: Points) -> Points {
2054 Points(reveal_focus_by(start.0, end.0, viewport.0))
2055}
2056
2057fn reveal_by(start: f32, end: f32, viewport: f32) -> f32 {
2058 let margin = REVEAL_MARGIN.min(viewport / 4.0);
2059 if start < margin {
2060 start - margin
2061 } else if end > viewport - margin {
2062 (end - (viewport - margin)).min(start - margin)
2063 } else {
2064 0.0
2065 }
2066}
2067
2068fn reveal_focus_by(start: f32, end: f32, viewport: f32) -> f32 {
2069 if end - start > viewport && end > 0.0 && start < viewport {
2070 0.0
2071 } else {
2072 reveal_by(start, end, viewport)
2073 }
2074}
2075
2076pub fn reveal(host: &impl ScrollHost, start: Points, len: Points) -> Points {
2082 let (start, len) = (start.0, len.0);
2083 let Some((base, pos, dim, min, max)) = host.scroll(|s, size| {
2084 let (min, max) = s.limits(size);
2085 (s.goal(), s.offset(), s.viewport(size), min, max)
2086 }) else {
2087 return Points(0.0);
2088 };
2089 let start = start - (base - pos);
2091 let delta = reveal_focus_by(start, start + len, dim);
2092 let to = (base + delta).clamp(min, max.max(min));
2093 if (to - base).abs() < 0.5 {
2094 return Points(0.0);
2095 }
2096 interrupt(host);
2097 animate_along(host, to, ANIMATION, false, true);
2098 Points(to - base)
2099}
2100
2101#[cfg(test)]
2102mod tests {
2103 use super::*;
2104 use crate::EdgeInsets;
2105
2106 #[test]
2107 fn content_is_read_in_the_order_it_is_on_screen() {
2108 let cells = [(0, 160.0), (1, 200.0), (2, 80.0), (3, 120.0)];
2111 let mut vertical = cells;
2112 reading_order(Axis::Vertical, &mut vertical, |c| {
2113 point(Points(0.0), Points(c.1))
2114 });
2115 assert_eq!(vertical.map(|c| c.0), [2, 3, 0, 1]);
2116 let grid = [
2118 (0, (50.0, 0.0)),
2119 (1, (0.0, 40.0)),
2120 (2, (0.0, 0.0)),
2121 (3, (50.0, 40.0)),
2122 ];
2123 let at = |c: &(i32, (f32, f32))| point(Points(c.1.0), Points(c.1.1));
2124 let mut rows = grid;
2125 reading_order(Axis::Vertical, &mut rows, at);
2126 assert_eq!(rows.map(|c| c.0), [2, 0, 1, 3]);
2127 let mut columns = grid;
2128 reading_order(Axis::Horizontal, &mut columns, at);
2129 assert_eq!(columns.map(|c| c.0), [2, 1, 0, 3]);
2130 }
2131
2132 fn scroll_state(content: (f32, f32), horizontal: bool) -> ScrollState {
2133 ScrollState {
2134 content: sz(content.0, content.1),
2135 horizontal,
2136 ..Default::default()
2137 }
2138 }
2139
2140 fn sz(w: f32, h: f32) -> Size<Points> {
2141 crate::geometry::size(Points(w), Points(h))
2142 }
2143
2144 fn pt(x: f32, y: f32) -> Point<Points> {
2145 point(Points(x), Points(y))
2146 }
2147
2148 #[test]
2149 fn rubber_band_resists() {
2150 assert_eq!(drag_position(50.0, 0.0, 100.0, 400.0, true), 50.0);
2151 let over = drag_position(-100.0, 0.0, 100.0, 400.0, true);
2152 assert!(over < 0.0 && over > -100.0, "{over}");
2153 let more = drag_position(-400.0, 0.0, 100.0, 400.0, true);
2154 assert!(more < over && more > -400.0 * 0.55);
2155 assert_eq!(drag_position(-100.0, 0.0, 100.0, 400.0, false), 0.0);
2156 assert_eq!(drag_position(300.0, 0.0, 100.0, 400.0, false), 100.0);
2157 assert!(drag_position(150.0, 0.0, 100.0, 400.0, true) > 100.0);
2158 let p = Points;
2159 assert_eq!(dragged(p(50.0), p(0.0), p(100.0), p(400.0), true), p(50.0));
2160 assert!(rubber(1e6, 400.0) < 400.0);
2162 }
2163
2164 #[test]
2165 fn glide_integrates_to_projection() {
2166 let rate = 0.998;
2167 let (mut pos, mut v) = (0.0f32, 2.0f32);
2168 for _ in 0..2000 {
2169 let (d, nv) = glide_step(v, rate, 16.0);
2170 pos += d;
2171 v = nv;
2172 }
2173 let end = projected(Points(0.0), 2.0, rate).0;
2174 assert!((pos - end).abs() < 1.0, "{pos} vs {end}");
2175 let (a, _) = glide_step(2.0, rate, 32.0);
2177 let (b1, v1) = glide_step(2.0, rate, 16.0);
2178 let (b2, _) = glide_step(v1, rate, 16.0);
2179 assert!((a - (b1 + b2)).abs() < 1e-3);
2180 }
2181
2182 #[test]
2183 fn animated_sticky_offsets_stick_further_in() {
2184 let mut s = scroll_state((320.0, 2000.0), false);
2185 s.y = Points(150.0);
2186 s.sticky = vec![
2187 crate::StickyCell {
2188 cell: 1,
2189 start: Points(100.0),
2190 end: Points(300.0),
2191 offset: None,
2192 },
2193 crate::StickyCell {
2194 cell: 2,
2195 start: Points(100.0),
2196 end: Points(300.0),
2197 offset: Some(7),
2198 },
2199 ];
2200 let shifts: Vec<_> = s
2202 .sticky_shifts_with(|n| if n == 7 { 56.0 } else { 0.0 })
2203 .map(|(c, p)| (c, p.y.0))
2204 .collect();
2205 assert_eq!(shifts, [(1, 50.0), (2, 106.0)]);
2206 }
2207
2208 #[test]
2209 fn sticky_shift_clamps() {
2210 let p = Points;
2211 assert_eq!(sticky_shift(p(0.0), p(100.0), p(300.0)), p(0.0));
2212 assert_eq!(sticky_shift(p(150.0), p(100.0), p(300.0)), p(50.0));
2213 assert_eq!(sticky_shift(p(500.0), p(100.0), p(300.0)), p(200.0));
2214 assert_eq!(sticky_shift(p(500.0), p(100.0), p(f32::INFINITY)), p(400.0));
2215 }
2216
2217 #[test]
2218 fn rates_follow_behavior() {
2219 let mut b = ScrollBehavior::default();
2220 assert_eq!(rate(&b), 0.998);
2221 b.paging = true;
2222 assert_eq!(rate(&b), 0.99);
2223 b.deceleration = 0.95;
2224 assert_eq!(rate(&b), 0.95);
2225 }
2226
2227 #[test]
2228 fn snapping_and_paging_targets() {
2229 let b = ScrollBehavior {
2232 paging: true,
2233 ..Default::default()
2234 };
2235 let r = rate(&b);
2236 let pt = Points;
2237 let t = b.snap_target(
2238 pt(250.0),
2239 projected(pt(250.0), 0.0, r),
2240 0.0,
2241 pt(400.0),
2242 pt(1600.0),
2243 );
2244 assert_eq!(t, Some(pt(400.0)));
2245 let t = b.snap_target(
2246 pt(100.0),
2247 projected(pt(100.0), 1.0, r),
2248 1.0,
2249 pt(400.0),
2250 pt(1600.0),
2251 );
2252 assert_eq!(t, Some(pt(400.0)));
2253 let t = b.snap_target(
2254 pt(300.0),
2255 projected(pt(300.0), -1.0, r),
2256 -1.0,
2257 pt(400.0),
2258 pt(1600.0),
2259 );
2260 assert_eq!(t, Some(pt(0.0)));
2261 let b = ScrollBehavior {
2262 snap_interval: pt(100.0),
2263 ..Default::default()
2264 };
2265 let t = b.snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0));
2266 assert_eq!(t, Some(pt(100.0)));
2267 assert_eq!(
2268 ScrollBehavior::default().snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0)),
2269 None
2270 );
2271 }
2272
2273 #[test]
2274 fn indicator_geometry() {
2275 assert_eq!(span(400.0, 400.0, 0.0), None);
2276 let (s0, l0) = span(400.0, 1600.0, 0.0).unwrap();
2277 assert_eq!(s0, 2.0);
2278 assert!((l0 - 99.0).abs() < 0.01);
2279 let (s1, l1) = span(400.0, 1600.0, 1200.0).unwrap();
2280 assert!((s1 + l1 - 398.0).abs() < 0.01);
2281 let (_, l2) = span(400.0, 1600.0, -50.0).unwrap();
2282 assert!(l2 < l0);
2283 assert_eq!(
2284 indicator_span(Points(400.0), Points(1600.0), Points(0.0)),
2285 Some((Points(s0), Points(l0)))
2286 );
2287 assert_eq!(indicator_alpha(0.0), 1.0);
2288 assert_eq!(indicator_alpha(INDICATOR_HOLD + INDICATOR_FADE), 0.0);
2289 }
2290
2291 #[test]
2292 fn snap_durations() {
2293 let p = Points;
2294 assert_eq!(snap_duration(p(0.2), 1.0), 0.0);
2295 assert_eq!(snap_duration(p(100.0), -1.0), ANIMATION);
2296 assert_eq!(snap_duration(p(300.0), 1.0), 600.0);
2297 assert_eq!(snap_duration(p(300.0), 3.0), 300.0);
2298 assert_eq!(ease_out(1.0), 1.0);
2299 assert_eq!(ease_out(2.0), 1.0);
2300 }
2301
2302 #[test]
2303 fn insets_clamp_and_report() {
2304 let mut s = scroll_state((300.0, 1000.0), false);
2305 let size = sz(300.0, 400.0);
2306 s.behavior.content_inset = EdgeInsets {
2307 top: Points(50.0),
2308 bottom: Points(20.0),
2309 ..Default::default()
2310 };
2311 assert_eq!(s.limits(size), (0.0, 670.0));
2312 assert_eq!(s.max(size), pt(0.0, 670.0));
2313 assert_eq!(s.reported(size), pt(0.0, -50.0));
2315 s.y = Points(900.0);
2316 assert_eq!(s.reported(size), pt(0.0, 620.0));
2317 assert_eq!(s.origin(), pt(0.0, 850.0));
2319 s.live.refreshing = true;
2321 assert_eq!(s.limits(size).0, -56.0);
2322 s.behavior.refresh_indicator = Some(Points(80.0));
2323 assert_eq!(s.limits(size).0, -80.0);
2324 }
2325
2326 #[test]
2327 fn can_scroll_follows_edges_and_mirroring() {
2328 let size = sz(300.0, 400.0);
2329 let mut s = scroll_state((300.0, 1000.0), false);
2330 s.behavior.enabled = true;
2331 assert!(s.can_scroll(size, pt(0.0, 10.0)));
2332 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2333 s.y = Points(600.0);
2334 assert!(!s.can_scroll(size, pt(0.0, 10.0)));
2335 s.behavior.enabled = false;
2336 assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2337
2338 let size = sz(300.0, 100.0);
2339 let mut row = scroll_state((1000.0, 100.0), true);
2340 row.behavior.enabled = true;
2341 row.mirrored = true;
2342 assert!(row.can_scroll(size, pt(-10.0, 0.0)));
2344 assert!(!row.can_scroll(size, pt(10.0, 0.0)));
2345 assert!(row.can_scroll(size, pt(0.0, 10.0)));
2347 }
2348
2349 #[test]
2350 fn scroll_by_moves_gestures_along() {
2351 let y = |v: f32| Offset::new(0.0, v);
2352 let drag = shifted(
2353 Phase::Drag {
2354 start: y(10.0),
2355 moved: y(5.0),
2356 },
2357 y(30.0),
2358 false,
2359 );
2360 assert_eq!(
2361 drag,
2362 Phase::Drag {
2363 start: y(40.0),
2364 moved: y(5.0)
2365 }
2366 );
2367 let anim = Phase::Animate {
2368 from: y(0.0),
2369 to: y(100.0),
2370 start: 1.0,
2371 duration: 300.0,
2372 momentum: false,
2373 end: true,
2374 };
2375 let Phase::Animate { from, to, .. } = shifted(anim, y(-20.0), false) else {
2376 panic!()
2377 };
2378 assert_eq!((from, to), (y(-20.0), y(80.0)));
2379 assert_eq!(shifted(Phase::Idle, y(5.0), false), Phase::Idle);
2380 assert_eq!(
2381 shifted(Phase::Thumb { start: 10.0 }, y(30.0), false),
2382 Phase::Thumb { start: 40.0 }
2383 );
2384 }
2385
2386 #[test]
2387 fn thumb_follows_the_pointer() {
2388 let p = Points;
2391 let (s0, l0) = span(400.0, 1600.0, 0.0).unwrap();
2392 let travel = 400.0 - 2.0 * INDICATOR_MARGIN - l0;
2393 let end = thumb_scroll(p(travel), p(1200.0), p(travel)).0;
2394 assert!((end - 1200.0).abs() < 0.01);
2395 let (s1, _) = span(400.0, 1600.0, end).unwrap();
2396 assert!((s1 - s0 - travel).abs() < 0.01);
2397 assert!(thumb_scroll(p(-10.0), p(1200.0), p(travel)).0 < 0.0);
2398 assert_eq!(thumb_scroll(p(10.0), p(1200.0), p(0.0)), p(0.0));
2399 }
2400
2401 #[test]
2402 fn thumb_is_grabbed_at_the_edge() {
2403 let mut s = scroll_state((300.0, 1600.0), false);
2404 s.indicator = true;
2405 s.behavior.enabled = true;
2406 let size = sz(300.0, 400.0);
2407 let (rect, _) = s.thumb(size).unwrap();
2408 assert_eq!(rect.origin.x.0, 300.0 - INDICATOR_THICK.0 - 2.0);
2409 assert!(s.grabs_thumb(size, pt(295.0, 10.0)));
2410 assert!(!s.grabs_thumb(size, pt(200.0, 10.0)));
2411 assert!(!s.grabs_thumb(size, pt(295.0, 300.0)));
2412 }
2413
2414 #[test]
2415 fn thumb_stays_in_the_visible_part() {
2416 let mut s = scroll_state((900.0, 2000.0), true);
2420 s.indicator = true;
2421 s.behavior.enabled = true;
2422 let size = sz(300.0, 2000.0);
2423 let visible = Bounds::new(pt(0.0, 600.0), sz(300.0, 400.0));
2424 let (rect, _) = s.thumb_within(size, visible).unwrap();
2425 assert_eq!(rect.origin.y.0, 1000.0 - INDICATOR_THICK.0 - 2.0);
2426 assert!(s.grabs_thumb_within(size, visible, pt(20.0, 997.0)));
2427 assert!(!s.grabs_thumb_within(size, visible, pt(20.0, 1997.0)));
2428 let (rect, _) = s.thumb(size).unwrap();
2430 assert_eq!(rect.origin.y.0, 2000.0 - INDICATOR_THICK.0 - 2.0);
2431 let hidden = Bounds::new(pt(0.0, 2100.0), sz(300.0, 400.0));
2433 assert!(s.thumb_within(size, hidden).is_none());
2434 }
2435
2436 #[test]
2437 fn scroll_keys() {
2438 assert_eq!(
2439 vk_key_move(0x28, false, false),
2440 Some((false, KeyMove::Points(KEY_LINE)))
2441 );
2442 assert_eq!(
2443 vk_key_move(0x25, false, false),
2444 Some((true, KeyMove::Points(-KEY_LINE)))
2445 );
2446 assert_eq!(
2447 vk_key_move(0x20, true, false),
2448 Some((false, KeyMove::Pages(-1.0)))
2449 );
2450 assert_eq!(
2451 vk_key_move(0x24, false, true),
2452 Some((false, KeyMove::Start))
2453 );
2454 assert_eq!(vk_key_move(0x28, false, true), None);
2455 assert_eq!(vk_key_move(b'A' as u16, false, false), None);
2456 assert_eq!(KeyMove::Start.sign(), -1.0);
2457 assert_eq!(KeyMove::Pages(1.0).sign(), 1.0);
2458 assert_eq!(
2459 key_target(KeyMove::Points(Points(40.0)), 10.0, 400.0, 0.0, 1000.0),
2460 50.0
2461 );
2462 assert_eq!(
2463 key_target(KeyMove::Pages(1.0), 0.0, 400.0, 0.0, 1000.0),
2464 350.0
2465 );
2466 assert_eq!(
2467 key_target(KeyMove::Pages(-1.0), 100.0, 400.0, 0.0, 1000.0),
2468 0.0
2469 );
2470 assert_eq!(key_target(KeyMove::End, 0.0, 400.0, 0.0, 1000.0), 1000.0);
2471 assert_eq!(
2472 key_target(KeyMove::Start, 500.0, 400.0, -56.0, 1000.0),
2473 -56.0
2474 );
2475 }
2476
2477 #[test]
2478 fn reveal_deltas() {
2479 assert_eq!(reveal_by(100.0, 140.0, 400.0), 0.0);
2480 assert_eq!(reveal_by(-30.0, 10.0, 400.0), -46.0);
2481 assert_eq!(reveal_by(380.0, 420.0, 400.0), 36.0);
2482 assert_eq!(reveal_by(200.0, 900.0, 400.0), 184.0);
2484 assert_eq!(reveal_focus_by(500.0, 1200.0, 400.0), 484.0);
2487 assert_eq!(reveal_focus_by(-1200.0, -500.0, 400.0), -1216.0);
2488 assert_eq!(reveal_focus_by(200.0, 900.0, 400.0), 0.0);
2489 assert_eq!(reveal_focus_by(-2000.0, 300.0, 400.0), 0.0);
2490 assert_eq!(reveal_focus_by(-2000.0, 900.0, 400.0), 0.0);
2491 assert_eq!(reveal_focus_by(-100.0, 290.0, 400.0), -116.0);
2494 assert_eq!(
2495 reveal_focus_delta(Points(200.0), Points(900.0), Points(400.0)),
2496 Points(0.0)
2497 );
2498 assert_eq!(
2499 reveal_delta(Points(-30.0), Points(10.0), Points(400.0)),
2500 Points(-46.0)
2501 );
2502 }
2503
2504 #[test]
2505 fn spinner_spokes() {
2506 assert_eq!(spokes(Percentage(0.3), Radians(0.0)).count(), 3);
2507 assert!(spokes(Percentage(0.3), Radians(0.0)).all(|(_, a)| a == 0.8));
2508 let all: Vec<_> = spokes(Percentage(1.0), Radians(0.0)).collect();
2509 assert_eq!(all.len(), 8);
2510 assert_eq!(all[0].1, 1.0);
2512 assert_eq!(all[1].0, Radians(PI / 4.0));
2513 }
2514
2515 #[test]
2516 fn refresh_follows_its_props() {
2517 let mut s = scroll_state((300.0, 1000.0), false);
2518 assert!(!s.behavior.refreshes(Points(-63.0)));
2519 assert!(s.behavior.refreshes(Points(-64.0)));
2520 s.y = Points(-32.0);
2522 assert_eq!(
2523 s.spinner(Points(300.0), true),
2524 Some((pt(150.0, 4.0), Percentage(0.5)))
2525 );
2526 s.behavior.refresh_indicator = Some(Points(100.0));
2529 assert!(!s.behavior.refreshes(Points(-64.0)));
2530 assert!(s.behavior.refreshes(Points(-100.0)));
2531 assert_eq!(s.behavior.refresh_inset(), Points(100.0));
2532 assert_eq!(s.spinner(Points(300.0), true), None);
2533 }
2534
2535 struct TestHost {
2538 state: std::cell::RefCell<ScrollState>,
2539 redraws: std::cell::Cell<u32>,
2540 reports: std::cell::RefCell<Vec<String>>,
2542 key_moves: std::cell::RefCell<Vec<KeyMove>>,
2544 }
2545
2546 impl TestHost {
2547 fn new(state: ScrollState) -> Self {
2548 Self {
2549 state: std::cell::RefCell::new(state),
2550 redraws: std::cell::Cell::new(0),
2551 reports: Default::default(),
2552 key_moves: Default::default(),
2553 }
2554 }
2555 }
2556
2557 impl ScrollHost for TestHost {
2558 fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R> {
2559 Some(f(&self.state.borrow(), sz(300.0, 500.0)))
2560 }
2561 fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R> {
2562 Some(f(&mut self.state.borrow_mut(), sz(300.0, 500.0)))
2563 }
2564 fn now(&self) -> f64 {
2565 0.0
2566 }
2567 fn listens(&self, _: EventKind) -> bool {
2568 true
2569 }
2570 fn event(&self, _: EventKind, _: EventPayload) {}
2571 fn report(&self, offset: Point<Points>, _: u32) {
2572 let line = format!("scroll {} {}", offset.x.0, offset.y.0);
2573 self.reports.borrow_mut().push(line);
2574 }
2575 fn report_zoom(&self, scale: f32) {
2576 self.reports.borrow_mut().push(format!("zoom {scale}"));
2577 }
2578 fn key_scrolled(&self, key_move: KeyMove) {
2579 self.key_moves.borrow_mut().push(key_move);
2580 }
2581 fn moved(&self, _: Point<Points>) {}
2582 fn pulled(&self, _: Points) {}
2583 fn relayout(&self) {}
2584 fn redraw(&self) {
2585 self.redraws.set(self.redraws.get() + 1);
2586 }
2587 fn attached(&self) -> bool {
2588 true
2589 }
2590 fn start_ticking(&self) {}
2591 }
2592
2593 #[test]
2594 fn a_key_scroll_tells_the_host_every_key_move() {
2595 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
2596 key_scroll(&host, KeyMove::End, false);
2597 key_scroll(&host, KeyMove::Pages(-1.0), false);
2598 assert_eq!(
2599 *host.key_moves.borrow(),
2600 [KeyMove::End, KeyMove::Pages(-1.0)]
2601 );
2602 assert!(matches!(
2603 host.state.borrow().live.phase,
2604 Phase::Animate { .. }
2605 ));
2606
2607 let mut row = scroll_state((100_000.0, 500.0), true);
2610 row.mirrored = true;
2611 row.x = Points(1000.0);
2612 let host = TestHost::new(row);
2613 key_scroll(&host, KeyMove::Points(KEY_LINE), true);
2614 assert_eq!(host.state.borrow().goal(), 1000.0 - KEY_LINE.0);
2615 assert_eq!(*host.key_moves.borrow(), [KeyMove::Points(KEY_LINE)]);
2616 }
2617
2618 #[test]
2619 fn a_glide_and_an_eased_move_end_at_their_deadlines() {
2620 let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
2621 assert_eq!(deadline(&host, 0.0), None);
2622 for phase in [
2623 Phase::Glide {
2624 velocity: Offset::new(0.0, 2.0),
2625 last: 0.0,
2626 },
2627 Phase::Animate {
2628 from: Offset::default(),
2629 to: Offset::new(0.0, 400.0),
2630 start: 0.0,
2631 duration: ANIMATION,
2632 momentum: false,
2633 end: true,
2634 },
2635 ] {
2636 host.state.borrow_mut().y = Points(0.0);
2637 host.state.borrow_mut().live.phase = phase;
2638 let mut now = 0.0;
2639 let mut frames = 0;
2640 while let Some(next) = deadline(&host, now) {
2641 now = next;
2642 frame(&host, now);
2643 frames += 1;
2644 assert!(frames < 5, "{:?}", host.state.borrow().live.phase);
2645 }
2646 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2647 let y = host.state.borrow().y.0;
2648 match phase {
2649 Phase::Glide { .. } => assert!(
2651 (y - projected(Points(0.0), 2.0, 0.998).0).abs() < 6.0,
2652 "{y}"
2653 ),
2654 _ => assert_eq!(y, 400.0),
2655 }
2656 }
2657 }
2658
2659 #[test]
2660 fn indicator_follows_the_view_on_either_axis() {
2661 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
2662 for horizontal in [false, true] {
2663 config(&host, horizontal, true, false, false);
2664 assert!(host.state.borrow().indicator);
2665 config(&host, horizontal, false, false, false);
2667 assert!(!host.state.borrow().indicator);
2668 config(&host, horizontal, true, true, false);
2670 assert!(!host.state.borrow().indicator);
2671 }
2672 }
2673
2674 #[test]
2675 fn switching_indicators_while_refreshing_keeps_the_new_room() {
2676 let host = TestHost::new(scroll_state((300.0, 1000.0), false));
2677 let own = ScrollBehavior {
2678 refresh_indicator: Some(Points(72.0)),
2679 ..Default::default()
2680 };
2681 behavior(&host, &own);
2682 refreshing(&host, true);
2683 frame(&host, 1000.0);
2684 assert_eq!(host.state.borrow().y, Points(-72.0));
2685 let redraws = host.redraws.get();
2687 behavior(&host, &ScrollBehavior::default());
2688 assert!(host.redraws.get() > redraws);
2689 frame(&host, 1000.0);
2690 assert_eq!(host.state.borrow().y, Points(-56.0));
2691 behavior(&host, &ScrollBehavior::default());
2693 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2694 }
2695
2696 fn zooming(content: (f32, f32)) -> TestHost {
2699 let mut s = scroll_state(content, false);
2700 s.can_zoom = true;
2701 s.behavior.min_zoom = 0.5;
2702 s.behavior.max_zoom = 4.0;
2703 TestHost::new(s)
2704 }
2705
2706 fn zoom_and_offset(host: &TestHost) -> (f32, f32, f32) {
2707 let s = host.state.borrow();
2708 (s.zoom, s.x.0, s.y.0)
2709 }
2710
2711 fn zoom_to(scale: f32, center: Option<Point<Points>>, animated: bool) -> Command {
2712 Command::ZoomTo {
2713 scale,
2714 center,
2715 animated,
2716 }
2717 }
2718
2719 #[test]
2720 fn only_a_backend_that_draws_zoomed_content_zooms() {
2721 let host = zooming((300.0, 500.0));
2722 host.state.borrow_mut().can_zoom = false;
2723 command(&host, &zoom_to(2.0, None, false));
2724 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
2725 assert!(host.reports.borrow().is_empty());
2726 host.state.borrow_mut().can_zoom = true;
2728 command(&host, &zoom_to(2.0, None, false));
2729 assert_eq!(zoom_and_offset(&host), (2.0, 150.0, 250.0));
2730 assert_eq!(*host.reports.borrow(), ["zoom 2", "scroll 150 250"]);
2731 }
2732
2733 #[test]
2734 fn a_pinch_keeps_the_content_under_the_pointer_and_springs_back() {
2735 let host = zooming((300.0, 500.0));
2736 let size = sz(300.0, 500.0);
2737 let at = pt(100.0, 120.0);
2738 pinch_begin(&host);
2739 pinch(&host, 2.0, at);
2740 assert_eq!(zoom_and_offset(&host), (2.0, 100.0, 120.0));
2741 {
2742 let s = host.state.borrow();
2743 assert_eq!(s.to_viewport(size, at), at);
2744 assert_eq!(s.to_content(size, at), at);
2745 }
2746 pinch(&host, 6.0, at);
2748 let banded = host.state.borrow().zoom;
2749 assert!(banded > 4.0 && banded < 6.0, "{banded}");
2750 pinch_end(&host, at);
2751 frame(&host, ANIMATION);
2752 assert_eq!(zoom_and_offset(&host), (4.0, 300.0, 360.0));
2754 assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
2755 }
2756
2757 #[test]
2758 fn zoomed_content_pans_both_ways_without_a_bar() {
2759 let host = zooming((300.0, 500.0));
2760 host.state.borrow_mut().indicator = true;
2761 let size = sz(300.0, 500.0);
2762 assert!(!host.state.borrow().can_scroll(size, pt(10.0, 10.0)));
2763 command(&host, &zoom_to(2.0, Some(pt(0.0, 0.0)), false));
2764 assert_eq!(zoom_and_offset(&host), (2.0, 0.0, 0.0));
2766 let s = host.state.borrow().clone();
2767 assert!(s.can_scroll(size, pt(10.0, 0.0)) && s.can_scroll(size, pt(0.0, 10.0)));
2768 assert!(!s.can_scroll(size, pt(-10.0, -10.0)));
2769 assert!(s.thumb(size).is_none());
2770 wheel(&host, pt(30.0, 40.0));
2771 assert_eq!(zoom_and_offset(&host), (2.0, 30.0, 40.0));
2772 wheel(&host, pt(1000.0, 1000.0));
2774 assert_eq!(zoom_and_offset(&host), (2.0, 300.0, 500.0));
2775 wheel_begin(&host);
2777 wheel(&host, pt(-10.0, -10.0));
2778 wheel_end(&host, -1000.0, -500.0);
2779 let mut now = 0.0;
2780 while let Some(next) = deadline(&host, now) {
2781 now = next;
2782 frame(&host, now);
2783 }
2784 let (_, x, y) = zoom_and_offset(&host);
2785 assert!(x < 280.0 && y < 480.0 && x < y, "{x} {y}");
2786 }
2787
2788 #[test]
2789 fn zoom_to_eases_to_the_point_it_centers() {
2790 let host = zooming((300.0, 500.0));
2791 command(&host, &zoom_to(2.0, Some(pt(100.0, 200.0)), true));
2792 assert!(matches!(host.state.borrow().live.phase, Phase::Zoom { .. }));
2793 assert_eq!(deadline(&host, 0.0), Some(ANIMATION + 1.0));
2794 frame(&host, ANIMATION / 2.0);
2795 let half = host.state.borrow().zoom;
2796 assert!(half > 1.0 && half < 2.0, "{half}");
2797 frame(&host, ANIMATION);
2798 assert_eq!(zoom_and_offset(&host), (2.0, 50.0, 150.0));
2800 command(&host, &zoom_to(10.0, None, false));
2802 assert_eq!(host.state.borrow().zoom, 4.0);
2803 }
2804
2805 #[test]
2806 fn small_content_is_centered() {
2807 let host = zooming((300.0, 500.0));
2808 host.state.borrow_mut().behavior.center_content = true;
2809 command(&host, &zoom_to(0.5, None, false));
2810 let s = host.state.borrow();
2811 let size = sz(300.0, 500.0);
2812 assert_eq!(s.centered(size), pt(75.0, 125.0));
2813 assert_eq!(s.to_viewport(size, pt(0.0, 0.0)), pt(75.0, 125.0));
2814 assert_eq!(s.to_content(size, pt(75.0, 125.0)), pt(0.0, 0.0));
2815 assert_eq!((s.x.0, s.y.0), (0.0, 0.0));
2816 }
2817
2818 #[test]
2819 fn new_limits_clamp_the_zoom_and_a_view_that_zooms_no_more_is_back_at_1() {
2820 let host = zooming((300.0, 500.0));
2821 command(&host, &zoom_to(3.0, None, false));
2822 let mut b = host.state.borrow().behavior.clone();
2823 b.max_zoom = 2.0;
2824 behavior(&host, &b);
2825 assert_eq!(host.state.borrow().zoom, 2.0);
2826 b.max_zoom = 0.5;
2827 behavior(&host, &b);
2828 assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
2829 frame(&host, 0.0);
2830 let reports = host.reports.borrow();
2831 assert_eq!(reports[reports.len() - 2..], ["zoom 1", "scroll 0 0"]);
2832 }
2833}