waft_widgets/widgets/scroll_metrics.rs
1//! Flutter counterpart: `widgets/scroll_metrics.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5
6use waft_embedder::clamp_double;
7use waft_painting::{Axis, AxisDirection, axis_direction_to_axis};
8
9/// A description of a `Scrollable`'s contents, useful for modeling the state
10/// of its viewport.
11///
12/// This trait defines a current position, [`pixels`](Self::pixels), and a range of values
13/// considered "in bounds" for that position. The range has a minimum value at
14/// [`min_scroll_extent`](Self::min_scroll_extent) and a maximum value at
15/// [`max_scroll_extent`](Self::max_scroll_extent) (inclusive). The viewport scrolls in the
16/// direction and axis described by [`axis_direction`](Self::axis_direction) and
17/// [`axis`](Self::axis).
18///
19/// The [`out_of_range`](Self::out_of_range) getter will return true if
20/// [`pixels`](Self::pixels) is outside this defined range. The [`at_edge`](Self::at_edge)
21/// getter will return true if the [`pixels`](Self::pixels) position equals either the
22/// [`min_scroll_extent`](Self::min_scroll_extent) or the
23/// [`max_scroll_extent`](Self::max_scroll_extent).
24///
25/// The dimensions of the viewport in the given [`axis`](Self::axis) are described by
26/// [`viewport_dimension`](Self::viewport_dimension).
27///
28/// The above values are also exposed in terms of [`extent_before`](Self::extent_before),
29/// [`extent_inside`](Self::extent_inside), and [`extent_after`](Self::extent_after), which
30/// may be more useful for use cases such as scroll bars.
31///
32/// See also:
33///
34/// * [`FixedScrollMetrics`], which is an immutable object that implements this
35/// interface.
36pub trait ScrollMetrics: Debug {
37 /// Downcast support for Dart's `is` on a metrics object (`position is _PagePosition`).
38 fn as_any(&self) -> &dyn Any;
39
40 /// Creates a [`ScrollMetrics`] that has the same properties as this object.
41 ///
42 /// This is useful if this object is mutable, but you want to get a snapshot
43 /// of the current state.
44 ///
45 /// The `with_*` setters on the result allow the values to be adjusted in the process.
46 /// This is useful to examine hypothetical situations, for example "would applying this
47 /// delta unmodified take the position [`out_of_range`](Self::out_of_range)?".
48 fn copy_with(&self) -> FixedScrollMetrics {
49 FixedScrollMetrics::new(
50 self.has_content_dimensions()
51 .then(|| self.min_scroll_extent()),
52 self.has_content_dimensions()
53 .then(|| self.max_scroll_extent()),
54 self.has_pixels().then(|| self.pixels()),
55 self.has_viewport_dimension()
56 .then(|| self.viewport_dimension()),
57 self.axis_direction(),
58 self.device_pixel_ratio(),
59 )
60 }
61
62 /// The minimum in-range value for [`pixels`](Self::pixels).
63 ///
64 /// The actual [`pixels`](Self::pixels) value might be
65 /// [`out_of_range`](Self::out_of_range).
66 ///
67 /// This value is typically less than or equal to
68 /// [`max_scroll_extent`](Self::max_scroll_extent). It can be negative infinity, if the
69 /// scroll is unbounded.
70 fn min_scroll_extent(&self) -> f64;
71
72 /// The maximum in-range value for [`pixels`](Self::pixels).
73 ///
74 /// The actual [`pixels`](Self::pixels) value might be
75 /// [`out_of_range`](Self::out_of_range).
76 ///
77 /// This value is typically greater than or equal to
78 /// [`min_scroll_extent`](Self::min_scroll_extent). It can be infinity, if the scroll is
79 /// unbounded.
80 ///
81 /// For scrollables that lazily construct their contents, such as
82 /// `ListView.builder`, this value can be an estimate that changes as more
83 /// children are laid out.
84 fn max_scroll_extent(&self) -> f64;
85
86 /// Whether the [`min_scroll_extent`](Self::min_scroll_extent) and the
87 /// [`max_scroll_extent`](Self::max_scroll_extent) properties are available.
88 fn has_content_dimensions(&self) -> bool;
89
90 /// The current scroll position, in logical pixels along the
91 /// [`axis_direction`](Self::axis_direction).
92 fn pixels(&self) -> f64;
93
94 /// Whether the [`pixels`](Self::pixels) property is available.
95 fn has_pixels(&self) -> bool;
96
97 /// The extent of the viewport along the [`axis_direction`](Self::axis_direction).
98 fn viewport_dimension(&self) -> f64;
99
100 /// Whether the [`viewport_dimension`](Self::viewport_dimension) property is available.
101 fn has_viewport_dimension(&self) -> bool;
102
103 /// The direction in which the scroll view scrolls.
104 fn axis_direction(&self) -> AxisDirection;
105
106 /// The axis in which the scroll view scrolls.
107 fn axis(&self) -> Axis {
108 axis_direction_to_axis(self.axis_direction())
109 }
110
111 /// Whether the [`pixels`](Self::pixels) value is outside the
112 /// [`min_scroll_extent`](Self::min_scroll_extent) and
113 /// [`max_scroll_extent`](Self::max_scroll_extent).
114 fn out_of_range(&self) -> bool {
115 self.pixels() < self.min_scroll_extent() || self.pixels() > self.max_scroll_extent()
116 }
117
118 /// Whether the [`pixels`](Self::pixels) value is exactly at the
119 /// [`min_scroll_extent`](Self::min_scroll_extent) or the
120 /// [`max_scroll_extent`](Self::max_scroll_extent).
121 fn at_edge(&self) -> bool {
122 self.pixels() == self.min_scroll_extent() || self.pixels() == self.max_scroll_extent()
123 }
124
125 /// The quantity of content conceptually "above" the viewport in the scrollable.
126 /// This is the content above the content described by
127 /// [`extent_inside`](Self::extent_inside).
128 fn extent_before(&self) -> f64 {
129 (self.pixels() - self.min_scroll_extent()).max(0.0)
130 }
131
132 /// The quantity of content conceptually "inside" the viewport in the
133 /// scrollable (including empty space if the total amount of content is less
134 /// than the [`viewport_dimension`](Self::viewport_dimension)).
135 ///
136 /// The value is typically the extent of the viewport
137 /// ([`viewport_dimension`](Self::viewport_dimension)) when
138 /// [`out_of_range`](Self::out_of_range) is false. It can be less when overscrolling.
139 ///
140 /// The value is always non-negative, and less than or equal to
141 /// [`viewport_dimension`](Self::viewport_dimension).
142 fn extent_inside(&self) -> f64 {
143 debug_assert!(self.min_scroll_extent() <= self.max_scroll_extent());
144 self.viewport_dimension()
145 // "above" overscroll value
146 - clamp_double(
147 self.min_scroll_extent() - self.pixels(),
148 0.0,
149 self.viewport_dimension(),
150 )
151 // "below" overscroll value
152 - clamp_double(
153 self.pixels() - self.max_scroll_extent(),
154 0.0,
155 self.viewport_dimension(),
156 )
157 }
158
159 /// The quantity of content conceptually "below" the viewport in the scrollable.
160 /// This is the content below the content described by
161 /// [`extent_inside`](Self::extent_inside).
162 fn extent_after(&self) -> f64 {
163 (self.max_scroll_extent() - self.pixels()).max(0.0)
164 }
165
166 /// The total quantity of content available.
167 ///
168 /// This is the sum of [`extent_before`](Self::extent_before),
169 /// [`extent_inside`](Self::extent_inside), and [`extent_after`](Self::extent_after),
170 /// modulo any rounding errors.
171 fn extent_total(&self) -> f64 {
172 self.max_scroll_extent() - self.min_scroll_extent() + self.viewport_dimension()
173 }
174
175 /// The `FlutterView.devicePixelRatio` of the view that the `Scrollable`
176 /// associated with this metrics object is drawn into.
177 fn device_pixel_ratio(&self) -> f64;
178}
179
180/// An immutable snapshot of values associated with a `Scrollable` viewport.
181///
182/// For details, see [`ScrollMetrics`], which defines this object's interfaces.
183#[derive(Clone, Copy)]
184pub struct FixedScrollMetrics {
185 min_scroll_extent: Option<f64>,
186 max_scroll_extent: Option<f64>,
187 pixels: Option<f64>,
188 viewport_dimension: Option<f64>,
189 axis_direction: AxisDirection,
190 device_pixel_ratio: f64,
191}
192
193impl FixedScrollMetrics {
194 /// Creates an immutable snapshot of values associated with a `Scrollable` viewport.
195 pub fn new(
196 min_scroll_extent: Option<f64>,
197 max_scroll_extent: Option<f64>,
198 pixels: Option<f64>,
199 viewport_dimension: Option<f64>,
200 axis_direction: AxisDirection,
201 device_pixel_ratio: f64,
202 ) -> FixedScrollMetrics {
203 FixedScrollMetrics {
204 min_scroll_extent,
205 max_scroll_extent,
206 pixels,
207 viewport_dimension,
208 axis_direction,
209 device_pixel_ratio,
210 }
211 }
212
213 /// Dart `copyWith(minScrollExtent:)`.
214 pub fn with_min_scroll_extent(mut self, min_scroll_extent: f64) -> FixedScrollMetrics {
215 self.min_scroll_extent = Some(min_scroll_extent);
216 self
217 }
218
219 /// Dart `copyWith(maxScrollExtent:)`.
220 pub fn with_max_scroll_extent(mut self, max_scroll_extent: f64) -> FixedScrollMetrics {
221 self.max_scroll_extent = Some(max_scroll_extent);
222 self
223 }
224
225 /// Dart `copyWith(pixels:)`.
226 pub fn with_pixels(mut self, pixels: f64) -> FixedScrollMetrics {
227 self.pixels = Some(pixels);
228 self
229 }
230
231 /// Dart `copyWith(viewportDimension:)`.
232 pub fn with_viewport_dimension(mut self, viewport_dimension: f64) -> FixedScrollMetrics {
233 self.viewport_dimension = Some(viewport_dimension);
234 self
235 }
236
237 /// Dart `copyWith(axisDirection:)`.
238 pub fn with_axis_direction(mut self, axis_direction: AxisDirection) -> FixedScrollMetrics {
239 self.axis_direction = axis_direction;
240 self
241 }
242
243 /// Dart `copyWith(devicePixelRatio:)`.
244 pub fn with_device_pixel_ratio(mut self, device_pixel_ratio: f64) -> FixedScrollMetrics {
245 self.device_pixel_ratio = device_pixel_ratio;
246 self
247 }
248}
249
250impl ScrollMetrics for FixedScrollMetrics {
251 fn as_any(&self) -> &dyn Any {
252 self
253 }
254
255 fn min_scroll_extent(&self) -> f64 {
256 self.min_scroll_extent
257 .expect("FixedScrollMetrics.minScrollExtent was read without content dimensions")
258 }
259
260 fn max_scroll_extent(&self) -> f64 {
261 self.max_scroll_extent
262 .expect("FixedScrollMetrics.maxScrollExtent was read without content dimensions")
263 }
264
265 fn has_content_dimensions(&self) -> bool {
266 self.min_scroll_extent.is_some() && self.max_scroll_extent.is_some()
267 }
268
269 fn pixels(&self) -> f64 {
270 self.pixels
271 .expect("FixedScrollMetrics.pixels was read before it was available")
272 }
273
274 fn has_pixels(&self) -> bool {
275 self.pixels.is_some()
276 }
277
278 fn viewport_dimension(&self) -> f64 {
279 self.viewport_dimension
280 .expect("FixedScrollMetrics.viewportDimension was read before it was available")
281 }
282
283 fn has_viewport_dimension(&self) -> bool {
284 self.viewport_dimension.is_some()
285 }
286
287 fn axis_direction(&self) -> AxisDirection {
288 self.axis_direction
289 }
290
291 fn device_pixel_ratio(&self) -> f64 {
292 self.device_pixel_ratio
293 }
294}
295
296impl Debug for FixedScrollMetrics {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 write!(
299 f,
300 "FixedScrollMetrics({:.1}..[{:.1}]..{:.1})",
301 self.extent_before(),
302 self.extent_inside(),
303 self.extent_after()
304 )
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn overscrolled() -> FixedScrollMetrics {
313 FixedScrollMetrics::new(
314 Some(0.0),
315 Some(400.0),
316 Some(-20.0),
317 Some(600.0),
318 AxisDirection::Down,
319 3.0,
320 )
321 }
322
323 #[test]
324 fn out_of_range_and_at_edge_read_the_pixels_against_the_extents() {
325 let metrics = overscrolled();
326 assert!(metrics.out_of_range());
327 assert!(!metrics.at_edge());
328
329 let at_min = metrics.copy_with().with_pixels(0.0);
330 assert!(!at_min.out_of_range());
331 assert!(at_min.at_edge());
332
333 let at_max = metrics.copy_with().with_pixels(400.0);
334 assert!(!at_max.out_of_range());
335 assert!(at_max.at_edge());
336
337 let inside = metrics.copy_with().with_pixels(100.0);
338 assert!(!inside.out_of_range());
339 assert!(!inside.at_edge());
340 }
341
342 #[test]
343 fn the_extents_split_the_content_around_the_viewport() {
344 let metrics = overscrolled();
345 assert_eq!(metrics.extent_before(), 0.0);
346 assert_eq!(metrics.extent_inside(), 580.0);
347 assert_eq!(metrics.extent_after(), 420.0);
348 assert_eq!(metrics.extent_total(), 1000.0);
349 assert_eq!(metrics.axis(), Axis::Vertical);
350 assert_eq!(
351 format!("{metrics:?}"),
352 "FixedScrollMetrics(0.0..[580.0]..420.0)"
353 );
354
355 let inside = metrics.copy_with().with_pixels(100.0);
356 assert_eq!(inside.extent_before(), 100.0);
357 assert_eq!(inside.extent_inside(), 600.0);
358 assert_eq!(inside.extent_after(), 300.0);
359 }
360
361 #[test]
362 fn copy_with_carries_the_absent_values_across() {
363 let empty = FixedScrollMetrics::new(None, None, None, None, AxisDirection::Right, 2.0);
364 assert!(!empty.has_content_dimensions());
365 assert!(!empty.has_pixels());
366 assert!(!empty.has_viewport_dimension());
367 assert_eq!(empty.axis(), Axis::Horizontal);
368
369 let copy = empty.copy_with().with_pixels(7.0);
370 assert!(!copy.has_content_dimensions());
371 assert_eq!(copy.pixels(), 7.0);
372 assert_eq!(copy.device_pixel_ratio(), 2.0);
373
374 let full = overscrolled().copy_with();
375 assert!(full.has_content_dimensions());
376 assert!(full.has_pixels());
377 assert!(full.has_viewport_dimension());
378 }
379}