Add vertical layouts to custom status lines (#63752)

## What changed

Add a `col` element that stacks children vertically with a required `gap` measured in blank terminal rows. Rows and columns can nest, and a column inside styled text starts a new block while inheriting the surrounding style.

In both `row` and `col`, adjacent strings form one layout item. Null children and standalone whitespace are skipped, while explicit empty elements still count when spacing items.

## Testing

Add renderer tests for nested layouts, wrapping, viewport clipping, and spacing around empty elements. Extend the TypeScript contract checks to cover `ColElement` and its required `gap`.

GitOrigin-RevId: cca7d0057582de001bd8f5008fe949a05d7ebe22
This commit is contained in:
Joe Savona
2026-11-24 21:58:29 +00:00
committed by copyberry
parent d18dddd984
commit 38e42cdb21
9 changed files with 283 additions and 26 deletions
@@ -14,6 +14,13 @@ export type ApprovalPolicy = "untrusted" | "on-request" | "granular" | "never";
export type ApprovalReviewer = "user" | "auto-review";
export type ColProps = {
/**
* Blank terminal rows between flex items, as a non-negative JavaScript-safe integer.
* Adjacent strings form one item. Separate elements each take a slot, even when empty.
*/
gap: number, };
export type Color = "primary" | "surface" | "accent" | "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | StatusColor | HexRgb;
export type Config = { statusline_items: StatuslineItemId[], profile?: string, };
@@ -24,7 +31,7 @@ export type Cost = { total_cost_usd?: number, total_credits?: number, };
export type DisplayMode = "standard" | "raw";
export type Element = { "type": "text", props?: TextProps, children: Array<Element | null>, } | { "type": "link", props: LinkProps, children: Array<Element | null>, } | { "type": "row", props: RowProps, children: Array<Element | null>, } | { "type": "bold", children: Array<Element | null>, } | { "type": "italic", children: Array<Element | null>, } | { "type": "underline", children: Array<Element | null>, } | string;
export type Element = { "type": "text", props?: TextProps, children: Array<Element | null>, } | { "type": "link", props: LinkProps, children: Array<Element | null>, } | { "type": "row", props: RowProps, children: Array<Element | null>, } | { "type": "col", props: ColProps, children: Array<Element | null>, } | { "type": "bold", children: Array<Element | null>, } | { "type": "italic", children: Array<Element | null>, } | { "type": "underline", children: Array<Element | null>, } | string;
export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" };
@@ -97,6 +104,7 @@ export type ItalicElement = Extract<Element, { type: "italic" }>;
export type UnderlineElement = Extract<Element, { type: "underline" }>;
export type LinkElement = Extract<Element, { type: "link" }>;
export type RowElement = Extract<Element, { type: "row" }>;
export type ColElement = Extract<Element, { type: "col" }>;
export type RateLimitWindow = {
/**
* Percentage of the allowance consumed during the window. Can exceed 100.
@@ -28,6 +28,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
"StatuslineState",
"UiTree",
"RowElement",
"ColElement",
"StatuslineItemId",
"Color",
] {
@@ -58,7 +59,7 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
"export type StatuslineItemId = {};",
items.join(" | ")
)?;
for name in ["Text", "Bold", "Italic", "Underline", "Link", "Row"] {
for name in ["Text", "Bold", "Italic", "Underline", "Link", "Row", "Col"] {
let tag = name.to_ascii_lowercase();
writeln!(
generated,
+15
View File
@@ -47,6 +47,10 @@ pub(crate) enum UiNode {
props: RowProps,
children: Vec<Option<UiNode>>,
},
Col {
props: ColProps,
children: Vec<Option<UiNode>>,
},
Bold {
children: Vec<Option<UiNode>>,
},
@@ -60,6 +64,17 @@ pub(crate) enum UiNode {
String(String),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) struct ColProps {
/// Blank terminal rows between flex items, as a non-negative JavaScript-safe integer.
/// Adjacent strings form one item. Separate elements each take a slot, even when empty.
#[serde(deserialize_with = "decode::gap")]
#[cfg_attr(test, ts(type = "number"))]
gap: u64,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))]
+2 -1
View File
@@ -41,7 +41,8 @@ impl std::str::FromStr for UiTree {
| UiNode::Italic { children }
| UiNode::Underline { children }
| UiNode::Link { children, .. }
| UiNode::Row { children, .. } => {
| UiNode::Row { children, .. }
| UiNode::Col { children, .. } => {
pending.extend(children.iter().flatten().map(|child| (child, depth + 1)));
}
}
+29 -1
View File
@@ -1,4 +1,4 @@
//! Lay out prepared text and nested rows within a terminal viewport.
//! Lay out prepared text, rows, and columns within a terminal viewport.
mod prepare;
mod text;
@@ -84,6 +84,8 @@ enum Fragment<'a> {
Gap(usize, &'a Paint),
/// The visible background of a flex item counts even on an otherwise blank line.
Background(usize, &'a Paint),
/// A vertical gap takes up a line without advancing the horizontal position.
BlankLine,
}
impl<'a> Fragment<'a> {
@@ -93,12 +95,14 @@ impl<'a> Fragment<'a> {
| Self::Padding(width, _)
| Self::Gap(width, _)
| Self::Background(width, _) => width,
Self::BlankLine => 0,
}
}
fn visit(self, limit: usize, mut draw: impl FnMut(usize, &str, usize, &'a Paint)) -> usize {
match self {
Self::Text(chunks, _) => visit_chunks(chunks, limit, draw),
Self::BlankLine => 0,
Self::Padding(width, paint)
| Self::Gap(width, paint)
| Self::Background(width, paint) => {
@@ -252,6 +256,26 @@ fn layout_node<'a>(
match &node.kind {
NodeKind::Empty => 0,
NodeKind::Text(text) => text.layout(width, limit, visit),
NodeKind::Col { children, gap } => {
let gap = (*gap).min(limit as u64) as usize;
let mut y = 0;
for (index, child) in children.iter().enumerate() {
if index > 0 {
let end = (y + gap).min(limit);
for row in y..end {
visit(row, Fragment::BlankLine);
}
y = end;
}
if y == limit {
break;
}
y += layout_node(child, width, limit - y, &mut |row, part| {
visit(y + row, part)
});
}
y
}
NodeKind::Row {
children,
props,
@@ -348,6 +372,10 @@ fn layout_band<'a>(
if y >= lines.len() {
lines.resize_with(y + 1, || (0, suppress_blank.then(Vec::new)));
}
if matches!(part, Fragment::BlankLine) {
visit(y, part);
return;
}
// Unpainted alignment and gaps alone do not make a blank line visible.
let (end, pending) = &mut lines[y];
if part.width() > 0
+67 -19
View File
@@ -1,4 +1,4 @@
//! Prepare inline content and measure each row child before viewport layout.
//! Prepare inline content and measure container children before viewport layout.
use super::text::InlineText;
use super::text::Paint;
@@ -28,6 +28,10 @@ pub(super) struct Widths {
#[derive(Debug, PartialEq)]
pub(super) enum NodeKind {
Text(PreparedText),
Col {
children: Vec<PreparedNode>,
gap: u64,
},
Row {
children: Vec<PreparedNode>,
props: RowProps,
@@ -36,16 +40,57 @@ pub(super) enum NodeKind {
Empty,
}
/// A column interrupts inline flow even when its contents have zero height.
#[derive(Default)]
struct Flow {
blocks: Vec<PreparedNode>,
line: Vec<PreparedNode>,
paint: Paint,
}
impl Flow {
fn take_line(&mut self) -> Option<PreparedNode> {
if self.line.len() <= 1 {
self.line.pop()
} else {
PreparedNode::row(
std::mem::take(&mut self.line),
RowProps::default(),
self.paint.clone(),
)
}
}
}
impl PreparedNode {
pub(super) fn from_node(node: UiNode, paint: Paint) -> Option<Self> {
let mut items = Vec::new();
let mut flow = Flow {
paint: paint.clone(),
..Flow::default()
};
let mut inline = InlineText::default();
Self::collect_inline(&mut items, &mut inline, node, paint.clone());
items.extend(Self::text(inline));
if items.len() <= 1 {
items.pop()
} else {
Self::row(items, RowProps::default(), paint)
Self::collect_inline(&mut flow, &mut inline, node, paint);
flow.line.extend(Self::text(inline));
let last = flow.take_line();
if flow.blocks.is_empty() {
return last;
}
flow.blocks.extend(last);
if flow.blocks.len() == 1 {
return flow.blocks.pop();
}
Some(Self::col(flow.blocks, /*gap*/ 0))
}
fn col(children: Vec<Self>, gap: u64) -> Self {
let mut widths = Widths::default();
for child in &children {
widths.minimum = widths.minimum.max(child.widths.minimum);
widths.preferred = widths.preferred.max(child.widths.preferred);
}
Self {
widths,
kind: NodeKind::Col { children, gap },
}
}
@@ -110,13 +155,13 @@ impl PreparedNode {
})
}
/// In flex layout, consecutive strings form one anonymous item.
/// In flex layout, consecutive strings form one anonymous item unless entirely whitespace.
fn flex_items(children: Vec<Option<UiNode>>, paint: &Paint) -> Vec<Self> {
let mut items = Vec::new();
let mut strings = InlineText::default();
for child in children.into_iter().flatten() {
match child {
UiNode::String(raw) => strings.push_leaf(raw, paint.clone()),
UiNode::String(raw) => strings.push_flex_leaf(raw, paint.clone()),
child => {
items.extend(Self::text(std::mem::take(&mut strings)));
// An explicit empty element still separates flex gaps.
@@ -133,19 +178,22 @@ impl PreparedNode {
items
}
fn collect_inline(
items: &mut Vec<Self>,
inline: &mut InlineText,
node: UiNode,
mut paint: Paint,
) {
fn collect_inline(flow: &mut Flow, inline: &mut InlineText, node: UiNode, mut paint: Paint) {
let children = match node {
UiNode::String(raw) => {
inline.push_leaf(raw, paint);
return;
}
UiNode::Col { props, children } => {
flow.line.extend(Self::text(std::mem::take(inline)));
let line = flow.take_line();
flow.blocks.extend(line);
let children = Self::flex_items(children, &paint);
flow.blocks.push(Self::col(children, props.gap));
return;
}
UiNode::Row { props, children } => {
items.extend(Self::text(std::mem::take(inline)));
flow.line.extend(Self::text(std::mem::take(inline)));
if let Some(color) = props.background {
paint.background = Some(color);
}
@@ -159,7 +207,7 @@ impl PreparedNode {
.filter_map(|node| Self::from_node(node, paint.clone()))
.collect()
};
items.extend(Self::row(children, props, paint));
flow.line.extend(Self::row(children, props, paint));
return;
}
UiNode::Text { props, children } => {
@@ -185,7 +233,7 @@ impl PreparedNode {
}
};
for node in children.into_iter().flatten() {
Self::collect_inline(items, inline, node, paint.clone());
Self::collect_inline(flow, inline, node, paint.clone());
}
}
+14 -1
View File
@@ -104,8 +104,21 @@ pub(super) struct InlineText {
}
impl InlineText {
/// Whitespace-only text nodes join an existing anonymous flex item but cannot start one.
pub(super) fn push_flex_leaf(&mut self, raw: String, paint: Paint) {
let raw = sanitize_leaf(raw);
if self.line.is_empty() && self.text.lines.is_empty() && raw.trim_ascii().is_empty() {
return;
}
self.push_sanitized(raw, paint);
}
pub(super) fn push_leaf(&mut self, raw: String, paint: Paint) {
let text = RunText::new(sanitize_leaf(raw));
self.push_sanitized(sanitize_leaf(raw), paint);
}
fn push_sanitized(&mut self, raw: String, paint: Paint) {
let text = RunText::new(raw);
let mut start = 0;
for (end, ch) in text
.match_indices([' ', '\t', '\n'])
+137 -2
View File
@@ -51,6 +51,7 @@ fn rejects_invalid_gaps_and_elements() {
r#"{"type":"text","children":[["Ready"]]}"#,
r#"{"type":"text","props":null,"children":[]}"#,
r#"{"type":"row","props":{},"children":[]}"#,
r#"{"type":"col","props":{},"children":[]}"#,
r#"{"type":"row","props":{"gap":0,"extra":true},"children":[]}"#,
r#"{"props":{"gap":0,"gap":1},"children":[],"type":"row"}"#,
] {
@@ -504,6 +505,135 @@ fn measures_viewport_sizes_in_cells() {
assert_eq!(painted_rows(&wide, Size::new(3, 1)), ["a…"]);
}
#[test]
fn col_stacks_rows_after_wrapping_and_skips_absent_children() {
let node = tree(json!({"type":"col","props":{"gap":1},"children":[
null, {"type":"row","props":{"gap":1,"wrap":"wrap"},"children":[{"type":"text","children":["model"]},{"type":"text","children":["main"]}]},
" ",
{"type":"row","props":{"gap":1},"children":[{"type":"text","children":["75%"]},{"type":"text","children":["1k"]}]}, null
]}));
let wide = Size::new(20, 4);
assert_eq!(node.measure(wide), Size::new(10, 3));
insta::assert_snapshot!(painted_rows(&node, wide).join("\n"), @r"
model main
75% 1k
");
assert_eq!(
painted_rows(&node, Size::new(7, 4)),
["model", "main", "", "75% 1k"]
);
let clipped = tree(
json!({"type":"col","props":{"gap":MAX_GAP},"children":[{"type":"text","children":["a"]},{"type":"text","children":["b"]}]}),
);
assert_eq!(painted_rows(&clipped, Size::new(5, 3)), ["a", "", "…"]);
}
#[test]
fn col_groups_bare_strings_and_counts_empty_elements_in_its_gaps() {
let node = tree(json!({"type":"col","props":{"gap":1},"children":[
{"type":"text","children":[]}, "L", null, "R",
{"type":"col","props":{"gap":0},"children":[]}, {"type":"text","children":["end"]}
]}));
let rows = painted_rows(&node, Size::new(10, 5));
let framed = rows
.iter()
.map(|row| format!("|{row}|"))
.collect::<Vec<_>>();
insta::assert_snapshot!(framed.join("\n"), @r"
||
|LR|
||
||
|end|
");
let nulls = tree(json!({"type":"col","props":{"gap":1},"children":[null," ",null]}));
assert_eq!(nulls.measure(Size::new(10, 4)), Size::default());
}
#[test]
fn col_skips_whitespace_only_anonymous_items_and_keeps_authored_breaks() {
let text = |s: &str| json!({"type":"text","children":[s]});
let bounds = Size::new(8, 6);
let col = |middle| {
tree(json!({"type":"col","props":{"gap":1},"children":[
text("a"), middle, text("b")
]}))
};
assert_eq!(painted_rows(&col(json!(" \t\n")), bounds), ["a", "", "b"]);
assert_eq!(painted_rows(&col(text("")), bounds), ["a", "", "", "b"]);
assert_eq!(
painted_rows(&col(text("\n")), bounds),
["a", "", "", "", "b"]
);
let stack = |children| {
let node = tree(json!({"type":"col","props":{"gap":0},"children":children}));
painted_rows(&node, bounds)
};
assert_eq!(stack(json!([text("a"), "\n", null, "b"])), ["a", "b"]);
assert_eq!(stack(json!([text("a"), "\nb"])), ["a", "", "b"]);
assert_eq!(stack(json!(["a", "\n", null, "b"])), ["a", "b"]);
}
#[test]
fn col_interrupts_inline_flow_even_when_empty() {
use ratatui::style::Modifier;
let surround = |children| {
tree(json!({"type":"text","children":[
"x ", {"type":"bold","children":[
{"type":"col","props":{"gap":0},"children":children}, "y"
]}, "z"
]}))
};
let area = Rect::new(0, 0, 8, 4);
let bounds = area.as_size();
let full = surround(json!([{"type":"text","children":["a"]},{"type":"text","children":["b"]}]));
assert_eq!(full.measure(bounds), Size::new(2, 4));
assert_eq!(painted_rows(&full, bounds), ["x", "a", "b", "yz"]);
let mut buf = Buffer::empty(area);
full.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
for y in 1..4 {
assert!(buf[(0, y)].modifier.contains(Modifier::BOLD));
}
assert!(buf[(1, 3)].modifier.is_empty());
let empty = surround(json!([null, ""]));
assert_eq!(painted_rows(&empty, bounds), ["x", "yz"]);
}
#[test]
fn wrapping_rows_reserve_a_gap_on_each_side_of_an_empty_column() {
for children in [
json!([]),
json!([null]),
json!([{"type":"text","children":[""]}]),
] {
let node = tree(
json!({"type":"row","props":{"gap":1,"wrap":"wrap"},"children":[
"a", {"type":"col","props":{"gap":0},"children":children}, "b"
]}),
);
assert_eq!(painted_rows(&node, Size::new(3, 2)), ["a", "b"]);
assert_eq!(painted_rows(&node, Size::new(8, 2)), ["a b"]);
}
}
#[test]
fn col_inside_a_row_wraps_within_its_assigned_width() {
let node = tree(json!({"type":"row","props":{"gap":1},"children":[
">", {"type":"col","props":{"gap":0},"children":[{"type":"text","children":["ab c"]},{"type":"text","children":["xyz"]}]}, "!"
]}));
assert_eq!(
painted_rows(&node, Size::new(7, 3)),
["> ab !", " c", " xyz"]
);
let clipped = tree(json!({"type":"row","props":{"gap":1},"children":[
"abc", {"type":"col","props":{"gap":1},"children":[{"type":"text","children":["a"]},{"type":"text","children":["b"]}]}
]}));
assert_eq!(painted_rows(&clipped, Size::new(3, 3)), ["ab…", "", " …"]);
}
#[test]
fn whitespace_collapses_across_styled_leaves() {
let node = tree(json!({"type":"text","children":[
@@ -618,7 +748,12 @@ fn aligned_rows_pad_visible_content_and_keep_link_targets_on_their_text() {
let row = |child: Value| {
tree(json!({"type":"row","props":{"gap":0,"justify":justify},"children":[child]}))
};
assert_eq!(row(json!("\n")).measure(Size::new(5, 2)), Size::new(0, 1));
let size = Size::new(5, 2);
assert_eq!(row(json!("\n")).measure(size), Size::default());
assert_eq!(
row(json!({"type":"text","children":["\n"]})).measure(size),
Size::new(0, 1)
);
assert_eq!(
painted_rows(&row(json!("abcdef")), Size::new(3, 1)),
["ab…"]
@@ -685,7 +820,7 @@ fn start_and_between_keep_their_gaps_before_blank_children() {
for (first, expected) in [("\n", blank), ("A", visible)] {
let node = tree(
json!({"type":"row","props":{"gap":1,"justify":justify,"background":"red"},
"children":[first,{"type":"text","children":["\n"]}]}),
"children":[{"type":"text","children":[first]},{"type":"text","children":["\n"]}]}),
);
assert_eq!(node.measure(area.as_size()), Size::new(expected, 1));
let mut buf = Buffer::empty(area);
@@ -1,4 +1,5 @@
import type {
ColElement,
Color,
RowElement,
StatuslineItemId,
@@ -46,6 +47,13 @@ export function render(state: StatuslineState): UiTree {
const alias: StatuslineItemId = "project-root";
// @ts-expect-error Row props require a gap in terminal columns.
const missingGap: RowElement = { type: "row", props: {}, children: [] };
const twoLines: ColElement = {
type: "col",
props: { gap: 0 },
children: [{ type: "text", children: ["model main"] }, { type: "text", children: ["75%"] }],
};
// @ts-expect-error Column props require a gap in terminal rows.
const missingColGap: ColElement = { type: "col", props: {}, children: [] };
// @ts-expect-error Color literals begin with a hash or match one of the named tokens.
const invalidColor: Color = "ff00bb";