Skip to main content

arc_ui/disclosure/
resizable_panels.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/resizable-panels/resizable-panels.tsx` & `.module.css`
3//!
4//! P3 Component #14: `resizable-panels`
5//!
6//! - Horizontal split view with `1px` visual dividers (`13px` grab area) and a `4×32px` center grip
7//!   pill that springs from `scaleY(0.6) -> 1.0` when hovered, focused, or dragged.
8//! - Dividers follow the pointer 1:1 inside `[lo, hi]`, apply asymptotic rubber-band resistance
9//!   (`panel_rubber`, `STRETCH = 44px`) past a pane's `min_size` / `max_size`, and snap
10//!   `collapsible` panes closed once dragged below `panel_collapse_threshold(min)`
11//!   (`min - max(min * 0.5, 40)`).
12//! - Collapsing panes dissolve (`opacity = clamp(width / min_size, 0, 1)`) rather than reflowing
13//!   below their minimum width; collapsed dividers reveal an `18×40px` restore tab with a directional
14//!   chevron (`ChevronRight` when the leading pane is hidden, `ChevronLeft` when the trailing pane
15//!   is hidden).
16//! - Clicking a collapsed divider (or pressing `Enter`) restores the hidden pane; double-clicking a
17//!   divider resets all panes to their default shares on `motion.spring.smooth`; `ArrowLeft` /
18//!   `ArrowRight` step by `16px` (`Shift` -> `64px`) on `motion.spring.snappy`, and `Home` / `End`
19//!   jump to limits.
20
21use std::{cell::RefCell, rc::Rc};
22
23use arc_motion::{arc_spring, is_reduced_motion, motion_now};
24use arc_tokens::{ActiveArcTheme as _, Radii, Shadows};
25use gpui_kit::{
26    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
27    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
28    Role, SharedString, Styled, TestSupportExt as _, Window, canvas, div, point, prelude::*, px,
29};
30
31/// Default minimum width in `px` before a pane starts resisting (`80px`).
32pub const PANEL_DEFAULT_MIN: f32 = 80.0;
33/// Asymptotic rubber-band stretch cap in `px` past a pane limit (`44px`).
34pub const PANEL_STRETCH_LIMIT: f32 = 44.0;
35/// Standard keyboard resize step in `px` (`16px`).
36pub const PANEL_KEY_STEP: f32 = 16.0;
37/// Shift-modified keyboard resize step in `px` (`64px`).
38pub const PANEL_KEY_BIG_STEP: f32 = 64.0;
39
40/// Collapse state of the pair of panes adjacent to a divider handle.
41#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
42pub enum DividerCollapseMode {
43    #[default]
44    Open,
45    /// The pane before the divider is collapsed (`width == 0`).
46    Before,
47    /// The pane after the divider is collapsed (`width == 0`).
48    After,
49}
50
51/// Elastic rubber-band curve past a pane's `min_size` / `max_size`, approaching [`PANEL_STRETCH_LIMIT`] (`44px`).
52pub fn panel_rubber(overshoot: f32) -> f32 {
53    let o = overshoot.max(0.0);
54    o * PANEL_STRETCH_LIMIT * 0.55 / (PANEL_STRETCH_LIMIT + 0.55 * o)
55}
56
57/// Applies [`panel_rubber`] outside `[lo, hi]`.
58pub fn panel_band(value: f32, lo: f32, hi: f32) -> f32 {
59    if value < lo {
60        lo - panel_rubber(lo - value)
61    } else if value > hi {
62        hi + panel_rubber(value - hi)
63    } else {
64        value
65    }
66}
67
68/// Width threshold (`px`) below which a collapsible pane snaps closed (`min - max(min * 0.5, 40)`).
69pub fn panel_collapse_threshold(min_size: f32) -> f32 {
70    min_size - (min_size * 0.5).max(40.0)
71}
72
73/// Resolves `(DividerCollapseMode, pane_a_width)` for a divider drag at `raw_a` within `pair_width`
74/// and limits `[lo, hi]`.
75#[allow(clippy::too_many_arguments)]
76pub fn resolve_panel_boundary(
77    raw_a: f32,
78    pair_width: f32,
79    lo: f32,
80    hi: f32,
81    min_a: f32,
82    min_b: f32,
83    collapsible_a: bool,
84    collapsible_b: bool,
85) -> (DividerCollapseMode, f32) {
86    if collapsible_a && raw_a < panel_collapse_threshold(min_a) {
87        return (DividerCollapseMode::Before, 0.0);
88    }
89    if collapsible_b && (pair_width - raw_a) < panel_collapse_threshold(min_b) {
90        return (DividerCollapseMode::After, pair_width);
91    }
92    (DividerCollapseMode::Open, panel_band(raw_a, lo, hi))
93}
94
95fn paint_horizontal_chevron(cx: f32, cy: f32, point_right: bool, color: Hsla, window: &mut Window) {
96    let dir = if point_right { 1.0_f32 } else { -1.0_f32 };
97    let mut b = PathBuilder::stroke(px(1.75));
98    b.move_to(point(px(cx - 1.6 * dir), px(cy - 3.6)));
99    b.line_to(point(px(cx + 2.0 * dir), px(cy)));
100    b.line_to(point(px(cx - 1.6 * dir), px(cy + 3.6)));
101    if let Ok(path) = b.build() {
102        window.paint_path(path, color);
103    }
104}
105
106/// Configuration for one pane inside [`ResizablePanels`].
107pub struct ResizablePanel {
108    pub id: SharedString,
109    pub label: SharedString,
110    pub default_size: f32,
111    pub min_size: f32,
112    pub max_size: Option<f32>,
113    pub collapsible: bool,
114    pub default_collapsed: bool,
115    pub content: AnyElement,
116}
117
118impl ResizablePanel {
119    pub fn new(
120        id: impl Into<SharedString>,
121        label: impl Into<SharedString>,
122        default_size: f32,
123        content: impl IntoElement,
124    ) -> Self {
125        Self {
126            id: id.into(),
127            label: label.into(),
128            default_size: default_size.max(1.0),
129            min_size: PANEL_DEFAULT_MIN,
130            max_size: None,
131            collapsible: false,
132            default_collapsed: false,
133            content: content.into_any_element(),
134        }
135    }
136
137    pub fn min_size(mut self, min_px: f32) -> Self {
138        self.min_size = min_px.max(32.0);
139        self
140    }
141
142    pub fn max_size(mut self, max_px: f32) -> Self {
143        self.max_size = Some(max_px.max(64.0));
144        self
145    }
146
147    pub fn collapsible(mut self, collapsible: bool) -> Self {
148        self.collapsible = collapsible;
149        self
150    }
151
152    pub fn default_collapsed(mut self, default_collapsed: bool) -> Self {
153        self.default_collapsed = default_collapsed;
154        self
155    }
156}
157
158type LayoutChangeCallback = Rc<dyn Fn(&[f32], &mut Window, &mut App)>;
159
160#[derive(Clone)]
161struct ResizablePanelsInternal {
162    /// Target share weights (normalized to sum to `100.0`).
163    shares: Vec<f32>,
164    collapsed: Vec<bool>,
165    restore_shares: Vec<Option<f32>>,
166    hovered_handle: Option<usize>,
167    focused_handle: usize,
168    dragging_handle: Option<usize>,
169    drag_moved: bool,
170    drag_start_x: f32,
171    drag_a0_px: f32,
172    drag_b0_px: f32,
173    drag_pair_px: f32,
174    drag_lo_px: f32,
175    drag_hi_px: f32,
176    drag_live_a_px: f32,
177    drag_mode: DividerCollapseMode,
178    drag_start_mode: DividerCollapseMode,
179    last_click_at: f64,
180    last_click_handle: Option<usize>,
181    group_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
182    focus_handle: FocusHandle,
183}
184
185impl ResizablePanelsInternal {
186    fn new(panels: &[ResizablePanel], now: f64, focus_handle: FocusHandle) -> Self {
187        let collapsed: Vec<bool> = panels
188            .iter()
189            .map(|p| p.collapsible && p.default_collapsed)
190            .collect();
191        let raw: Vec<f32> = panels
192            .iter()
193            .zip(collapsed.iter())
194            .map(|(p, &col)| if col { 0.0 } else { p.default_size })
195            .collect();
196        let sum: f32 = raw.iter().sum::<f32>().max(1.0);
197        let shares = raw.into_iter().map(|v| v / sum * 100.0).collect();
198        let count = panels.len();
199        Self {
200            shares,
201            collapsed,
202            restore_shares: vec![None; count],
203            hovered_handle: None,
204            focused_handle: 0,
205            dragging_handle: None,
206            drag_moved: false,
207            drag_start_x: 0.0,
208            drag_a0_px: 0.0,
209            drag_b0_px: 0.0,
210            drag_pair_px: 0.0,
211            drag_lo_px: 0.0,
212            drag_hi_px: 0.0,
213            drag_live_a_px: 0.0,
214            drag_mode: DividerCollapseMode::Open,
215            drag_start_mode: DividerCollapseMode::Open,
216            last_click_at: now - 10.0,
217            last_click_handle: None,
218            group_bounds: Rc::new(RefCell::new(None)),
219            focus_handle,
220        }
221    }
222}
223
224/// Arc `ResizablePanels` — horizontal split pane group with 1:1 divider drag, `44px` rubber-band
225/// resistance past limits, collapsible panes with restore tabs, double-click reset, and keyboard resizing.
226#[derive(IntoElement)]
227pub struct ResizablePanels {
228    id: ElementId,
229    label: Option<SharedString>,
230    height: f32,
231    panels: Vec<ResizablePanel>,
232    on_layout_change: Option<LayoutChangeCallback>,
233}
234
235impl ResizablePanels {
236    pub fn new(id: impl Into<ElementId>) -> Self {
237        Self {
238            id: id.into(),
239            label: None,
240            height: 280.0,
241            panels: Vec::new(),
242            on_layout_change: None,
243        }
244    }
245
246    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
247        self.label = Some(label.into());
248        self
249    }
250
251    pub fn height(mut self, height_px: f32) -> Self {
252        self.height = height_px.max(120.0);
253        self
254    }
255
256    pub fn panel(mut self, panel: ResizablePanel) -> Self {
257        self.panels.push(panel);
258        self
259    }
260
261    pub fn panels(mut self, panels: impl IntoIterator<Item = ResizablePanel>) -> Self {
262        self.panels.extend(panels);
263        self
264    }
265
266    pub fn on_layout_change(
267        mut self,
268        handler: impl Fn(&[f32], &mut Window, &mut App) + 'static,
269    ) -> Self {
270        self.on_layout_change = Some(Rc::new(handler));
271        self
272    }
273}
274
275impl RenderOnce for ResizablePanels {
276    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
277        let theme = cx.arc_theme().clone();
278        let colors = theme.colors;
279        let motion = theme.motion;
280        let reduced = is_reduced_motion(cx);
281        let now = motion_now(cx);
282        let count = self.panels.len();
283
284        let state_id = ElementId::NamedChild(
285            self.id.clone().into(),
286            "__arc-resizable-panels-state".into(),
287        );
288        let panels_ref = &self.panels;
289        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
290            ResizablePanelsInternal::new(panels_ref, now, cx.focus_handle())
291        });
292
293        let snap = internal.read(cx).clone();
294        let gaps = count.saturating_sub(1) as f32;
295        let total_w = snap
296            .group_bounds
297            .borrow()
298            .map(|b| f32::from(b.size.width))
299            .unwrap_or(680.0)
300            .max(240.0);
301        let available = (total_w - gaps).max(120.0);
302
303        let min_total: f32 = self.panels.iter().map(|p| p.min_size).sum::<f32>().max(1.0);
304        let mins: Vec<f32> = self
305            .panels
306            .iter()
307            .map(|p| {
308                if available < min_total {
309                    p.min_size * available / min_total
310                } else {
311                    p.min_size
312                }
313            })
314            .collect();
315        let maxs: Vec<f32> = self
316            .panels
317            .iter()
318            .map(|p| p.max_size.unwrap_or(available))
319            .collect();
320        let min_of = |idx: usize| -> f32 { mins.get(idx).copied().unwrap_or(PANEL_DEFAULT_MIN) };
321        let max_of = |idx: usize| -> f32 { maxs.get(idx).copied().unwrap_or(available) };
322
323        let default_shares: Vec<f32> = {
324            let raw: Vec<f32> = self
325                .panels
326                .iter()
327                .map(|p| {
328                    if p.collapsible && p.default_collapsed {
329                        0.0
330                    } else {
331                        p.default_size
332                    }
333                })
334                .collect();
335            let s = raw.iter().sum::<f32>().max(1.0);
336            raw.into_iter().map(|v| v / s * 100.0).collect()
337        };
338        let default_collapsed: Vec<bool> = self
339            .panels
340            .iter()
341            .map(|p| p.collapsible && p.default_collapsed)
342            .collect();
343
344        // Compute each pane's current width in px (either live drag or spring-animated from target shares).
345        let mut current_px = Vec::with_capacity(count);
346        for idx in 0..count {
347            let share = snap.shares.get(idx).copied().unwrap_or(0.0);
348            let target_w = share / 100.0 * available;
349            let live_w = if let Some(h) = snap.dragging_handle
350                && snap.drag_moved
351                && (idx == h || idx == h + 1)
352            {
353                let w = if idx == h {
354                    snap.drag_live_a_px
355                } else {
356                    (snap.drag_pair_px - snap.drag_live_a_px).max(0.0)
357                };
358                let _ = arc_spring(
359                    (self.id.clone(), SharedString::from(format!("pane-w-{idx}"))),
360                    w,
361                    motion.spring.snappy,
362                    window,
363                    cx,
364                );
365                w
366            } else if reduced {
367                target_w
368            } else {
369                arc_spring(
370                    (self.id.clone(), SharedString::from(format!("pane-w-{idx}"))),
371                    target_w,
372                    motion.spring.smooth,
373                    window,
374                    cx,
375                )
376            };
377            current_px.push(live_w.max(0.0));
378        }
379
380        let bounds_ref = snap.group_bounds.clone();
381        let active_drag = snap.dragging_handle;
382        let int_win = internal.clone();
383        let on_change_win = self.on_layout_change.clone();
384        let collapsible_flags: Vec<(bool, f32)> = self
385            .panels
386            .iter()
387            .enumerate()
388            .map(|(i, p)| (p.collapsible, min_of(i)))
389            .collect();
390
391        let group_probe = canvas(
392            move |rect, _, _| {
393                *bounds_ref.borrow_mut() = Some(rect);
394            },
395            move |_, _, window, _| {
396                if let Some(h) = active_drag {
397                    let st_move = int_win.clone();
398                    let flags_move = collapsible_flags.clone();
399                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
400                        if !phase.bubble() {
401                            return;
402                        }
403                        let x = f32::from(event.position.x);
404                        st_move.update(cx, |s, _| {
405                            let dx = x - s.drag_start_x;
406                            if !s.drag_moved && dx.abs() < 2.0 {
407                                return;
408                            }
409                            s.drag_moved = true;
410                            let (col_a, min_a) =
411                                flags_move.get(h).copied().unwrap_or((false, 80.0));
412                            let (col_b, min_b) =
413                                flags_move.get(h + 1).copied().unwrap_or((false, 80.0));
414                            let (mode, size_a) = resolve_panel_boundary(
415                                s.drag_a0_px + dx,
416                                s.drag_pair_px,
417                                s.drag_lo_px,
418                                s.drag_hi_px,
419                                min_a,
420                                min_b,
421                                col_a,
422                                col_b,
423                            );
424                            s.drag_mode = mode;
425                            s.drag_live_a_px = size_a;
426                        });
427                        window.refresh();
428                    });
429
430                    let st_up = int_win.clone();
431                    let cb_up = on_change_win.clone();
432                    let flags_up = collapsible_flags.clone();
433                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
434                        if !phase.bubble() {
435                            return;
436                        }
437                        let mut notify_shares: Option<Vec<f32>> = None;
438                        st_up.update(cx, |s, _| {
439                            let moved = s.drag_moved;
440                            let start_mode = s.drag_start_mode;
441                            let mode = s.drag_mode;
442                            let pair = s.drag_pair_px;
443                            let lo = s.drag_lo_px;
444                            let hi = s.drag_hi_px;
445                            let raw_a = s.drag_live_a_px;
446                            s.dragging_handle = None;
447                            s.drag_moved = false;
448
449                            let (_, min_a) = flags_up.get(h).copied().unwrap_or((false, 80.0));
450                            let (_, min_b) = flags_up.get(h + 1).copied().unwrap_or((false, 80.0));
451
452                            if !moved {
453                                // Clicking a collapsed divider restores the hidden neighbour.
454                                if start_mode != DividerCollapseMode::Open {
455                                    let restored_a = match start_mode {
456                                        DividerCollapseMode::Before => {
457                                            let saved = s
458                                                .restore_shares
459                                                .get(h)
460                                                .and_then(|v| *v)
461                                                .map(|sh| sh / 100.0 * available)
462                                                .unwrap_or(min_a);
463                                            saved.clamp(lo, hi)
464                                        }
465                                        DividerCollapseMode::After => {
466                                            let saved_b = s
467                                                .restore_shares
468                                                .get(h + 1)
469                                                .and_then(|v| *v)
470                                                .map(|sh| sh / 100.0 * available)
471                                                .unwrap_or(min_b);
472                                            (pair - saved_b).clamp(lo, hi)
473                                        }
474                                        DividerCollapseMode::Open => raw_a.clamp(lo, hi),
475                                    };
476                                    if let Some(c) = s.collapsed.get_mut(h) {
477                                        *c = false;
478                                    }
479                                    if let Some(c) = s.collapsed.get_mut(h + 1) {
480                                        *c = false;
481                                    }
482                                    s.shares[h] = restored_a / available * 100.0;
483                                    s.shares[h + 1] =
484                                        (pair - restored_a).max(0.0) / available * 100.0;
485                                    notify_shares = Some(s.shares.clone());
486                                }
487                                return;
488                            }
489
490                            let final_a = match mode {
491                                DividerCollapseMode::Before => {
492                                    if s.drag_a0_px > 1.0 {
493                                        s.restore_shares[h] =
494                                            Some(s.drag_a0_px / available * 100.0);
495                                    }
496                                    0.0
497                                }
498                                DividerCollapseMode::After => {
499                                    if s.drag_b0_px > 1.0 {
500                                        s.restore_shares[h + 1] =
501                                            Some(s.drag_b0_px / available * 100.0);
502                                    }
503                                    pair
504                                }
505                                DividerCollapseMode::Open => raw_a.clamp(lo, hi),
506                            };
507                            s.collapsed[h] = mode == DividerCollapseMode::Before;
508                            s.collapsed[h + 1] = mode == DividerCollapseMode::After;
509                            s.shares[h] = final_a / available * 100.0;
510                            s.shares[h + 1] = (pair - final_a).max(0.0) / available * 100.0;
511                            notify_shares = Some(s.shares.clone());
512                        });
513                        if let (Some(sh), Some(cb)) = (notify_shares, &cb_up) {
514                            cb(&sh, window, cx);
515                        }
516                        window.refresh();
517                    });
518                }
519            },
520        )
521        .absolute()
522        .inset_0();
523
524        let int_key = internal.clone();
525        let on_change_key = self.on_layout_change.clone();
526        let collapsible_for_key: Vec<(bool, f32, f32)> = self
527            .panels
528            .iter()
529            .enumerate()
530            .map(|(i, p)| (p.collapsible, min_of(i), max_of(i)))
531            .collect();
532
533        let mut root = div()
534            .id(self.id.clone())
535            .test_support()
536            .track_focus(&snap.focus_handle)
537            .role(Role::Group)
538            .when_some(self.label, |d, l| d.aria_label(l))
539            .relative()
540            .w_full()
541            .h(px(self.height))
542            .overflow_hidden()
543            .flex()
544            .flex_row()
545            .on_key_down(move |event: &KeyDownEvent, window, cx| {
546                if count < 2 {
547                    return;
548                }
549                let h = int_key.read(cx).focused_handle.min(count - 2);
550                let (col_a, min_a, max_a) = collapsible_for_key[h];
551                let (col_b, min_b, max_b) = collapsible_for_key[h + 1];
552                let key = event.keystroke.key.as_str();
553                let step = if event.keystroke.modifiers.shift {
554                    PANEL_KEY_BIG_STEP
555                } else {
556                    PANEL_KEY_STEP
557                };
558
559                let mut changed: Option<Vec<f32>> = None;
560                int_key.update(cx, |s, _| {
561                    let a_px = s.shares[h] / 100.0 * available;
562                    let b_px = s.shares[h + 1] / 100.0 * available;
563                    let pair = a_px + b_px;
564                    let lo = min_a.max(pair - max_b).clamp(0.0, pair);
565                    let hi = max_a.min(pair - min_b).clamp(lo, pair);
566                    let mode = if s.collapsed[h] {
567                        DividerCollapseMode::Before
568                    } else if s.collapsed[h + 1] {
569                        DividerCollapseMode::After
570                    } else {
571                        DividerCollapseMode::Open
572                    };
573
574                    match key {
575                        "enter" => {
576                            if mode != DividerCollapseMode::Open {
577                                let target_a = if mode == DividerCollapseMode::Before {
578                                    s.restore_shares[h]
579                                        .map(|sh| sh / 100.0 * available)
580                                        .unwrap_or(min_a)
581                                        .clamp(lo, hi)
582                                } else {
583                                    let sb = s.restore_shares[h + 1]
584                                        .map(|sh| sh / 100.0 * available)
585                                        .unwrap_or(min_b);
586                                    (pair - sb).clamp(lo, hi)
587                                };
588                                s.collapsed[h] = false;
589                                s.collapsed[h + 1] = false;
590                                s.shares[h] = target_a / available * 100.0;
591                                s.shares[h + 1] = (pair - target_a).max(0.0) / available * 100.0;
592                                changed = Some(s.shares.clone());
593                            } else if col_a {
594                                s.restore_shares[h] = Some(s.shares[h]);
595                                s.collapsed[h] = true;
596                                s.shares[h] = 0.0;
597                                s.shares[h + 1] = pair / available * 100.0;
598                                changed = Some(s.shares.clone());
599                            } else if col_b {
600                                s.restore_shares[h + 1] = Some(s.shares[h + 1]);
601                                s.collapsed[h + 1] = true;
602                                s.shares[h] = pair / available * 100.0;
603                                s.shares[h + 1] = 0.0;
604                                changed = Some(s.shares.clone());
605                            }
606                        }
607                        "left" | "arrowleft" => {
608                            if mode == DividerCollapseMode::After {
609                                s.collapsed[h + 1] = false;
610                                s.shares[h] = hi / available * 100.0;
611                                s.shares[h + 1] = (pair - hi).max(0.0) / available * 100.0;
612                            } else if mode == DividerCollapseMode::Open && a_px <= lo + 0.5 && col_a
613                            {
614                                s.restore_shares[h] = Some(s.shares[h]);
615                                s.collapsed[h] = true;
616                                s.shares[h] = 0.0;
617                                s.shares[h + 1] = pair / available * 100.0;
618                            } else if mode == DividerCollapseMode::Open {
619                                let next_a = (a_px - step).clamp(lo, hi);
620                                s.shares[h] = next_a / available * 100.0;
621                                s.shares[h + 1] = (pair - next_a).max(0.0) / available * 100.0;
622                            }
623                            changed = Some(s.shares.clone());
624                        }
625                        "right" | "arrowright" => {
626                            if mode == DividerCollapseMode::Before {
627                                s.collapsed[h] = false;
628                                s.shares[h] = lo / available * 100.0;
629                                s.shares[h + 1] = (pair - lo).max(0.0) / available * 100.0;
630                            } else if mode == DividerCollapseMode::Open && a_px >= hi - 0.5 && col_b
631                            {
632                                s.restore_shares[h + 1] = Some(s.shares[h + 1]);
633                                s.collapsed[h + 1] = true;
634                                s.shares[h] = pair / available * 100.0;
635                                s.shares[h + 1] = 0.0;
636                            } else if mode == DividerCollapseMode::Open {
637                                let next_a = (a_px + step).clamp(lo, hi);
638                                s.shares[h] = next_a / available * 100.0;
639                                s.shares[h + 1] = (pair - next_a).max(0.0) / available * 100.0;
640                            }
641                            changed = Some(s.shares.clone());
642                        }
643                        "home" if mode == DividerCollapseMode::Open => {
644                            s.shares[h] = lo / available * 100.0;
645                            s.shares[h + 1] = (pair - lo).max(0.0) / available * 100.0;
646                            changed = Some(s.shares.clone());
647                        }
648                        "end" if mode == DividerCollapseMode::Open => {
649                            s.shares[h] = hi / available * 100.0;
650                            s.shares[h + 1] = (pair - hi).max(0.0) / available * 100.0;
651                            changed = Some(s.shares.clone());
652                        }
653                        _ => {}
654                    }
655                });
656                if let Some(sh) = changed {
657                    if let Some(cb) = &on_change_key {
658                        cb(&sh, window, cx);
659                    }
660                    window.refresh();
661                }
662            })
663            .child(group_probe);
664
665        let mut running_x = 0.0_f32;
666        let mut handle_overlays = Vec::with_capacity(count.saturating_sub(1));
667
668        for (index, panel) in self.panels.into_iter().enumerate() {
669            if index > 0 {
670                let handle_idx = index - 1;
671                let divider_x = running_x;
672                running_x += 1.0;
673
674                let mode = if snap.dragging_handle == Some(handle_idx) && snap.drag_moved {
675                    snap.drag_mode
676                } else if snap.collapsed.get(handle_idx).copied().unwrap_or(false) {
677                    DividerCollapseMode::Before
678                } else if snap.collapsed.get(index).copied().unwrap_or(false) {
679                    DividerCollapseMode::After
680                } else {
681                    DividerCollapseMode::Open
682                };
683
684                let is_hovered = snap.hovered_handle == Some(handle_idx);
685                let is_active = snap.dragging_handle == Some(handle_idx);
686                let show_grip = (is_hovered || is_active) && mode == DividerCollapseMode::Open;
687                let grip_p = if reduced {
688                    if show_grip { 1.0 } else { 0.0 }
689                } else {
690                    arc_spring(
691                        (
692                            self.id.clone(),
693                            SharedString::from(format!("grip-p-{handle_idx}")),
694                        ),
695                        if show_grip { 1.0 } else { 0.0 },
696                        motion.spring.snappy,
697                        window,
698                        cx,
699                    )
700                };
701                let grip_h = 32.0 * (0.6 + 0.4 * grip_p);
702
703                let line_bg = if mode != DividerCollapseMode::Open {
704                    Hsla::transparent_black()
705                } else if is_active || is_hovered {
706                    colors.border_strong
707                } else {
708                    colors.border
709                };
710                let grip_bg = if is_active {
711                    colors.foreground
712                } else {
713                    colors.border_strong
714                };
715
716                root = root.child(div().w(px(1.0)).h_full().flex_none().bg(line_bg));
717
718                let int_hover = internal.clone();
719                let int_down = internal.clone();
720                let on_change_dbl = self.on_layout_change.clone();
721                let focus_down = snap.focus_handle.clone();
722                let def_shares = default_shares.clone();
723                let def_col = default_collapsed.clone();
724                let a_cur = current_px[handle_idx];
725                let b_cur = current_px[index];
726                let min_a = min_of(handle_idx);
727                let max_a = max_of(handle_idx);
728                let min_b = min_of(index);
729                let max_b = max_of(index);
730
731                // 26px draggable hit target centered on the 1px divider (±12.5px),
732                // expanded to encompass the 18x40px restore tab when collapsed.
733                let (hit_left, hit_w) = match mode {
734                    DividerCollapseMode::Open => (divider_x - 12.5, 26.0),
735                    DividerCollapseMode::Before => (divider_x - 12.5, 36.5),
736                    DividerCollapseMode::After => (divider_x - 23.0, 36.5),
737                };
738                let line_offset = divider_x - hit_left;
739
740                let mut handle_overlay = div()
741                    .id(ElementId::NamedChild(
742                        self.id.clone().into(),
743                        SharedString::from(format!("handle-{handle_idx}")),
744                    ))
745                    .test_support()
746                    .role(Role::Slider)
747                    .aria_label(panel.label.clone())
748                    .absolute()
749                    .top_0()
750                    .bottom_0()
751                    .left(px(hit_left))
752                    .w(px(hit_w))
753                    .cursor_col_resize()
754                    .on_hover(move |hovered, window, cx| {
755                        int_hover.update(cx, |s, _| {
756                            if *hovered {
757                                s.hovered_handle = Some(handle_idx);
758                            } else if s.hovered_handle == Some(handle_idx) {
759                                s.hovered_handle = None;
760                            }
761                        });
762                        window.refresh();
763                    })
764                    .on_mouse_down(
765                        MouseButton::Left,
766                        move |event: &MouseDownEvent, window, cx| {
767                            let t = motion_now(cx);
768                            focus_down.focus(window, cx);
769                            let is_double = {
770                                let s = int_down.read(cx);
771                                s.last_click_handle == Some(handle_idx)
772                                    && (t - s.last_click_at) < 0.32
773                            };
774                            if is_double {
775                                int_down.update(cx, |s, _| {
776                                    s.shares = def_shares.clone();
777                                    s.collapsed = def_col.clone();
778                                    s.dragging_handle = None;
779                                    s.drag_moved = false;
780                                    s.last_click_handle = None;
781                                });
782                                if let Some(cb) = &on_change_dbl {
783                                    cb(&def_shares, window, cx);
784                                }
785                                window.refresh();
786                                return;
787                            }
788
789                            let pair = a_cur + b_cur;
790                            let mut lo = min_a.max(pair - max_b);
791                            let mut hi = max_a.min(pair - min_b);
792                            if a_cur > 0.0 && b_cur > 0.0 {
793                                lo = lo.min(a_cur);
794                                hi = hi.max(a_cur);
795                            }
796                            if lo > hi {
797                                let mid = ((lo + hi) * 0.5).clamp(0.0, pair);
798                                lo = mid;
799                                hi = mid;
800                            }
801                            lo = lo.clamp(0.0, pair);
802                            hi = hi.clamp(0.0, pair);
803
804                            int_down.update(cx, |s, _| {
805                                s.focused_handle = handle_idx;
806                                s.last_click_at = t;
807                                s.last_click_handle = Some(handle_idx);
808                                s.dragging_handle = Some(handle_idx);
809                                s.drag_moved = false;
810                                s.drag_start_x = f32::from(event.position.x);
811                                s.drag_a0_px = a_cur;
812                                s.drag_b0_px = b_cur;
813                                s.drag_pair_px = pair;
814                                s.drag_lo_px = lo;
815                                s.drag_hi_px = hi;
816                                s.drag_live_a_px = a_cur;
817                                s.drag_mode = mode;
818                                s.drag_start_mode = mode;
819                            });
820                            window.refresh();
821                        },
822                    );
823
824                if grip_p > 0.01 && mode == DividerCollapseMode::Open {
825                    handle_overlay = handle_overlay.child(
826                        div()
827                            .absolute()
828                            .left(px(line_offset - 1.5))
829                            .top(px((self.height - grip_h) * 0.5))
830                            .w(px(4.0))
831                            .h(px(grip_h))
832                            .rounded(Radii::PILL)
833                            .bg(grip_bg)
834                            .opacity(grip_p),
835                    );
836                }
837
838                if mode != DividerCollapseMode::Open {
839                    let point_right = mode == DividerCollapseMode::Before;
840                    let tab_left = if point_right {
841                        line_offset + 5.0
842                    } else {
843                        line_offset - 22.0
844                    };
845                    let tab_border = if is_hovered {
846                        colors.border_strong
847                    } else {
848                        colors.border
849                    };
850                    let tab_icon = if is_hovered {
851                        colors.foreground
852                    } else {
853                        colors.text_secondary
854                    };
855                    handle_overlay = handle_overlay.child(
856                        div()
857                            .absolute()
858                            .left(px(tab_left))
859                            .top(px((self.height - 40.0) * 0.5))
860                            .w(px(18.0))
861                            .h(px(40.0))
862                            .rounded(Radii::PILL)
863                            .border_1()
864                            .border_color(tab_border)
865                            .bg(colors.surface)
866                            .shadow(Shadows::resting(theme.mode))
867                            .child(
868                                canvas(
869                                    |_, _, _| {},
870                                    move |bounds, _, window, _| {
871                                        let cx_pt = f32::from(bounds.origin.x)
872                                            + f32::from(bounds.size.width) * 0.5;
873                                        let cy_pt = f32::from(bounds.origin.y)
874                                            + f32::from(bounds.size.height) * 0.5;
875                                        paint_horizontal_chevron(
876                                            cx_pt,
877                                            cy_pt,
878                                            point_right,
879                                            tab_icon,
880                                            window,
881                                        );
882                                    },
883                                )
884                                .size_full(),
885                            ),
886                    );
887                }
888
889                handle_overlays.push(handle_overlay);
890            }
891
892            let pane_w = current_px[index];
893            running_x += pane_w;
894            let min_w = min_of(index);
895            let fade_opacity = (pane_w / min_w.max(1.0)).clamp(0.0, 1.0);
896            let inner_w = pane_w.max(min_w);
897
898            root = root.child(
899                div()
900                    .id(ElementId::NamedChild(self.id.clone().into(), panel.id))
901                    .test_support()
902                    .relative()
903                    .w(px(pane_w))
904                    .h_full()
905                    .flex_none()
906                    .overflow_hidden()
907                    .child(
908                        div()
909                            .w(px(inner_w))
910                            .h_full()
911                            .opacity(fade_opacity)
912                            .child(panel.content),
913                    ),
914            );
915        }
916
917        for overlay in handle_overlays {
918            root = root.child(overlay);
919        }
920
921        root
922    }
923}
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    #[test]
930    fn panel_rubber_approaches_44px_asymptote() {
931        assert!(panel_rubber(0.0).abs() < 1e-5);
932        let r40 = panel_rubber(40.0);
933        let r200 = panel_rubber(200.0);
934        assert!(r40 > 12.0 && r40 < PANEL_STRETCH_LIMIT);
935        assert!(r200 > r40 && r200 < PANEL_STRETCH_LIMIT);
936    }
937
938    #[test]
939    fn resolve_panel_boundary_snaps_collapsible_panes_below_threshold() {
940        // min_a = 120 -> collapse threshold = 120 - 60 = 60
941        let (mode_closed, w_closed) =
942            resolve_panel_boundary(48.0, 600.0, 120.0, 480.0, 120.0, 120.0, true, false);
943        assert_eq!(mode_closed, DividerCollapseMode::Before);
944        assert!(w_closed.abs() < 1e-4);
945
946        // Above threshold but below min_a -> rubber-banded open
947        let (mode_band, w_band) =
948            resolve_panel_boundary(90.0, 600.0, 120.0, 480.0, 120.0, 120.0, true, false);
949        assert_eq!(mode_band, DividerCollapseMode::Open);
950        assert!(w_band > 90.0 && w_band < 120.0);
951    }
952}