Guide API
Skip to main content

tvision_rs/widgets/splitter/
mod.rs

1//! A resizable multi-pane layout: [`Splitter`] arranges N panes along one axis,
2//! separated by 1-cell dividers that the user drags (or moves from the keyboard
3//! in resize mode) to resize the panes. [`Constraints`] bound each pane's size,
4//! [`DividerStyle`] sets how each divider looks and whether it moves, and
5//! [`Splitter::joined`] connects the divider lines to the window frame and to
6//! each other through the [`junction`](crate::junction) glyph selectors.
7//!
8//! **Guide:** [Windows & the desktop](../../../../apps/windows.html#splitter-resizable-panes).
9//!
10//! # Turbo Vision heritage
11//! **tvision-rs extension**: no Turbo Vision counterpart. A splitter is a `Group`
12//! specialization; Turbo Vision lays out panes only by hand-placed bounds and
13//! grow modes.
14
15pub mod layout;
16
17use crate::capture::TrackMask;
18use crate::event::Event;
19use crate::junction::{Edge, Junction, JunctionMark, Weight, divider_junction};
20use crate::theme::Role;
21use crate::view::{Context, DrawCtx, Group, GrowMode, Point, Rect, View, ViewId};
22
23pub use layout::{Constraints, Orientation};
24use layout::{Slot, relax_weight, solve};
25
26/// How the seam *after* a given pane looks and behaves.
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28pub enum DividerStyle {
29    /// Always drawn; grab-and-drag anytime.
30    Line,
31    /// Clean look; only a small grab nub at the midpoint.
32    Handle,
33    /// Invisible & seamless in normal use, but resizable in resize mode.
34    Hidden,
35    /// Invisible AND immovable — a permanent boundary, even in resize mode.
36    Locked,
37}
38
39impl DividerStyle {
40    /// Whether a *live* mouse drag may grab this divider in normal use.
41    pub fn draggable_live(&self) -> bool {
42        matches!(self, DividerStyle::Line | DividerStyle::Handle)
43    }
44    /// Whether this divider may be moved (true for everything except `Locked`).
45    pub fn movable(&self) -> bool {
46        !matches!(self, DividerStyle::Locked)
47    }
48}
49
50/// Color role for a divider line: being-moved beats everything, then the line
51/// matches the owning window frame (active vs passive).
52fn divider_role(moving: bool, active: bool) -> Role {
53    if moving {
54        Role::FrameDragging
55    } else if active {
56        Role::FrameActive
57    } else {
58        Role::FramePassive
59    }
60}
61
62/// A generic, N-ary, resizable multi-pane view. One axis, N child panes, N−1
63/// dividers in 1-cell gaps. Embeds a `Group` and delegates the un-overridden
64/// `View` methods to it. See `docs/superpowers/specs/2026-06-13-splitter-design.md`.
65///
66/// # Turbo Vision heritage
67/// **tvision-rs extension**: no Turbo Vision counterpart.
68pub struct Splitter {
69    group: Group,
70    orientation: Orientation,
71    /// Per-pane solver slots, parallel to the group's children in INSERTION order.
72    slots: Vec<Slot>,
73    /// Per-divider styles (len ≤ panes−1); `default_style` fills any gap.
74    divider_styles: Vec<DividerStyle>,
75    default_style: DividerStyle,
76    /// The divider that is the active keyboard resize target (highlighted), if any.
77    active_divider: Option<usize>,
78    /// Weight snapshot taken at [`Splitter::begin_resize_session`]; restored on Esc cancel.
79    saved_weights: Vec<f64>,
80    /// Absolute origin captured each `draw`, for the mouse-track capture (Task 6).
81    abs_origin: Point,
82    /// Active divider being mouse-dragged (Task 6).
83    dragging: Option<usize>,
84    /// Opt-in: join this splitter's linework — interior `├`/`┼` divider crossings
85    /// and (when it is a window's body) the divider→frame junctions the window
86    /// brokers. Default `false` — an un-joined splitter renders plain `│`/`─`
87    /// dividers and emits no frame marks. Cascades to pane sub-splitters.
88    joined: bool,
89}
90
91impl Splitter {
92    fn new(bounds: Rect, orientation: Orientation) -> Self {
93        let mut group = Group::new(bounds);
94        // A splitter is a layout container: by default it grows with its owner
95        // (bottom-right tracks the owner's resize, top-left stays — keeping any
96        // inset), so its panes fill and resize without the caller wiring grow_mode.
97        // Opt out with `with_grow_mode` (e.g. `GrowMode::default()` for fixed size).
98        // (Harmless when nested: a parent splitter sets child bounds explicitly,
99        // so a sub-splitter's grow_mode is never consulted.)
100        group.state_mut().grow_mode = GrowMode {
101            hi_x: true,
102            hi_y: true,
103            ..Default::default()
104        };
105        Splitter {
106            group,
107            orientation,
108            slots: Vec::new(),
109            divider_styles: Vec::new(),
110            default_style: DividerStyle::Line,
111            active_divider: None,
112            saved_weights: Vec::new(),
113            abs_origin: bounds.a,
114            dragging: None,
115            joined: false,
116        }
117    }
118
119    /// Builder: opt this splitter's linework into joining — its divider lines
120    /// connect to each other (interior `├`/`┼` crossings) and, when it is a
121    /// window's body, to the surrounding frame (the window auto-brokers). Joining
122    /// cascades to pane sub-splitters, so a nested grid needs `.joined()` only on
123    /// the outermost splitter.
124    pub fn joined(mut self) -> Self {
125        self.set_joined(true);
126        self
127    }
128
129    /// Override the grow mode (how the splitter resizes with its owner). A
130    /// splitter grows to fill by default (`{ hi_x, hi_y }`); pass
131    /// `GrowMode::default()` for a fixed-size splitter, or any custom mode.
132    pub fn with_grow_mode(mut self, grow_mode: GrowMode) -> Self {
133        self.group.state_mut().grow_mode = grow_mode;
134        self
135    }
136
137    /// Set joining at runtime. Propagates to pane sub-splitters (ancestor joined
138    /// ⇒ subtree joined), so the whole grid follows the outermost setting.
139    pub fn set_joined(&mut self, on: bool) {
140        self.joined = on;
141        let ids = self.group.child_ids_in_order();
142        for id in ids {
143            if let Some(sub) = self
144                .group
145                .child_mut(id)
146                .and_then(|v| v.as_any_mut())
147                .and_then(|a| a.downcast_mut::<Splitter>())
148            {
149                sub.set_joined(on);
150            }
151        }
152    }
153
154    /// Empty horizontal-axis splitter (side-by-side panes, vertical dividers).
155    pub fn cols() -> Self {
156        Splitter::new(Rect::new(0, 0, 0, 0), Orientation::Cols)
157    }
158
159    /// Empty vertical-axis splitter (stacked panes, horizontal dividers).
160    pub fn rows() -> Self {
161        Splitter::new(Rect::new(0, 0, 0, 0), Orientation::Rows)
162    }
163
164    /// Axis length available to content = bounds extent minus the N−1 divider cells.
165    fn content_len(&self) -> i32 {
166        let b = self.group.state().get_bounds();
167        let extent = match self.orientation {
168            Orientation::Cols => b.b.x - b.a.x,
169            Orientation::Rows => b.b.y - b.a.y,
170        };
171        let dividers = self.slots.len().saturating_sub(1) as i32;
172        (extent - dividers).max(0)
173    }
174
175    /// Insert a pane with its constraints; returns the pane's `ViewId`. Re-solves.
176    pub fn insert(&mut self, view: Box<dyn View>, c: Constraints) -> ViewId {
177        let id = self.group.insert(view);
178        self.slots.push(Slot::from_constraints(c));
179        // If this splitter is already joined, a sub-splitter pane added afterwards
180        // must inherit it (so `.joined()` set before adding panes still cascades).
181        if self.joined
182            && let Some(sub) = self
183                .group
184                .child_mut(id)
185                .and_then(|v| v.as_any_mut())
186                .and_then(|a| a.downcast_mut::<Splitter>())
187        {
188            sub.set_joined(true);
189        }
190        self.resolve_layout_local();
191        id
192    }
193
194    /// The effective style of divider `i` (between pane `i` and `i+1`).
195    fn style_of(&self, i: usize) -> DividerStyle {
196        self.divider_styles
197            .get(i)
198            .copied()
199            .unwrap_or(self.default_style)
200    }
201
202    /// True while divider `i` is being moved (mouse drag or the active keyboard
203    /// resize target) — drives the FrameDragging highlight.
204    fn is_moving(&self, i: usize) -> bool {
205        self.dragging == Some(i) || self.active_divider == Some(i)
206    }
207
208    /// Paint the N−1 dividers into the 1-cell gaps. Called by `draw` AFTER the
209    /// group paints its children. `ctx` is the splitter's own draw context
210    /// (origin == splitter bounds origin), so coordinates are local (0-based).
211    fn draw_dividers(&self, ctx: &mut DrawCtx) {
212        let b = self.group.state().get_bounds();
213        let sizes = solve(&self.slots, self.content_len());
214        // Extract glyph chars before any mutable put_char borrow.
215        let (frame_v, frame_h) = {
216            let g = ctx.glyphs();
217            (g.frame_v, g.frame_h)
218        };
219        // `run` = length of the divider line across the cross-axis (local).
220        let run = match self.orientation {
221            Orientation::Cols => b.b.y - b.a.y,
222            Orientation::Rows => b.b.x - b.a.x,
223        };
224        let mut cursor = 0i32; // local position along the split axis
225        for i in 0..self.slots.len().saturating_sub(1) {
226            cursor += sizes.get(i).copied().unwrap_or(0);
227            let style = self.style_of(i);
228            let moving = self.is_moving(i);
229            let role = divider_role(moving, self.state().state.active);
230            let st = ctx.style(role);
231            // Single-line always (match frame COLOR, not weight).
232            let (line_glyph, nub_glyph) = match self.orientation {
233                Orientation::Cols => (frame_v, frame_v),
234                Orientation::Rows => (frame_h, frame_h),
235            };
236            let draw_full = matches!(style, DividerStyle::Line) || moving;
237            let draw_handle = matches!(style, DividerStyle::Handle) && !moving;
238            for k in 0..run {
239                let (x, y) = match self.orientation {
240                    Orientation::Cols => (cursor, k),
241                    Orientation::Rows => (k, cursor),
242                };
243                if draw_full {
244                    ctx.put_char(x, y, line_glyph, st);
245                } else if draw_handle && k == run / 2 {
246                    ctx.put_char(x, y, nub_glyph, st);
247                }
248                // Hidden / Locked in normal mode: draw nothing (pane background shows).
249            }
250            cursor += 1; // step over the divider cell
251        }
252    }
253
254    /// Builder: add a pane (discards the returned id — for static layouts). Chains.
255    pub fn pane(mut self, view: Box<dyn View>, c: Constraints) -> Self {
256        self.insert(view, c);
257        self
258    }
259
260    /// Builder: set the default divider style for gaps without an explicit style.
261    pub fn default_divider(mut self, style: DividerStyle) -> Self {
262        self.default_style = style;
263        self.resolve_layout_local();
264        self
265    }
266
267    /// Builder: set the style of divider `i` (between pane `i` and `i+1`).
268    pub fn divider(mut self, i: usize, style: DividerStyle) -> Self {
269        self.ensure_divider_len();
270        if i < self.divider_styles.len() {
271            self.divider_styles[i] = style;
272        }
273        self
274    }
275
276    /// Grow `divider_styles` to cover all current gaps, filling with `default_style`.
277    fn ensure_divider_len(&mut self) {
278        let want = self.slots.len().saturating_sub(1);
279        while self.divider_styles.len() < want {
280            self.divider_styles.push(self.default_style);
281        }
282    }
283
284    /// Compute each child's `Rect` from the solver and apply via `change_bounds`.
285    /// Local (no `Context`) — used at insert/build/resize time.
286    fn resolve_layout_local(&mut self) {
287        let sizes = solve(&self.slots, self.content_len());
288        // Children are positioned in the splitter's OWN 0-based local space
289        // (Group::draw translates each child by its bounds on top of the
290        // splitter's already-translated context), so use the extent, not the
291        // owner-space bounds — otherwise an inset splitter shifts every pane by
292        // its own origin.
293        let ext = self.group.state().get_extent();
294        let mut cursor = match self.orientation {
295            Orientation::Cols => ext.a.x,
296            Orientation::Rows => ext.a.y,
297        };
298        let ids = self.group.child_ids_in_order();
299        let mut resized = false;
300        for (i, id) in ids.iter().enumerate() {
301            let size = sizes.get(i).copied().unwrap_or(0);
302            let rect = match self.orientation {
303                Orientation::Cols => Rect::new(cursor, ext.a.y, cursor + size, ext.b.y),
304                Orientation::Rows => Rect::new(ext.a.x, cursor, ext.b.x, cursor + size),
305            };
306            if let Some(child) = self.group.find_mut(*id) {
307                resized |= child.state().size != rect.b - rect.a;
308                child.change_bounds(rect);
309            }
310            cursor += size + 1; // +1 for the divider cell that follows
311        }
312        // The panes were re-bounded by the layout, not the group cascade: let
313        // the next (delegated) `on_bounds_changed` reach them.
314        if resized {
315            self.group.mark_bounds_dirty();
316        }
317    }
318
319    /// Local axis coordinate of divider `i` (the gap cell after pane `i`).
320    /// `None` if `i` is out of range.
321    fn divider_axis_pos(&self, i: usize) -> Option<i32> {
322        if i + 1 >= self.slots.len() {
323            return None;
324        }
325        let sizes = solve(&self.slots, self.content_len());
326        let mut pos = 0;
327        for k in 0..=i {
328            pos += sizes.get(k).copied().unwrap_or(0);
329            if k < i {
330                pos += 1; // earlier divider cells
331            }
332        }
333        Some(pos)
334    }
335
336    /// Owner-data-down producer: for each divider whose drawn line abuts a frame
337    /// edge, emit a [`JunctionMark`] in `frame_bounds`-local coordinates; recurses
338    /// into pane sub-splitters. A pure function of layout (no drawing), but `&mut
339    /// self` because reaching a pane child to recurse needs `Group::child_mut`
340    /// (the only child accessor `Group` exposes is `&mut`). The owning window
341    /// already holds the `&mut Splitter`, so this is free there.
342    pub(crate) fn frame_junction_marks(&mut self, frame_bounds: Rect) -> Vec<JunctionMark> {
343        if !self.joined {
344            return Vec::new();
345        }
346        let mut out = Vec::new();
347        let origin = self.group.state().get_bounds().a; // top splitter: frame-space origin
348        self.collect_frame_marks(frame_bounds, origin, &mut out);
349        out
350    }
351
352    /// Recursive worker for [`frame_junction_marks`]. `origin` is this splitter's
353    /// top-left in the frame's coordinate space; children are 0-based local, so a
354    /// sub-splitter's frame-space origin is `origin + child_local_bounds.a`.
355    fn collect_frame_marks(&mut self, fb: Rect, origin: Point, out: &mut Vec<JunctionMark>) {
356        let ext = self.group.state().get_extent();
357        let w = ext.b.x - ext.a.x;
358        let h = ext.b.y - ext.a.y;
359        let sizes = solve(&self.slots, self.content_len());
360        let stem = Weight::Single; // dividers are single-line; frame tee weight unchanged at rest
361        let fw = fb.b.x - fb.a.x; // frame width
362        let fh = fb.b.y - fb.a.y; // frame height
363
364        let mut cursor = 0i32; // splitter-local 0-based axis position
365        for i in 0..self.slots.len().saturating_sub(1) {
366            cursor += sizes.get(i).copied().unwrap_or(0);
367            let local = cursor; // this divider's local axis position
368            let draws_full = matches!(self.style_of(i), DividerStyle::Line) || self.is_moving(i);
369            if draws_full {
370                match self.orientation {
371                    Orientation::Cols => {
372                        let off = (origin.x - fb.a.x) + local;
373                        let interior = off > 0 && off < fw - 1;
374                        if interior && origin.y == fb.a.y + 1 {
375                            out.push(JunctionMark {
376                                edge: Edge::Top,
377                                offset: off,
378                                stem,
379                            });
380                        }
381                        if interior && origin.y + h == fb.b.y - 1 {
382                            out.push(JunctionMark {
383                                edge: Edge::Bottom,
384                                offset: off,
385                                stem,
386                            });
387                        }
388                    }
389                    Orientation::Rows => {
390                        let off = (origin.y - fb.a.y) + local;
391                        let interior = off > 0 && off < fh - 1;
392                        if interior && origin.x == fb.a.x + 1 {
393                            out.push(JunctionMark {
394                                edge: Edge::Left,
395                                offset: off,
396                                stem,
397                            });
398                        }
399                        if interior && origin.x + w == fb.b.x - 1 {
400                            out.push(JunctionMark {
401                                edge: Edge::Right,
402                                offset: off,
403                                stem,
404                            });
405                        }
406                    }
407                }
408            }
409            cursor += 1; // step over the divider cell
410        }
411
412        // Recurse: a child's frame-space origin = this splitter's origin + the
413        // child's 0-based local position.
414        let ids = self.group.child_ids_in_order();
415        for id in ids {
416            if let Some(sp) = self
417                .group
418                .child_mut(id)
419                .and_then(|v| v.as_any_mut())
420                .and_then(|a| a.downcast_mut::<Splitter>())
421            {
422                let ca = sp.group.state().get_bounds().a; // 0-based local within self
423                let child_origin = Point::new(origin.x + ca.x, origin.y + ca.y);
424                sp.collect_frame_marks(fb, child_origin, out);
425            }
426        }
427    }
428
429    /// Hit-test a **local** point to the divider index whose cell it lands on.
430    fn divider_at(&self, local: Point) -> Option<usize> {
431        let along = match self.orientation {
432            Orientation::Cols => local.x,
433            Orientation::Rows => local.y,
434        };
435        (0..self.slots.len().saturating_sub(1)).find(|&i| self.divider_axis_pos(i) == Some(along))
436    }
437
438    /// Move divider `i` so its boundary local axis position becomes `target`.
439    /// Option A: rewrite only the two flexible neighbors' f64 weights, preserving
440    /// their sum; a fixed (`min==max`) neighbor is a hard wall (clamped). Callers
441    /// must gate `Locked` at the event layer.
442    fn drag_divider_to(&mut self, i: usize, target: i32) {
443        if i + 1 >= self.slots.len() {
444            return;
445        }
446        let sizes = solve(&self.slots, self.content_len());
447        let (a, b) = (i, i + 1);
448        let cur_boundary = self.divider_axis_pos(i).unwrap_or(0);
449        let mut delta = target - cur_boundary; // +delta grows pane a, shrinks b
450        let (size_a, size_b) = (sizes[a], sizes[b]);
451        let max_grow_a = (self.slots[a].max - size_a).max(0);
452        let max_shrink_b = (size_b - self.slots[b].min).max(0);
453        let max_pos = max_grow_a.min(max_shrink_b);
454        let max_shrink_a = (size_a - self.slots[a].min).max(0);
455        let max_grow_b = (self.slots[b].max - size_b).max(0);
456        let max_neg = max_shrink_a.min(max_grow_b);
457        delta = delta.clamp(-max_neg, max_pos);
458        if delta == 0 {
459            return;
460        }
461        let new_a = size_a + delta;
462        let new_b = size_b - delta;
463        let free_a = (new_a - self.slots[a].min).max(0) as f64;
464        let free_b = (new_b - self.slots[b].min).max(0) as f64;
465        let pair_w = self.slots[a].weight + self.slots[b].weight;
466        let free_sum = free_a + free_b;
467        if pair_w > 0.0 && free_sum > 0.0 {
468            self.slots[a].weight = pair_w * free_a / free_sum;
469            self.slots[b].weight = pair_w * free_b / free_sum;
470        }
471    }
472
473    /// Re-flow children to current solved sizes via DEFERRED bounds (loop owns writes).
474    fn request_relayout(&mut self, ctx: &mut Context) {
475        let sizes = solve(&self.slots, self.content_len());
476        let ext = self.group.state().get_extent();
477        let mut cursor = match self.orientation {
478            Orientation::Cols => ext.a.x,
479            Orientation::Rows => ext.a.y,
480        };
481        let ids = self.group.child_ids_in_order();
482        for (i, id) in ids.iter().enumerate() {
483            let size = sizes.get(i).copied().unwrap_or(0);
484            let rect = match self.orientation {
485                Orientation::Cols => Rect::new(cursor, ext.a.y, cursor + size, ext.b.y),
486                Orientation::Rows => Rect::new(ext.a.x, cursor, ext.b.x, cursor + size),
487            };
488            ctx.request_bounds(*id, rect);
489            cursor += size + 1;
490        }
491    }
492
493    // -- runtime mutators -------------------------------------------------------
494
495    /// Index of the pane with this id, in slot/insertion order.
496    fn pane_index(&self, id: ViewId) -> Option<usize> {
497        self.group
498            .child_ids_in_order()
499            .iter()
500            .position(|&c| c == id)
501    }
502
503    /// Replace a pane's constraints at runtime; re-solves.
504    pub fn set_constraints(&mut self, id: ViewId, c: Constraints) {
505        if let Some(i) = self.pane_index(id) {
506            self.slots[i] = Slot::from_constraints(c);
507            self.resolve_layout_local();
508        }
509    }
510
511    /// Set divider `i`'s style at runtime.
512    pub fn set_divider_style(&mut self, i: usize, style: DividerStyle) {
513        self.ensure_divider_len();
514        if i < self.divider_styles.len() {
515            self.divider_styles[i] = style;
516        }
517    }
518
519    /// Set the default divider style at runtime.
520    pub fn set_default_divider_style(&mut self, style: DividerStyle) {
521        self.default_style = style;
522    }
523
524    /// Remove a pane (and its slot); re-solves. Returns `true` if found.
525    pub fn remove(&mut self, id: ViewId) -> bool {
526        if let Some(i) = self.pane_index(id) {
527            self.group.remove_child_by_id(id);
528            self.slots.remove(i);
529            if i < self.divider_styles.len() {
530                self.divider_styles.remove(i);
531            }
532            self.resolve_layout_local();
533            true
534        } else {
535            false
536        }
537    }
538
539    /// Make a (possibly fixed) pane flexible WITHOUT moving any divider: drop its
540    /// min/max to (0, `i32::MAX`) and set its weight to the position-preserving
541    /// closed form (Σ flexible weights × current_size / current_free).
542    pub fn relax(&mut self, id: ViewId) {
543        let Some(i) = self.pane_index(id) else {
544            return;
545        };
546        let sizes = solve(&self.slots, self.content_len());
547        let cur = sizes.get(i).copied().unwrap_or(0);
548        let others: f64 = self
549            .slots
550            .iter()
551            .enumerate()
552            .filter(|(k, s)| *k != i && s.weight > 0.0)
553            .map(|(_, s)| s.weight)
554            .sum();
555        let free = self.content_len() - self.slots.iter().map(|s| s.min).sum::<i32>();
556        let w = relax_weight(others, cur, free);
557        self.slots[i].min = 0;
558        self.slots[i].max = i32::MAX;
559        self.slots[i].weight = w;
560        self.resolve_layout_local();
561    }
562
563    // -- keyboard resize session (driven by the window's resize capture via the
564    //    SplitterDivider broker; see docs/.../splitter-resize-unification-design.md)
565
566    /// Begin a keyboard resize session: snapshot every slot weight (for Esc
567    /// restore) and clear the active-target highlight (the capture sets it via
568    /// [`set_active_divider`]). Recurses into pane children that are themselves
569    /// splitters so a nested grid resizes too. Returns every movable divider as
570    /// `(splitter_id, divider_index, orientation)` in depth-first axis order — this
571    /// splitter's dividers first, then each sub-splitter's.
572    ///
573    /// Precondition: the splitter must already be inserted (have a [`ViewId`]) for
574    /// its own dividers to appear in the list — `self.state().id()` is `None` before
575    /// insertion, and its own dividers would then be silently omitted (recursion into
576    /// inserted sub-splitters is unaffected).
577    pub(crate) fn begin_resize_session(&mut self) -> Vec<(ViewId, usize, Orientation)> {
578        // Only splitters that contribute a movable divider take a snapshot — they
579        // are the only ones that appear in the capture's target list and thus the
580        // only ones that receive a matching end_resize_session. A divider-less
581        // splitter would otherwise leave a dangling snapshot that is never cleared.
582        self.saved_weights = if self.has_movable_divider() {
583            self.slots.iter().map(|s| s.weight).collect()
584        } else {
585            Vec::new()
586        };
587        self.active_divider = None;
588        let mut out = Vec::new();
589        if let Some(id) = self.state().id() {
590            for i in 0..self.slots.len().saturating_sub(1) {
591                if self.style_of(i).movable() {
592                    out.push((id, i, self.orientation));
593                }
594            }
595        }
596        let ids = self.group.child_ids_in_order();
597        for cid in ids {
598            if let Some(sub) = self
599                .group
600                .child_mut(cid)
601                .and_then(|v| v.as_any_mut())
602                .and_then(|a| a.downcast_mut::<Splitter>())
603            {
604                out.extend(sub.begin_resize_session());
605            }
606        }
607        out
608    }
609
610    /// Set (or clear) which divider is the active resize target. Drives the
611    /// `FrameDragging` highlight in `draw_dividers`. Per-splitter (not recursive):
612    /// the broker addresses each splitter by id.
613    pub(crate) fn set_active_divider(&mut self, sel: Option<usize>) {
614        self.active_divider = sel;
615    }
616
617    /// Move divider `index` by `delta` cells along the split axis, then re-flow
618    /// children synchronously (`resolve_layout_local` writes child bounds
619    /// directly). The caller then calls [`View::on_bounds_changed`] so the
620    /// re-sized panes re-publish their scroll state.
621    pub(crate) fn nudge_divider(&mut self, index: usize, delta: i32) {
622        if let Some(p) = self.divider_axis_pos(index) {
623            self.drag_divider_to(index, p + delta);
624        }
625        self.resolve_layout_local();
626    }
627
628    /// End the resize session. On `!commit` restore the snapshotted weights (Esc).
629    /// Clears the highlight and the snapshot. Per-splitter (not recursive).
630    pub(crate) fn end_resize_session(&mut self, commit: bool) {
631        if !commit && self.saved_weights.len() == self.slots.len() {
632            for (s, w) in self.slots.iter_mut().zip(&self.saved_weights) {
633                s.weight = *w;
634            }
635        }
636        self.active_divider = None;
637        self.saved_weights.clear();
638        self.resolve_layout_local();
639    }
640
641    /// True if this splitter has ≥1 movable divider (used by the window to decide
642    /// whether to enable Command::RESIZE / offer divider targets).
643    pub(crate) fn has_movable_divider(&self) -> bool {
644        (0..self.slots.len().saturating_sub(1)).any(|i| self.style_of(i).movable())
645    }
646
647    // -- interior crossings (Site 2) --------------------------------------------
648
649    /// Site 2 (tvision-rs extension): overlay `├`/`┤`/`┴`/`┬` on this splitter's own
650    /// divider cells where a perpendicular pane sub-splitter's divider meets them.
651    /// `&mut self` because reaching a pane child to read its divider positions
652    /// needs `Group::child_mut` (the `&self draw_dividers` cannot do this). Reads
653    /// the child's positions into owned data (borrow released) before drawing on
654    /// this splitter's own cells via `ctx`.
655    ///
656    /// Scope: each outer divider is joined from the pane(s) it borders. The common
657    /// grid (one perpendicular sub-splitter per outer divider) renders correctly.
658    /// Two ADJACENT perpendicular sub-splitters whose dividers coincide on the same
659    /// shared outer-divider cell would need a `┼` (the [`Junction::Cross`] glyph
660    /// exists for it); that topology is not composed here — the last-written tee
661    /// wins — and is left for a future extension. Mixed-weight crossings are
662    /// likewise out of scope (the glyph uses the outer divider's weight).
663    fn draw_interior_crossings(&mut self, ctx: &mut DrawCtx) {
664        if self.slots.len() < 2 {
665            return; // no dividers of our own → nothing to cross
666        }
667        let weight = Weight::Single;
668        let ids = self.group.child_ids_in_order();
669        for (p, id) in ids.iter().enumerate() {
670            // Owned (sub bounds, perpendicular divider local positions) or None.
671            let info = self.group.child_mut(*id).and_then(|v| {
672                v.as_any_mut()
673                    .and_then(|a| a.downcast_mut::<Splitter>())
674                    .filter(|sub| sub.orientation != self.orientation)
675                    .map(|sub| {
676                        let cb = sub.group.state().get_bounds();
677                        let csizes = solve(&sub.slots, sub.content_len());
678                        let mut pos = Vec::new();
679                        let mut c = 0i32;
680                        for i in 0..sub.slots.len().saturating_sub(1) {
681                            c += csizes.get(i).copied().unwrap_or(0);
682                            let full =
683                                matches!(sub.style_of(i), DividerStyle::Line) || sub.is_moving(i);
684                            if full {
685                                pos.push(c);
686                            }
687                            c += 1;
688                        }
689                        (cb, pos)
690                    })
691            });
692            let Some((cb, perp)) = info else { continue };
693
694            let low = if p > 0 {
695                self.divider_axis_pos(p - 1)
696            } else {
697                None
698            };
699            let high = if p < self.slots.len() - 1 {
700                self.divider_axis_pos(p)
701            } else {
702                None
703            };
704
705            for d in &perp {
706                let (cross_local, branch_low, branch_high) = match self.orientation {
707                    // Cols outer: vertical dividers; sub is Rows (horizontal). The
708                    // crossing's cross-axis is the ROW.
709                    Orientation::Cols => {
710                        let row = cb.a.y + d;
711                        (row, Junction::TeeLeft, Junction::TeeRight)
712                    }
713                    // Rows outer: horizontal dividers; sub is Cols (vertical). The
714                    // crossing's cross-axis is the COLUMN.
715                    Orientation::Rows => {
716                        let col = cb.a.x + d;
717                        (col, Junction::TeeUp, Junction::TeeDown)
718                    }
719                };
720                // Sub on the HIGH side of the low divider → branch toward high.
721                if let Some(ld) = low {
722                    let glyph = divider_junction(branch_high, weight, ctx.glyphs());
723                    self.put_crossing(ctx, ld, cross_local, glyph);
724                }
725                // Sub on the LOW side of the high divider → branch toward low.
726                if let Some(hd) = high {
727                    let glyph = divider_junction(branch_low, weight, ctx.glyphs());
728                    self.put_crossing(ctx, hd, cross_local, glyph);
729                }
730            }
731        }
732    }
733
734    /// Overlay one crossing glyph at (outer-divider axis pos, cross-axis pos),
735    /// mapped to (x, y) by orientation. Local 0-based coords (same as `draw_dividers`).
736    fn put_crossing(&self, ctx: &mut DrawCtx, axis: i32, cross: i32, glyph: char) {
737        // Crossings are never the moved target, so moving=false.
738        let role = divider_role(false, self.state().state.active);
739        let st = ctx.style(role);
740        let (x, y) = match self.orientation {
741            Orientation::Cols => (axis, cross), // vertical divider: column=axis, row=cross
742            Orientation::Rows => (cross, axis), // horizontal divider: row=axis, column=cross
743        };
744        ctx.put_char(x, y, glyph, st);
745    }
746}
747
748#[crate::delegate(to = group)]
749impl View for Splitter {
750    fn draw(&mut self, ctx: &mut DrawCtx) {
751        self.abs_origin = ctx.origin();
752        self.group.draw(ctx);
753        self.draw_dividers(ctx);
754        if self.joined {
755            self.draw_interior_crossings(ctx);
756        }
757    }
758
759    fn change_bounds(&mut self, bounds: Rect) {
760        self.group.state_mut().set_bounds(bounds);
761        self.resolve_layout_local();
762    }
763
764    /// Downcast seam: a parent (the owning window, or an outer splitter reaching a
765    /// pane sub-splitter) reaches this `Splitter` concretely via `child_mut` +
766    /// `as_any_mut` + `downcast_mut::<Splitter>()` — the same mechanism a window
767    /// uses to push data to its `Frame`. The `#[delegate(to = group)]` macro would
768    /// otherwise forward this to the inner `Group` (which returns `None`), so the
769    /// override body here is required; the macro auto-excludes it from forwarding.
770    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
771        Some(self)
772    }
773
774    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
775        match ev {
776            Event::KeyDown(_) => {
777                // No splitter-owned keys. Tab focus traversal (including descending
778                // into and cycling among the panes) is handled by the hierarchical
779                // pass in `Group::handle_event`, so the splitter is transparent to
780                // focus here. Divider resize is driven by the window's resize
781                // capture (Command::RESIZE), not a raw KeyDown.
782                self.group.handle_event(ev, ctx);
783            }
784            Event::MouseDown(me) => {
785                let local = me.position; // already view-local; copy before ev.clear()
786                if let Some(i) = self.divider_at(local) {
787                    let style = self.style_of(i);
788                    // Any non-Locked divider is mouse-draggable (incl. Hidden, which
789                    // becomes visible in FrameDragging while dragged) — deliberate per spec.
790                    let allowed = style.movable();
791                    if let (true, Some(id)) = (allowed, self.state().id()) {
792                        self.dragging = Some(i);
793                        ctx.start_mouse_track(
794                            id,
795                            self.abs_origin,
796                            TrackMask {
797                                mouse_move: true,
798                                ..Default::default()
799                            },
800                        );
801                        ev.clear();
802                        return;
803                    }
804                }
805                self.group.handle_event(ev, ctx);
806            }
807            Event::MouseMove(me) if self.dragging.is_some() => {
808                let i = self.dragging.unwrap();
809                let target = match self.orientation {
810                    Orientation::Cols => me.position.x,
811                    Orientation::Rows => me.position.y,
812                };
813                self.drag_divider_to(i, target);
814                self.request_relayout(ctx);
815                ev.clear();
816            }
817            Event::MouseUp(_) if self.dragging.is_some() => {
818                self.dragging = None;
819                ev.clear();
820            }
821            _ => self.group.handle_event(ev, ctx),
822        }
823    }
824}
825
826#[cfg(test)]
827mod divider_tests {
828    use super::*;
829    use crate::backend::{HeadlessBackend, Renderer};
830    use crate::screen::Buffer;
831    use crate::theme::{Role, Theme};
832    use crate::view::ViewState;
833
834    // Minimal fill view for snapshot tests.
835    struct Fill(char, ViewState);
836    impl Fill {
837        fn boxed(ch: char) -> Box<dyn View> {
838            Box::new(Fill(ch, ViewState::new(Rect::new(0, 0, 1, 1))))
839        }
840    }
841    impl View for Fill {
842        fn state(&self) -> &ViewState {
843            &self.1
844        }
845        fn state_mut(&mut self) -> &mut ViewState {
846            &mut self.1
847        }
848        fn draw(&mut self, ctx: &mut DrawCtx) {
849            let b = self.1.get_bounds();
850            let (w, h) = (b.b.x - b.a.x, b.b.y - b.a.y);
851            ctx.fill(Rect::new(0, 0, w, h), self.0, ctx.style(Role::Normal));
852        }
853    }
854
855    fn render_splitter(sp: &mut Splitter, w: u16, h: u16) -> String {
856        let theme = Theme::classic_blue();
857        let (backend, screen) = HeadlessBackend::new(w, h);
858        let mut r = Renderer::new(Box::new(backend));
859        r.render(|buf: &mut Buffer| {
860            let bounds = sp.state().get_bounds();
861            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
862            sp.draw(&mut dc);
863        });
864        screen.snapshot()
865    }
866
867    #[test]
868    fn splitter_grows_with_owner_by_default() {
869        let sp = Splitter::cols();
870        let gm = sp.state().grow_mode;
871        assert!(gm.hi_x && gm.hi_y, "splitter fills/grows by default");
872        assert!(!gm.lo_x && !gm.lo_y, "top-left stays (keeps any inset)");
873        // rows() too
874        let sp2 = Splitter::rows();
875        assert!(sp2.state().grow_mode.hi_x && sp2.state().grow_mode.hi_y);
876    }
877
878    #[test]
879    fn with_grow_mode_can_disable_growth() {
880        let sp = Splitter::cols().with_grow_mode(GrowMode::default());
881        let gm = sp.state().grow_mode;
882        assert!(
883            !gm.hi_x && !gm.hi_y && !gm.lo_x && !gm.lo_y,
884            "fixed-size opt-out"
885        );
886    }
887
888    #[test]
889    fn draggability_matrix() {
890        assert!(DividerStyle::Line.draggable_live());
891        assert!(DividerStyle::Handle.draggable_live());
892        assert!(!DividerStyle::Hidden.draggable_live());
893        assert!(!DividerStyle::Locked.draggable_live());
894
895        assert!(DividerStyle::Hidden.movable());
896        assert!(!DividerStyle::Locked.movable());
897    }
898
899    // Minimal view used by resize-session tests (no rendering needed here).
900    struct Leaf(ViewState);
901    impl Leaf {
902        fn boxed() -> Box<dyn View> {
903            Box::new(Leaf(ViewState::new(Rect::new(0, 0, 1, 1))))
904        }
905    }
906    impl View for Leaf {
907        fn state(&self) -> &ViewState {
908            &self.0
909        }
910        fn state_mut(&mut self) -> &mut ViewState {
911            &mut self.0
912        }
913        fn draw(&mut self, _ctx: &mut DrawCtx) {}
914    }
915
916    /// Three-pane column splitter laid out in a 30×5 box (2 dividers → 28 content
917    /// cols → the largest-remainder solver gives the extra cell to the first pane,
918    /// e.g. [10, 9, 9]). `divider_axis_pos` is well-defined after this.
919    fn three_pane_cols() -> Splitter {
920        let mut sp = Splitter::cols();
921        sp.change_bounds(Rect::new(0, 0, 30, 5));
922        sp.insert(Fill::boxed('A'), Constraints::flex());
923        sp.insert(Fill::boxed('B'), Constraints::flex());
924        sp.insert(Fill::boxed('C'), Constraints::flex());
925        // Give the splitter a stable ViewId so begin_resize_session can include it.
926        sp.state_mut().id = Some(ViewId::next());
927        sp
928    }
929
930    #[test]
931    fn begin_resize_session_lists_movable_dividers_and_snapshots() {
932        // Three panes → two dividers (indices 0 and 1), both movable (default Line style).
933        let mut sp = three_pane_cols(); // helper below; 3 panes → dividers 0 and 1
934        let targets = sp.begin_resize_session();
935        let id = sp.state().id().unwrap();
936        assert_eq!(
937            targets,
938            vec![(id, 0, Orientation::Cols), (id, 1, Orientation::Cols)],
939            "movable dividers enumerated in axis order with this splitter's id"
940        );
941        assert_eq!(
942            sp.active_divider, None,
943            "begin does NOT auto-select a divider"
944        );
945        assert_eq!(
946            sp.saved_weights.len(),
947            sp.slots.len(),
948            "weights snapshotted"
949        );
950    }
951
952    #[test]
953    fn nudge_divider_moves_then_end_commit_keeps_position() {
954        let mut sp = three_pane_cols();
955        sp.begin_resize_session();
956        let before = sp.divider_axis_pos(0).unwrap();
957        sp.nudge_divider(0, 1);
958        let after = sp.divider_axis_pos(0).unwrap();
959        assert_eq!(
960            after,
961            before + 1,
962            "nudge moves the divider one cell along the axis"
963        );
964        sp.end_resize_session(true); // commit
965        assert_eq!(
966            sp.divider_axis_pos(0).unwrap(),
967            after,
968            "commit keeps the new position"
969        );
970        assert!(sp.saved_weights.is_empty(), "session ended");
971        assert_eq!(sp.active_divider, None);
972    }
973
974    #[test]
975    fn end_resize_session_cancel_restores_weights() {
976        let mut sp = three_pane_cols();
977        sp.begin_resize_session();
978        let before = sp.divider_axis_pos(0).unwrap();
979        sp.nudge_divider(0, 2);
980        assert_ne!(sp.divider_axis_pos(0).unwrap(), before);
981        sp.end_resize_session(false); // Esc / cancel
982        assert_eq!(
983            sp.divider_axis_pos(0).unwrap(),
984            before,
985            "cancel restores pre-session position"
986        );
987    }
988
989    #[test]
990    fn set_active_divider_drives_active_field() {
991        let mut sp = three_pane_cols();
992        sp.begin_resize_session();
993        sp.set_active_divider(Some(1));
994        assert_eq!(sp.active_divider, Some(1));
995        sp.set_active_divider(None);
996        assert_eq!(sp.active_divider, None);
997    }
998
999    #[test]
1000    fn divider_role_rule() {
1001        use crate::theme::Role;
1002        // moving wins over everything.
1003        assert_eq!(divider_role(true, true), Role::FrameDragging);
1004        assert_eq!(divider_role(true, false), Role::FrameDragging);
1005        // not moving: active window -> FrameActive, else FramePassive.
1006        assert_eq!(divider_role(false, true), Role::FrameActive);
1007        assert_eq!(divider_role(false, false), Role::FramePassive);
1008    }
1009
1010    #[test]
1011    fn divider_inactive_is_single_line_passive() {
1012        let mut sp = three_pane_cols(); // default state: not active
1013        let snap = render_splitter(&mut sp, 30, 5);
1014        insta::assert_snapshot!("divider_inactive", snap);
1015    }
1016
1017    #[test]
1018    fn divider_dragging_highlight_on_mouse() {
1019        let mut sp = three_pane_cols();
1020        sp.dragging = Some(0); // simulate mid-drag (plain field, no ctx needed)
1021        let snap = render_splitter(&mut sp, 30, 5);
1022        insta::assert_snapshot!("divider_dragging_highlight_on_mouse", snap);
1023    }
1024
1025    #[test]
1026    fn divider_active_is_single_line_active() {
1027        let mut sp = three_pane_cols();
1028        sp.state_mut().state.active = true; // owning window is active
1029        let snap = render_splitter(&mut sp, 30, 5);
1030        insta::assert_snapshot!("divider_active", snap);
1031    }
1032
1033    #[test]
1034    fn begin_resize_session_recurses_into_sub_splitter() {
1035        // OUTER cols splitter (1 divider) with a SUB rows splitter (1 divider) as
1036        // its second pane. begin_resize_session enumerates the outer's dividers
1037        // first, then recurses depth-first into the sub.
1038        let sub = Splitter::rows()
1039            .pane(Leaf::boxed(), Constraints::flex())
1040            .pane(Leaf::boxed(), Constraints::flex());
1041        let mut outer = Splitter::cols();
1042        outer.change_bounds(Rect::new(0, 0, 30, 10));
1043        outer.insert(Leaf::boxed(), Constraints::flex());
1044        // insert() stamps the child's own ViewId, so the sub-splitter is addressable.
1045        let sub_id = outer.insert(Box::new(sub), Constraints::flex());
1046        // The outer splitter needs its own id for its dividers to be listed.
1047        outer.state_mut().id = Some(ViewId::next());
1048        let outer_id = outer.state().id().unwrap();
1049
1050        let targets = outer.begin_resize_session();
1051        assert_eq!(
1052            targets,
1053            vec![
1054                (outer_id, 0, Orientation::Cols), // outer's divider first
1055                (sub_id, 0, Orientation::Rows),   // then the sub's, depth-first
1056            ],
1057            "depth-first: outer's dividers (outer id/orientation) then the sub's (sub id/orientation)"
1058        );
1059
1060        // The recursion must have begun the sub's session too (its weights snapshotted).
1061        let sub = outer
1062            .group
1063            .child_mut(sub_id)
1064            .and_then(|v| v.as_any_mut())
1065            .and_then(|a| a.downcast_mut::<Splitter>())
1066            .expect("sub pane is a Splitter");
1067        assert_eq!(
1068            sub.saved_weights.len(),
1069            sub.slots.len(),
1070            "sub-splitter's weights snapshotted by the recursive begin"
1071        );
1072    }
1073}
1074
1075#[cfg(test)]
1076mod view_tests {
1077    use super::*;
1078    use crate::backend::{HeadlessBackend, Renderer};
1079    use crate::screen::Buffer;
1080    use crate::theme::{Role, Theme};
1081    use crate::view::ViewState;
1082
1083    struct Fill(char, ViewState);
1084    impl Fill {
1085        fn boxed(ch: char) -> Box<dyn View> {
1086            Box::new(Fill(ch, ViewState::new(Rect::new(0, 0, 1, 1))))
1087        }
1088    }
1089    impl View for Fill {
1090        fn state(&self) -> &ViewState {
1091            &self.1
1092        }
1093        fn state_mut(&mut self) -> &mut ViewState {
1094            &mut self.1
1095        }
1096        fn draw(&mut self, ctx: &mut DrawCtx) {
1097            // Group hands each child a sub-context translated to the child's
1098            // origin, so the child fills in LOCAL coords (0,0)-(w,h).
1099            let b = self.1.get_bounds();
1100            let (w, h) = (b.b.x - b.a.x, b.b.y - b.a.y);
1101            ctx.fill(Rect::new(0, 0, w, h), self.0, ctx.style(Role::Normal));
1102        }
1103    }
1104
1105    fn render_buf(sp: &mut Splitter, w: u16, h: u16) -> crate::screen::Buffer {
1106        let theme = crate::theme::Theme::classic_blue();
1107        let mut buf = crate::screen::Buffer::new(w, h);
1108        let bounds = sp.state().get_bounds();
1109        let mut dc = DrawCtx::new(&mut buf, &theme, bounds, bounds.a);
1110        sp.draw(&mut dc);
1111        buf
1112    }
1113
1114    fn render(sp: &mut Splitter, w: u16, h: u16) -> String {
1115        let theme = Theme::classic_blue();
1116        let (backend, screen) = HeadlessBackend::new(w, h);
1117        let mut r = Renderer::new(Box::new(backend));
1118        r.render(|buf: &mut Buffer| {
1119            let bounds = sp.state().get_bounds();
1120            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
1121            sp.draw(&mut dc);
1122        });
1123        screen.snapshot()
1124    }
1125
1126    #[test]
1127    fn three_equal_columns_render() {
1128        let mut sp = Splitter::cols();
1129        sp.change_bounds(Rect::new(0, 0, 32, 4)); // 32 wide; 2 dividers => 30 content => 10/10/10
1130        sp.insert(Fill::boxed('A'), Constraints::flex());
1131        sp.insert(Fill::boxed('B'), Constraints::flex());
1132        sp.insert(Fill::boxed('C'), Constraints::flex());
1133        insta::assert_snapshot!(render(&mut sp, 32, 4));
1134    }
1135
1136    #[test]
1137    fn dividers_line_style() {
1138        let mut sp = Splitter::cols(); // default_style == Line
1139        sp.change_bounds(Rect::new(0, 0, 13, 3)); // 2 panes => 1 divider, 12 content => 6/6
1140        sp.insert(Fill::boxed('A'), Constraints::flex());
1141        sp.insert(Fill::boxed('B'), Constraints::flex());
1142        insta::assert_snapshot!(render(&mut sp, 13, 3)); // AAAAAA│BBBBBB ×3 rows
1143    }
1144
1145    #[test]
1146    fn dividers_hidden_style_is_seamless() {
1147        let mut sp = Splitter::cols();
1148        sp.default_style = DividerStyle::Hidden;
1149        sp.change_bounds(Rect::new(0, 0, 13, 3));
1150        sp.insert(Fill::boxed('A'), Constraints::flex());
1151        sp.insert(Fill::boxed('B'), Constraints::flex());
1152        insta::assert_snapshot!(render(&mut sp, 13, 3)); // AAAAAA BBBBBB (blank gap)
1153    }
1154
1155    #[test]
1156    fn dividers_rows_orientation() {
1157        let mut sp = Splitter::rows();
1158        sp.change_bounds(Rect::new(0, 0, 6, 7)); // 2 panes => 1 divider, 6 content rows => 3/3
1159        sp.insert(Fill::boxed('A'), Constraints::flex());
1160        sp.insert(Fill::boxed('B'), Constraints::flex());
1161        insta::assert_snapshot!(render(&mut sp, 6, 7)); // AAA rows, ────── divider row, BBB rows
1162    }
1163
1164    #[test]
1165    fn builder_builds_same_layout_as_imperative() {
1166        let mut imperative = Splitter::cols();
1167        imperative.change_bounds(Rect::new(0, 0, 13, 2));
1168        imperative.insert(Fill::boxed('A'), Constraints::flex());
1169        imperative.insert(Fill::boxed('B'), Constraints::flex());
1170
1171        let mut built = Splitter::cols()
1172            .pane(Fill::boxed('A'), Constraints::flex())
1173            .pane(Fill::boxed('B'), Constraints::flex());
1174        built.change_bounds(Rect::new(0, 0, 13, 2));
1175
1176        assert_eq!(render(&mut imperative, 13, 2), render(&mut built, 13, 2));
1177    }
1178
1179    #[test]
1180    fn per_divider_override_renders() {
1181        let mut sp = Splitter::cols()
1182            .default_divider(DividerStyle::Hidden)
1183            .pane(Fill::boxed('A'), Constraints::flex())
1184            .pane(Fill::boxed('B'), Constraints::flex())
1185            .pane(Fill::boxed('C'), Constraints::flex())
1186            .divider(1, DividerStyle::Line); // seam after pane 1 (B|C) visible; others hidden
1187        sp.change_bounds(Rect::new(0, 0, 14, 1)); // 3 panes, 2 dividers, 12 content => 4/4/4
1188        insta::assert_snapshot!(render(&mut sp, 14, 1)); // AAAA BBBB│CCCC
1189    }
1190
1191    #[test]
1192    fn drag_repartitions_two_neighbors_sum_preserved() {
1193        let mut sp = Splitter::cols();
1194        sp.change_bounds(Rect::new(0, 0, 31, 1)); // 3 panes, 2 dividers, 29 content
1195        sp.insert(Fill::boxed('A'), Constraints::flex());
1196        sp.insert(Fill::boxed('B'), Constraints::flex());
1197        sp.insert(Fill::boxed('C'), Constraints::flex());
1198        let w_before_c = sp.slots[2].weight;
1199        let pair_before = sp.slots[0].weight + sp.slots[1].weight;
1200        let d0 = sp.divider_axis_pos(0).unwrap();
1201        sp.drag_divider_to(0, d0 + 3);
1202        assert!(
1203            (sp.slots[2].weight - w_before_c).abs() < 1e-9,
1204            "pane C weight untouched (locality)"
1205        );
1206        assert!(
1207            (sp.slots[0].weight + sp.slots[1].weight - pair_before).abs() < 1e-9,
1208            "pair sum preserved"
1209        );
1210        let sizes = super::layout::solve(&sp.slots, sp.content_len());
1211        assert!(sizes[0] > sizes[1], "pane 0 grew, pane 1 shrank");
1212    }
1213
1214    #[test]
1215    fn drag_against_fixed_neighbor_is_a_wall() {
1216        let mut sp = Splitter::cols();
1217        sp.change_bounds(Rect::new(0, 0, 31, 1));
1218        sp.insert(Fill::boxed('A'), Constraints::fixed(10)); // pinned
1219        sp.insert(Fill::boxed('B'), Constraints::flex());
1220        let before = super::layout::solve(&sp.slots, sp.content_len());
1221        let d0 = sp.divider_axis_pos(0).unwrap();
1222        sp.drag_divider_to(0, d0 + 5); // try to grow the fixed pane
1223        let after = super::layout::solve(&sp.slots, sp.content_len());
1224        assert_eq!(
1225            before, after,
1226            "fixed pane is immovable — divider does not move"
1227        );
1228    }
1229
1230    #[test]
1231    fn relax_does_not_move_dividers() {
1232        let mut sp = Splitter::cols();
1233        sp.change_bounds(Rect::new(0, 0, 41, 1)); // 3 panes, 2 dividers, 39 content
1234        let a = sp.insert(Fill::boxed('A'), Constraints::fixed(12));
1235        sp.insert(Fill::boxed('B'), Constraints::flex());
1236        sp.insert(Fill::boxed('C'), Constraints::flex());
1237        let before = solve(&sp.slots, sp.content_len());
1238        sp.relax(a);
1239        let after = solve(&sp.slots, sp.content_len());
1240        assert_eq!(before, after, "relax keeps every pane the same size");
1241        assert!(
1242            sp.slots[0].min != sp.slots[0].max,
1243            "pane A is now draggable (not fixed)"
1244        );
1245    }
1246
1247    #[test]
1248    fn remove_pane_resolves_remaining() {
1249        let mut sp = Splitter::cols();
1250        sp.change_bounds(Rect::new(0, 0, 21, 1)); // after remove: 2 panes, 1 divider, 20 content
1251        let a = sp.insert(Fill::boxed('A'), Constraints::flex());
1252        sp.insert(Fill::boxed('B'), Constraints::flex());
1253        sp.insert(Fill::boxed('C'), Constraints::flex());
1254        assert!(sp.remove(a));
1255        let sizes = solve(&sp.slots, sp.content_len());
1256        assert_eq!(sizes.len(), 2);
1257        assert_eq!(sizes.iter().sum::<i32>(), sp.content_len());
1258    }
1259
1260    #[test]
1261    fn frame_marks_two_pane_cols_abut_top_and_bottom() {
1262        use crate::junction::{Edge, Weight};
1263        let frame_bounds = Rect::new(0, 0, 13, 5);
1264        let mut sp = Splitter::cols();
1265        sp.set_joined(true);
1266        sp.change_bounds(Rect::new(1, 1, 12, 4));
1267        sp.insert(Fill::boxed('A'), Constraints::flex());
1268        sp.insert(Fill::boxed('B'), Constraints::flex());
1269        let marks = sp.frame_junction_marks(frame_bounds);
1270        assert_eq!(marks.len(), 2, "one top + one bottom mark");
1271        assert!(marks.contains(&crate::junction::JunctionMark {
1272            edge: Edge::Top,
1273            offset: 6,
1274            stem: Weight::Single
1275        }));
1276        assert!(marks.contains(&crate::junction::JunctionMark {
1277            edge: Edge::Bottom,
1278            offset: 6,
1279            stem: Weight::Single
1280        }));
1281    }
1282
1283    #[test]
1284    fn frame_marks_handle_divider_emits_nothing() {
1285        let frame_bounds = Rect::new(0, 0, 13, 5);
1286        let mut sp = Splitter::cols()
1287            .default_divider(DividerStyle::Handle)
1288            .joined();
1289        sp.change_bounds(Rect::new(1, 1, 12, 4));
1290        sp.insert(Fill::boxed('A'), Constraints::flex());
1291        sp.insert(Fill::boxed('B'), Constraints::flex());
1292        // Joined, but a Handle divider draws no full line, so it abuts nothing.
1293        assert!(sp.frame_junction_marks(frame_bounds).is_empty());
1294    }
1295
1296    #[test]
1297    fn frame_marks_inset_splitter_emits_nothing() {
1298        let frame_bounds = Rect::new(0, 0, 13, 7);
1299        let mut sp = Splitter::cols().joined();
1300        sp.change_bounds(Rect::new(2, 2, 11, 5)); // not adjacent to any frame edge
1301        sp.insert(Fill::boxed('A'), Constraints::flex());
1302        sp.insert(Fill::boxed('B'), Constraints::flex());
1303        // Joined, but the splitter is inset from every frame edge, so no abutment.
1304        assert!(sp.frame_junction_marks(frame_bounds).is_empty());
1305    }
1306
1307    #[test]
1308    fn frame_marks_empty_when_not_joined() {
1309        let frame_bounds = Rect::new(0, 0, 13, 5);
1310        let mut sp = Splitter::cols(); // NOT joined
1311        sp.change_bounds(Rect::new(1, 1, 12, 4));
1312        sp.insert(Fill::boxed('A'), Constraints::flex());
1313        sp.insert(Fill::boxed('B'), Constraints::flex());
1314        assert!(
1315            sp.frame_junction_marks(frame_bounds).is_empty(),
1316            "no marks unless joined"
1317        );
1318    }
1319
1320    #[test]
1321    fn frame_marks_nested_grid_inner_divider_hits_right_frame() {
1322        use crate::junction::Edge;
1323        let frame_bounds = Rect::new(0, 0, 22, 7);
1324        let inner = Splitter::rows()
1325            .pane(Fill::boxed('L'), Constraints::flex())
1326            .pane(Fill::boxed('F'), Constraints::flex());
1327        let mut outer = Splitter::cols();
1328        outer.set_joined(true); // OUTER only — propagation joins the inner sub-splitter
1329        outer.change_bounds(Rect::new(1, 1, 21, 6));
1330        outer.insert(Fill::boxed('T'), Constraints::fixed(8));
1331        outer.insert(Box::new(inner), Constraints::flex());
1332        let marks = outer.frame_junction_marks(frame_bounds);
1333        assert_eq!(
1334            marks.len(),
1335            3,
1336            "outer top+bottom + inner right, got {marks:?}"
1337        );
1338        assert!(
1339            marks.iter().any(|m| m.edge == Edge::Right && m.offset == 3),
1340            "inner horizontal divider abuts the right frame edge at offset 3, got {marks:?}"
1341        );
1342        assert_eq!(
1343            marks.iter().filter(|m| m.edge == Edge::Top).count(),
1344            1,
1345            "outer vertical divider abuts the top edge once"
1346        );
1347        assert!(
1348            !marks.iter().any(|m| m.edge == Edge::Left),
1349            "no spurious left mark, got {marks:?}"
1350        );
1351    }
1352
1353    #[test]
1354    fn interior_crossing_grid_renders_left_tee() {
1355        // `├` is Junction::TeeRight (vertical bar, branch pointing RIGHT into the
1356        // inner pane); "left tee" in the name refers to the glyph's open-left shape.
1357        // Outer cols: [tree(fixed 6) | inner-rows(flex)]. The inner rows splitter
1358        // has a horizontal divider; where it meets the outer vertical divider, the
1359        // outer divider cell must show ├ (a vertical line branching right into the
1360        // inner pane), not a plain │.
1361        let inner = Splitter::rows()
1362            .pane(Fill::boxed('L'), Constraints::flex())
1363            .pane(Fill::boxed('F'), Constraints::flex());
1364        let mut outer = Splitter::cols();
1365        outer.set_joined(true); // join the linework so the crossing tee renders
1366        outer.change_bounds(Rect::new(0, 0, 20, 7));
1367        outer.insert(Fill::boxed('T'), Constraints::fixed(6));
1368        outer.insert(Box::new(inner), Constraints::flex());
1369        insta::assert_snapshot!(render(&mut outer, 20, 7));
1370    }
1371
1372    #[test]
1373    fn interior_crossings_absent_when_not_joined() {
1374        // Same grid as interior_crossing_grid_renders_left_tee but NOT joined:
1375        // the outer divider column stays plain │ (no ├).
1376        let inner = Splitter::rows()
1377            .pane(Fill::boxed('L'), Constraints::flex())
1378            .pane(Fill::boxed('F'), Constraints::flex());
1379        let mut outer = Splitter::cols(); // NOT joined
1380        outer.change_bounds(Rect::new(0, 0, 20, 7));
1381        outer.insert(Fill::boxed('T'), Constraints::fixed(6));
1382        outer.insert(Box::new(inner), Constraints::flex());
1383        let out = render(&mut outer, 20, 7);
1384        assert!(!out.contains('├'), "no interior tee unless joined:\n{out}");
1385    }
1386
1387    #[test]
1388    fn inset_splitter_panes_fill_from_origin() {
1389        // Regression: an inset splitter (non-zero origin) must lay its panes out in
1390        // 0-based local space, so pane content begins exactly at the splitter's
1391        // origin column — NOT shifted right by the origin. Before the fix, pane A
1392        // started at column 4 (origin.x + 1), leaving column 3 blank.
1393        let mut sp = Splitter::cols();
1394        sp.change_bounds(Rect::new(3, 2, 16, 5)); // origin (3,2), width 13, height 3
1395        sp.insert(Fill::boxed('A'), Constraints::flex());
1396        sp.insert(Fill::boxed('B'), Constraints::flex());
1397        let buf = render_buf(&mut sp, 16, 5);
1398        // First pane content fills from the splitter's own origin column (3),
1399        // on a middle content row (y=3, inside [2,5)).
1400        assert_eq!(
1401            buf.get(3, 3).symbol(),
1402            "A",
1403            "pane A must start at the splitter origin column, not be shifted by it"
1404        );
1405        // And there is no blank gap immediately inside the origin.
1406        assert_ne!(
1407            buf.get(3, 3).symbol(),
1408            " ",
1409            "no blank column at the splitter origin"
1410        );
1411    }
1412
1413    #[test]
1414    fn splitter_downcasts_through_as_any_mut() {
1415        let mut sp = Splitter::cols();
1416        sp.change_bounds(Rect::new(0, 0, 13, 3));
1417        sp.insert(Fill::boxed('A'), Constraints::flex());
1418        sp.insert(Fill::boxed('B'), Constraints::flex());
1419        let resolved = (&mut sp as &mut dyn View)
1420            .as_any_mut()
1421            .and_then(|a| a.downcast_mut::<Splitter>())
1422            .is_some();
1423        assert!(resolved, "Splitter must override as_any_mut → Some(self)");
1424    }
1425}