1use crate::{LayoutNode, Point, Rect, Size, place_in_direction};
2use xrack_runtime::{LayoutDirection, Node, SpinAction};
3
4pub struct SpinGeometry {
5 pub text: Rect,
6 pub up: Rect,
7 pub down: Rect,
8}
9
10impl SpinGeometry {
11 const DEFAULT_WIDTH: f32 = 28.0;
12
13 pub fn new(bounds: Rect) -> Self {
14 Self::with_stepper_width(bounds, Self::DEFAULT_WIDTH, LayoutDirection::LeftToRight)
15 }
16
17 pub fn for_node(bounds: Rect, node: &Node) -> Self {
18 Self::with_layout_direction(bounds, node, node.layout_direction().unwrap_or_default())
19 }
20
21 pub fn for_layout(layout: &LayoutNode, node: &Node) -> Self {
22 Self::with_layout_direction(layout.bounds, node, layout.layout_direction)
23 }
24
25 pub(crate) fn with_layout_direction(
26 bounds: Rect,
27 node: &Node,
28 direction: LayoutDirection,
29 ) -> Self {
30 Self::with_stepper_width(bounds, Self::preferred_stepper_size(node).width, direction)
31 }
32
33 pub(crate) fn preferred_stepper_size(node: &Node) -> Size {
34 let mut size = Size::new(Self::DEFAULT_WIDTH, 0.0);
35 for kind in ["SpinUpIndicator", "SpinDownIndicator"] {
36 if let Some(part) = node.control_part(kind) {
37 size.width = size.width.max(part.length("width").unwrap_or(0.0));
38 size.height = size.height.max(2.0 * part.length("height").unwrap_or(0.0));
39 }
40 }
41 size
42 }
43
44 fn with_stepper_width(bounds: Rect, preferred: f32, direction: LayoutDirection) -> Self {
45 let width = preferred.min(bounds.width * 0.5);
46 let half_height = bounds.height * 0.5;
47 let x = bounds.x + bounds.width - width;
48 let mirror = |rect| place_in_direction(rect, bounds, direction);
49 Self {
50 text: mirror(Rect::new(
51 bounds.x,
52 bounds.y,
53 bounds.width - width,
54 bounds.height,
55 )),
56 up: mirror(Rect::new(x, bounds.y, width, half_height)),
57 down: mirror(Rect::new(x, bounds.y + half_height, width, half_height)),
58 }
59 }
60
61 pub fn action_at(&self, point: Point) -> Option<SpinAction> {
62 if self.up.contains(point) {
63 Some(SpinAction::Increase)
64 } else if self.down.contains(point) {
65 Some(SpinAction::Decrease)
66 } else {
67 None
68 }
69 }
70}