arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/resizable-panels/resizable-panels.tsx` & `.module.css`
//!
//! P3 Component #14: `resizable-panels`
//!
//! - Horizontal split view with `1px` visual dividers (`13px` grab area) and a `4×32px` center grip
//!   pill that springs from `scaleY(0.6) -> 1.0` when hovered, focused, or dragged.
//! - Dividers follow the pointer 1:1 inside `[lo, hi]`, apply asymptotic rubber-band resistance
//!   (`panel_rubber`, `STRETCH = 44px`) past a pane's `min_size` / `max_size`, and snap
//!   `collapsible` panes closed once dragged below `panel_collapse_threshold(min)`
//!   (`min - max(min * 0.5, 40)`).
//! - Collapsing panes dissolve (`opacity = clamp(width / min_size, 0, 1)`) rather than reflowing
//!   below their minimum width; collapsed dividers reveal an `18×40px` restore tab with a directional
//!   chevron (`ChevronRight` when the leading pane is hidden, `ChevronLeft` when the trailing pane
//!   is hidden).
//! - Clicking a collapsed divider (or pressing `Enter`) restores the hidden pane; double-clicking a
//!   divider resets all panes to their default shares on `motion.spring.smooth`; `ArrowLeft` /
//!   `ArrowRight` step by `16px` (`Shift` -> `64px`) on `motion.spring.snappy`, and `Home` / `End`
//!   jump to limits.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
    Role, SharedString, Styled, TestSupportExt as _, Window, canvas, div, point, prelude::*, px,
};

/// Default minimum width in `px` before a pane starts resisting (`80px`).
pub const PANEL_DEFAULT_MIN: f32 = 80.0;
/// Asymptotic rubber-band stretch cap in `px` past a pane limit (`44px`).
pub const PANEL_STRETCH_LIMIT: f32 = 44.0;
/// Standard keyboard resize step in `px` (`16px`).
pub const PANEL_KEY_STEP: f32 = 16.0;
/// Shift-modified keyboard resize step in `px` (`64px`).
pub const PANEL_KEY_BIG_STEP: f32 = 64.0;

/// Collapse state of the pair of panes adjacent to a divider handle.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DividerCollapseMode {
    #[default]
    Open,
    /// The pane before the divider is collapsed (`width == 0`).
    Before,
    /// The pane after the divider is collapsed (`width == 0`).
    After,
}

/// Elastic rubber-band curve past a pane's `min_size` / `max_size`, approaching [`PANEL_STRETCH_LIMIT`] (`44px`).
pub fn panel_rubber(overshoot: f32) -> f32 {
    let o = overshoot.max(0.0);
    o * PANEL_STRETCH_LIMIT * 0.55 / (PANEL_STRETCH_LIMIT + 0.55 * o)
}

/// Applies [`panel_rubber`] outside `[lo, hi]`.
pub fn panel_band(value: f32, lo: f32, hi: f32) -> f32 {
    if value < lo {
        lo - panel_rubber(lo - value)
    } else if value > hi {
        hi + panel_rubber(value - hi)
    } else {
        value
    }
}

/// Width threshold (`px`) below which a collapsible pane snaps closed (`min - max(min * 0.5, 40)`).
pub fn panel_collapse_threshold(min_size: f32) -> f32 {
    min_size - (min_size * 0.5).max(40.0)
}

/// Resolves `(DividerCollapseMode, pane_a_width)` for a divider drag at `raw_a` within `pair_width`
/// and limits `[lo, hi]`.
#[allow(clippy::too_many_arguments)]
pub fn resolve_panel_boundary(
    raw_a: f32,
    pair_width: f32,
    lo: f32,
    hi: f32,
    min_a: f32,
    min_b: f32,
    collapsible_a: bool,
    collapsible_b: bool,
) -> (DividerCollapseMode, f32) {
    if collapsible_a && raw_a < panel_collapse_threshold(min_a) {
        return (DividerCollapseMode::Before, 0.0);
    }
    if collapsible_b && (pair_width - raw_a) < panel_collapse_threshold(min_b) {
        return (DividerCollapseMode::After, pair_width);
    }
    (DividerCollapseMode::Open, panel_band(raw_a, lo, hi))
}

fn paint_horizontal_chevron(cx: f32, cy: f32, point_right: bool, color: Hsla, window: &mut Window) {
    let dir = if point_right { 1.0_f32 } else { -1.0_f32 };
    let mut b = PathBuilder::stroke(px(1.75));
    b.move_to(point(px(cx - 1.6 * dir), px(cy - 3.6)));
    b.line_to(point(px(cx + 2.0 * dir), px(cy)));
    b.line_to(point(px(cx - 1.6 * dir), px(cy + 3.6)));
    if let Ok(path) = b.build() {
        window.paint_path(path, color);
    }
}

/// Configuration for one pane inside [`ResizablePanels`].
pub struct ResizablePanel {
    pub id: SharedString,
    pub label: SharedString,
    pub default_size: f32,
    pub min_size: f32,
    pub max_size: Option<f32>,
    pub collapsible: bool,
    pub default_collapsed: bool,
    pub content: AnyElement,
}

impl ResizablePanel {
    pub fn new(
        id: impl Into<SharedString>,
        label: impl Into<SharedString>,
        default_size: f32,
        content: impl IntoElement,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            default_size: default_size.max(1.0),
            min_size: PANEL_DEFAULT_MIN,
            max_size: None,
            collapsible: false,
            default_collapsed: false,
            content: content.into_any_element(),
        }
    }

    pub fn min_size(mut self, min_px: f32) -> Self {
        self.min_size = min_px.max(32.0);
        self
    }

    pub fn max_size(mut self, max_px: f32) -> Self {
        self.max_size = Some(max_px.max(64.0));
        self
    }

    pub fn collapsible(mut self, collapsible: bool) -> Self {
        self.collapsible = collapsible;
        self
    }

    pub fn default_collapsed(mut self, default_collapsed: bool) -> Self {
        self.default_collapsed = default_collapsed;
        self
    }
}

type LayoutChangeCallback = Rc<dyn Fn(&[f32], &mut Window, &mut App)>;

#[derive(Clone)]
struct ResizablePanelsInternal {
    /// Target share weights (normalized to sum to `100.0`).
    shares: Vec<f32>,
    collapsed: Vec<bool>,
    restore_shares: Vec<Option<f32>>,
    hovered_handle: Option<usize>,
    focused_handle: usize,
    dragging_handle: Option<usize>,
    drag_moved: bool,
    drag_start_x: f32,
    drag_a0_px: f32,
    drag_b0_px: f32,
    drag_pair_px: f32,
    drag_lo_px: f32,
    drag_hi_px: f32,
    drag_live_a_px: f32,
    drag_mode: DividerCollapseMode,
    drag_start_mode: DividerCollapseMode,
    last_click_at: f64,
    last_click_handle: Option<usize>,
    group_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl ResizablePanelsInternal {
    fn new(panels: &[ResizablePanel], now: f64, focus_handle: FocusHandle) -> Self {
        let collapsed: Vec<bool> = panels
            .iter()
            .map(|p| p.collapsible && p.default_collapsed)
            .collect();
        let raw: Vec<f32> = panels
            .iter()
            .zip(collapsed.iter())
            .map(|(p, &col)| if col { 0.0 } else { p.default_size })
            .collect();
        let sum: f32 = raw.iter().sum::<f32>().max(1.0);
        let shares = raw.into_iter().map(|v| v / sum * 100.0).collect();
        let count = panels.len();
        Self {
            shares,
            collapsed,
            restore_shares: vec![None; count],
            hovered_handle: None,
            focused_handle: 0,
            dragging_handle: None,
            drag_moved: false,
            drag_start_x: 0.0,
            drag_a0_px: 0.0,
            drag_b0_px: 0.0,
            drag_pair_px: 0.0,
            drag_lo_px: 0.0,
            drag_hi_px: 0.0,
            drag_live_a_px: 0.0,
            drag_mode: DividerCollapseMode::Open,
            drag_start_mode: DividerCollapseMode::Open,
            last_click_at: now - 10.0,
            last_click_handle: None,
            group_bounds: Rc::new(RefCell::new(None)),
            focus_handle,
        }
    }
}

/// Arc `ResizablePanels` — horizontal split pane group with 1:1 divider drag, `44px` rubber-band
/// resistance past limits, collapsible panes with restore tabs, double-click reset, and keyboard resizing.
#[derive(IntoElement)]
pub struct ResizablePanels {
    id: ElementId,
    label: Option<SharedString>,
    height: f32,
    panels: Vec<ResizablePanel>,
    on_layout_change: Option<LayoutChangeCallback>,
}

impl ResizablePanels {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: None,
            height: 280.0,
            panels: Vec::new(),
            on_layout_change: None,
        }
    }

    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn height(mut self, height_px: f32) -> Self {
        self.height = height_px.max(120.0);
        self
    }

    pub fn panel(mut self, panel: ResizablePanel) -> Self {
        self.panels.push(panel);
        self
    }

    pub fn panels(mut self, panels: impl IntoIterator<Item = ResizablePanel>) -> Self {
        self.panels.extend(panels);
        self
    }

    pub fn on_layout_change(
        mut self,
        handler: impl Fn(&[f32], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_layout_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for ResizablePanels {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);
        let count = self.panels.len();

        let state_id = ElementId::NamedChild(
            self.id.clone().into(),
            "__arc-resizable-panels-state".into(),
        );
        let panels_ref = &self.panels;
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            ResizablePanelsInternal::new(panels_ref, now, cx.focus_handle())
        });

        let snap = internal.read(cx).clone();
        let gaps = count.saturating_sub(1) as f32;
        let total_w = snap
            .group_bounds
            .borrow()
            .map(|b| f32::from(b.size.width))
            .unwrap_or(680.0)
            .max(240.0);
        let available = (total_w - gaps).max(120.0);

        let min_total: f32 = self.panels.iter().map(|p| p.min_size).sum::<f32>().max(1.0);
        let mins: Vec<f32> = self
            .panels
            .iter()
            .map(|p| {
                if available < min_total {
                    p.min_size * available / min_total
                } else {
                    p.min_size
                }
            })
            .collect();
        let maxs: Vec<f32> = self
            .panels
            .iter()
            .map(|p| p.max_size.unwrap_or(available))
            .collect();
        let min_of = |idx: usize| -> f32 { mins.get(idx).copied().unwrap_or(PANEL_DEFAULT_MIN) };
        let max_of = |idx: usize| -> f32 { maxs.get(idx).copied().unwrap_or(available) };

        let default_shares: Vec<f32> = {
            let raw: Vec<f32> = self
                .panels
                .iter()
                .map(|p| {
                    if p.collapsible && p.default_collapsed {
                        0.0
                    } else {
                        p.default_size
                    }
                })
                .collect();
            let s = raw.iter().sum::<f32>().max(1.0);
            raw.into_iter().map(|v| v / s * 100.0).collect()
        };
        let default_collapsed: Vec<bool> = self
            .panels
            .iter()
            .map(|p| p.collapsible && p.default_collapsed)
            .collect();

        // Compute each pane's current width in px (either live drag or spring-animated from target shares).
        let mut current_px = Vec::with_capacity(count);
        for idx in 0..count {
            let share = snap.shares.get(idx).copied().unwrap_or(0.0);
            let target_w = share / 100.0 * available;
            let live_w = if let Some(h) = snap.dragging_handle
                && snap.drag_moved
                && (idx == h || idx == h + 1)
            {
                let w = if idx == h {
                    snap.drag_live_a_px
                } else {
                    (snap.drag_pair_px - snap.drag_live_a_px).max(0.0)
                };
                let _ = arc_spring(
                    (self.id.clone(), SharedString::from(format!("pane-w-{idx}"))),
                    w,
                    motion.spring.snappy,
                    window,
                    cx,
                );
                w
            } else if reduced {
                target_w
            } else {
                arc_spring(
                    (self.id.clone(), SharedString::from(format!("pane-w-{idx}"))),
                    target_w,
                    motion.spring.smooth,
                    window,
                    cx,
                )
            };
            current_px.push(live_w.max(0.0));
        }

        let bounds_ref = snap.group_bounds.clone();
        let active_drag = snap.dragging_handle;
        let int_win = internal.clone();
        let on_change_win = self.on_layout_change.clone();
        let collapsible_flags: Vec<(bool, f32)> = self
            .panels
            .iter()
            .enumerate()
            .map(|(i, p)| (p.collapsible, min_of(i)))
            .collect();

        let group_probe = canvas(
            move |rect, _, _| {
                *bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if let Some(h) = active_drag {
                    let st_move = int_win.clone();
                    let flags_move = collapsible_flags.clone();
                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let x = f32::from(event.position.x);
                        st_move.update(cx, |s, _| {
                            let dx = x - s.drag_start_x;
                            if !s.drag_moved && dx.abs() < 2.0 {
                                return;
                            }
                            s.drag_moved = true;
                            let (col_a, min_a) =
                                flags_move.get(h).copied().unwrap_or((false, 80.0));
                            let (col_b, min_b) =
                                flags_move.get(h + 1).copied().unwrap_or((false, 80.0));
                            let (mode, size_a) = resolve_panel_boundary(
                                s.drag_a0_px + dx,
                                s.drag_pair_px,
                                s.drag_lo_px,
                                s.drag_hi_px,
                                min_a,
                                min_b,
                                col_a,
                                col_b,
                            );
                            s.drag_mode = mode;
                            s.drag_live_a_px = size_a;
                        });
                        window.refresh();
                    });

                    let st_up = int_win.clone();
                    let cb_up = on_change_win.clone();
                    let flags_up = collapsible_flags.clone();
                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
                        if !phase.bubble() {
                            return;
                        }
                        let mut notify_shares: Option<Vec<f32>> = None;
                        st_up.update(cx, |s, _| {
                            let moved = s.drag_moved;
                            let start_mode = s.drag_start_mode;
                            let mode = s.drag_mode;
                            let pair = s.drag_pair_px;
                            let lo = s.drag_lo_px;
                            let hi = s.drag_hi_px;
                            let raw_a = s.drag_live_a_px;
                            s.dragging_handle = None;
                            s.drag_moved = false;

                            let (_, min_a) = flags_up.get(h).copied().unwrap_or((false, 80.0));
                            let (_, min_b) = flags_up.get(h + 1).copied().unwrap_or((false, 80.0));

                            if !moved {
                                // Clicking a collapsed divider restores the hidden neighbour.
                                if start_mode != DividerCollapseMode::Open {
                                    let restored_a = match start_mode {
                                        DividerCollapseMode::Before => {
                                            let saved = s
                                                .restore_shares
                                                .get(h)
                                                .and_then(|v| *v)
                                                .map(|sh| sh / 100.0 * available)
                                                .unwrap_or(min_a);
                                            saved.clamp(lo, hi)
                                        }
                                        DividerCollapseMode::After => {
                                            let saved_b = s
                                                .restore_shares
                                                .get(h + 1)
                                                .and_then(|v| *v)
                                                .map(|sh| sh / 100.0 * available)
                                                .unwrap_or(min_b);
                                            (pair - saved_b).clamp(lo, hi)
                                        }
                                        DividerCollapseMode::Open => raw_a.clamp(lo, hi),
                                    };
                                    if let Some(c) = s.collapsed.get_mut(h) {
                                        *c = false;
                                    }
                                    if let Some(c) = s.collapsed.get_mut(h + 1) {
                                        *c = false;
                                    }
                                    s.shares[h] = restored_a / available * 100.0;
                                    s.shares[h + 1] =
                                        (pair - restored_a).max(0.0) / available * 100.0;
                                    notify_shares = Some(s.shares.clone());
                                }
                                return;
                            }

                            let final_a = match mode {
                                DividerCollapseMode::Before => {
                                    if s.drag_a0_px > 1.0 {
                                        s.restore_shares[h] =
                                            Some(s.drag_a0_px / available * 100.0);
                                    }
                                    0.0
                                }
                                DividerCollapseMode::After => {
                                    if s.drag_b0_px > 1.0 {
                                        s.restore_shares[h + 1] =
                                            Some(s.drag_b0_px / available * 100.0);
                                    }
                                    pair
                                }
                                DividerCollapseMode::Open => raw_a.clamp(lo, hi),
                            };
                            s.collapsed[h] = mode == DividerCollapseMode::Before;
                            s.collapsed[h + 1] = mode == DividerCollapseMode::After;
                            s.shares[h] = final_a / available * 100.0;
                            s.shares[h + 1] = (pair - final_a).max(0.0) / available * 100.0;
                            notify_shares = Some(s.shares.clone());
                        });
                        if let (Some(sh), Some(cb)) = (notify_shares, &cb_up) {
                            cb(&sh, window, cx);
                        }
                        window.refresh();
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let int_key = internal.clone();
        let on_change_key = self.on_layout_change.clone();
        let collapsible_for_key: Vec<(bool, f32, f32)> = self
            .panels
            .iter()
            .enumerate()
            .map(|(i, p)| (p.collapsible, min_of(i), max_of(i)))
            .collect();

        let mut root = div()
            .id(self.id.clone())
            .test_support()
            .track_focus(&snap.focus_handle)
            .role(Role::Group)
            .when_some(self.label, |d, l| d.aria_label(l))
            .relative()
            .w_full()
            .h(px(self.height))
            .overflow_hidden()
            .flex()
            .flex_row()
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if count < 2 {
                    return;
                }
                let h = int_key.read(cx).focused_handle.min(count - 2);
                let (col_a, min_a, max_a) = collapsible_for_key[h];
                let (col_b, min_b, max_b) = collapsible_for_key[h + 1];
                let key = event.keystroke.key.as_str();
                let step = if event.keystroke.modifiers.shift {
                    PANEL_KEY_BIG_STEP
                } else {
                    PANEL_KEY_STEP
                };

                let mut changed: Option<Vec<f32>> = None;
                int_key.update(cx, |s, _| {
                    let a_px = s.shares[h] / 100.0 * available;
                    let b_px = s.shares[h + 1] / 100.0 * available;
                    let pair = a_px + b_px;
                    let lo = min_a.max(pair - max_b).clamp(0.0, pair);
                    let hi = max_a.min(pair - min_b).clamp(lo, pair);
                    let mode = if s.collapsed[h] {
                        DividerCollapseMode::Before
                    } else if s.collapsed[h + 1] {
                        DividerCollapseMode::After
                    } else {
                        DividerCollapseMode::Open
                    };

                    match key {
                        "enter" => {
                            if mode != DividerCollapseMode::Open {
                                let target_a = if mode == DividerCollapseMode::Before {
                                    s.restore_shares[h]
                                        .map(|sh| sh / 100.0 * available)
                                        .unwrap_or(min_a)
                                        .clamp(lo, hi)
                                } else {
                                    let sb = s.restore_shares[h + 1]
                                        .map(|sh| sh / 100.0 * available)
                                        .unwrap_or(min_b);
                                    (pair - sb).clamp(lo, hi)
                                };
                                s.collapsed[h] = false;
                                s.collapsed[h + 1] = false;
                                s.shares[h] = target_a / available * 100.0;
                                s.shares[h + 1] = (pair - target_a).max(0.0) / available * 100.0;
                                changed = Some(s.shares.clone());
                            } else if col_a {
                                s.restore_shares[h] = Some(s.shares[h]);
                                s.collapsed[h] = true;
                                s.shares[h] = 0.0;
                                s.shares[h + 1] = pair / available * 100.0;
                                changed = Some(s.shares.clone());
                            } else if col_b {
                                s.restore_shares[h + 1] = Some(s.shares[h + 1]);
                                s.collapsed[h + 1] = true;
                                s.shares[h] = pair / available * 100.0;
                                s.shares[h + 1] = 0.0;
                                changed = Some(s.shares.clone());
                            }
                        }
                        "left" | "arrowleft" => {
                            if mode == DividerCollapseMode::After {
                                s.collapsed[h + 1] = false;
                                s.shares[h] = hi / available * 100.0;
                                s.shares[h + 1] = (pair - hi).max(0.0) / available * 100.0;
                            } else if mode == DividerCollapseMode::Open && a_px <= lo + 0.5 && col_a
                            {
                                s.restore_shares[h] = Some(s.shares[h]);
                                s.collapsed[h] = true;
                                s.shares[h] = 0.0;
                                s.shares[h + 1] = pair / available * 100.0;
                            } else if mode == DividerCollapseMode::Open {
                                let next_a = (a_px - step).clamp(lo, hi);
                                s.shares[h] = next_a / available * 100.0;
                                s.shares[h + 1] = (pair - next_a).max(0.0) / available * 100.0;
                            }
                            changed = Some(s.shares.clone());
                        }
                        "right" | "arrowright" => {
                            if mode == DividerCollapseMode::Before {
                                s.collapsed[h] = false;
                                s.shares[h] = lo / available * 100.0;
                                s.shares[h + 1] = (pair - lo).max(0.0) / available * 100.0;
                            } else if mode == DividerCollapseMode::Open && a_px >= hi - 0.5 && col_b
                            {
                                s.restore_shares[h + 1] = Some(s.shares[h + 1]);
                                s.collapsed[h + 1] = true;
                                s.shares[h] = pair / available * 100.0;
                                s.shares[h + 1] = 0.0;
                            } else if mode == DividerCollapseMode::Open {
                                let next_a = (a_px + step).clamp(lo, hi);
                                s.shares[h] = next_a / available * 100.0;
                                s.shares[h + 1] = (pair - next_a).max(0.0) / available * 100.0;
                            }
                            changed = Some(s.shares.clone());
                        }
                        "home" if mode == DividerCollapseMode::Open => {
                            s.shares[h] = lo / available * 100.0;
                            s.shares[h + 1] = (pair - lo).max(0.0) / available * 100.0;
                            changed = Some(s.shares.clone());
                        }
                        "end" if mode == DividerCollapseMode::Open => {
                            s.shares[h] = hi / available * 100.0;
                            s.shares[h + 1] = (pair - hi).max(0.0) / available * 100.0;
                            changed = Some(s.shares.clone());
                        }
                        _ => {}
                    }
                });
                if let Some(sh) = changed {
                    if let Some(cb) = &on_change_key {
                        cb(&sh, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(group_probe);

        let mut running_x = 0.0_f32;
        let mut handle_overlays = Vec::with_capacity(count.saturating_sub(1));

        for (index, panel) in self.panels.into_iter().enumerate() {
            if index > 0 {
                let handle_idx = index - 1;
                let divider_x = running_x;
                running_x += 1.0;

                let mode = if snap.dragging_handle == Some(handle_idx) && snap.drag_moved {
                    snap.drag_mode
                } else if snap.collapsed.get(handle_idx).copied().unwrap_or(false) {
                    DividerCollapseMode::Before
                } else if snap.collapsed.get(index).copied().unwrap_or(false) {
                    DividerCollapseMode::After
                } else {
                    DividerCollapseMode::Open
                };

                let is_hovered = snap.hovered_handle == Some(handle_idx);
                let is_active = snap.dragging_handle == Some(handle_idx);
                let show_grip = (is_hovered || is_active) && mode == DividerCollapseMode::Open;
                let grip_p = if reduced {
                    if show_grip { 1.0 } else { 0.0 }
                } else {
                    arc_spring(
                        (
                            self.id.clone(),
                            SharedString::from(format!("grip-p-{handle_idx}")),
                        ),
                        if show_grip { 1.0 } else { 0.0 },
                        motion.spring.snappy,
                        window,
                        cx,
                    )
                };
                let grip_h = 32.0 * (0.6 + 0.4 * grip_p);

                let line_bg = if mode != DividerCollapseMode::Open {
                    Hsla::transparent_black()
                } else if is_active || is_hovered {
                    colors.border_strong
                } else {
                    colors.border
                };
                let grip_bg = if is_active {
                    colors.foreground
                } else {
                    colors.border_strong
                };

                root = root.child(div().w(px(1.0)).h_full().flex_none().bg(line_bg));

                let int_hover = internal.clone();
                let int_down = internal.clone();
                let on_change_dbl = self.on_layout_change.clone();
                let focus_down = snap.focus_handle.clone();
                let def_shares = default_shares.clone();
                let def_col = default_collapsed.clone();
                let a_cur = current_px[handle_idx];
                let b_cur = current_px[index];
                let min_a = min_of(handle_idx);
                let max_a = max_of(handle_idx);
                let min_b = min_of(index);
                let max_b = max_of(index);

                // 26px draggable hit target centered on the 1px divider (±12.5px),
                // expanded to encompass the 18x40px restore tab when collapsed.
                let (hit_left, hit_w) = match mode {
                    DividerCollapseMode::Open => (divider_x - 12.5, 26.0),
                    DividerCollapseMode::Before => (divider_x - 12.5, 36.5),
                    DividerCollapseMode::After => (divider_x - 23.0, 36.5),
                };
                let line_offset = divider_x - hit_left;

                let mut handle_overlay = div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("handle-{handle_idx}")),
                    ))
                    .test_support()
                    .role(Role::Slider)
                    .aria_label(panel.label.clone())
                    .absolute()
                    .top_0()
                    .bottom_0()
                    .left(px(hit_left))
                    .w(px(hit_w))
                    .cursor_col_resize()
                    .on_hover(move |hovered, window, cx| {
                        int_hover.update(cx, |s, _| {
                            if *hovered {
                                s.hovered_handle = Some(handle_idx);
                            } else if s.hovered_handle == Some(handle_idx) {
                                s.hovered_handle = None;
                            }
                        });
                        window.refresh();
                    })
                    .on_mouse_down(
                        MouseButton::Left,
                        move |event: &MouseDownEvent, window, cx| {
                            let t = motion_now(cx);
                            focus_down.focus(window, cx);
                            let is_double = {
                                let s = int_down.read(cx);
                                s.last_click_handle == Some(handle_idx)
                                    && (t - s.last_click_at) < 0.32
                            };
                            if is_double {
                                int_down.update(cx, |s, _| {
                                    s.shares = def_shares.clone();
                                    s.collapsed = def_col.clone();
                                    s.dragging_handle = None;
                                    s.drag_moved = false;
                                    s.last_click_handle = None;
                                });
                                if let Some(cb) = &on_change_dbl {
                                    cb(&def_shares, window, cx);
                                }
                                window.refresh();
                                return;
                            }

                            let pair = a_cur + b_cur;
                            let mut lo = min_a.max(pair - max_b);
                            let mut hi = max_a.min(pair - min_b);
                            if a_cur > 0.0 && b_cur > 0.0 {
                                lo = lo.min(a_cur);
                                hi = hi.max(a_cur);
                            }
                            if lo > hi {
                                let mid = ((lo + hi) * 0.5).clamp(0.0, pair);
                                lo = mid;
                                hi = mid;
                            }
                            lo = lo.clamp(0.0, pair);
                            hi = hi.clamp(0.0, pair);

                            int_down.update(cx, |s, _| {
                                s.focused_handle = handle_idx;
                                s.last_click_at = t;
                                s.last_click_handle = Some(handle_idx);
                                s.dragging_handle = Some(handle_idx);
                                s.drag_moved = false;
                                s.drag_start_x = f32::from(event.position.x);
                                s.drag_a0_px = a_cur;
                                s.drag_b0_px = b_cur;
                                s.drag_pair_px = pair;
                                s.drag_lo_px = lo;
                                s.drag_hi_px = hi;
                                s.drag_live_a_px = a_cur;
                                s.drag_mode = mode;
                                s.drag_start_mode = mode;
                            });
                            window.refresh();
                        },
                    );

                if grip_p > 0.01 && mode == DividerCollapseMode::Open {
                    handle_overlay = handle_overlay.child(
                        div()
                            .absolute()
                            .left(px(line_offset - 1.5))
                            .top(px((self.height - grip_h) * 0.5))
                            .w(px(4.0))
                            .h(px(grip_h))
                            .rounded(Radii::PILL)
                            .bg(grip_bg)
                            .opacity(grip_p),
                    );
                }

                if mode != DividerCollapseMode::Open {
                    let point_right = mode == DividerCollapseMode::Before;
                    let tab_left = if point_right {
                        line_offset + 5.0
                    } else {
                        line_offset - 22.0
                    };
                    let tab_border = if is_hovered {
                        colors.border_strong
                    } else {
                        colors.border
                    };
                    let tab_icon = if is_hovered {
                        colors.foreground
                    } else {
                        colors.text_secondary
                    };
                    handle_overlay = handle_overlay.child(
                        div()
                            .absolute()
                            .left(px(tab_left))
                            .top(px((self.height - 40.0) * 0.5))
                            .w(px(18.0))
                            .h(px(40.0))
                            .rounded(Radii::PILL)
                            .border_1()
                            .border_color(tab_border)
                            .bg(colors.surface)
                            .shadow(Shadows::resting(theme.mode))
                            .child(
                                canvas(
                                    |_, _, _| {},
                                    move |bounds, _, window, _| {
                                        let cx_pt = f32::from(bounds.origin.x)
                                            + f32::from(bounds.size.width) * 0.5;
                                        let cy_pt = f32::from(bounds.origin.y)
                                            + f32::from(bounds.size.height) * 0.5;
                                        paint_horizontal_chevron(
                                            cx_pt,
                                            cy_pt,
                                            point_right,
                                            tab_icon,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                    );
                }

                handle_overlays.push(handle_overlay);
            }

            let pane_w = current_px[index];
            running_x += pane_w;
            let min_w = min_of(index);
            let fade_opacity = (pane_w / min_w.max(1.0)).clamp(0.0, 1.0);
            let inner_w = pane_w.max(min_w);

            root = root.child(
                div()
                    .id(ElementId::NamedChild(self.id.clone().into(), panel.id))
                    .test_support()
                    .relative()
                    .w(px(pane_w))
                    .h_full()
                    .flex_none()
                    .overflow_hidden()
                    .child(
                        div()
                            .w(px(inner_w))
                            .h_full()
                            .opacity(fade_opacity)
                            .child(panel.content),
                    ),
            );
        }

        for overlay in handle_overlays {
            root = root.child(overlay);
        }

        root
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn panel_rubber_approaches_44px_asymptote() {
        assert!(panel_rubber(0.0).abs() < 1e-5);
        let r40 = panel_rubber(40.0);
        let r200 = panel_rubber(200.0);
        assert!(r40 > 12.0 && r40 < PANEL_STRETCH_LIMIT);
        assert!(r200 > r40 && r200 < PANEL_STRETCH_LIMIT);
    }

    #[test]
    fn resolve_panel_boundary_snaps_collapsible_panes_below_threshold() {
        // min_a = 120 -> collapse threshold = 120 - 60 = 60
        let (mode_closed, w_closed) =
            resolve_panel_boundary(48.0, 600.0, 120.0, 480.0, 120.0, 120.0, true, false);
        assert_eq!(mode_closed, DividerCollapseMode::Before);
        assert!(w_closed.abs() < 1e-4);

        // Above threshold but below min_a -> rubber-banded open
        let (mode_band, w_band) =
            resolve_panel_boundary(90.0, 600.0, 120.0, 480.0, 120.0, 120.0, true, false);
        assert_eq!(mode_band, DividerCollapseMode::Open);
        assert!(w_band > 90.0 && w_band < 120.0);
    }
}