Add maxLines to statusline text blocks (#64007)

## Why

Long statusline text can wrap across enough lines to push fields below it out of view.

## What changed

Set `maxLines` to a positive safe integer to cap a text block after wrapping. If content exceeds the cap, the last visible line ends with an ellipsis when space permits. Long words can break at grapheme boundaries so a clamped block can shrink alongside other fields.

## Testing

Cover invalid limits, visibility of neighboring fields, and truncation that preserves whole graphemes and leaves the ellipsis outside hyperlinks.

GitOrigin-RevId: 42f57b3f92e81860f888b733ce6121bb94dc78c3
This commit is contained in:
Joe Savona
2026-11-25 22:50:04 +00:00
committed by copyberry
parent 7d0d2ac81a
commit b8498ada1c
8 changed files with 299 additions and 45 deletions
@@ -83,7 +83,12 @@ export type TextProps = { color?: Color | null, weight?: TextWeight | null, ital
/**
* Preserve spaces and tabs across styled children.
*/
preserveWhitespace?: boolean, };
preserveWhitespace?: boolean,
/**
* Clamp this text block after wrapping. Must be a positive safe integer.
* If support is unknown for app.cli_version, return a literal string for the entire tree.
*/
maxLines?: number, };
export type TextWeight = "normal" | "bold";
+10 -1
View File
@@ -16,7 +16,7 @@ mod tests;
use serde::Deserialize;
use serde::Serialize;
const MAX_GAP: u64 = (1 << 53) - 1;
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
const MAX_TEXT_BYTES: usize = 16 * 1024;
/// A nullable root. JSON is limited to 64 KiB, 256 non-null nodes, depth 16 (root at 0),
@@ -101,6 +101,15 @@ pub(crate) struct TextProps {
#[serde(rename = "preserveWhitespace", skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<bool>", optional))]
preserve_whitespace: bool,
/// Clamp this text block after wrapping. Must be a positive safe integer.
/// If support is unknown for app.cli_version, return a literal string for the entire tree.
#[serde(
rename = "maxLines",
deserialize_with = "decode::max_lines",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(test, ts(type = "number", optional))]
max_lines: Option<u64>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+10 -2
View File
@@ -1,6 +1,6 @@
//! Enforce the input byte limit before parsing and the UI tree limits after deserialization.
use super::MAX_GAP;
use super::MAX_SAFE_INTEGER;
use super::MAX_TEXT_BYTES;
use super::UiNode;
use super::UiTree;
@@ -71,9 +71,17 @@ pub(super) fn present_token<'de, D: Deserializer<'de>, T: DeserializeOwned>(
token(d).map(Some)
}
pub(super) fn max_lines<'de, D: Deserializer<'de>>(de: D) -> Result<Option<u64>, D::Error> {
let lines = u64::deserialize(de)?;
if !(1..=MAX_SAFE_INTEGER).contains(&lines) {
return Err(D::Error::custom("maxLines must be a positive safe integer"));
}
Ok(Some(lines))
}
pub(super) fn gap<'de, D: Deserializer<'de>>(de: D) -> Result<u64, D::Error> {
let gap = u64::deserialize(de)?;
if gap > MAX_GAP {
if gap > MAX_SAFE_INTEGER {
return Err(D::Error::custom("gap exceeds the maximum safe integer"));
}
Ok(gap)
+88 -22
View File
@@ -86,6 +86,7 @@ enum Fragment<'a> {
Background(usize, &'a Paint),
/// A vertical gap takes up a line without advancing the horizontal position.
BlankLine,
Ellipsis(&'a Paint),
}
impl<'a> Fragment<'a> {
@@ -96,11 +97,33 @@ impl<'a> Fragment<'a> {
| Self::Gap(width, _)
| Self::Background(width, _) => width,
Self::BlankLine => 0,
Self::Ellipsis(_) => 1,
}
}
fn prefix(self, limit: usize) -> Self {
if self.width() <= limit {
return self;
}
match self {
Self::Text(chunks, _) => Self::Text(chunks, self.visit(limit, |_, _, _, _| {})),
Self::Padding(_, paint) => Self::Padding(limit, paint),
Self::Gap(_, paint) => Self::Gap(limit, paint),
Self::Background(_, paint) => Self::Background(limit, paint),
Self::Ellipsis(_) | Self::BlankLine => Self::BlankLine,
}
}
fn visit(self, limit: usize, mut draw: impl FnMut(usize, &str, usize, &'a Paint)) -> usize {
match self {
Self::Ellipsis(paint) => {
if limit > 0 {
draw(0, "…", 1, paint);
1
} else {
0
}
}
Self::Text(chunks, width) => visit_chunks(chunks, limit.min(width), draw),
Self::BlankLine => 0,
Self::Padding(width, paint)
@@ -123,6 +146,7 @@ type Visit<'a, 'b> = dyn FnMut(usize, Fragment<'a>) + 'b;
/// Only the fragment that reaches the right edge must wait until overflow is known.
#[derive(Default)]
struct Row<'a> {
ends_in_marker: bool,
width: usize,
edge: Option<(usize, Fragment<'a>)>,
last_paint: Option<&'a Paint>,
@@ -156,27 +180,37 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
in_aligned_row: false,
fill_background: false,
};
let total = layout_visible(root, available, height, &mut |y, fragment| {
if rows.len() <= y {
rows.resize_with(y + 1, Row::default);
}
let row = &mut rows[y];
let start = row.width;
row.width += fragment.width();
if start < width {
if row.width >= width {
row.edge = Some((start, fragment));
} else if let Some(draw) = draw.as_deref_mut() {
fragment.visit(usize::MAX, |offset, text, cells, paint| {
draw(y, start + offset, text, cells, paint);
row.last_paint = Some(paint);
});
let total = layout_visible(
root,
available,
height,
/*marker*/ None,
&mut |y, fragment| {
if rows.len() <= y {
rows.resize_with(y + 1, Row::default);
}
}
});
let row = &mut rows[y];
let start = row.width;
row.width += fragment.width();
if fragment.width() > 0 {
row.ends_in_marker = matches!(fragment, Fragment::Ellipsis(_));
}
if start < width {
if row.width >= width {
row.edge = Some((start, fragment));
} else if let Some(draw) = draw.as_deref_mut() {
fragment.visit(usize::MAX, |offset, text, cells, paint| {
draw(y, start + offset, text, cells, paint);
row.last_paint = Some(paint);
});
}
}
},
);
let mut measured = Size::new(0, total.min(height) as u16);
for (y, row) in rows.into_iter().enumerate() {
let clipped = row.width > width || (y + 1 == height && total > height);
let clipped =
row.width > width || (y + 1 == height && total > height && !row.ends_in_marker);
let mut end = row.width;
let mut last_paint = row.last_paint;
if clipped && width == 1 {
@@ -213,6 +247,7 @@ fn layout_visible<'a>(
root: &'a PreparedNode,
width: AvailableWidth,
height: usize,
marker: Option<&'a Paint>,
visit: &mut Visit<'a, '_>,
) -> usize {
let mut tail = Vec::new();
@@ -224,23 +259,42 @@ fn layout_visible<'a>(
}
if y + 1 == height {
last_width += fragment.width();
if matches!(fragment, Fragment::Padding(..)) {
if matches!(fragment, Fragment::Padding(cells, _) if cells > 0) {
padding = Some(tail.len());
}
if padding.is_some() {
if marker.is_some() || padding.is_some() {
tail.push(fragment);
return;
}
}
visit(y, fragment);
});
if total > height
let marked = tail
.iter()
.rev()
.find(|f| f.width() > 0)
.is_some_and(|f| matches!(f, Fragment::Ellipsis(_)));
let clipped = total > height && (!marked || last_width > width.cells);
if clipped
&& last_width == width.cells
&& let Some(index) = padding
&& let Fragment::Padding(cells, _) = &mut tail[index]
{
*cells -= 1;
}
if let Some(marker) = marker.filter(|_| clipped && width.cells > 0) {
let mut remaining = width.cells - 1;
for fragment in tail {
let prefix = fragment.prefix(remaining);
visit(height - 1, prefix);
remaining -= prefix.width();
if prefix.width() < fragment.width() {
break;
}
}
visit(height - 1, Fragment::Ellipsis(marker));
return height;
}
for fragment in tail {
visit(height - 1, fragment);
}
@@ -255,6 +309,18 @@ fn layout_node<'a>(
) -> usize {
match &node.kind {
NodeKind::Empty => 0,
NodeKind::Clamped {
content,
max_lines,
marker,
} => {
if *max_lines >= limit as u64 {
layout_node(content, width, limit, visit)
} else {
let height = *max_lines as usize;
layout_visible(content, width, height, Some(marker), visit).min(height)
}
}
NodeKind::Text(text) => text.layout(width, limit, visit),
NodeKind::Col { children, gap } => {
let gap = (*gap).min(limit as u64) as usize;
@@ -472,7 +538,7 @@ pub(crate) fn sanitize_leaf(mut raw: String) -> String {
impl TextProps {
fn apply_to(&self, paint: &mut Paint) {
paint.preserve_whitespace |= self.preserve_whitespace;
paint.preserve_whitespace |= self.preserve_whitespace && self.max_lines.is_none();
if let Some(color) = self.color {
paint.foreground = Some(color);
}
+59 -5
View File
@@ -19,7 +19,7 @@ pub(super) struct PreparedNode {
pub(super) widths: Widths,
}
#[derive(Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Widths {
pub(super) minimum: u64,
pub(super) preferred: u64,
@@ -28,6 +28,11 @@ pub(super) struct Widths {
#[derive(Debug, PartialEq)]
pub(super) enum NodeKind {
Text(PreparedText),
Clamped {
content: Box<PreparedNode>,
max_lines: u64,
marker: Paint,
},
Col {
children: Vec<PreparedNode>,
gap: u64,
@@ -40,7 +45,7 @@ pub(super) enum NodeKind {
Empty,
}
/// A column interrupts inline flow even when its contents have zero height.
/// A block interrupts inline flow even when its contents have zero height.
#[derive(Default)]
struct Flow {
blocks: Vec<PreparedNode>,
@@ -49,6 +54,12 @@ struct Flow {
}
impl Flow {
fn finish_line(&mut self, inline: &mut InlineText) {
self.line.extend(PreparedNode::text(std::mem::take(inline)));
let line = self.take_line();
self.blocks.extend(line);
}
fn take_line(&mut self) -> Option<PreparedNode> {
if self.line.len() <= 1 {
self.line.pop()
@@ -82,6 +93,28 @@ impl PreparedNode {
Some(Self::col(flow.blocks, /*gap*/ 0))
}
// Emergency word breaks allow each chunk to fit independently. Flex rows
// retain the space required by their children and gaps.
fn breakable_minimum(&self) -> u64 {
match &self.kind {
NodeKind::Text(text) => text
.lines
.iter()
.flatten()
.map(super::text::Chunk::minimum_cells)
.max()
.unwrap_or_default() as u64,
NodeKind::Col { children, .. } => children
.iter()
.map(Self::breakable_minimum)
.max()
.unwrap_or_default(),
NodeKind::Clamped { .. } | NodeKind::Row { .. } | NodeKind::Empty => {
self.widths.minimum
}
}
}
fn col(children: Vec<Self>, gap: u64) -> Self {
let mut widths = Widths::default();
for child in &children {
@@ -201,9 +234,7 @@ impl PreparedNode {
children
}
UiNode::Col { props, children } => {
flow.line.extend(Self::text(std::mem::take(inline)));
let line = flow.take_line();
flow.blocks.extend(line);
flow.finish_line(inline);
let children = Self::flex_items(children, &paint);
flow.blocks.push(Self::col(children, props.gap));
return;
@@ -228,6 +259,29 @@ impl PreparedNode {
}
UiNode::Text { props, children } => {
props.apply_to(&mut paint);
if let Some(max_lines) = props.max_lines {
paint.break_long_words = true;
flow.finish_line(inline);
let node = UiNode::Text {
props: Default::default(),
children,
};
if let Some(content) = Self::from_node(node, paint.clone()) {
paint.href = None;
flow.blocks.push(Self {
widths: Widths {
minimum: content.breakable_minimum(),
preferred: content.widths.preferred,
},
kind: NodeKind::Clamped {
content: Box::new(content),
max_lines,
marker: paint,
},
});
}
return;
}
children
}
UiNode::Link { props, children } => {
+22 -12
View File
@@ -27,6 +27,7 @@ pub(super) struct Paint {
pub(super) href: Option<Arc<String>>,
pub(super) inline_code: bool,
pub(super) preserve_whitespace: bool,
pub(super) break_long_words: bool,
}
impl Paint {
@@ -327,19 +328,20 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
let mut offset = 0;
let mut previous: Option<char> = None;
let mut word_hyphen = false;
let mut previous_preserved = false;
let mut previous_break_words = false;
for run in runs {
let break_words = run.paint.preserve_whitespace || run.paint.break_long_words;
let mut start = 0;
for (i, grapheme) in run.text.grapheme_indices(true) {
let position = offset + i;
while breaks.next_if(|b| *b < position).is_some() {}
// Ordinary text uses textwrap’s word hyphens. In preserved text, Chromium also breaks
// Ordinary text uses textwrap’s word hyphens. In break-word text, Chromium also breaks
// at flag hyphens and keeps paths and shell operators within a word.
let first = grapheme.as_bytes()[0];
let can_break = match previous {
_ if i == 0 && run.break_before => true,
Some(prev)
if (previous_preserved || run.paint.preserve_whitespace)
if (previous_break_words || break_words)
&& prev.is_ascii_graphic()
&& first.is_ascii_graphic() =>
{
@@ -348,7 +350,7 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
Some('-') => word_hyphen && grapheme.starts_with(char::is_alphanumeric),
// A collapsed separator can wrap before the first preserved space.
Some(' ' | '\t')
if previous_preserved
if previous_break_words
|| (run.paint.preserve_whitespace && matches!(first, b' ' | b'\t')) =>
{
true
@@ -356,16 +358,16 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
Some('\u{ad}') => false,
_ => breaks.peek() == Some(&position),
};
// Preserve normal word breaks first. An overlong preserved word can also
// Preserve normal word breaks first. An overlong preserved or clamped word can also
// wrap at a grapheme boundary, as it does under overflow-wrap: break-word.
let preserved_boundary = position > 0
&& (run.paint.preserve_whitespace
|| (previous_preserved && !matches!(run.text, RunText::Space)));
if can_break || preserved_boundary {
let emergency_boundary = position > 0
&& (break_words || previous_break_words)
&& !matches!(run.text, RunText::Space);
if can_break || emergency_boundary {
// A break after a literal space or tab can precede a collapsed
// prose separator. Keep the separator on this chunk, so only
// the prose space disappears when the line wraps.
let end = if previous_preserved && matches!(run.text, RunText::Space) {
let end = if previous_break_words && matches!(run.text, RunText::Space) {
run.text.len()
} else {
i
@@ -385,13 +387,13 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
}
chunk.break_before = if !can_break {
BreakBefore::Emergency
} else if previous_preserved && word_hyphen && first.is_ascii_digit() {
} else if previous_break_words && word_hyphen && first.is_ascii_digit() {
BreakBefore::AfterHyphenBeforeDigit
} else {
BreakBefore::Preferred
};
}
previous_preserved = run.paint.preserve_whitespace;
previous_break_words = break_words;
for ch in grapheme.chars() {
word_hyphen = ch == '-' && previous.is_some_and(char::is_alphanumeric);
previous = Some(ch);
@@ -426,6 +428,14 @@ impl Chunk {
}
}
pub(super) fn minimum_cells(&self) -> usize {
if self.tab_paint().is_some() {
1
} else {
self.width_cells
}
}
pub(super) fn width_at(&self, column: usize) -> usize {
if self.tab_paint().is_some() {
TAB_SPACES.len() - column % TAB_SPACES.len()
+102 -2
View File
@@ -32,7 +32,12 @@ fn elements_round_trip_and_require_explicit_row_spacing() {
] {
assert!(parse(json!({"type":"link","props":{"href":href},"children":[]})).is_err());
}
for (gap, expected) in [(0, "AB"), (1, "A B"), (2, "A B"), (MAX_GAP, "A …")] {
for (gap, expected) in [
(0, "AB"),
(1, "A B"),
(2, "A B"),
(MAX_SAFE_INTEGER, "A …"),
] {
let row = tree(json!({"type":"row","props":{"gap":gap},"children":["A","B"]}));
assert_eq!(painted_rows(&row, Size::new(4, 1)), [expected]);
}
@@ -218,6 +223,69 @@ fn preserved_text_keeps_spacing_across_inline_styles_and_wraps() {
);
}
#[test]
fn clamping_text_reserves_space_for_following_fields() {
let node = tree(json!({"type":"col","props":{"gap":0},"children":[
{"type":"text","props":{"maxLines":2,"preserveWhitespace":true},"children":["aa bb cc dd ee"]},
"ok"
]}));
insta::assert_snapshot!(painted_rows(&node, Size::new(5, 3)).join("\n"), @"aa bb\ncc d…\nok");
assert_eq!(
painted_rows(&node, Size::new(8, 3)),
["aa bb cc", "dd ee", "ok"]
);
assert_eq!(painted_rows(&node, Size::new(5, 1)), ["aa b…"]);
assert_eq!(painted_rows(&node, Size::new(3, 2)), ["aa", "bb…"]);
let word = tree(json!({"type":"text","props":{"maxLines":2},"children":["123456789"]}));
assert_eq!(painted_rows(&word, Size::new(4, 3)), ["1234", "567…"]);
let job = tree(json!({"type":"text","props":{"maxLines":2},"children":["job-123"]}));
assert_eq!(painted_rows(&job, Size::new(3, 2)), ["job", "-1…"]);
for invalid in [
json!(0),
json!(-1),
json!(1.5),
json!(null),
json!(9007199254740992u64),
] {
assert!(parse(json!({"type":"text","props":{"maxLines":invalid},"children":[]})).is_err());
}
}
#[test]
fn viewport_overflow_cannot_reclaim_padding_already_used_by_a_clamp() {
let node = tree(json!({"type":"col","props":{"gap":0},"children":[
{"type":"row","props":{"gap":0},"children":[
{"type":"text","props":{"maxLines":1},"children":[
{"type":"row","props":{"gap":1,"justify":"end","wrap":"wrap"},"children":[
{"type":"text","children":["X"]}, {"type":"text","children":["Y"]}
]}
]},
"B"
]},
"C"
]}));
assert_eq!(painted_rows(&node, Size::new(3, 1)), ["X……"]);
assert_eq!(painted_rows(&node, Size::new(3, 2)), ["X…B", "C"]);
assert_eq!(painted_rows(&node, Size::new(4, 2)), ["X YB", "C"]);
}
#[test]
fn clamped_link_keeps_whole_graphemes_and_an_unlinked_marker() {
let href = "https://example.com/";
let node = tree(json!({"type":"link","props":{"href":href},"children":[
{"type":"text","props":{"maxLines":1},"children":["a界\nb"]}
]}));
let bounds = Size::new(3, 3);
assert_eq!(node.measure(bounds), Size::new(2, 1));
assert_eq!(
painted_rows(&node, bounds),
[format!(
"{}…",
crate::terminal_hyperlinks::osc8_hyperlink(href, "a")
)]
);
}
#[test]
fn wrapped_code_keeps_a_leading_hyphen_with_the_hash() {
let bounds = Size::new(8, 3);
@@ -805,7 +873,7 @@ fn col_stacks_rows_after_wrapping_and_skips_absent_children() {
["model", "main", "", "75% 1k"]
);
let clipped = tree(
json!({"type":"col","props":{"gap":MAX_GAP},"children":[{"type":"text","children":["a"]},{"type":"text","children":["b"]}]}),
json!({"type":"col","props":{"gap":MAX_SAFE_INTEGER},"children":[{"type":"text","children":["a"]},{"type":"text","children":["b"]}]}),
);
assert_eq!(painted_rows(&clipped, Size::new(5, 3)), ["a", "", "…"]);
}
@@ -1351,6 +1419,38 @@ fn blank_nested_row_keeps_its_height_without_displacing_a_wide_sibling() {
}
}
#[test]
fn clamped_word_shrinks_to_keep_its_sibling_visible() {
let node = tree(json!({"type":"row","props":{"gap":1},"children":[
{"type":"text","props":{"maxLines":1},"children":["abcdefghij"]}, "!"
]}));
assert_eq!(painted_rows(&node, Size::new(8, 1)), ["abcde… !"]);
assert_eq!(painted_rows(&node, Size::new(3, 1)), ["… !"]);
assert_eq!(painted_rows(&node, Size::new(1, 1)), ["…"]);
}
#[test]
fn blank_clamp_keeps_its_sibling_end_aligned_without_a_marker() {
let node = tree(
json!({"type":"row","props":{"gap":0,"justify":"end"},"children":[
{"type":"text","props":{"maxLines":1},"children":["\n\n"]}, "ok"
]}),
);
assert_eq!(painted_rows(&node, Size::new(5, 1)), [" ok"]);
assert_eq!(painted_rows(&node, Size::new(2, 1)), ["ok"]);
}
#[test]
fn clamped_blank_text_keeps_its_height_in_a_zero_width_slot() {
let node = tree(json!({
"type": "row", "props": {"gap": 0}, "children": [
{"type": "text", "props": {"maxLines": 2}, "children": ["\n\n\n"]},
"A"
]
}));
assert_eq!(painted_rows(&node, Size::new(1, 3)), ["A", ""]);
}
#[test]
fn trailing_gap_keeps_the_aligned_glyph_at_the_viewport_edge() {
let node = tree(json!({
@@ -46,6 +46,8 @@ export function render(state: StatuslineState): UiTree {
const indented: UiTree = { type: "text", props: { preserveWhitespace: true }, children: [" ready"] };
const summary: UiTree = { type: "text", props: { maxLines: 2 }, children: ["build results"] };
const command: CodeElement = {
type: "code",
children: ["cargo ", null, { type: "bold", children: [" test"] }],