Skip to main content

xrack_layout/
search.rs

1use crate::{LayoutNode, Point, Rect, place_in_direction};
2use xrack_runtime::{ControlAction, LayoutDirection, Node, text_input_value};
3
4pub struct SearchGeometry {
5    pub submit: Rect,
6    pub entry: Rect,
7    pub clear: Rect,
8}
9
10impl SearchGeometry {
11    pub fn new(bounds: Rect) -> Self {
12        Self::with_layout_direction(bounds, LayoutDirection::LeftToRight)
13    }
14
15    pub fn for_layout(layout: &LayoutNode) -> Self {
16        Self::with_layout_direction(layout.bounds, layout.layout_direction)
17    }
18
19    pub fn with_layout_direction(bounds: Rect, direction: LayoutDirection) -> Self {
20        let button = (bounds.width * 0.25).min(30.0);
21        let entry = bounds.width - 2.0 * button;
22        let mirror = |rect| place_in_direction(rect, bounds, direction);
23        Self {
24            submit: mirror(Rect::new(bounds.x, bounds.y, button, bounds.height)),
25            entry: Rect::new(bounds.x + button, bounds.y, entry, bounds.height),
26            clear: mirror(Rect::new(
27                bounds.x + button + entry,
28                bounds.y,
29                button,
30                bounds.height,
31            )),
32        }
33    }
34
35    pub fn actions(&self, node: &Node) -> impl Iterator<Item = (Rect, ControlAction)> {
36        let clear = (!node.boolean("read-only", false) && !text_input_value(node).is_empty())
37            .then_some((self.clear, ControlAction::ClearSearch));
38        [(self.submit, ControlAction::SubmitSearch)]
39            .into_iter()
40            .chain(clear)
41    }
42
43    pub fn action_at(&self, node: &Node, point: Point) -> Option<ControlAction> {
44        self.actions(node)
45            .find_map(|(rect, action)| rect.contains(point).then_some(action))
46    }
47}