Skip to main content

lumen_dioxus/layout/
resizable.rs

1//! `Resizable` and `ResizablePanel`: panes split by keyboard- and pointer-operable separators.
2//!
3//! The sizing rules port `useResizable` from `@santi020k/lumen-react`: percentages normalized to
4//! 100, per-pane minimum (default 12) and maximum (default 88), and pair-wise resizing that keeps
5//! both neighbors inside their limits.
6
7// cspell:words onmousedown onmousemove onmouseup onpointercancel
8
9use std::rc::Rc;
10use std::time::Duration;
11
12use dioxus::html::input_data::MouseButton;
13use dioxus::prelude::*;
14
15use super::structure::use_direction;
16use super::util::{ContainerElement, attr, directional_key, element, join_style, js_number};
17use crate::class::compose;
18
19/// Axis along which a [`Resizable`] lays out its panes.
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum ResizableDirection {
22    /// Panes side by side, separated by vertical handles.
23    #[default]
24    Horizontal,
25    /// Panes stacked, separated by horizontal handles.
26    Vertical,
27}
28
29impl ResizableDirection {
30    /// The `data-orientation` value.
31    pub fn as_str(self) -> &'static str {
32        match self {
33            Self::Horizontal => "horizontal",
34            Self::Vertical => "vertical",
35        }
36    }
37}
38
39const DEFAULT_MIN_SIZE: f64 = 12.0;
40const DEFAULT_MAX_SIZE: f64 = 88.0;
41/// Largest pane count, like the `useResizable` guard.
42const MAX_PANELS: usize = 1000;
43/// Container length assumed when the renderer cannot measure it.
44const DEFAULT_DRAG_EXTENT: f64 = 800.0;
45/// Two presses on the same handle within this window reset the sizes.
46const DOUBLE_PRESS: Duration = Duration::from_millis(400);
47
48/// `values[i] ?? values[0] ?? fallback` for every pane.
49pub(crate) fn resizable_number_list(values: &[f64], count: usize, fallback: f64) -> Vec<f64> {
50    (0..count)
51        .map(|index| {
52            values
53                .get(index)
54                .or(values.first())
55                .copied()
56                .unwrap_or(fallback)
57        })
58        .collect()
59}
60
61/// The `default_sizes` the sizing state is keyed on, with every non-finite size replaced by 0.
62///
63/// `NaN != NaN`, so a `NaN` default would make every render look like new defaults and drop the
64/// user's resize. [`normalize_resizable_sizes`] gives 0 the same even share as `NaN` or an
65/// infinity, so the sizes do not change.
66pub(crate) fn resizable_default_sizes(values: &[f64]) -> Vec<f64> {
67    values
68        .iter()
69        .map(|size| if size.is_finite() { *size } else { 0.0 })
70        .collect()
71}
72
73/// Replaces unusable sizes with an even share and scales the sizes to sum to 100.
74pub(crate) fn normalize_resizable_sizes(sizes: &[f64], count: usize) -> Vec<f64> {
75    #[allow(clippy::cast_precision_loss, reason = "pane counts are capped at 1000")]
76    let fallback = 100.0 / count.max(1) as f64;
77    let usable: Vec<f64> = (0..count)
78        .map(|index| {
79            let size = sizes.get(index).copied().unwrap_or(fallback);
80            if size.is_finite() && size > 0.0 {
81                size
82            } else {
83                fallback
84            }
85        })
86        .collect();
87    let total = usable.iter().fold(0.0, |sum, size| sum + size);
88
89    if total <= 0.0 {
90        return vec![fallback; count];
91    }
92
93    usable.iter().map(|size| (size / total) * 100.0).collect()
94}
95
96/// Sets pane `index` to `next` and gives the remainder of the pair to pane `index + 1`, keeping
97/// both inside their limits.
98pub(crate) fn resize_pair(
99    sizes: &[f64],
100    index: usize,
101    next: f64,
102    min: &[f64],
103    max: &[f64],
104) -> Vec<f64> {
105    let mut sizes = sizes.to_vec();
106    let after = index + 1;
107
108    if after >= sizes.len() || !next.is_finite() {
109        return sizes;
110    }
111
112    let total = sizes[index] + sizes[after];
113    let lower = min
114        .get(index)
115        .copied()
116        .unwrap_or(0.0)
117        .max(total - max.get(after).copied().unwrap_or(100.0));
118    let upper = max
119        .get(index)
120        .copied()
121        .unwrap_or(100.0)
122        .min(total - min.get(after).copied().unwrap_or(0.0));
123    let pane = upper.min(lower.max(next));
124
125    sizes[index] = pane;
126    sizes[after] = total - pane;
127    sizes
128}
129
130/// `Math.round`: halves round up.
131fn js_round(value: f64) -> f64 {
132    (value + 0.5).floor()
133}
134
135#[derive(Clone, Debug, PartialEq)]
136struct ResizableConfig {
137    count: usize,
138    default_sizes: Vec<f64>,
139    min: Vec<f64>,
140    max: Vec<f64>,
141    direction: ResizableDirection,
142    reset: bool,
143    right_to_left: bool,
144    drag_extent: f64,
145}
146
147impl ResizableConfig {
148    fn initial_sizes(&self) -> Vec<f64> {
149        #[allow(clippy::cast_precision_loss, reason = "pane counts are capped at 1000")]
150        let even = 100.0 / self.count.max(1) as f64;
151        normalize_resizable_sizes(
152            &resizable_number_list(&self.default_sizes, self.count, even),
153            self.count,
154        )
155    }
156
157    fn min_sizes(&self) -> Vec<f64> {
158        resizable_number_list(&self.min, self.count, DEFAULT_MIN_SIZE)
159    }
160
161    fn max_sizes(&self) -> Vec<f64> {
162        resizable_number_list(&self.max, self.count, DEFAULT_MAX_SIZE)
163    }
164
165    /// What resets the sizes when it changes, like `initialSizes` in `useResizable`.
166    fn sizes_key(&self) -> (usize, Vec<f64>) {
167        (self.count, self.default_sizes.clone())
168    }
169}
170
171#[derive(Clone, Copy, Debug, PartialEq)]
172struct ResizableDrag {
173    index: usize,
174    start: f64,
175    start_size: f64,
176    extent: f64,
177    /// Started by touch or pen through pointer events, which keep targeting the handle.
178    pointer: bool,
179}
180
181type StoredSizes = Option<((usize, Vec<f64>), Vec<f64>)>;
182
183#[derive(Clone, Copy)]
184struct ResizableContext {
185    config: Signal<ResizableConfig>,
186    stored: Signal<StoredSizes>,
187    next_order: CopyValue<usize>,
188    drag: Signal<Option<ResizableDrag>>,
189    root: Signal<Option<Rc<MountedData>>>,
190    measured: Signal<Option<(f64, f64)>>,
191    on_change: Signal<Option<EventHandler<Vec<f64>>>>,
192    press: Signal<Option<(usize, u64)>>,
193    press_generation: CopyValue<u64>,
194}
195
196impl ResizableContext {
197    fn effective(config: &ResizableConfig, stored: &StoredSizes) -> Vec<f64> {
198        match stored {
199            Some((key, sizes)) if *key == config.sizes_key() => sizes.clone(),
200            _ => config.initial_sizes(),
201        }
202    }
203
204    /// Current sizes; subscribes the caller.
205    fn sizes(&self) -> Vec<f64> {
206        Self::effective(&self.config.read(), &self.stored.read())
207    }
208
209    fn sizes_peek(&self) -> Vec<f64> {
210        Self::effective(&self.config.peek(), &self.stored.peek())
211    }
212
213    fn update(&self, next: Vec<f64>) {
214        let key = self.config.peek().sizes_key();
215        let mut stored = self.stored;
216        stored.set(Some((key, next.clone())));
217
218        if let Some(handler) = *self.on_change.peek() {
219            handler.call(next);
220        }
221    }
222
223    fn resize(&self, index: usize, next: f64) {
224        let config = self.config.peek().clone();
225        let sizes = resize_pair(
226            &self.sizes_peek(),
227            index,
228            next,
229            &config.min_sizes(),
230            &config.max_sizes(),
231        );
232        self.update(sizes);
233    }
234
235    fn reset(&self) {
236        let initial = self.config.peek().initial_sizes();
237        self.update(initial);
238    }
239
240    fn axis(&self, point: (f64, f64)) -> f64 {
241        match self.config.peek().direction {
242            ResizableDirection::Horizontal => point.0,
243            ResizableDirection::Vertical => point.1,
244        }
245    }
246
247    fn start_drag(&self, index: usize, point: (f64, f64), pointer: bool) {
248        let config = self.config.peek().clone();
249        let start_size = self.sizes_peek().get(index).copied().unwrap_or(0.0);
250        let measured = (*self.measured.peek()).map(|(width, height)| match config.direction {
251            ResizableDirection::Horizontal => width,
252            ResizableDirection::Vertical => height,
253        });
254        let mut drag = self.drag;
255        drag.set(Some(ResizableDrag {
256            index,
257            start: self.axis(point),
258            start_size,
259            extent: measured.unwrap_or(config.drag_extent).max(1.0),
260            pointer,
261        }));
262
263        // Refresh the measurement where the renderer supports it (web and desktop).
264        if let Some(root) = self.root.peek().clone() {
265            let mut measured = self.measured;
266            spawn(async move {
267                if let Ok(rect) = root.get_client_rect().await {
268                    let size = (rect.width(), rect.height());
269                    measured.set(Some(size));
270                    let extent = match config.direction {
271                        ResizableDirection::Horizontal => size.0,
272                        ResizableDirection::Vertical => size.1,
273                    };
274
275                    if let Some(current) = drag.write().as_mut() {
276                        current.extent = extent.max(1.0);
277                    }
278                }
279            });
280        }
281    }
282
283    fn move_drag(&self, point: (f64, f64), pointer: bool) {
284        let Some(drag) = *self.drag.peek() else {
285            return;
286        };
287
288        if drag.pointer != pointer {
289            return;
290        }
291
292        let config = self.config.peek().clone();
293        let delta = (self.axis(point) - drag.start) / drag.extent * 100.0;
294        let flip = config.direction == ResizableDirection::Horizontal && config.right_to_left;
295        let multiplier = if flip { -1.0 } else { 1.0 };
296
297        self.resize(drag.index, drag.start_size + delta * multiplier);
298    }
299
300    fn finish_drag(&self) {
301        let mut drag = self.drag;
302
303        if drag.peek().is_some() {
304            drag.set(None);
305        }
306    }
307
308    /// Records a press and reports whether it completes a double press on the same handle.
309    fn double_press(&self, index: usize) -> bool {
310        let mut press = self.press;
311
312        if matches!(*press.peek(), Some((pressed, _)) if pressed == index) {
313            press.set(None);
314            return true;
315        }
316
317        let mut generation = self.press_generation;
318        let token = *generation.peek() + 1;
319        generation.set(token);
320        press.set(Some((index, token)));
321
322        spawn(async move {
323            crate::time::sleep(DOUBLE_PRESS).await;
324
325            if matches!(*press.peek(), Some((_, current)) if current == token) {
326                press.set(None);
327            }
328        });
329
330        false
331    }
332}
333
334fn use_resizable(component: &str) -> ResizableContext {
335    try_use_context::<ResizableContext>()
336        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Resizable."))
337}
338
339fn serialize_sizes(values: &[f64]) -> Option<String> {
340    (!values.is_empty()).then(|| {
341        values
342            .iter()
343            .map(|value| js_number(*value))
344            .collect::<Vec<_>>()
345            .join(",")
346    })
347}
348
349/// Props for [`Resizable`].
350#[derive(Props, Clone, PartialEq)]
351pub struct ResizableProps {
352    /// Layout axis.
353    #[props(default)]
354    pub direction: ResizableDirection,
355    /// Initial pane sizes in percent, normalized to 100. Unset panes share the space evenly.
356    #[props(default)]
357    pub default_sizes: Vec<f64>,
358    /// Minimum pane sizes in percent. One value applies to every pane. Defaults to 12.
359    #[props(default)]
360    pub min_size: Vec<f64>,
361    /// Maximum pane sizes in percent. One value applies to every pane. Defaults to 88.
362    #[props(default)]
363    pub max_size: Vec<f64>,
364    /// Number of [`ResizablePanel`]s. Defaults to the length of `default_sizes`, or the mounted
365    /// panel count. Set it (or `default_sizes`) so server-rendered sizes are right.
366    pub panel_count: Option<usize>,
367    /// Pressing a handle twice resets the sizes. Defaults to `true`.
368    #[props(default = true)]
369    pub reset_on_double_click: bool,
370    /// Container length in pixels used to turn drag distance into percent when the renderer
371    /// cannot measure the container (Dioxus Native). Web and desktop measure it. Defaults to 800.
372    pub drag_extent: Option<f64>,
373    /// Called with the new sizes after every resize or reset.
374    pub on_sizes_change: Option<EventHandler<Vec<f64>>>,
375    /// Extra classes appended after the Lumen classes.
376    #[props(into)]
377    pub class: Option<String>,
378    /// Any other `<div>` or global attribute.
379    #[props(extends = GlobalAttributes, extends = div)]
380    pub attributes: Vec<Attribute>,
381    /// [`ResizablePanel`]s. Handles are inserted between them.
382    pub children: Element,
383}
384
385/// Panes separated by handles that resize the panes on either side.
386///
387/// Handles follow the WAI-ARIA window splitter pattern: arrow keys move by 2 percent (10 with
388/// Shift, flipped horizontally in right-to-left layouts), Home and End jump to the limits, and
389/// dragging with the mouse, touch, or pen resizes.
390#[component]
391pub fn Resizable(props: ResizableProps) -> Element {
392    let right_to_left = use_direction().is_rtl();
393    let mut registered = use_signal(|| 2_usize);
394    let count = props
395        .panel_count
396        .unwrap_or_else(|| {
397            if props.default_sizes.is_empty() {
398                registered()
399            } else {
400                props.default_sizes.len()
401            }
402        })
403        .min(MAX_PANELS);
404    let config = ResizableConfig {
405        count,
406        default_sizes: resizable_default_sizes(&props.default_sizes),
407        min: props.min_size.clone(),
408        max: props.max_size.clone(),
409        direction: props.direction,
410        reset: props.reset_on_double_click,
411        right_to_left,
412        drag_extent: props.drag_extent.unwrap_or(DEFAULT_DRAG_EXTENT),
413    };
414    let mut config_signal = use_signal(|| config.clone());
415    let mut on_change = use_signal(|| props.on_sizes_change);
416    let resizable = use_context_provider(|| ResizableContext {
417        config: config_signal,
418        stored: Signal::new(None),
419        next_order: CopyValue::new(0),
420        drag: Signal::new(None),
421        root: Signal::new(None),
422        measured: Signal::new(None),
423        on_change,
424        press: Signal::new(None),
425        press_generation: CopyValue::new(0),
426    });
427
428    if *config_signal.peek() != config {
429        config_signal.set(config);
430    }
431
432    if *on_change.peek() != props.on_sizes_change {
433        on_change.set(props.on_sizes_change);
434    }
435
436    // Panels register while rendering; adopt their count once they have mounted.
437    use_effect(move || {
438        let mounted = *resizable.next_order.peek();
439
440        if mounted != *registered.peek() {
441            registered.set(mounted);
442        }
443    });
444
445    let drag = (resizable.drag)();
446    let vertical = props.direction == ResizableDirection::Vertical;
447    let class = compose([
448        Some("ui-resizable"),
449        vertical.then_some("ui-resizable--vertical"),
450        props.class.as_deref(),
451    ]);
452    let cursor = if vertical { "row-resize" } else { "col-resize" };
453
454    rsx! {
455        div {
456            class,
457            "data-orientation": props.direction.as_str(),
458            "data-resizing": drag.is_some().then_some("true"),
459            "data-ui-resizable": "true",
460            "data-ui-resizable-default-sizes": serialize_sizes(&props.default_sizes),
461            "data-ui-resizable-enhanced": "true",
462            "data-ui-resizable-max-size": serialize_sizes(&props.max_size),
463            "data-ui-resizable-min-size": serialize_sizes(&props.min_size),
464            "data-ui-resizable-reset": props.reset_on_double_click.then_some("true"),
465            onmounted: move |event| {
466                let mut root = resizable.root;
467                root.set(Some(event.data()));
468            },
469            onmousemove: move |event| {
470                let point = event.client_coordinates();
471                resizable.move_drag((point.x, point.y), false);
472            },
473            onmouseup: move |_| {
474                if resizable.drag.peek().is_some_and(|drag| !drag.pointer) {
475                    resizable.finish_drag();
476                }
477            },
478            ..props.attributes,
479            {props.children}
480            if drag.is_some_and(|drag| !drag.pointer) {
481                // Catches the mouse while dragging, so the drag survives leaving the thin handle.
482                div {
483                    aria_hidden: "true",
484                    "data-slot": "resizable-drag-layer",
485                    style: "position: fixed; inset: 0; z-index: 2147483647; padding: 0; background: transparent; cursor: {cursor}",
486                }
487            }
488        }
489    }
490}
491
492/// Props for [`ResizablePanel`].
493#[derive(Props, Clone, PartialEq)]
494pub struct ResizablePanelProps {
495    /// The rendered element. Defaults to `<div>`.
496    #[props(default)]
497    pub r#as: ContainerElement,
498    /// Inline style. The pane size is appended after it.
499    #[props(into)]
500    pub style: Option<String>,
501    /// Classes for the pane.
502    #[props(into)]
503    pub class: Option<String>,
504    /// Any other global attribute.
505    #[props(extends = GlobalAttributes, extends = div)]
506    pub attributes: Vec<Attribute>,
507    /// Pane content.
508    pub children: Element,
509}
510
511/// One pane of a [`Resizable`]. Every pane after the first renders the handle before it.
512///
513/// Panes are numbered in mount order; keep the set of panes stable.
514#[component]
515pub fn ResizablePanel(props: ResizablePanelProps) -> Element {
516    let resizable = use_resizable("ResizablePanel");
517    let index = use_hook(|| {
518        let mut next_order = resizable.next_order;
519        let order = *next_order.peek();
520        next_order.set(order + 1);
521        order
522    });
523    let sizes = resizable.sizes();
524    let config = (resizable.config)();
525    let size = format!(
526        "--ui-resizable-size: {}%",
527        js_number(sizes.get(index).copied().unwrap_or(0.0))
528    );
529    let mut attributes = vec![
530        attr("class", compose([props.class.as_deref()])),
531        attr("data-ui-resizable-panel", "true"),
532    ];
533
534    if let Some(style) = join_style([props.style.as_deref(), Some(size.as_str())]) {
535        attributes.push(attr("style", style));
536    }
537
538    attributes.extend(props.attributes);
539
540    let dragging = (*resizable.drag.read()).map(|drag| drag.index);
541    let handle = index.checked_sub(1).map(|handle| {
542        resizable_handle(
543            &resizable,
544            &config,
545            &sizes,
546            handle,
547            dragging == Some(handle),
548        )
549    });
550
551    rsx! {
552        {handle}
553        {element(props.r#as, attributes, props.children)}
554    }
555}
556
557fn resizable_handle(
558    resizable: &ResizableContext,
559    config: &ResizableConfig,
560    sizes: &[f64],
561    index: usize,
562    active: bool,
563) -> Element {
564    let min = config.min_sizes();
565    let max = config.max_sizes();
566    let value_min = js_number(js_round(min.get(index).copied().unwrap_or(0.0)));
567    let value_max = js_number(js_round(max.get(index).copied().unwrap_or(100.0)));
568    let value_now = js_number(js_round(sizes.get(index).copied().unwrap_or(0.0)));
569    let orientation = match config.direction {
570        ResizableDirection::Horizontal => "vertical",
571        ResizableDirection::Vertical => "horizontal",
572    };
573    let direction = config.direction;
574    let right_to_left = config.right_to_left;
575    let reset = config.reset;
576    let resizable = *resizable;
577
578    rsx! {
579        button {
580            aria_label: "Resize panel {index + 1}",
581            aria_orientation: orientation,
582            aria_valuemax: value_max,
583            aria_valuemin: value_min,
584            aria_valuenow: value_now,
585            class: "ui-resizable__handle",
586            "data-active": active.then_some("true"),
587            "data-index": index.to_string(),
588            "data-ui-resizable-handle": "true",
589            role: "separator",
590            tabindex: "0",
591            r#type: "button",
592            onkeydown: move |event| {
593                let config = resizable.config.peek().clone();
594
595                match event.key() {
596                    Key::Home => {
597                        event.prevent_default();
598                        resizable.resize(index, config.min_sizes().get(index).copied().unwrap_or(0.0));
599                    }
600                    Key::End => {
601                        event.prevent_default();
602                        resizable.resize(index, config.max_sizes().get(index).copied().unwrap_or(100.0));
603                    }
604                    key => {
605                        let step = if event.modifiers().shift() { 10.0 } else { 2.0 };
606                        let delta = match (direction, directional_key(&key, right_to_left)) {
607                            (ResizableDirection::Horizontal, Key::ArrowLeft)
608                            | (ResizableDirection::Vertical, Key::ArrowUp) => -step,
609                            (ResizableDirection::Horizontal, Key::ArrowRight)
610                            | (ResizableDirection::Vertical, Key::ArrowDown) => step,
611                            _ => return,
612                        };
613                        event.prevent_default();
614                        let current = resizable.sizes_peek().get(index).copied().unwrap_or(0.0);
615                        resizable.resize(index, current + delta);
616                    }
617                }
618            },
619            onmousedown: move |event| {
620                if event.trigger_button() != Some(MouseButton::Primary) {
621                    return;
622                }
623
624                event.prevent_default();
625
626                if resizable.double_press(index) {
627                    if reset {
628                        resizable.reset();
629                    }
630
631                    return;
632                }
633
634                let point = event.client_coordinates();
635                resizable.start_drag(index, (point.x, point.y), false);
636            },
637            onpointerdown: move |event| {
638                // Mouse input uses the mouse events above, which Dioxus Native also delivers.
639                if event.pointer_type() == "mouse" {
640                    return;
641                }
642
643                let point = event.client_coordinates();
644                resizable.start_drag(index, (point.x, point.y), true);
645            },
646            onpointermove: move |event| {
647                if event.pointer_type() != "mouse" {
648                    let point = event.client_coordinates();
649                    resizable.move_drag((point.x, point.y), true);
650                }
651            },
652            onpointerup: move |event| {
653                if event.pointer_type() != "mouse" {
654                    resizable.finish_drag();
655                }
656            },
657            onpointercancel: move |event| {
658                if event.pointer_type() != "mouse" {
659                    resizable.finish_drag();
660                }
661            },
662        }
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::{
669        normalize_resizable_sizes, resizable_default_sizes, resizable_number_list, resize_pair,
670    };
671
672    #[test]
673    fn non_finite_default_sizes_compare_equal_and_normalize_alike() {
674        let raw = [f64::NAN, f64::INFINITY, 30.0, f64::NEG_INFINITY];
675        let sanitized = resizable_default_sizes(&raw);
676
677        assert_eq!(sanitized, vec![0.0, 0.0, 30.0, 0.0]);
678        assert_eq!(sanitized, resizable_default_sizes(&raw));
679        assert_eq!(
680            normalize_resizable_sizes(&sanitized, 4),
681            normalize_resizable_sizes(&raw, 4)
682        );
683    }
684
685    #[test]
686    fn number_lists_fall_back_to_the_first_value() {
687        assert_eq!(resizable_number_list(&[], 3, 12.0), vec![12.0; 3]);
688        assert_eq!(resizable_number_list(&[18.0], 3, 12.0), vec![18.0; 3]);
689        assert_eq!(
690            resizable_number_list(&[18.0, 24.0], 3, 12.0),
691            vec![18.0, 24.0, 18.0]
692        );
693    }
694
695    #[test]
696    fn sizes_normalize_to_one_hundred() {
697        assert_eq!(normalize_resizable_sizes(&[1.0, 1.0], 2), vec![50.0, 50.0]);
698        assert_eq!(
699            normalize_resizable_sizes(&[28.0, 44.0, 28.0], 3),
700            vec![28.000_000_000_000_004, 44.0, 28.000_000_000_000_004]
701        );
702        assert_eq!(
703            normalize_resizable_sizes(&[f64::NAN, -1.0], 2),
704            vec![50.0, 50.0]
705        );
706        assert_eq!(normalize_resizable_sizes(&[], 4), vec![25.0; 4]);
707        assert_eq!(normalize_resizable_sizes(&[], 0), Vec::<f64>::new());
708    }
709
710    #[test]
711    fn resizing_keeps_both_panes_in_their_limits() {
712        let min = [12.0, 12.0];
713        let max = [88.0, 88.0];
714        assert_eq!(
715            resize_pair(&[50.0, 50.0], 0, 60.0, &min, &max),
716            vec![60.0, 40.0]
717        );
718        assert_eq!(
719            resize_pair(&[50.0, 50.0], 0, 99.0, &min, &max),
720            vec![88.0, 12.0]
721        );
722        assert_eq!(
723            resize_pair(&[50.0, 50.0], 0, -5.0, &min, &max),
724            vec![12.0, 88.0]
725        );
726        assert_eq!(
727            resize_pair(&[50.0, 50.0], 1, 60.0, &min, &max),
728            vec![50.0, 50.0]
729        );
730        assert_eq!(
731            resize_pair(&[50.0, 50.0], 0, f64::NAN, &min, &max),
732            vec![50.0, 50.0]
733        );
734    }
735
736    #[test]
737    fn the_neighbor_limits_bound_the_pane() {
738        // The second pane may not grow past 70, so the first stays at or above 30.
739        let sizes = resize_pair(&[40.0, 60.0], 0, 10.0, &[5.0, 5.0], &[95.0, 70.0]);
740        assert_eq!(sizes, vec![30.0, 70.0]);
741    }
742}