Skip to main content

qframe/widgets/
splitter.rs

1//! Splitters: two panes side by side or stacked, divided by a boundary that is never a line.
2
3use crate::event::Event;
4use crate::geometry::{Rect, Size};
5use crate::widget::{Axis as FlexAxis, EventCx, Flex, Length, MeasureCx, Node, NodeMut, PaintCx, View, Widget};
6
7use super::boundary::{self, Axis, Change};
8
9type Pane<'a, Msg> = Box<dyn FnOnce(&mut View<'_, Msg>) + 'a>;
10
11/// Builds a message from a new size in cells.
12type SizeMessage<Msg> = Box<dyn Fn(u16) -> Msg>;
13
14/// Two panes that share an area: side by side with [`Splitter::columns`], stacked with
15/// [`Splitter::rows`]. The application owns the size of the first pane; the second takes the
16/// rest.
17///
18/// Without [`Splitter::on_resize`] the panes simply sit next to each other. With it, a one-cell
19/// boundary separates them. The boundary is invisible until the pointer reaches it: then it
20/// brightens one step, and while dragged it takes the accent. It can also be focused with Tab
21/// and moved with the arrow keys (Shift moves five cells, Home and End jump to the limits).
22///
23/// Style keys: `split-handle` (`bg`, `fg`) with `hover`, `focus` and `active` (dragging).
24pub struct Splitter<'a, Msg> {
25    axis: Axis,
26    size: u16,
27    min: u16,
28    max: Option<u16>,
29    on_resize: Option<SizeMessage<Msg>>,
30    first: Option<Pane<'a, Msg>>,
31    second: Option<Pane<'a, Msg>>,
32}
33
34impl<'a, Msg: 'static> Splitter<'a, Msg> {
35    fn new(axis: Axis, size: u16) -> Self {
36        Self { axis, size, min: 1, max: None, on_resize: None, first: None, second: None }
37    }
38
39    /// Panes side by side; the first (left) pane is `width` columns wide.
40    #[must_use]
41    pub fn columns(width: u16) -> Self {
42        Self::new(Axis::Columns, width)
43    }
44
45    /// Stacked panes; the first (top) pane is `height` rows tall.
46    #[must_use]
47    pub fn rows(height: u16) -> Self {
48        Self::new(Axis::Rows, height)
49    }
50
51    /// The smallest and largest size of the first pane, in cells: `limits(16, 60)` for a range, or
52    /// `limits(16, None)` for no upper limit. By default 1 and no upper limit; whatever the limits,
53    /// the second pane keeps at least one cell. A `max` below `min` counts as `min`.
54    #[must_use]
55    pub fn limits(mut self, min: u16, max: impl Into<Option<u16>>) -> Self {
56        self.min = min;
57        self.max = max.into();
58        self
59    }
60
61    /// Makes the boundary draggable and focusable; the message carries the first pane's new
62    /// size, already within the limits.
63    #[must_use]
64    pub fn on_resize(mut self, message: impl Fn(u16) -> Msg + 'static) -> Self {
65        self.on_resize = Some(Box::new(message));
66        self
67    }
68
69    /// The left or top pane.
70    #[must_use]
71    pub fn first(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
72        self.first = Some(Box::new(build));
73        self
74    }
75
76    /// The right or bottom pane.
77    #[must_use]
78    pub fn second(mut self, build: impl FnOnce(&mut View<'_, Msg>) + 'a) -> Self {
79        self.second = Some(Box::new(build));
80        self
81    }
82
83    /// Adds the splitter to `ui`, filling the space it gets.
84    pub fn show<'v>(self, ui: &'v mut View<'_, Msg>) -> NodeMut<'v, Msg> {
85        let build = |pane: Option<Pane<'a, Msg>>| {
86            let mut children = Vec::new();
87            if let Some(pane) = pane {
88                pane(&mut ui.nested(&mut children));
89            }
90            let mut node = Node::new(Flex::new(FlexAxis::Column, children), 0);
91            node.layout.width = Length::Fill(1);
92            node.layout.height = Length::Fill(1);
93            node
94        };
95        let split = Split {
96            axis: self.axis,
97            size: self.size,
98            min: self.min,
99            max: self.max,
100            on_resize: self.on_resize,
101            panes: vec![build(self.first), build(self.second)],
102        };
103        ui.add(split).fill()
104    }
105}
106
107struct Split<Msg> {
108    axis: Axis,
109    size: u16,
110    min: u16,
111    /// The largest first pane the application allows; `None` for no limit.
112    max: Option<u16>,
113    on_resize: Option<SizeMessage<Msg>>,
114    panes: Vec<Node<Msg>>,
115}
116
117impl<Msg: 'static> Split<Msg> {
118    fn extent(&self, area: Rect) -> u16 {
119        match self.axis {
120            Axis::Columns => area.width,
121            Axis::Rows => area.height,
122        }
123    }
124
125    /// The largest first-pane size within the limits that leaves the handle and one cell of the
126    /// second pane.
127    fn max_size(&self, area: Rect) -> u16 {
128        let handle = u16::from(self.on_resize.is_some());
129        let room = self.extent(area).saturating_sub(handle + 1);
130        self.max.map_or(room, |max| max.min(room))
131    }
132
133    fn first_size(&self, area: Rect) -> u16 {
134        boundary::clamp_size(i32::from(self.size), self.min, self.max_size(area)).min(self.extent(area))
135    }
136
137    fn resize(&self, cx: &mut EventCx<'_, Msg>, target: i32) {
138        let area = cx.area();
139        let size = boundary::clamp_size(target, self.min, self.max_size(area));
140        if let Some(message) = &self.on_resize
141            && size != self.first_size(area)
142        {
143            cx.emit(message(size));
144        }
145    }
146}
147
148impl<Msg: 'static> Widget<Msg> for Split<Msg> {
149    fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
150        available
151    }
152
153    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
154        let first = self.first_size(area);
155        let handle = u16::from(self.on_resize.is_some());
156        let rest = self.extent(area).saturating_sub(first + handle);
157        let offset = |cells: u16| i32::from(cells);
158        let (first_rect, handle_rect, second_rect) = match self.axis {
159            Axis::Columns => (
160                Rect::new(area.x, area.y, first, area.height),
161                Rect::new(area.x + offset(first), area.y, handle, area.height),
162                Rect::new(area.x + offset(first + handle), area.y, rest, area.height),
163            ),
164            Axis::Rows => (
165                Rect::new(area.x, area.y, area.width, first),
166                Rect::new(area.x, area.y + offset(first), area.width, handle),
167                Rect::new(area.x, area.y + offset(first + handle), area.width, rest),
168            ),
169        };
170        cx.paint_child(&self.panes[0], first_rect);
171        cx.paint_child(&self.panes[1], second_rect);
172        if self.on_resize.is_some() {
173            boundary::paint(cx, handle_rect, None);
174        }
175    }
176
177    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
178        if self.on_resize.is_none() {
179            return false;
180        }
181        let area = cx.area();
182        let current = i32::from(self.first_size(area));
183        match boundary::event(cx, event, self.axis) {
184            Change::Ignored => false,
185            Change::Used | Change::Activate => true,
186            Change::DragTo(at) => {
187                let start = match self.axis {
188                    Axis::Columns => area.x,
189                    Axis::Rows => area.y,
190                };
191                self.resize(cx, at - start);
192                true
193            }
194            Change::Nudge(cells) => {
195                self.resize(cx, current + cells);
196                true
197            }
198            Change::Jump(end) => {
199                self.resize(cx, if end { i32::MAX } else { 0 });
200                true
201            }
202        }
203    }
204
205    fn focusable(&self) -> bool {
206        self.on_resize.is_some()
207    }
208
209    fn children(&self) -> &[Node<Msg>] {
210        &self.panes
211    }
212
213    fn children_mut(&mut self) -> &mut [Node<Msg>] {
214        &mut self.panes
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::event::{MouseButton, MouseKind};
222    use crate::runtime::{App, Command, Harness};
223    use crate::theme::State;
224    use crate::widgets::Text;
225
226    struct Demo {
227        size: u16,
228        rows: bool,
229        resizable: bool,
230        max: Option<u16>,
231    }
232
233    impl App for Demo {
234        type Msg = u16;
235        fn update(&mut self, size: u16) -> Command<u16> {
236            self.size = size;
237            Command::none()
238        }
239        fn view(&self, ui: &mut View<'_, u16>) {
240            let split = if self.rows { Splitter::rows(self.size) } else { Splitter::columns(self.size) };
241            let split = if self.resizable { split.on_resize(|size| size) } else { split };
242            split
243                .limits(3, self.max)
244                .first(|ui| {
245                    ui.add(Text::new("left"));
246                })
247                .second(|ui| {
248                    ui.add(Text::new("right"));
249                })
250                .show(ui)
251                .id("split");
252        }
253    }
254
255    #[test]
256    fn plain_panes_sit_side_by_side_without_a_boundary() {
257        let h = Harness::new(Demo { size: 6, rows: false, resizable: false, max: Some(12) }, 20, 2);
258        assert_eq!(h.screen(), "left  right\n\n");
259    }
260
261    #[test]
262    fn boundary_is_invisible_until_hovered_and_takes_the_accent_while_dragged() {
263        let mut h = Harness::new(Demo { size: 6, rows: false, resizable: true, max: Some(12) }, 20, 3);
264        assert_eq!(h.screen(), "left   right\n\n\n");
265        let theme = h.env().theme();
266        let canvas = theme.color("canvas");
267        let hover = theme.style("split-handle", None, &[State::Hover]).paint("bg").map(|p| p.at(0.0));
268        let active = theme.style("split-handle", None, &[State::Active]).paint("bg").map(|p| p.at(0.0));
269        assert_eq!(h.bg(6, 1), canvas);
270        h.hover(6, 1);
271        assert_eq!(h.bg(6, 1), hover);
272        assert_ne!(hover, canvas);
273        h.mouse(MouseKind::Down(MouseButton::Left), 6, 1);
274        h.mouse(MouseKind::Drag(MouseButton::Left), 9, 1);
275        assert_eq!(h.app().size, 9);
276        assert_eq!(h.bg(9, 0), active);
277        h.mouse(MouseKind::Drag(MouseButton::Left), 30, 1);
278        assert_eq!(h.app().size, 12, "limited by max");
279        h.mouse(MouseKind::Up(MouseButton::Left), 30, 1);
280        assert_eq!(h.screen(), "left         right\n\n\n");
281    }
282
283    #[test]
284    fn keyboard_moves_the_focused_boundary() {
285        let mut h = Harness::new(Demo { size: 6, rows: true, resizable: true, max: Some(12) }, 20, 20);
286        h.press("tab");
287        assert!(h.is_focused("split"));
288        h.press("down");
289        assert_eq!(h.app().size, 7);
290        h.press("shift+up");
291        assert_eq!(h.app().size, 3, "limited by min");
292        h.press("end");
293        assert_eq!(h.app().size, 12);
294        assert_eq!(h.screen().lines().nth(13), Some("right"));
295    }
296
297    #[test]
298    fn without_an_upper_limit_only_the_second_pane_stops_the_boundary() {
299        let mut h = Harness::new(Demo { size: 6, rows: false, resizable: true, max: None }, 20, 3);
300        h.mouse(MouseKind::Down(MouseButton::Left), 6, 1);
301        h.mouse(MouseKind::Drag(MouseButton::Left), 30, 1);
302        assert_eq!(h.app().size, 18, "20 columns: the handle and one cell of the second pane stay");
303        h.mouse(MouseKind::Drag(MouseButton::Left), 0, 1);
304        assert_eq!(h.app().size, 3, "the lower limit still holds");
305        h.mouse(MouseKind::Up(MouseButton::Left), 0, 1);
306        h.press("end");
307        assert_eq!(h.app().size, 18);
308        assert_eq!(h.screen(), "left               r\n                   i\n                   g\n");
309        h.press("home");
310        assert_eq!(h.app().size, 3);
311    }
312
313    #[test]
314    fn a_max_below_min_counts_as_min() {
315        let mut h = Harness::new(Demo { size: 6, rows: false, resizable: true, max: Some(2) }, 20, 1);
316        assert_eq!(h.screen(), "lef right\n", "the first pane is held at the minimum of 3");
317        h.press("tab").press("right");
318        assert_eq!(h.app().size, 6, "already at the only allowed size: nothing to send");
319    }
320
321    #[test]
322    fn narrow_area_keeps_the_second_pane() {
323        let h = Harness::new(Demo { size: 12, rows: false, resizable: true, max: Some(12) }, 8, 1);
324        assert_eq!(h.screen(), "left   r\n");
325    }
326}