Add justification to custom statusline rows (#62569)

## Why

A fixed gap cannot keep two statusline groups at opposite edges as the terminal width changes.

## What changed

Set `justify: "between"` on a root `row` to distribute spare footer columns between its items on each line, in addition to the configured `gap`. Nested rows size to their content within the available width, so they can keep related fields together.

Use `justify: "start"` to pack items at the leading edge with the configured gap. Both explicit modes group adjacent bare strings into one item. Separate `text` or `row` elements can be positioned independently. Omitting `justify` preserves the existing gaps between authored children.

## Testing

Add renderer tests for edge alignment during resizing, spacing on wrapped lines, and root versus nested rows. Extend the row decoding tests and the TypeScript contract fixture to cover `justify`.

GitOrigin-RevId: 3319e688f3adfe6d35709ef279345f1db3eb9693
This commit is contained in:
Joe Savona
2026-11-19 18:53:03 +00:00
committed by copyberry
parent 0762dfa710
commit 99870c4f49
7 changed files with 227 additions and 56 deletions
@@ -46,11 +46,23 @@ export type Permissions = { display_name: string, profile_id?: string, } & ({ "t
export type RateLimitSnapshot = { limit_id: string, limit_name: string | null, primary_limit: RateLimitWindow | null, secondary_limit: RateLimitWindow | null, };
export type RowJustify = "start" | "between";
/**
* A root row receives the available footer width. A row inside another row takes up to its content width.
* An explicit `justify` groups adjacent bare strings into one item. Use separate `text` or `row`
* elements to position fields independently. Omitting `justify` keeps gaps between authored children.
*/
export type RowProps = {
/**
* Horizontal spacing in terminal columns, expressed as a non-negative JavaScript-safe integer.
*/
gap: number, background?: Color | null, wrap?: RowWrap, };
gap: number, background?: Color | null, wrap?: RowWrap,
/**
* `between` distributes spare columns between children on each line.
* `start` positions items at the leading edge with the requested gap.
*/
justify?: RowJustify, };
export type RowWrap = "nowrap" | "wrap";
+21
View File
@@ -118,6 +118,9 @@ impl TryFrom<&str> for LinkHref {
}
}
/// A root row receives the available footer width. A row inside another row takes up to its content width.
/// An explicit `justify` groups adjacent bare strings into one item. Use separate `text` or `row`
/// elements to position fields independently. Omitting `justify` keeps gaps between authored children.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))]
@@ -139,6 +142,15 @@ pub(crate) struct RowProps {
)]
#[cfg_attr(test, ts(as = "Option<RowWrap>", optional))]
wrap: RowWrap,
/// `between` distributes spare columns between children on each line.
/// `start` positions items at the leading edge with the requested gap.
#[serde(
default,
deserialize_with = "decode::present_token",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(test, ts(optional))]
justify: Option<RowJustify>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
@@ -150,6 +162,15 @@ enum RowWrap {
Wrap,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum RowJustify {
#[default]
Start,
Between,
}
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}
+7
View File
@@ -62,6 +62,13 @@ pub(super) fn token<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Res
T::deserialize(String::deserialize(d)?.into_deserializer())
}
// A present token must be a string. Serde defaults an omitted property to `None`.
pub(super) fn present_token<'de, D: Deserializer<'de>, T: DeserializeOwned>(
d: D,
) -> Result<Option<T>, D::Error> {
token(d).map(Some)
}
pub(super) fn gap<'de, D: Deserializer<'de>>(de: D) -> Result<u64, D::Error> {
let gap = u64::deserialize(de)?;
if gap > MAX_GAP {
+36 -24
View File
@@ -9,6 +9,7 @@ use self::text::Chunk;
use self::text::Paint;
use self::text::visit_chunks;
use super::MAX_TEXT_BYTES;
use super::RowJustify;
use super::RowWrap;
use super::TextProps;
use super::TextWeight;
@@ -186,28 +187,36 @@ fn layout_node<'a>(
visit: &mut Visit<'a, '_>,
) -> usize {
match &node.kind {
NodeKind::Empty => 0,
NodeKind::Text(text) => text.layout(width, limit, visit),
NodeKind::Row {
children,
gap,
wrap,
props,
paint,
} => {
let gap = (*gap).min((width + 1) as u64) as usize;
let gap = props.gap.min((width + 1) as u64) as usize;
let mut place_band = |children: &'a [PreparedNode], used, y| {
let spare = match props.justify.unwrap_or_default() {
RowJustify::Start => 0,
RowJustify::Between => width.saturating_sub(used),
};
layout_band(
children,
width,
limit - y,
gap,
spare,
paint,
&mut |row, part| visit(y + row, part),
)
};
let mut y = 0;
let mut start = 0;
let mut used = 0;
for (i, child) in children.iter().enumerate() {
let preferred = child.widths.preferred.min((width + 1) as u64) as usize;
if *wrap == RowWrap::Wrap && i > start && used + gap + preferred > width {
y += layout_band(
&children[start..i],
width,
limit - y,
gap,
paint,
&mut |row, part| visit(y + row, part),
);
if props.wrap == RowWrap::Wrap && i > start && used + gap + preferred > width {
y += place_band(&children[start..i], used, y);
if y == limit {
return y;
}
@@ -219,14 +228,7 @@ fn layout_node<'a>(
}
used += preferred;
}
y + layout_band(
&children[start..],
width,
limit - y,
gap,
paint,
&mut |row, part| visit(y + row, part),
)
y + place_band(&children[start..], used, y)
}
}
}
@@ -236,18 +238,23 @@ fn layout_band<'a>(
width: usize,
limit: usize,
gap: usize,
spare: usize,
paint: &'a Paint,
visit: &mut Visit<'a, '_>,
) -> usize {
let bounded = |cells: u64| cells.min((width + 1) as u64) as usize;
let gaps = children.len().saturating_sub(1);
// Round each item's cumulative share to the nearest cell, keeping both edges fixed.
let share = |i: usize| (i * spare + gaps / 2).checked_div(gaps).unwrap_or_default();
let mut reserved = children
.iter()
.map(|c| bounded(c.widths.minimum))
.sum::<usize>()
+ gap * children.len().saturating_sub(1);
+ gap * gaps
+ share(gaps);
let mut offset = 0usize;
let mut ends = Vec::new();
for child in children {
for (i, child) in children.iter().enumerate() {
let minimum = bounded(child.widths.minimum);
reserved -= minimum;
let available = bounded(child.widths.preferred)
@@ -268,8 +275,13 @@ fn layout_band<'a>(
*end += part.width();
}
});
offset += available + gap;
reserved = reserved.saturating_sub(gap);
let next_gap = if i < gaps {
gap + share(i + 1) - share(i)
} else {
0
};
offset += available + next_gap;
reserved = reserved.saturating_sub(next_gap);
}
ends.len()
}
+51 -24
View File
@@ -3,6 +3,7 @@
use super::text::InlineText;
use super::text::Paint;
use super::text::PreparedText;
use crate::ui_tree::RowProps;
use crate::ui_tree::RowWrap;
use crate::ui_tree::UiNode;
@@ -12,7 +13,7 @@ pub(super) struct PreparedNode {
pub(super) widths: Widths,
}
#[derive(Debug, PartialEq)]
#[derive(Debug, Default, PartialEq)]
pub(super) struct Widths {
pub(super) minimum: u64,
pub(super) preferred: u64,
@@ -23,10 +24,10 @@ pub(super) enum NodeKind {
Text(PreparedText),
Row {
children: Vec<PreparedNode>,
gap: u64,
wrap: RowWrap,
props: RowProps,
paint: Paint,
},
Empty,
}
impl PreparedNode {
@@ -38,7 +39,7 @@ impl PreparedNode {
if items.len() <= 1 {
items.pop()
} else {
Self::row(items, /*gap*/ 0, RowWrap::Nowrap, paint)
Self::row(items, RowProps::default(), paint)
}
}
@@ -47,10 +48,7 @@ impl PreparedNode {
if text.lines.is_empty() {
return None;
}
let mut widths = Widths {
minimum: 0,
preferred: 0,
};
let mut widths = Widths::default();
for line in &text.lines {
let mut width = 0;
for chunk in line {
@@ -66,20 +64,17 @@ impl PreparedNode {
})
}
fn row(mut children: Vec<Self>, gap: u64, wrap: RowWrap, paint: Paint) -> Option<Self> {
fn row(mut children: Vec<Self>, props: RowProps, paint: Paint) -> Option<Self> {
children.retain(|child| {
child.widths.preferred > 0
|| match &child.kind {
NodeKind::Row { .. } => true,
NodeKind::Text(text) => text.has_authored_break,
}
// An authored blank line occupies a row even when it paints no cells.
!child.is_empty()
});
if children.is_empty() {
return None;
}
let gaps = gap.saturating_mul(children.len() as u64 - 1);
let gaps = props.gap.saturating_mul(children.len() as u64 - 1);
let widths = Widths {
minimum: match wrap {
minimum: match props.wrap {
RowWrap::Nowrap => children
.iter()
.fold(gaps, |w, c| w.saturating_add(c.widths.minimum)),
@@ -97,13 +92,35 @@ impl PreparedNode {
widths,
kind: NodeKind::Row {
children,
gap,
wrap,
props,
paint,
},
})
}
/// In flex layout, consecutive strings form one anonymous item.
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()),
child => {
items.extend(Self::text(std::mem::take(&mut strings)));
// An explicit empty element still separates flex gaps.
items.push(
Self::from_node(child, paint.clone()).unwrap_or_else(|| Self {
kind: NodeKind::Empty,
widths: Widths::default(),
}),
);
}
}
}
items.extend(Self::text(strings));
items
}
fn collect_inline(
items: &mut Vec<Self>,
inline: &mut InlineText,
@@ -120,12 +137,17 @@ impl PreparedNode {
if let Some(color) = props.background {
paint.background = Some(color);
}
let children = children
.into_iter()
.flatten()
.filter_map(|node| Self::from_node(node, paint.clone()))
.collect();
items.extend(Self::row(children, props.gap, props.wrap, paint));
let children = if props.justify.is_some() {
Self::flex_items(children, &paint)
} else {
// Existing providers apply the gap to each authored child.
children
.into_iter()
.flatten()
.filter_map(|node| Self::from_node(node, paint.clone()))
.collect()
};
items.extend(Self::row(children, props, paint));
return;
}
UiNode::Text { props, children } => {
@@ -154,6 +176,11 @@ impl PreparedNode {
Self::collect_inline(items, inline, node, paint.clone());
}
}
fn is_empty(&self) -> bool {
self.widths.preferred == 0
&& matches!(&self.kind, NodeKind::Text(text) if !text.has_authored_break)
}
}
#[cfg(test)]
+94 -3
View File
@@ -517,7 +517,7 @@ fn whitespace_collapses_across_styled_leaves() {
}
#[test]
fn reads_row_wrap_without_moving_existing_positional_props() {
fn reads_row_layout_without_moving_existing_positional_props() {
let row = |props| json!({"type":"row","props":props,"children":["ok"]});
assert_eq!(
parse(row(json!([1, "red"]))).unwrap(),
@@ -530,6 +530,93 @@ fn reads_row_wrap_without_moving_existing_positional_props() {
for invalid in [json!("wrap-reverse"), json!(null), json!({"wrap":null})] {
assert!(parse(row(json!({"gap":0,"wrap":invalid}))).is_err());
}
assert_eq!(
parse(row(json!([1, "red", "wrap"]))).unwrap(),
parse(row(json!({"gap":1,"background":"red","wrap":"wrap"}))).unwrap()
);
let explicit = row(json!({"gap":1,"background":"red","wrap":"wrap","justify":"start"}));
let positional = parse(row(json!([1, "red", "wrap", "start"]))).unwrap();
assert_eq!(parse(explicit.clone()).unwrap(), positional);
assert_eq!(serde_json::to_value(positional).unwrap(), explicit);
for invalid in [json!("center"), json!("space-between"), json!(null)] {
assert!(parse(row(json!({"gap":0,"justify":invalid}))).is_err());
}
}
#[test]
fn between_keeps_statusline_groups_at_opposite_edges_when_resized() {
let group = |fields: [&str; 2]| {
let children = fields.map(|field| json!({"type": "text", "children": [field]}));
json!({"type": "row", "props": {"gap": 1}, "children": children})
};
let node = tree(json!({
"type": "row", "props": {"gap": 1, "justify": "between", "wrap": "wrap"},
"children": [group(["界", "git"]), group(["75%", "2k"])]
}));
let wide = Size::new(20, 2);
assert_eq!(node.measure(wide), Size::new(20, 1));
insta::assert_snapshot!(painted_rows(&node, wide).join("\n"), @"界 git 75% 2k");
assert_eq!(painted_rows(&node, Size::new(13, 2)), ["界 git 75% 2k"]);
assert_eq!(painted_rows(&node, Size::new(12, 2)), ["界 git", "75% 2k"]);
}
#[test]
fn between_distributes_indivisible_cells_on_each_wrapped_line() {
let children = ["a", "b", "c", "longest"].map(|s| json!({"type": "text", "children": [s]}));
let node = tree(json!({
"type": "row", "props": {"gap": 1, "justify": "between", "wrap": "wrap"},
"children": children
}));
assert_eq!(
painted_rows(&node, Size::new(8, 2)),
["a b c", "longest"]
);
}
#[test]
fn explicit_start_groups_bare_strings_and_omitted_justify_keeps_authored_gaps() {
let children = json!(["L", null, "R", {"type":"text","children":["end"]}]);
let row = |props| tree(json!({"type":"row","props":props,"children":children}));
let size = Size::new(12, 1);
assert_eq!(painted_rows(&row(json!({"gap":1})), size), ["L R end"]);
assert_eq!(
painted_rows(&row(json!({"gap":1,"justify":"start"})), size),
["LR end"]
);
}
#[test]
fn between_matches_web_for_root_and_nested_rows() {
let bounds = Size::new(10, 1);
let text = |s: &str| json!({"type": "text", "children": [s]});
let mut rows = vec!["children |root |nested |".to_string()];
for (label, children) in [
("strings", json!(["L", "R"])),
("elements", json!([text("L"), text("R")])),
("mixed", json!(["L", null, "M", text("R")])),
("empty", json!([text(""), text("R")])),
] {
let inner =
json!({"type": "row", "props": {"gap": 0, "justify": "between"}, "children": children});
let outer = json!({"type": "row", "props": {"gap": 0}, "children": [inner]});
let [root, nested] = [inner, outer].map(|row| painted_rows(&tree(row), bounds).join("\n"));
rows.push(format!("{label:<10}|{root:<10}|{nested:<10}|"));
}
insta::assert_snapshot!(rows.join("\n"), @r"
children |root |nested |
strings |LR |LR |
elements |L R|LR |
mixed |LM R|LMR |
empty | R|R |
");
}
#[test]
fn between_rounds_each_fractional_position_to_the_nearest_cell() {
let children = ["A", "B", "C", "D", "E", "F"].map(|s| json!({"type":"text","children":[s]}));
let node =
tree(json!({"type":"row","props":{"gap":0,"justify":"between"},"children":children}));
insta::assert_snapshot!(painted_rows(&node, Size::new(14, 1)).join("\n"), @"A B C D E F");
}
#[test]
@@ -575,8 +662,12 @@ fn styled_text_wraps_in_the_space_its_nowrap_row_assigns() {
#[test]
fn shrinking_a_hyphenated_word_reserves_the_siblings_column() {
let node = tree(json!({"type":"row","props":{"gap":1},"children":["aa-bb", "!"]}));
assert_eq!(painted_rows(&node, Size::new(6, 2)), ["aa- !", "bb"]);
for props in [json!({"gap":1}), json!({"gap":1,"justify":"between"})] {
let node = tree(json!({"type":"row","props":props,"children":[
"aa-bb", {"type":"text","children":["!"]}
]}));
assert_eq!(painted_rows(&node, Size::new(6, 2)), ["aa- !", "bb"]);
}
}
#[test]
+5 -4
View File
@@ -10,6 +10,7 @@ import type {
// each returned element is sent as resource text.
export function render(state: StatuslineState): UiTree {
const children: UiTree[] = [];
const text = (value: string): UiTree => ({ type: "text", children: [value] });
const { account, config, thread } = state;
if (config.statusline_items.includes("model")) {
children.push({
@@ -26,19 +27,19 @@ export function render(state: StatuslineState): UiTree {
const window = account.rate_limits[0]?.primary_limit;
if (window && window.resets_at !== null) {
children.push(
`${window.used_percent}% until ${new Date(window.resets_at * 1_000).toISOString()}`,
text(`${window.used_percent}% until ${new Date(window.resets_at * 1_000).toISOString()}`),
);
}
if (thread.usage.total) {
children.push(String(thread.usage.total.output_tokens));
children.push(text(String(thread.usage.total.output_tokens)));
}
if (config.statusline_items.includes("current-dir")) {
children.push(thread.workspace.cwd);
children.push(text(thread.workspace.cwd));
}
if (children.length === 0) {
return null;
}
return { type: "row", props: { gap: 1, wrap: "wrap" }, children };
return { type: "row", props: { gap: 1, wrap: "wrap", justify: "between" }, children };
}
// @ts-expect-error The snapshot emits the canonical ID even when config used an alias.