Add center and end alignment to status line rows (#62637)

## Why

Status line authors can start rows at the leading edge or distribute
extra space between items. They also need to center or right-align a
group while keeping its configured gaps.

## What changed

Add `justify: "center"` and `justify: "end"` to the row renderer and
TypeScript contract. Align each wrapped line independently within its
available width.

Leading padding uses the row background, stays outside hyperlink
targets, and leaves blank lines unpainted. When the last visible line
fills the width and more lines follow, the renderer can reclaim a
padding cell for the overflow ellipsis.

## Testing

Add rendering coverage for wrapped and nested rows, wide characters,
blank lines, hyperlink boundaries, and overflow. Extend the TypeScript
contract check to cover both new values.

GitOrigin-RevId: 85dd907fe60b5d2cfb759b32058d0876430dd9e6
This commit is contained in:
Joe Savona
2026-11-20 01:34:16 +00:00
committed by copyberry
parent f16c998db5
commit 78f6b11303
7 changed files with 293 additions and 37 deletions
@@ -46,7 +46,7 @@ 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";
export type RowJustify = "start" | "center" | "end" | "between";
/**
* A root row receives the available footer width. A row inside another row takes up to its content width.
@@ -59,8 +59,8 @@ export type RowProps = {
*/
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.
* Position each line's items at the `start`, `center`, or `end`.
* `between` distributes spare columns across the gaps between children.
*/
justify?: RowJustify, };
+4 -2
View File
@@ -142,8 +142,8 @@ 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.
/// Position each line's items at the `start`, `center`, or `end`.
/// `between` distributes spare columns across the gaps between children.
#[serde(
default,
deserialize_with = "decode::present_token",
@@ -168,6 +168,8 @@ enum RowWrap {
enum RowJustify {
#[default]
Start,
Center,
End,
Between,
}
+101 -28
View File
@@ -5,11 +5,13 @@ mod text;
use self::prepare::NodeKind;
use self::prepare::PreparedNode;
use self::prepare::RowPaint;
use self::text::Chunk;
use self::text::Paint;
use self::text::visit_chunks;
use super::MAX_TEXT_BYTES;
use super::RowJustify;
use super::RowProps;
use super::RowWrap;
use super::TextProps;
use super::TextWeight;
@@ -78,20 +80,21 @@ impl PreparedUiTree {
#[derive(Clone, Copy)]
enum Fragment<'a> {
Text(&'a [Chunk], usize),
Padding(usize, &'a Paint),
Gap(usize, &'a Paint),
}
impl<'a> Fragment<'a> {
fn width(self) -> usize {
match self {
Self::Text(_, width) | Self::Gap(width, _) => width,
Self::Text(_, width) | Self::Padding(width, _) | Self::Gap(width, _) => width,
}
}
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::Gap(width, paint) => {
Self::Padding(width, paint) | Self::Gap(width, paint) => {
const SPACES: &str = " ";
let end = width.min(limit);
for start in (0..end).step_by(SPACES.len()) {
@@ -116,6 +119,13 @@ struct Row<'a> {
type Draw<'a> = dyn FnMut(usize, usize, &str, usize, &Paint) + 'a;
#[derive(Clone, Copy)]
struct AvailableWidth {
cells: usize,
// A centered or end-aligned group leaves wholly blank lines unpainted, even in nested rows.
align_content_only: bool,
}
fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<'_>>) -> Size {
let Some(root) = root else {
return Size::default();
@@ -126,10 +136,11 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
return Size::default();
}
let mut rows = Vec::<Row>::new();
let total = layout_node(root, width, height + 1, &mut |y, fragment| {
if y >= height {
return;
}
let available = AvailableWidth {
cells: width,
align_content_only: false,
};
let total = layout_visible(root, available, height, &mut |y, fragment| {
if rows.len() <= y {
rows.resize_with(y + 1, Row::default);
}
@@ -180,9 +191,49 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
measured
}
// On the last visible line, alignment padding can give up a cell for the vertical
// overflow marker. Defer the suffix starting at that padding until we see the next line.
fn layout_visible<'a>(
root: &'a PreparedNode,
width: AvailableWidth,
height: usize,
visit: &mut Visit<'a, '_>,
) -> usize {
let mut tail = Vec::new();
let mut padding = None;
let mut last_width = 0;
let total = layout_node(root, width, height + 1, &mut |y, fragment| {
if y >= height {
return;
}
if y + 1 == height {
last_width += fragment.width();
if matches!(fragment, Fragment::Padding(..)) {
padding = Some(tail.len());
}
if padding.is_some() {
tail.push(fragment);
return;
}
}
visit(y, fragment);
});
if total > height
&& last_width == width.cells
&& let Some(index) = padding
&& let Fragment::Padding(cells, _) = &mut tail[index]
{
*cells -= 1;
}
for fragment in tail {
visit(height - 1, fragment);
}
total
}
fn layout_node<'a>(
node: &'a PreparedNode,
width: usize,
width: AvailableWidth,
limit: usize,
visit: &mut Visit<'a, '_>,
) -> usize {
@@ -194,18 +245,19 @@ fn layout_node<'a>(
props,
paint,
} => {
let gap = props.gap.min((width + 1) as u64) as usize;
let width = AvailableWidth {
align_content_only: width.align_content_only
|| matches!(props.justify, Some(RowJustify::Center | RowJustify::End)),
..width
};
let gap = props.gap.min((width.cells + 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,
props,
width.cells.saturating_sub(used),
paint,
&mut |row, part| visit(y + row, part),
)
@@ -214,8 +266,9 @@ fn layout_node<'a>(
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 props.wrap == RowWrap::Wrap && i > start && used + gap + preferred > width {
let preferred = child.widths.preferred.min((width.cells + 1) as u64) as usize;
if props.wrap == RowWrap::Wrap && i > start && used + gap + preferred > width.cells
{
y += place_band(&children[start..i], used, y);
if y == limit {
return y;
@@ -235,42 +288,62 @@ fn layout_node<'a>(
fn layout_band<'a>(
children: &'a [PreparedNode],
width: usize,
width: AvailableWidth,
limit: usize,
gap: usize,
props: &RowProps,
spare: usize,
paint: &'a Paint,
paint: &'a RowPaint,
visit: &mut Visit<'a, '_>,
) -> usize {
let bounded = |cells: u64| cells.min((width + 1) as u64) as usize;
let bounded = |cells: u64| cells.min((width.cells + 1) as u64) as usize;
let gap = bounded(props.gap);
let (leading, between) = match props.justify.unwrap_or_default() {
RowJustify::Start => (0, 0),
RowJustify::Center => (spare / 2, 0),
RowJustify::End => (spare, 0),
RowJustify::Between => (0, spare),
};
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 share = |i: usize| {
(i * between + gaps / 2)
.checked_div(gaps)
.unwrap_or_default()
};
let mut reserved = children
.iter()
.map(|c| bounded(c.widths.minimum))
.sum::<usize>()
+ gap * gaps
+ share(gaps);
let mut offset = 0usize;
let mut offset = leading;
let mut ends = Vec::new();
for (i, child) in children.iter().enumerate() {
let minimum = bounded(child.widths.minimum);
reserved -= minimum;
let available = bounded(child.widths.preferred)
.min(width.saturating_sub(offset + reserved))
.min(width.cells.saturating_sub(offset + reserved))
.max(minimum);
layout_node(child, available.clamp(1, width), limit, &mut |y, part| {
let child_width = AvailableWidth {
cells: available.clamp(1, width.cells),
..width
};
layout_node(child, child_width, limit, &mut |y, part| {
if y >= ends.len() {
ends.resize(y + 1, 0);
}
let end = &mut ends[y];
let start = offset.min(width + 1);
if start > *end {
visit(y, Fragment::Gap(start - *end, paint));
let start = offset.min(width.cells + 1);
if part.width() > 0 && *end == 0 && leading > 0 {
visit(y, Fragment::Padding(leading, &paint.leading));
*end = leading;
}
if start > *end && (!width.align_content_only || *end > 0 || part.width() > 0) {
visit(y, Fragment::Gap(start - *end, &paint.gap));
*end = start;
}
if offset <= width {
// Forward blank lines so ancestors count them toward the height limit.
if offset <= width.cells || part.width() == 0 {
visit(y, part);
*end += part.width();
}
+14 -2
View File
@@ -7,6 +7,12 @@ use crate::ui_tree::RowProps;
use crate::ui_tree::RowWrap;
use crate::ui_tree::UiNode;
#[derive(Debug, PartialEq)]
pub(super) struct RowPaint {
pub(super) gap: Paint,
pub(super) leading: Paint,
}
#[derive(Debug, PartialEq)]
pub(super) struct PreparedNode {
pub(super) kind: NodeKind,
@@ -25,7 +31,7 @@ pub(super) enum NodeKind {
Row {
children: Vec<PreparedNode>,
props: RowProps,
paint: Paint,
paint: RowPaint,
},
Empty,
}
@@ -93,7 +99,13 @@ impl PreparedNode {
kind: NodeKind::Row {
children,
props,
paint,
paint: RowPaint {
leading: Paint {
background: paint.background,
..Paint::default()
},
gap: paint,
},
},
})
}
+3 -1
View File
@@ -1,5 +1,6 @@
//! Prepared inline text retains styled chunks and their legal line breaks across leaves.
use super::AvailableWidth;
use super::Fragment;
use super::RenderTheme;
use super::Visit;
@@ -318,10 +319,11 @@ impl Chunk {
impl PreparedText {
pub(super) fn layout<'a>(
&'a self,
width: usize,
width: AvailableWidth,
limit: usize,
visit: &mut Visit<'a, '_>,
) -> usize {
let width = width.cells;
let mut y = 0;
for line in &self.lines {
let mut start = 0;
+166 -1
View File
@@ -538,7 +538,7 @@ fn reads_row_layout_without_moving_existing_positional_props() {
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)] {
for invalid in [json!("right"), json!("space-between"), json!(null)] {
assert!(parse(row(json!({"gap":0,"justify":invalid}))).is_err());
}
}
@@ -560,6 +560,171 @@ fn between_keeps_statusline_groups_at_opposite_edges_when_resized() {
assert_eq!(painted_rows(&node, Size::new(12, 2)), ["界 git", "75% 2k"]);
}
#[test]
fn center_and_end_align_each_wrapped_line_with_its_requested_gap() {
let layout = |justify| {
let children = ["界", "bb", "xyz"].map(|s| json!({"type":"text","children":[s]}));
let node = tree(
json!({"type":"row","props":{"gap":1,"wrap":"wrap","justify":justify},
"children":children}),
);
painted_rows(&node, Size::new(8, 2))
.iter()
.map(|line| format!("|{line}|"))
.collect::<Vec<_>>()
.join("\n")
};
insta::assert_snapshot!(layout("center"), @r"
| 界 bb|
| xyz|
");
insta::assert_snapshot!(layout("end"), @r"
| 界 bb|
| xyz|
");
}
#[test]
fn end_alignment_uses_spare_padding_for_vertical_overflow() {
let node = tree(json!({
"type": "row", "props": {"gap": 1, "justify": "end", "wrap": "wrap"},
"children": ["界", {"type": "text", "children": ["12345678"]}]
}));
let bounds = Size::new(8, 1);
assert_eq!(node.measure(bounds), bounds);
insta::assert_snapshot!(format!("|{}|", painted_rows(&node, bounds).join("\n")), @"| 界…|");
assert_eq!(
painted_rows(&node, Size::new(8, 2)),
[" 界", "12345678"]
);
}
#[test]
fn center_and_end_place_consecutive_strings_as_one_item() {
let layout = |justify| {
let row =
json!({"type":"row","props":{"gap":1,"justify":justify},"children":["L",null,"R"]});
let outer = json!({"type":"row","props":{"gap":0},"children":[row]});
[row, outer].map(|row| painted_rows(&tree(row), Size::new(10, 1)).join("\n"))
};
assert_eq!(layout("center"), [" LR", "LR"]);
assert_eq!(layout("end"), [" LR", "LR"]);
}
#[test]
fn aligned_rows_pad_visible_content_and_keep_link_targets_on_their_text() {
let href = "https://example.com/pr";
for (justify, expected) in [("center", " PR"), ("end", " PR")] {
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));
assert_eq!(
painted_rows(&row(json!("abcdef")), Size::new(3, 1)),
["ab…"]
);
let link = row(json!({"type":"link","props":{"href":href},"children":["PR"]}));
assert_eq!(
painted_rows(&link, Size::new(7, 1)),
[linked_columns(
expected,
expected.len() - 2..expected.len(),
href
)]
);
}
}
#[test]
fn offscreen_blank_lines_count_toward_the_height_of_a_nested_row() {
for justify in ["center", "end"] {
let node = tree(
json!({"type":"row","props":{"gap":0,"wrap":"wrap"},"children":[
{"type":"row","props":{"gap":6,"justify":justify},"children":[
{"type":"text","children":[""]}, {"type":"text","children":["\n\nB"]}
]}, "ok"
]}),
);
assert_eq!(painted_rows(&node, Size::new(5, 1)), ["…"]);
assert_eq!(painted_rows(&node, Size::new(5, 2)), ["", "…"]);
}
}
#[test]
fn nested_aligned_rows_leave_authored_blank_lines_unpainted() {
let area = Rect::new(0, 0, 8, 2);
for justify in ["center", "end"] {
let row = |children: Value| {
tree(
json!({"type":"row","props":{"gap":0,"justify":justify,"background":"red"},
"children":[{"type":"row","props":{"gap":1},"children":children}]}),
)
};
assert_eq!(
row(json!(["\n", "\n"])).measure(area.as_size()),
Size::new(0, 1)
);
let mut buf = Buffer::empty(area);
row(json!(["A\n\n", "B\n\n"])).render(
area,
&Theme::default(),
&mut buf,
/*plain_style*/ None,
);
assert_eq!(buf[(0, 0)].bg, ratatui::style::Color::Red);
for x in 0..area.width {
assert_eq!(buf[(x, 1)], ratatui::buffer::Cell::default());
}
}
}
#[test]
fn start_and_between_keep_their_gaps_before_blank_children() {
let area = Rect::new(0, 0, 8, 1);
for (justify, blank, visible) in [("start", 1, 2), ("between", 8, 8)] {
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"]}]}),
);
assert_eq!(node.measure(area.as_size()), Size::new(expected, 1));
let mut buf = Buffer::empty(area);
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
for x in 0..expected {
assert_eq!(buf[(x, 0)].bg, ratatui::style::Color::Red);
}
}
}
}
#[test]
fn a_link_around_an_aligned_row_keeps_its_padding_unlinked() {
let href = "https://example.com/pr";
let area = Rect::new(0, 0, 8, 1);
for (justify, leading) in [("center", 2), ("end", 5)] {
let node = tree(json!({"type":"link","props":{"href":href},"children":[
{"type":"row","props":{"gap":1,"justify":justify,"background":"red"},
"children":["P",{"type":"text","children":["R"]}]}
]}));
let mut buf = Buffer::empty(area);
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
for x in 0..leading {
let cell = &buf[(x, 0)];
assert_eq!(cell.symbol(), " ");
assert_eq!(cell.bg, ratatui::style::Color::Red);
assert!(cell.modifier.is_empty());
}
assert_eq!(
painted_rows(&node, area.as_size()),
[format!(
"{}{}",
" ".repeat(usize::from(leading)),
linked_columns("P R", 0..3, href)
)]
);
}
}
#[test]
fn between_distributes_indivisible_cells_on_each_wrapped_line() {
let children = ["a", "b", "c", "longest"].map(|s| json!({"type": "text", "children": [s]}));
@@ -48,3 +48,5 @@ const alias: StatuslineItemId = "project-root";
const missingGap: RowElement = { type: "row", props: {}, children: [] };
// @ts-expect-error Color literals begin with a hash or match one of the named tokens.
const invalidColor: Color = "ff00bb";
const groupedPositions: RowElement["props"]["justify"][] = ["center", "end"];