lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! `Resizable` and `ResizablePanel`: panes split by keyboard- and pointer-operable separators.
//!
//! The sizing rules port `useResizable` from `@santi020k/lumen-react`: percentages normalized to
//! 100, per-pane minimum (default 12) and maximum (default 88), and pair-wise resizing that keeps
//! both neighbors inside their limits.

// cspell:words onmousedown onmousemove onmouseup onpointercancel

use std::rc::Rc;
use std::time::Duration;

use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;

use super::structure::use_direction;
use super::util::{ContainerElement, attr, directional_key, element, join_style, js_number};
use crate::class::compose;

/// Axis along which a [`Resizable`] lays out its panes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ResizableDirection {
    /// Panes side by side, separated by vertical handles.
    #[default]
    Horizontal,
    /// Panes stacked, separated by horizontal handles.
    Vertical,
}

impl ResizableDirection {
    /// The `data-orientation` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Horizontal => "horizontal",
            Self::Vertical => "vertical",
        }
    }
}

const DEFAULT_MIN_SIZE: f64 = 12.0;
const DEFAULT_MAX_SIZE: f64 = 88.0;
/// Largest pane count, like the `useResizable` guard.
const MAX_PANELS: usize = 1000;
/// Container length assumed when the renderer cannot measure it.
const DEFAULT_DRAG_EXTENT: f64 = 800.0;
/// Two presses on the same handle within this window reset the sizes.
const DOUBLE_PRESS: Duration = Duration::from_millis(400);

/// `values[i] ?? values[0] ?? fallback` for every pane.
pub(crate) fn resizable_number_list(values: &[f64], count: usize, fallback: f64) -> Vec<f64> {
    (0..count)
        .map(|index| {
            values
                .get(index)
                .or(values.first())
                .copied()
                .unwrap_or(fallback)
        })
        .collect()
}

/// The `default_sizes` the sizing state is keyed on, with every non-finite size replaced by 0.
///
/// `NaN != NaN`, so a `NaN` default would make every render look like new defaults and drop the
/// user's resize. [`normalize_resizable_sizes`] gives 0 the same even share as `NaN` or an
/// infinity, so the sizes do not change.
pub(crate) fn resizable_default_sizes(values: &[f64]) -> Vec<f64> {
    values
        .iter()
        .map(|size| if size.is_finite() { *size } else { 0.0 })
        .collect()
}

/// Replaces unusable sizes with an even share and scales the sizes to sum to 100.
pub(crate) fn normalize_resizable_sizes(sizes: &[f64], count: usize) -> Vec<f64> {
    #[allow(clippy::cast_precision_loss, reason = "pane counts are capped at 1000")]
    let fallback = 100.0 / count.max(1) as f64;
    let usable: Vec<f64> = (0..count)
        .map(|index| {
            let size = sizes.get(index).copied().unwrap_or(fallback);
            if size.is_finite() && size > 0.0 {
                size
            } else {
                fallback
            }
        })
        .collect();
    let total = usable.iter().fold(0.0, |sum, size| sum + size);

    if total <= 0.0 {
        return vec![fallback; count];
    }

    usable.iter().map(|size| (size / total) * 100.0).collect()
}

/// Sets pane `index` to `next` and gives the remainder of the pair to pane `index + 1`, keeping
/// both inside their limits.
pub(crate) fn resize_pair(
    sizes: &[f64],
    index: usize,
    next: f64,
    min: &[f64],
    max: &[f64],
) -> Vec<f64> {
    let mut sizes = sizes.to_vec();
    let after = index + 1;

    if after >= sizes.len() || !next.is_finite() {
        return sizes;
    }

    let total = sizes[index] + sizes[after];
    let lower = min
        .get(index)
        .copied()
        .unwrap_or(0.0)
        .max(total - max.get(after).copied().unwrap_or(100.0));
    let upper = max
        .get(index)
        .copied()
        .unwrap_or(100.0)
        .min(total - min.get(after).copied().unwrap_or(0.0));
    let pane = upper.min(lower.max(next));

    sizes[index] = pane;
    sizes[after] = total - pane;
    sizes
}

