Skip to main content

hyprforge_ui/widgets/
split.rs

1//! The divider between two panes side by side, as something to drag.
2//!
3//! The line is [`super::vertical_divider`]'s hairline; what this adds is
4//! a hit area around it wide enough to grab, the resize cursor that says
5//! it can be, and the arithmetic for where a drag leaves it — kept here,
6//! pure, so every two-pane window splits by the same rule.
7
8use iced::widget::{container, mouse_area};
9use iced::{mouse, Element, Length};
10
11/// How wide the grabbable strip is. The line stays one pixel; a strip
12/// that narrow is a target nobody can hit, and one much wider eats into
13/// both panes.
14pub const SPLIT_HANDLE_WIDTH: f32 = 7.0;
15
16/// The divider, draggable: `on_press` starts a drag (the host follows the
17/// pointer until the button is let go, and asks [`split_ratio`] where it
18/// is), `on_reset` is a double click, which puts the halves back even.
19pub fn split_handle<'a, Message: Clone + 'a>(on_press: Message, on_reset: Message) -> Element<'a, Message> {
20    let strip = container(super::vertical_divider())
21        .width(Length::Fixed(SPLIT_HANDLE_WIDTH))
22        .height(Length::Fill)
23        .center_x(Length::Fixed(SPLIT_HANDLE_WIDTH));
24    mouse_area(strip)
25        .interaction(mouse::Interaction::ResizingHorizontally)
26        .on_press(on_press)
27        .on_double_click(on_reset)
28        .into()
29}
30
31/// Where a divider dragged to `x` in a `width`-wide area leaves it, as the
32/// left pane's share — never so far that either pane is narrower than
33/// `min_side`. An area too narrow for two of those splits evenly, the
34/// one answer that favours neither.
35pub fn split_ratio(x: f32, width: f32, min_side: f32) -> f32 {
36    if !(x.is_finite() && width.is_finite()) || width <= 2.0 * min_side {
37        return 0.5;
38    }
39    let edge = min_side / width;
40    (x / width).clamp(edge, 1.0 - edge)
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn a_drag_follows_the_pointer_but_never_squeezes_a_pane_below_its_minimum() {
49        assert_eq!(split_ratio(300.0, 1000.0, 200.0), 0.3);
50        assert_eq!(split_ratio(50.0, 1000.0, 200.0), 0.2, "left kept at 200");
51        assert_eq!(split_ratio(990.0, 1000.0, 200.0), 0.8, "right kept at 200");
52    }
53
54    #[test]
55    fn an_area_too_narrow_for_two_minimums_splits_evenly() {
56        assert_eq!(split_ratio(100.0, 300.0, 200.0), 0.5);
57        assert_eq!(split_ratio(f32::NAN, 1000.0, 200.0), 0.5);
58    }
59}