fix(tui): tui split no longer hangs with many 1fr children (#19566)

## Description

A `tui split` with 30 or more `1fr` children can hang, because ratatui's
layout solver may not finish with that many `Fill` constraints. At 40,
none of 10 runs did.

Up to 16 `Fill` children, ratatui solves the split as before, so
ordinary splits don't change. Past 16, the solver gets the `Fill`
children as one `Fill` of their summed weight, and `pin_fills` in
`layout.rs` then gives each child its share of that space as a `Length`.
With `Length` and `max:N` siblings, those are the widths ratatui's own
solve gives. With an `N%` sibling a child can be one cell off. With a
`min:N` sibling, the `Fill` children and the `min:N` one can be up to
two cells off. Drawing, mouse drags and the arrow-key resize all go
through the new `SplitDir::split`.

## User-facing changes (Release notes)

Fixed `tui split` hanging when it has 30 or more `1fr` children.

## Additional notes
This commit is contained in:
Darren Schroeder
2026-11-16 08:54:01 -06:00
committed by GitHub
parent 4e0328f49f
commit cee5b7df4c
3 changed files with 231 additions and 9 deletions
+173 -1
View File
@@ -275,7 +275,7 @@ fn layout_split(
// A split of fixed-height leaves (a button row, a form line) is not
// resizable: no gap and no handle between its children.
let fixed = fixed_height(w).is_some();
let (segments, spacers) = direction.layout(sizes, !fixed).split_with_spacers(area);
let (segments, spacers) = direction.split(sizes, !fixed, area);
for (child, rect) in w.children.iter().zip(segments.iter()) {
assign_node(ctx, child, *rect);
}
@@ -302,6 +302,97 @@ fn layout_split(
}
}
/// How many `Fill` constraints [`pin_fills`] leaves to ratatui's solver.
/// kasuari, the solver, picks pivots in hash order with no rule against
/// cycling, and the more `Fill`s it gets, the likelier a solve never ends:
/// at 40 equal ones, none of 10 release-build runs finished within 5 s,
/// while at 28 all 40 runs finished within 60 ms. 16 is a margin below 28,
/// not a guarantee: in an area too narrow for the other constraints, the
/// solver can stall with fewer `Fill`s.
const MAX_SOLVER_FILLS: usize = 16;
/// `constraints` ready for ratatui's solver on a line of `length` cells,
/// `spacing` cells apart, under the default `Flex::Start`.
///
/// Up to [`MAX_SOLVER_FILLS`] `Fill`s come back as they are. Past it, each
/// `Fill` becomes a `Length` of its share of the cells the solver gives all
/// of them as one `Fill`. Beside `Length` and `Max` constraints those are
/// the cells the solver would give each `Fill`. Beside a `Percentage` a
/// `Fill` can be a cell off, and beside a `Min` the `Fill`s and the `Min`
/// can be up to two cells off.
pub fn pin_fills(constraints: Vec<Constraint>, spacing: u16, length: u16) -> Vec<Constraint> {
pin_fills_past(MAX_SOLVER_FILLS, constraints, spacing, length)
}
/// [`pin_fills`] past `max_fills` `Fill`s; tests lower it to compare the
/// pinned cells with the solver's own.
fn pin_fills_past(
max_fills: usize,
constraints: Vec<Constraint>,
spacing: u16,
length: u16,
) -> Vec<Constraint> {
let weight = |c: &Constraint| match c {
Constraint::Fill(w) => Some(u64::from(*w)),
_ => None,
};
let fills = constraints.iter().filter_map(weight).count();
let Some(last) = constraints
.iter()
.rposition(|c| weight(c).is_some())
.filter(|_| fills > max_fills)
else {
return constraints;
};
let total: u64 = constraints.iter().filter_map(weight).sum();
// First pass: the `Fill`s as one, in the last one's place. It weighs
// their sum because under `Flex::Start` a `Min` shares space with the
// `Fill`s by weight.
let group = Constraint::Fill(u16::try_from(total).unwrap_or(u16::MAX));
let merged = constraints
.iter()
.enumerate()
.filter_map(|(i, &c)| match c {
Constraint::Fill(_) => (i == last).then_some(group),
other => Some(other),
});
let segments = Layout::horizontal(merged)
.spacing(spacing)
.split(Rect::new(0, 0, length, 1));
let index = constraints[..last]
.iter()
.filter(|c| weight(c).is_none())
.count();
// The second pass also puts a spacer between the `Fill`s.
let spacers = u16::try_from(fills - 1)
.unwrap_or(u16::MAX)
.saturating_mul(spacing);
let cells = segments
.get(index)
.map_or(0, |rect| rect.width.saturating_sub(spacers));
let cells = u64::from(cells);
// Second pass: each `Fill` pinned to its share. As in the solver, a
// `0fr` gets nothing beside weighted `Fill`s, and `0fr`s alone share
// evenly. Rounding the running total, as the solver rounds edges, keeps
// the sum exact.
let parts = if total == 0 { fills as u64 } else { total };
let mut done = 0;
let mut start = 0;
constraints
.into_iter()
.map(|c| {
let Some(w) = weight(&c) else {
return c;
};
done += if total == 0 { 1 } else { w };
let end = (2 * cells * done + parts) / (2 * parts);
let share = end - start;
start = end;
Constraint::Length(u16::try_from(share).unwrap_or(u16::MAX))
})
.collect()
}
/// Ids in the subtree of `root`, preorder. Used to scope searches and to
/// find the nearest row source for a preview.
pub fn subtree_ids(app: &TuiApp, path: &[usize]) -> Vec<String> {
@@ -318,3 +409,84 @@ fn push_ids(w: &Widget, out: &mut Vec<String>) {
push_ids(c, out);
}
}
#[cfg(test)]
mod tests {
use super::*;
use Constraint::{Fill, Length, Max};
#[test]
fn many_fills_reach_the_solver_as_lengths() {
// 40 `1fr` a cell apart in 400 cells: 361 cells, 9.025 each. The
// running total rounds up at the 20th.
let mut want = vec![Length(9); 40];
want[19] = Length(10);
assert_eq!(pin_fills(vec![Fill(1); 40], 1, 400), want);
// Up to the limit the solver gets them as they are.
let fills = vec![Fill(1); MAX_SOLVER_FILLS];
assert_eq!(pin_fills(fills.clone(), 1, 400), fills);
}
#[test]
fn fill_group_weighs_against_a_min() {
// Under `Flex::Start` a `Min` grows like a `1fr`: beside 17 `1fr` it
// gets 1/18 of 400 cells, as the solver gives it beside 17 `Fill`s.
let mut constraints = vec![Fill(1); 17];
constraints.push(Constraint::Min(5));
let pinned = pin_fills(constraints, 0, 400);
let cells: u16 = pinned
.iter()
.map(|c| match c {
Length(n) => *n,
_ => 0,
})
.sum();
assert_eq!(cells, 378, "{pinned:?}");
}
#[test]
fn pinned_fills_get_the_solvers_cells() {
// Pinned even below the limit, the `Fill`s get the cells the solver
// gives them beside `Length` and `Max` siblings. Few `Fill`s on wide
// lines, and no `0fr`, so the solver always finishes.
let weights: [fn(usize) -> u16; 3] = [
|_| 1,
|i| if i % 2 == 0 { 1 } else { 2 },
|i| if i == 0 { 3 } else { 1 },
];
for (front, back) in [(None, None), (Some(Length(20)), None), (None, Some(Max(5)))] {
for weight in weights {
for n in 2..=5 {
let constraints: Vec<Constraint> = front
.into_iter()
.chain((0..n).map(|i| Fill(weight(i))))
.chain(back)
.collect();
for spacing in [0, 1] {
for length in [50, 79, 100, 201] {
let area = Rect::new(0, 0, length, 1);
let layout =
|c: Vec<Constraint>| Layout::horizontal(c).spacing(spacing);
let pinned = pin_fills_past(0, constraints.clone(), spacing, length);
assert_eq!(
layout(pinned).split_with_spacers(area),
layout(constraints.clone()).split_with_spacers(area),
"{constraints:?} on {length}, spacing {spacing}"
);
}
}
}
}
}
}
#[test]
fn zero_weight_fills_pin_like_the_solver() {
// Beside weighted `Fill`s a `0fr` gets nothing; `0fr`s alone share
// evenly.
let pinned = pin_fills_past(0, vec![Fill(0), Fill(1), Fill(1)], 0, 10);
assert_eq!(pinned, [Length(0), Length(5), Length(5)]);
let pinned = pin_fills_past(0, vec![Fill(0), Fill(0)], 0, 10);
assert_eq!(pinned, [Length(5), Length(5)]);
}
}
+47 -8
View File
@@ -1,11 +1,13 @@
//! `tui split`: children side by side or stacked, with draggable handles.
use crate::keys::KeyPress;
use crate::layout::pin_fills;
use crate::session::Session;
use crate::widget::{Caps, Effect, Size, SplitState, TuiWidget, WidgetState};
use nu_protocol::{Record, Span, Value};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use serde::{Deserialize, Serialize};
use std::rc::Rc;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum SplitDir {
@@ -23,21 +25,39 @@ impl SplitDir {
}
}
/// The ratatui layout for children of these sizes, with a one-cell
/// handle between each pair when the split is `resizable`. Drawing
/// and resizing both use it, so a resize is judged by the cells the
/// new size will really get.
pub fn layout(self, sizes: &[Size], resizable: bool) -> Layout {
/// Children of these sizes laid out in `area`, and the spacers around
/// them, with a one-cell handle between each pair when the split is
/// `resizable`. Drawing and resizing both use it, so a resize is judged
/// by the cells the new size will really get.
///
/// Many `Fill` children reach the solver pinned to their shares, see
/// [`pin_fills`].
pub fn split(self, sizes: &[Size], resizable: bool, area: Rect) -> (Rc<[Rect]>, Rc<[Rect]>) {
let constraints = sizes.iter().map(|s| s.to_constraint()).collect();
let constraints = pin_fills(constraints, u16::from(resizable), self.length(area));
self.layout(constraints, resizable).split_with_spacers(area)
}
/// The ratatui layout for `constraints` along this direction.
fn layout(self, constraints: impl IntoIterator<Item = Constraint>, resizable: bool) -> Layout {
let direction = match self {
SplitDir::Horizontal => Direction::Horizontal,
SplitDir::Vertical => Direction::Vertical,
};
Layout::default()
.direction(direction)
.constraints(sizes.iter().map(|s| s.to_constraint()))
.constraints(constraints)
.spacing(u16::from(resizable))
}
/// The cells `rect` covers along this direction.
fn length(self, rect: Rect) -> u16 {
match self {
SplitDir::Horizontal => rect.width,
SplitDir::Vertical => rect.height,
}
}
/// Where `rect` ends along this direction: the column after it, or
/// the row below it for `--vertical`.
fn end(self, rect: Rect) -> u16 {
@@ -95,7 +115,7 @@ impl SplitWidget {
};
// Measure from the sizes rather than the last drawn frame: several
// presses can arrive before the next one.
let segments = self.direction.layout(&state.sizes, true).split(area);
let (segments, _) = self.direction.split(&state.sizes, true, area);
let Some(current) = segments.first().map(|&rect| self.direction.end(rect)) else {
return;
};
@@ -134,7 +154,7 @@ fn move_edge(
let reachable: Vec<(u16, u16)> = (MIN_PERCENT..=MAX_PERCENT)
.filter_map(|percent| {
trial[index] = Size::Percent(percent);
let segments = direction.layout(&trial, true).split(area);
let (segments, _) = direction.split(&trial, true, area);
let edge = direction.end(*segments.get(index)?);
segments
.iter()
@@ -287,4 +307,23 @@ mod tests {
);
assert!(parse_size(&Value::test_string("wide")).is_err());
}
#[test]
fn many_fill_children_share_the_split_by_weight() {
// Past the limit in `pin_fills`: the 39 `Fill` children share 341 cells
// (400, less 20, less 39 handles) by weight, 2 of 40 for the `2fr`
// child.
let mut sizes = vec![Size::Length(20), Size::Fill(2)];
sizes.resize(40, Size::Fill(1));
let area = Rect::new(0, 0, 400, 10);
let (segments, _) = SplitDir::Horizontal.split(&sizes, true, area);
let widths: Vec<u16> = segments.iter().map(|rect| rect.width).collect();
assert_eq!(widths[..2], [20, 17]);
assert!(
widths[2..].iter().all(|w| (8..=9).contains(w)),
"{widths:?}"
);
assert_eq!(widths.iter().sum::<u16>(), 400 - 39);
assert_eq!(segments.last().map(|rect| rect.right()), Some(400));
}
}
+11
View File
@@ -676,6 +676,17 @@ fn split_sizes_take_cells_percent_and_fractions() -> Result {
Ok(())
}
/// Forty `1fr` children once left ratatui's solver looping forever.
#[test]
fn split_of_many_children_lays_out() -> Result {
let widths: Vec<i64> = test().run(
"tui split (0..<40 | each { [a] | tui table }) | tui debug --size [400 8] | get widgets.0.children.rect.width",
)?;
assert_eq!(widths.len(), 40);
assert_eq!(widths.iter().sum::<i64>(), 400 - 39, "{widths:?}");
Ok(())
}
#[test]
fn tree_expands_nested_record() -> Result {
let screen: String = test().run(