tessera_ui_basic_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).
9///
10/// This is a small convenience wrapper around [`is_position_in_rect`].
11pub fn is_position_in_component(size: ComputedData, position: PxPosition) -> bool {
12    is_position_in_rect(position, PxPosition::ZERO, size.width, size.height)
13}
14
15/// Returns true when `position` lies within the rectangle defined by
16/// `rect_pos`, `rect_width` and `rect_height` (inclusive).
17///
18/// Coordinates use Px units and comparisons are inclusive on edges. The check
19/// evaluates X and Y independently and returns true only if both are within
20/// bounds.
21pub fn is_position_in_rect(
22    position: PxPosition,
23    rect_pos: PxPosition,
24    rect_width: Px,
25    rect_height: Px,
26) -> bool {
27    let x = position.x;
28    let y = position.y;
29    let rect_x = rect_pos.x;
30    let rect_y = rect_pos.y;
31
32    // Check X and Y independently and combine for clarity.
33    let within_x = x >= rect_x && x <= rect_x + rect_width;
34    let within_y = y >= rect_y && y <= rect_y + rect_height;
35    within_x && within_y
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_is_position_in_component() {
44        let size = ComputedData {
45            width: Px(100),
46            height: Px(50),
47        };
48        assert!(is_position_in_component(
49            size,
50            PxPosition::new(Px(50), Px(25))
51        ));
52        assert!(!is_position_in_component(
53            size,
54            PxPosition::new(Px(150), Px(25))
55        ));
56        assert!(!is_position_in_component(
57            size,
58            PxPosition::new(Px(50), Px(75))
59        ));
60    }
61}