/// `Math.round`: halves round up.
fn js_round(value: f64) -> f64 {
    (value + 0.5).floor()
}

#[derive(Clone, Debug, PartialEq)]
struct ResizableConfig {
    count: usize,
    default_sizes: Vec<f64>,
    min: Vec<f64>,
    max: Vec<f64>,
    direction: ResizableDirection,
    reset: bool,
    right_to_left: bool,
    drag_extent: f64,
}

impl ResizableConfig {
    fn initial_sizes(&self) -> Vec<f64> {
        #[allow(clippy::cast_precision_loss, reason = "pane counts are capped at 1000")]
        let even = 100.0 / self.count.max(1) as f64;
        normalize_resizable_sizes(
            &resizable_number_list(&self.default_sizes, self.count, even),
            self.count,
        )
    }

    fn min_sizes(&self) -> Vec<f64> {
        resizable_number_list(&self.min, self.count, DEFAULT_MIN_SIZE)
    }

    fn max_sizes(&self) -> Vec<f64> {
        resizable_number_list(&self.max, self.count, DEFAULT_MAX_SIZE)
    }

    /// What resets the sizes when it changes, like `initialSizes` in `useResizable`.
    fn sizes_key(&self) -> (usize, Vec<f64>) {
        (self.count, self.default_sizes.clone())
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
struct ResizableDrag {
    index: usize,
    start: f64,
    start_size: f64,
    extent: f64,
    /// Started by touch or pen through pointer events, which keep targeting the handle.
    pointer: bool,
}

type StoredSizes = Option<((usize, Vec<f64>), Vec<f64>)>;

#[derive(Clone, Copy)]
struct ResizableContext {
    config: Signal<ResizableConfig>,
    stored: Signal<StoredSizes>,
    next_order: CopyValue<usize>,
    drag: Signal<Option<ResizableDrag>>,
    root: Signal<Option<Rc<MountedData>>>,
    measured: Signal<Option<(f64, f64)>>,
    on_change: Signal<Option<EventHandler<Vec<f64>>>>,
    press: Signal<Option<(usize, u64)>>,
    press_generation: CopyValue<u64>,
}

impl ResizableContext {
    fn effective(config: &ResizableConfig, stored: &StoredSizes) -> Vec<f64> {
        match stored {
            Some((key, sizes)) if *key == config.sizes_key() => sizes.clone(),
            _ => config.initial_sizes(),
        }
    }

    /// Current sizes; subscribes the caller.
    fn sizes(&self) -> Vec<f64> {
        Self::effective(&self.config.read(), &self.stored.read())
    }

    fn sizes_peek(&self) -> Vec<f64> {
        Self::effective(&self.config.peek(), &self.stored.peek())
    }

    fn update(&self, next: Vec<f64>) {
        let key = self.config.peek().sizes_key();
        let mut stored = self.stored;
        stored.set(Some((key, next.clone())));

        if let Some(handler) = *self.on_change.peek() {
            handler.call(next);
        }
    }

    fn resize(&self, index: usize, next: f64) {
        let config = self.config.peek().clone();
        let sizes = resize_pair(
            &self.sizes_peek(),
            index,
            next,
            &config.min_sizes(),
            &config.max_sizes(),
        );
        self.update(sizes);
    }

    fn reset(&self) {
        let initial = self.config.peek().initial_sizes();
        self.update(initial);
    }

    fn axis(&self, point: (f64, f64)) -> f64 {
        match self.config.peek().direction {
            ResizableDirection::Horizontal => point.0,
            ResizableDirection::Vertical => point.1,
        }
    }

    fn start_drag(&self, index: usize, point: (f64, f64), pointer: bool) {
        let config = self.config.peek().clone();
        let start_size = self.sizes_peek().get(index).copied().unwrap_or(0.0);
        let measured = (*self.measured.peek()).map(|(width, height)| match config.direction {
            ResizableDirection::Horizontal => width,
            ResizableDirection::Vertical => height,
        });
        let mut drag = self.drag;
        drag.set(Some(ResizableDrag {
            index,
            start: self.axis(point),
            start_size,
            extent: measured.unwrap_or(config.drag_extent).max(1.0),
            pointer,
        }));

        // Refresh the measurement where the renderer supports it (web and desktop).
        if let Some(root) = self.root.peek().clone() {
            let mut measured = self.measured;
            spawn(async move {
                if let Ok(rect) = root.get_client_rect().await {
                    let size = (rect.width(), rect.height());
                    measured.set(Some(size));
                    let extent = match config.direction {
                        ResizableDirection::Horizontal => size.0,
                        ResizableDirection::Vertical => size.1,
                    };

                    if let Some(current) = drag.write().as_mut() {
                        current.extent = extent.max(1.0);
                    }
                }
            });
        }
    }

    fn move_drag(&self, point: (f64, f64), pointer: bool) {
        let Some(drag) = *self.drag.peek() else {
            return;
        };

        if drag.pointer != pointer {
            return;
        }

        let config = self.config.peek().clone();
        let delta = (self.axis(point) - drag.start) / drag.extent * 100.0;
        let flip = config.direction == ResizableDirection::Horizontal && config.right_to_left;
        let multiplier = if flip { -1.0 } else { 1.0 };

        self.resize(drag.index, drag.start_size + delta * multiplier);
    }

    fn finish_drag(&self) {
        let mut drag = self.drag;

        if drag.peek().is_some() {
            drag.set(None);
        }
    }

    /// Records a press and reports whether it completes a double press on the same handle.
    fn double_press(&self, index: usize) -> bool {
        let mut press = self.press;

        if matches!(*press.peek(), Some((pressed, _)) if pressed == index) {
            press.set(None);
            return true;
        }

        let mut generation = self.press_generation;
        let token = *generation.peek() + 1;
        generation.set(token);
        press.set(Some((index, token)));

        spawn(async move {
            crate::time::sleep(DOUBLE_PRESS).await;

            if matches!(*press.peek(), Some((_, current)) if current == token) {
                press.set(None);
            }
        });

        false
    }
}

fn use_resizable(component: &str) -> ResizableContext {
    try_use_context::<ResizableContext>()
        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Resizable."))
}

fn serialize_sizes(values: &[f64]) -> Option<String> {
    (!values.is_empty()).then(|| {
        values
            .iter()
            .map(|value| js_number(*value))
            .collect::<Vec<_>>()
            .join(",")
    })
}

/// Props for [`Resizable`].
#[derive(Props, Clone, PartialEq)]
pub struct ResizableProps {
    /// Layout axis.
    #[props(default)]
    pub direction: ResizableDirection,
    /// Initial pane sizes in percent, normalized to 100. Unset panes share the space evenly.
    #[props(default)]
    pub default_sizes: Vec<f64>,
    /// Minimum pane sizes in percent. One value applies to every pane. Defaults to 12.
    #[props(default)]
    pub min_size: Vec<f64>,
    /// Maximum pane sizes in percent. One value applies to every pane. Defaults to 88.
    #[props(default)]
    pub max_size: Vec<f64>,
    /// Number of [`ResizablePanel`]s. Defaults to the length of `default_sizes`, or the mounted
    /// panel count. Set it (or `default_sizes`) so server-rendered sizes are right.
    pub panel_count: Option<usize>,
    /// Pressing a handle twice resets the sizes. Defaults to `true`.
    #[props(default = true)]
    pub reset_on_double_click: bool,
    /// Container length in pixels used to turn drag distance into percent when the renderer
    /// cannot measure the container (Dioxus Native). Web and desktop measure it. Defaults to 800.
    pub drag_extent: Option<f64>,
    /// Called with the new sizes after every resize or reset.
    pub on_sizes_change: Option<EventHandler<Vec<f64>>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// [`ResizablePanel`]s. Handles are inserted between them.
    pub children: Element,
}

/// Panes separated by handles that resize the panes on either side.
///
/// Handles follow the WAI-ARIA window splitter pattern: arrow keys move by 2 percent (10 with
/// Shift, flipped horizontally in right-to-left layouts), Home and End jump to the limits, and
/// dragging with the mouse, touch, or pen resizes.
#[component]
pub fn Resizable(props: ResizableProps) -> Element {
    let right_to_left = use_direction().is_rtl();
    let mut registered = use_signal(|| 2_usize);
    let count = props
        .panel_count
        .unwrap_or_else(|| {
            if props.default_sizes.is_empty() {
                registered()
            } else {
                props.default_sizes.len()
            }
        })
        .min(MAX_PANELS);
    let config = ResizableConfig {
        count,
        default_sizes: resizable_default_sizes(&props.default_sizes),
        min: props.min_size.clone(),
        max: props.max_size.clone(),
        direction: props.direction,
        reset: props.reset_on_double_click,
        right_to_left,
        drag_extent: props.drag_extent.unwrap_or(DEFAULT_DRAG_EXTENT),
    };
    let mut config_signal = use_signal(|| config.clone());
    let mut on_change = use_signal(|| props.on_sizes_change);
    let resizable = use_context_provider(|| ResizableContext {
        config: config_signal,
        stored: Signal::new(None),
        next_order: CopyValue::new(0),
        drag: Signal::new(None),
        root: Signal::new(None),
        measured: Signal::new(None),
        on_change,
        press: Signal::new(None),
        press_generation: CopyValue::new(0),
    });

    if *config_signal.peek() != config {
        config_signal.set(config);
    }

    if *on_change.peek() != props.on_sizes_change {
        on_change.set(props.on_sizes_change);
    }

    // Panels register while rendering; adopt their count once they have mounted.
    use_effect(move || {
        let mounted = *resizable.next_order.peek();

        if mounted != *registered.peek() {
            registered.set(mounted);
        }
    });

    let drag = (resizable.drag)();
    let vertical = props.direction == ResizableDirection::Vertical;
    let class = compose([
        Some("ui-resizable"),
        vertical.then_some("ui-resizable--vertical"),
        props.class.as_deref(),
    ]);
    let cursor = if vertical { "row-resize" } else { "col-resize" };

    rsx! {
        div {
            class,
            "data-orientation": props.direction.as_str(),
            "data-resizing": drag.is_some().then_some("true"),
            "data-ui-resizable": "true",
            "data-ui-resizable-default-sizes": serialize_sizes(&props.default_sizes),
            "data-ui-resizable-enhanced": "true",
            "data-ui-resizable-max-size": serialize_sizes(&props.max_size),
            "data-ui-resizable-min-size": serialize_sizes(&props.min_size),
            "data-ui-resizable-reset": props.reset_on_double_click.then_some("true"),
            onmounted: move |event| {
                let mut root = resizable.root;
                root.set(Some(event.data()));
            },
            onmousemove: move |event| {
                let point = event.client_coordinates();
                resizable.move_drag((point.x, point.y), false);
            },
            onmouseup: move |_| {
                if resizable.drag.peek().is_some_and(|drag| !drag.pointer) {
                    resizable.finish_drag();
                }
            },
            ..props.attributes,
            {props.children}
            if drag.is_some_and(|drag| !drag.pointer) {
                // Catches the mouse while dragging, so the drag survives leaving the thin handle.
                div {
                    aria_hidden: "true",
                    "data-slot": "resizable-drag-layer",
                    style: "position: fixed; inset: 0; z-index: 2147483647; padding: 0; background: transparent; cursor: {cursor}",
                }
            }
        }
    }
}

/// Props for [`ResizablePanel`].
#[derive(Props, Clone, PartialEq)]
pub struct ResizablePanelProps {
    /// The rendered element. Defaults to `<div>`.
    #[props(default)]
    pub r#as: ContainerElement,
    /// Inline style. The pane size is appended after it.
    #[props(into)]
    pub style: Option<String>,
    /// Classes for the pane.
    #[props(into)]
    pub class: Option<String>,
    /// Any other global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Pane content.
    pub children: Element,
}

/// One pane of a [`Resizable`]. Every pane after the first renders the handle before it.
///
/// Panes are numbered in mount order; keep the set of panes stable.
#[component]
pub fn ResizablePanel(props: ResizablePanelProps) -> Element {
    let resizable = use_resizable("ResizablePanel");
    let index = use_hook(|| {
        let mut next_order = resizable.next_order;
        let order = *next_order.peek();
        next_order.set(order + 1);
        order
    });
    let sizes = resizable.sizes();
    let config = (resizable.config)();
    let size = format!(
        "--ui-resizable-size: {}%",
        js_number(sizes.get(index).copied().unwrap_or(0.0))
    );
    let mut attributes = vec![
        attr("class", compose([props.class.as_deref()])),
        attr("data-ui-resizable-panel", "true"),
    ];

    if let Some(style) = join_style([props.style.as_deref(), Some(size.as_str())]) {
        attributes.push(attr("style", style));
    }

    attributes.extend(props.attributes);

    let dragging = (*resizable.drag.read()).map(|drag| drag.index);
    let handle = index.checked_sub(1).map(|handle| {
        resizable_handle(
            &resizable,
            &config,
            &sizes,
            handle,
            dragging == Some(handle),
        )
    });

    rsx! {
        {handle}
        {element(props.r#as, attributes, props.children)}
    }
}

fn resizable_handle(
    resizable: &ResizableContext,
    config: &ResizableConfig,
    sizes: &[f64],
    index: usize,
    active: bool,
) -> Element {
    let min = config.min_sizes();
    let max = config.max_sizes();
    let value_min = js_number(js_round(min.get(index).copied().unwrap_or(0.0)));
    let value_max = js_number(js_round(max.get(index).copied().unwrap_or(100.0)));
    let value_now = js_number(js_round(sizes.get(index).copied().unwrap_or(0.0)));
    let orientation = match config.direction {
        ResizableDirection::Horizontal => "vertical",
        ResizableDirection::Vertical => "horizontal",
    };
    let direction = config.direction;
    let right_to_left = config.right_to_left;
    let reset = config.reset;
    let resizable = *resizable;

    rsx! {
        button {
            aria_label: "Resize panel {index + 1}",
            aria_orientation: orientation,
            aria_valuemax: value_max,
            aria_valuemin: value_min,
            aria_valuenow: value_now,
            class: "ui-resizable__handle",
            "data-active": active.then_some("true"),
            "data-index": index.to_string(),
            "data-ui-resizable-handle": "true",
            role: "separator",
            tabindex: "0",
            r#type: "button",
            onkeydown: move |event| {
                let config = resizable.config.peek().clone();

                match event.key() {
                    Key::Home => {
                        event.prevent_default();
                        resizable.resize(index, config.min_sizes().get(index).copied().unwrap_or(0.0));
                    }
                    Key::End => {
                        event.prevent_default();
                        resizable.resize(index, config.max_sizes().get(index).copied().unwrap_or(100.0));
                    }
                    key => {
                        let step = if event.modifiers().shift() { 10.0 } else { 2.0 };
                        let delta = match (direction, directional_key(&key, right_to_left)) {
                            (ResizableDirection::Horizontal, Key::ArrowLeft)
                            | (ResizableDirection::Vertical, Key::ArrowUp) => -step,
                            (ResizableDirection::Horizontal, Key::ArrowRight)
                            | (ResizableDirection::Vertical, Key::ArrowDown) => step,
                            _ => return,
                        };
                        event.prevent_default();
                        let current = resizable.sizes_peek().get(index).copied().unwrap_or(0.0);
                        resizable.resize(index, current + delta);
                    }
                }
            },
            onmousedown: move |event| {
                if event.trigger_button() != Some(MouseButton::Primary) {
                    return;
                }

                event.prevent_default();

                if resizable.double_press(index) {
                    if reset {
                        resizable.reset();
                    }

                    return;
                }

                let point = event.client_coordinates();
                resizable.start_drag(index, (point.x, point.y), false);
            },
            onpointerdown: move |event| {
                // Mouse input uses the mouse events above, which Dioxus Native also delivers.
                if event.pointer_type() == "mouse" {
                    return;
                }

                let point = event.client_coordinates();
                resizable.start_drag(index, (point.x, point.y), true);
            },
            onpointermove: move |event| {
                if event.pointer_type() != "mouse" {
                    let point = event.client_coordinates();
                    resizable.move_drag((point.x, point.y), true);
                }
            },
            onpointerup: move |event| {
                if event.pointer_type() != "mouse" {
                    resizable.finish_drag();
                }
            },
            onpointercancel: move |event| {
                if event.pointer_type() != "mouse" {
                    resizable.finish_drag();
                }
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        normalize_resizable_sizes, resizable_default_sizes, resizable_number_list, resize_pair,
    };

    #[test]
    fn non_finite_default_sizes_compare_equal_and_normalize_alike() {
        let raw = [f64::NAN, f64::INFINITY, 30.0, f64::NEG_INFINITY];
        let sanitized = resizable_default_sizes(&raw);

        assert_eq!(sanitized, vec![0.0, 0.0, 30.0, 0.0]);
        assert_eq!(sanitized, resizable_default_sizes(&raw));
        assert_eq!(
            normalize_resizable_sizes(&sanitized, 4),
            normalize_resizable_sizes(&raw, 4)
        );
    }

    #[test]
    fn number_lists_fall_back_to_the_first_value() {
        assert_eq!(resizable_number_list(&[], 3, 12.0), vec![12.0; 3]);
        assert_eq!(resizable_number_list(&[18.0], 3, 12.0), vec![18.0; 3]);
        assert_eq!(
            resizable_number_list(&[18.0, 24.0], 3, 12.0),
            vec![18.0, 24.0, 18.0]
        );
    }

    #[test]
    fn sizes_normalize_to_one_hundred() {
        assert_eq!(normalize_resizable_sizes(&[1.0, 1.0], 2), vec![50.0, 50.0]);
        assert_eq!(
            normalize_resizable_sizes(&[28.0, 44.0, 28.0], 3),
            vec![28.000_000_000_000_004, 44.0, 28.000_000_000_000_004]
        );
        assert_eq!(
            normalize_resizable_sizes(&[f64::NAN, -1.0], 2),
            vec![50.0, 50.0]
        );
        assert_eq!(normalize_resizable_sizes(&[], 4), vec![25.0; 4]);
        assert_eq!(normalize_resizable_sizes(&[], 0), Vec::<f64>::new());
    }

    #[test]
    fn resizing_keeps_both_panes_in_their_limits() {
        let min = [12.0, 12.0];
        let max = [88.0, 88.0];
        assert_eq!(
            resize_pair(&[50.0, 50.0], 0, 60.0, &min, &max),
            vec![60.0, 40.0]
        );
        assert_eq!(
            resize_pair(&[50.0, 50.0], 0, 99.0, &min, &max),
            vec![88.0, 12.0]
        );
        assert_eq!(
            resize_pair(&[50.0, 50.0], 0, -5.0, &min, &max),
            vec![12.0, 88.0]
        );
        assert_eq!(
            resize_pair(&[50.0, 50.0], 1, 60.0, &min, &max),
            vec![50.0, 50.0]
        );
        assert_eq!(
            resize_pair(&[50.0, 50.0], 0, f64::NAN, &min, &max),
            vec![50.0, 50.0]
        );
    }

    #[test]
    fn the_neighbor_limits_bound_the_pane() {
        // The second pane may not grow past 70, so the first stays at or above 30.
        let sizes = resize_pair(&[40.0, 60.0], 0, 10.0, &[5.0, 5.0], &[95.0, 70.0]);
        assert_eq!(sizes, vec![30.0, 70.0]);
    }
}