Skip to main content

pax_std/layout/
resizable.rs

1use crate::*;
2#[allow(unused)]
3use pax_engine::api::LocalProperty;
4use pax_engine::api::*;
5use pax_engine::*;
6use std::cmp::Ordering;
7
8/// Divides slotted content into resizable horizontal or vertical sections.
9///
10/// `dividers` contains positions along the main axis. With `n` dividers,
11/// `Resizable` expects `n + 1` slot children.
12#[pax]
13#[engine_import_path("pax_engine")]
14#[inlined(
15    <Group
16        @mouse_down=on_mouse_down
17        @mouse_move=on_mouse_move
18        @mouse_up=on_mouse_up
19    >
20        for s in self._sections {
21            <Group
22                x={s.x}
23                y={s.y}
24                width={s.width}
25                height={s.height}
26                anchor_x=0%
27                anchor_y=0%
28            >
29                slot(s.i)
30            </Group>
31        }
32        <Rectangle fill=rgb(20, 20, 20)/>
33    </Group>
34
35    @settings {
36        @mount: on_mount
37    }
38)]
39pub struct Resizable {
40    /// Divider positions along the main axis.
41    pub dividers: Property<Vec<Size>>,
42    /// Whether sections are split horizontally or vertically.
43    pub direction: Property<ResizableDirection>,
44
45    // Computed sections emitted into the inline template.
46    pub _sections: Property<Vec<Section>>,
47    // Divider currently being dragged, if any.
48    pub _index_moving: Property<Option<usize>>,
49}
50
51/// Axis direction for a `Resizable` split.
52#[pax]
53#[engine_import_path("pax_engine")]
54pub enum ResizableDirection {
55    /// Split content into top-to-bottom sections.
56    Vertical,
57    /// Split content into left-to-right sections.
58    #[default]
59    Horizontal,
60}
61
62// Internal section rectangle emitted into the inline template.
63#[pax]
64#[engine_import_path("pax_engine")]
65pub struct Section {
66    // Section x position.
67    pub x: Size,
68    // Section y position.
69    pub y: Size,
70    // Section width.
71    pub width: Size,
72    // Section height.
73    pub height: Size,
74    // Slot index rendered into this section.
75    pub i: usize,
76}
77
78impl Resizable {
79    // Computes section rectangles from divider positions and slot count.
80    pub fn on_mount(&mut self, ctx: &NodeContext) {
81        let slot_count = ctx.projected_children_count.clone();
82        let dividers = self.dividers.local();
83        let direction = self.direction.local();
84        let deps = [
85            slot_count.untyped(),
86            dividers.untyped(),
87            direction.untyped(),
88        ];
89
90        self._sections.replace_with(LocalProperty::computed(
91            move || {
92                let divs = dividers.get();
93                if slot_count.get() != divs.len() + 1 {
94                    log::warn!("slots in Resizable doesn't match number of Segments")
95                };
96
97                let mut positions = Vec::new();
98                positions.push(Size::ZERO());
99                positions.extend(divs);
100                positions.push(Size::default());
101                let mut sections = vec![];
102                for (i, w) in positions.windows(2).enumerate() {
103                    let (pos_main, extent_main) = (w[0].clone(), w[1] - w[0]);
104                    let (pos_off, extent_off) = (Size::ZERO(), Size::default());
105                    let (x, width, y, height) = match direction.get() {
106                        ResizableDirection::Vertical => {
107                            (pos_off, extent_off, pos_main, extent_main)
108                        }
109                        ResizableDirection::Horizontal => {
110                            (pos_main, extent_main, pos_off, extent_off)
111                        }
112                    };
113                    sections.push(Section {
114                        x,
115                        width,
116                        y,
117                        height,
118                        i,
119                    })
120                }
121                sections
122            },
123            &deps,
124        ));
125    }
126
127    // Starts dragging the nearest divider when the pointer is close enough.
128    pub fn on_mouse_down(&mut self, ctx: &NodeContext, event: Event<MouseDown>) {
129        let bounds = ctx.bounds_self.get();
130
131        let (dim, axis) = match self.direction.get() {
132            ResizableDirection::Vertical => (event.mouse.y, Axis::Y),
133            ResizableDirection::Horizontal => (event.mouse.x, Axis::X),
134        };
135        let (closest_ind, distance) = self
136            .dividers
137            .get()
138            .iter()
139            .map(|d| (d.evaluate(bounds, axis) - dim).abs())
140            .enumerate()
141            .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
142            .unwrap_or_default();
143        if distance < 10.0 {
144            self._index_moving.set(Some(closest_ind));
145        }
146    }
147
148    // Updates the active divider position while dragging.
149    pub fn on_mouse_move(&mut self, ctx: &NodeContext, event: Event<MouseMove>) {
150        let bounds = ctx.bounds_self.get();
151
152        let (dim, bound) = match self.direction.get() {
153            ResizableDirection::Vertical => (event.mouse.y, bounds.1),
154            ResizableDirection::Horizontal => (event.mouse.x, bounds.0),
155        };
156
157        if let Some(ind) = self._index_moving.get() {
158            self.dividers.update(|dividers| {
159                let divider = &mut dividers[ind];
160                *divider = match divider.clone() {
161                    Size::Percent(_) => Size::Percent((100.0 * dim / bound).into()),
162                    Size::Pixels(_) => Size::Pixels(dim.into()),
163                    Size::Combined(_, perc) => {
164                        Size::Combined((dim - perc.to_float() * bound / 100.0).into(), perc)
165                    }
166                };
167            });
168        }
169    }
170
171    // Ends any in-progress divider drag.
172    pub fn on_mouse_up(&mut self, _ctx: &NodeContext, _event: Event<MouseUp>) {
173        self._index_moving.set(None);
174    }
175}