Skip to main content

tessera_components/
pos_misc.rs

1//! Convenience utilities for testing whether a cursor/point falls inside a
2//! component or a rectangle. Functions operate using Px units and simple
3//! inclusive comparisons on edges.
4
5use tessera_ui::{ComputedData, Px, PxPosition};
6
7/// Returns true if `position` is inside a component of the given `size`.
8/// The component is assumed to be located at the origin (0, 0).
9pub fn is_position_inside_bounds(size: ComputedData, position: PxPosition) -> bool {
10    is_position_in_rect(position, PxPosition::ZERO, size.width, size.height)
11}
12
13/// Returns true when `position` lies within the rectangle defined by
14/// `rect_pos`, `rect_width` and `rect_height` (inclusive).
15pub fn is_position_in_rect(
16    position: PxPosition,
17    rect_pos: PxPosition,
18    rect_width: Px,
19    rect_height: Px,
20) -> bool {
21    let x = position.x;
22    let y = position.y;
23    let rect_x = rect_pos.x;
24    let rect_y = rect_pos.y;
25
26    let within_x = x >= rect_x && x <= rect_x + rect_width.0 as f32;
27    let within_y = y >= rect_y && y <= rect_y + rect_height.0 as f32;
28    within_x && within_y
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn test_is_position_inside_bounds() {
37        let size = ComputedData {
38            width: Px(100),
39            height: Px(50),
40        };
41        assert!(is_position_inside_bounds(
42            size,
43            PxPosition::new(Px(50), Px(25))
44        ));
45        assert!(!is_position_inside_bounds(
46            size,
47            PxPosition::new(Px(150), Px(25))
48        ));
49        assert!(!is_position_inside_bounds(
50            size,
51            PxPosition::new(Px(50), Px(75))
52        ));
53    }
54}