cranpose_foundation/bring_into_view_spec.rs
1/// Where a scroll container puts a child that asks to be seen, such as a
2/// control that takes focus. Compose's `BringIntoViewSpec`, which a
3/// container reads from `local_bring_into_view_spec()`.
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub enum BringIntoViewSpec {
6 /// Scrolls as little as shows the child, and not at all while the child
7 /// is in view or larger than the container. Compose's default spec.
8 #[default]
9 Default,
10 /// Puts the child's leading edge at a fixed place in the container on
11 /// every request, so focus stays at one place while the content moves.
12 /// A child that would not fit after that place ends at the container's
13 /// end instead. Compose's pivot spec on a TV is
14 /// `Pivot { parent_fraction: 0.3, child_fraction: 0.0 }`.
15 Pivot {
16 /// The place, as a fraction of the container's size.
17 parent_fraction: f32,
18 /// How far the child sits before that place, as a fraction of the
19 /// child's size: 0.5 centers it on the place.
20 child_fraction: f32,
21 },
22}
23
24impl BringIntoViewSpec {
25 /// How far the container scrolls to put a child where this spec wants
26 /// it. The child starts `offset` past the container's leading edge and
27 /// is `size` long; the container is `container_size` long. A positive
28 /// answer moves the content toward the leading edge. Compose's
29 /// `calculateScrollDistance`.
30 pub fn calculate_scroll_distance(self, offset: f32, size: f32, container_size: f32) -> f32 {
31 match self {
32 Self::Default => {
33 let trailing = offset + size;
34 if (offset >= 0.0 && trailing <= container_size)
35 || (offset < 0.0 && trailing > container_size)
36 {
37 0.0
38 } else if offset.abs() < (trailing - container_size).abs() {
39 offset
40 } else {
41 trailing - container_size
42 }
43 }
44 Self::Pivot {
45 parent_fraction,
46 child_fraction,
47 } => {
48 let pivot = parent_fraction * container_size - child_fraction * size;
49 let target = if size <= container_size && container_size - pivot < size {
50 container_size - size
51 } else {
52 pivot
53 };
54 offset - target
55 }
56 }
57 }
58}