mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Add flexible spacers to custom statusline layouts (#64009)
## Why Statusline authors can set fixed gaps or justify a whole row. An expandable gap lets them place a field at the far edge by putting a spacer between it and the other fields. ## What changed Add the empty `spacer` element to the statusline renderer and its bundled TypeScript contract. Spacers share the remaining width on each wrapped row line before `justify` is applied. In columns stretched by a taller sibling, spacers share the added height. ## Testing Add renderer tests for wrapped and nested layouts, background fill, and clipping. Cover empty spacer declarations and reject spacer children in the parser and TypeScript contract tests. GitOrigin-RevId: d8bb58304b2a1f10ac0c60ec198aa3c25a169cae
This commit is contained in:
+4
-2
@@ -39,7 +39,7 @@ export type DirectedBox = { "direction": "row" } & RowProps | { "direction": "co
|
||||
|
||||
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": "box", props: BoxProps, 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>, } | { "type": "code", 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": "spacer", children?: [], } | { "type": "box", props: BoxProps, 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>, } | { "type": "code", children: Array<Element | null>, } | string;
|
||||
|
||||
export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" };
|
||||
|
||||
@@ -66,7 +66,8 @@ 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.
|
||||
* 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.
|
||||
* elements to position fields independently. Rows with a direct spacer also group adjacent strings. Other rows with omitted
|
||||
* `justify` keep gaps between authored children.
|
||||
*/
|
||||
export type RowProps = {
|
||||
/**
|
||||
@@ -123,6 +124,7 @@ export type LinkElement = Extract<Element, { type: "link" }>;
|
||||
export type RowElement = Extract<Element, { type: "row" }>;
|
||||
export type ColElement = Extract<Element, { type: "col" }>;
|
||||
export type BoxElement = Extract<Element, { type: "box" }>;
|
||||
export type SpacerElement = Extract<Element, { type: "spacer" }>;
|
||||
export type CodeElement = Extract<Element, { type: "code" }>;
|
||||
type BoxColumnProps = ColProps & { [K in Exclude<keyof RowProps, keyof ColProps>]?: never };
|
||||
export type RateLimitWindow = {
|
||||
|
||||
@@ -30,6 +30,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
|
||||
"RowElement",
|
||||
"ColElement",
|
||||
"BoxElement",
|
||||
"SpacerElement",
|
||||
"CodeElement",
|
||||
"StatuslineItemId",
|
||||
"Color",
|
||||
@@ -70,6 +71,7 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
|
||||
"Row",
|
||||
"Col",
|
||||
"Box",
|
||||
"Spacer",
|
||||
"Code",
|
||||
] {
|
||||
let tag = name.to_ascii_lowercase();
|
||||
|
||||
@@ -47,6 +47,12 @@ pub(crate) enum UiNode {
|
||||
props: RowProps,
|
||||
children: Vec<Option<UiNode>>,
|
||||
},
|
||||
/// Empty flex item sharing spare space on its parent's main axis.
|
||||
Spacer {
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
#[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))]
|
||||
children: [(); 0],
|
||||
},
|
||||
Box {
|
||||
props: BoxProps,
|
||||
children: Vec<Option<UiNode>>,
|
||||
@@ -174,7 +180,8 @@ 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.
|
||||
/// elements to position fields independently. Rows with a direct spacer also group adjacent strings. Other rows with omitted
|
||||
/// `justify` keep 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))]
|
||||
|
||||
@@ -30,6 +30,7 @@ impl std::str::FromStr for UiTree {
|
||||
return Err(Self::Err::custom("UI tree exceeds 256 non-null nodes"));
|
||||
}
|
||||
match node {
|
||||
UiNode::Spacer { .. } => {}
|
||||
UiNode::String(text) => {
|
||||
text_bytes += text.len();
|
||||
if text_bytes > MAX_TEXT_BYTES {
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
//! Lay out prepared text, rows, and columns within a terminal viewport.
|
||||
|
||||
mod flex;
|
||||
mod prepare;
|
||||
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;
|
||||
use super::UiTree;
|
||||
@@ -162,6 +159,30 @@ struct AvailableWidth {
|
||||
in_aligned_row: bool,
|
||||
// A row used as a flex item has an allocated width, unlike the root viewport.
|
||||
fill_background: bool,
|
||||
height: Height,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Height {
|
||||
// Intrinsic height only. Count gaps arithmetically and skip nested stretch passes.
|
||||
Measure,
|
||||
Grow(usize),
|
||||
}
|
||||
|
||||
impl Height {
|
||||
fn extra(self) -> usize {
|
||||
match self {
|
||||
Self::Grow(extra) => extra,
|
||||
Self::Measure => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_extra(self, extra: usize) -> Self {
|
||||
match self {
|
||||
Self::Grow(_) => Self::Grow(extra),
|
||||
Self::Measure => Self::Measure,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<'_>>) -> Size {
|
||||
@@ -179,6 +200,7 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
|
||||
visible: width,
|
||||
in_aligned_row: false,
|
||||
fill_background: false,
|
||||
height: Height::Grow(0),
|
||||
};
|
||||
let total = layout_visible(
|
||||
root,
|
||||
@@ -308,7 +330,7 @@ fn layout_node<'a>(
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
match &node.kind {
|
||||
NodeKind::Empty => 0,
|
||||
NodeKind::Empty | NodeKind::Spacer => 0,
|
||||
NodeKind::Clamped {
|
||||
content,
|
||||
max_lines,
|
||||
@@ -318,200 +340,27 @@ fn layout_node<'a>(
|
||||
layout_node(content, width, limit, visit)
|
||||
} else {
|
||||
let height = *max_lines as usize;
|
||||
layout_visible(content, width, height, Some(marker), visit).min(height)
|
||||
if matches!(width.height, Height::Measure) {
|
||||
layout_node(content, width, height, visit)
|
||||
} else {
|
||||
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;
|
||||
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::Col {
|
||||
children,
|
||||
gap,
|
||||
spacers,
|
||||
} => flex::column(children, *gap, *spacers, width, limit, visit),
|
||||
NodeKind::Row {
|
||||
children,
|
||||
props,
|
||||
paint,
|
||||
} => {
|
||||
let gap = props.gap.min((width.cells + 1) as u64) as usize;
|
||||
let mut place_band = |children: &'a [PreparedNode], used, y| {
|
||||
layout_band(
|
||||
children,
|
||||
width,
|
||||
limit - y,
|
||||
props,
|
||||
width.cells.saturating_sub(used),
|
||||
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.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;
|
||||
}
|
||||
start = i;
|
||||
used = 0;
|
||||
}
|
||||
if i > start {
|
||||
used += gap;
|
||||
}
|
||||
used += preferred;
|
||||
}
|
||||
y + place_band(&children[start..], used, y)
|
||||
}
|
||||
} => flex::row(children, props, paint, width, limit, visit),
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_band<'a>(
|
||||
children: &'a [PreparedNode],
|
||||
width: AvailableWidth,
|
||||
limit: usize,
|
||||
props: &RowProps,
|
||||
spare: usize,
|
||||
paint: &'a RowPaint,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> 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 * 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 = leading;
|
||||
let aligned = matches!(props.justify, Some(RowJustify::Center | RowJustify::End));
|
||||
let background_width = if width.fill_background && props.background.is_some() {
|
||||
width.cells.min(width.visible)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let suppress_blank = aligned && !width.in_aligned_row && background_width == 0;
|
||||
let mut lines = 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.cells.saturating_sub(offset + reserved))
|
||||
.max(minimum);
|
||||
let child_width = AvailableWidth {
|
||||
cells: available.min(width.cells),
|
||||
visible: width.visible.saturating_sub(offset),
|
||||
in_aligned_row: width.in_aligned_row || aligned,
|
||||
fill_background: true,
|
||||
};
|
||||
layout_node(child, child_width, limit, &mut |y, part| {
|
||||
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
|
||||
&& !matches!(part, Fragment::Padding(..) | Fragment::Gap(..))
|
||||
&& let Some(gaps) = pending.take()
|
||||
{
|
||||
for gap in gaps {
|
||||
visit(y, gap);
|
||||
}
|
||||
}
|
||||
let mut emit = |fragment: Fragment<'a>| {
|
||||
if let Some(gaps) = pending
|
||||
&& fragment.width() > 0
|
||||
{
|
||||
gaps.push(fragment);
|
||||
} else {
|
||||
visit(y, fragment);
|
||||
}
|
||||
};
|
||||
// A gap before an empty fragment can paint to the edge, but
|
||||
// only content beyond that edge should trigger overflow.
|
||||
let start = if part.width() == 0 {
|
||||
offset.min(width.visible).min(width.cells)
|
||||
} else {
|
||||
offset.min(width.cells + 1)
|
||||
};
|
||||
if *end == 0 && leading > 0 && start > 0 {
|
||||
let padding = leading.min(start);
|
||||
emit(if padding == background_width {
|
||||
Fragment::Background(padding, &paint.leading)
|
||||
} else {
|
||||
Fragment::Padding(padding, &paint.leading)
|
||||
});
|
||||
*end = padding;
|
||||
}
|
||||
if start > *end {
|
||||
emit(if background_width > 0 {
|
||||
Fragment::Background(start - *end, &paint.gap)
|
||||
} else {
|
||||
Fragment::Gap(start - *end, &paint.gap)
|
||||
});
|
||||
*end = start;
|
||||
}
|
||||
// Forward blank lines so ancestors count them toward the height limit.
|
||||
emit(part);
|
||||
*end += part.width();
|
||||
});
|
||||
let next_gap = if i < gaps {
|
||||
gap + share(i + 1) - share(i)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
offset += available + next_gap;
|
||||
reserved = reserved.saturating_sub(next_gap);
|
||||
}
|
||||
// Fill the rest of each visible line of an explicitly colored flex item,
|
||||
// including blank continuations. Never take cells from the next sibling.
|
||||
if background_width > 0 {
|
||||
for (y, (end, _)) in lines.iter().enumerate() {
|
||||
if *end < background_width {
|
||||
visit(
|
||||
y,
|
||||
Fragment::Background(background_width - end, &paint.leading),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.len()
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_leaf(mut raw: String) -> String {
|
||||
// Directly constructed trees can bypass the wire decoder's text limit.
|
||||
if raw.len() > MAX_TEXT_BYTES {
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Size and place flex items in terminal cells. Each wrapped band distributes its
|
||||
//! own free space. Cross-axis stretch uses intrinsic heights before viewport clipping.
|
||||
|
||||
use super::AvailableWidth;
|
||||
use super::Fragment;
|
||||
use super::Height;
|
||||
use super::NodeKind;
|
||||
use super::PreparedNode;
|
||||
use super::Visit;
|
||||
use super::layout_node;
|
||||
use super::prepare::RowPaint;
|
||||
use crate::ui_tree::RowJustify;
|
||||
use crate::ui_tree::RowProps;
|
||||
use crate::ui_tree::RowWrap;
|
||||
|
||||
pub(super) fn column<'a>(
|
||||
children: &'a [PreparedNode],
|
||||
gap: u64,
|
||||
spacers: usize,
|
||||
width: AvailableWidth,
|
||||
limit: usize,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
let mut growth = Shares::new(width.height.extra(), spacers);
|
||||
let measuring = matches!(width.height, Height::Measure);
|
||||
let width = AvailableWidth {
|
||||
height: width.height.with_extra(/*extra*/ 0),
|
||||
..width
|
||||
};
|
||||
let gap = gap.min(limit as u64) as usize;
|
||||
let mut y: usize = 0;
|
||||
for (index, child) in children.iter().enumerate() {
|
||||
let mut blank = if index > 0 { gap } else { 0 };
|
||||
if matches!(child.kind, NodeKind::Spacer) {
|
||||
blank = blank.saturating_add(growth.take());
|
||||
}
|
||||
let end = y.saturating_add(blank).min(limit);
|
||||
if !measuring {
|
||||
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
|
||||
}
|
||||
|
||||
pub(super) fn row<'a>(
|
||||
children: &'a [PreparedNode],
|
||||
props: &RowProps,
|
||||
paint: &'a RowPaint,
|
||||
width: AvailableWidth,
|
||||
limit: usize,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
let gap = props.gap.min((width.cells + 1) as u64) as usize;
|
||||
let mut rest = children;
|
||||
let bands = std::iter::from_fn(move || {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut used = 0;
|
||||
let mut count = 0;
|
||||
for child in rest {
|
||||
let preferred = child.widths.preferred.min((width.cells + 1) as u64) as usize;
|
||||
let next = used + if count > 0 { gap } else { 0 } + preferred;
|
||||
if props.wrap == RowWrap::Wrap && count > 0 && next > width.cells {
|
||||
break;
|
||||
}
|
||||
used = next;
|
||||
count += 1;
|
||||
}
|
||||
let (band, tail) = rest.split_at(count);
|
||||
rest = tail;
|
||||
Some((band, width.cells.saturating_sub(used)))
|
||||
});
|
||||
let extra = width.height.extra();
|
||||
let mut growth = Shares::new(extra, if extra > 0 { bands.clone().count() } else { 0 });
|
||||
let mut y = 0;
|
||||
for (band, spare) in bands {
|
||||
let width = AvailableWidth {
|
||||
height: width.height.with_extra(growth.take()),
|
||||
..width
|
||||
};
|
||||
y += layout_band(
|
||||
band,
|
||||
width,
|
||||
limit - y,
|
||||
props,
|
||||
spare,
|
||||
paint,
|
||||
&mut |row, part| visit(y + row, part),
|
||||
);
|
||||
if y == limit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
// Round cumulative positions so the last share always lands at the far edge.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Shares {
|
||||
space: usize,
|
||||
count: usize,
|
||||
used: usize,
|
||||
}
|
||||
impl Shares {
|
||||
fn new(space: usize, count: usize) -> Self {
|
||||
Self {
|
||||
space,
|
||||
count,
|
||||
used: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self) -> usize {
|
||||
if self.space == 0 || self.count == 0 {
|
||||
return 0;
|
||||
}
|
||||
let position = |i: usize| {
|
||||
((i as u128 * self.space as u128 + (self.count / 2) as u128) / self.count as u128)
|
||||
as usize
|
||||
};
|
||||
self.used += 1;
|
||||
position(self.used) - position(self.used - 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_band<'a>(
|
||||
children: &'a [PreparedNode],
|
||||
width: AvailableWidth,
|
||||
limit: usize,
|
||||
props: &RowProps,
|
||||
spare: usize,
|
||||
paint: &'a RowPaint,
|
||||
visit: &mut Visit<'a, '_>,
|
||||
) -> usize {
|
||||
let bounded = |cells: u64| cells.min((width.cells + 1) as u64) as usize;
|
||||
let gap = bounded(props.gap);
|
||||
// Flex growth consumes free space before justification, separately on each band.
|
||||
let spacers = children
|
||||
.iter()
|
||||
.filter(|c| matches!(c.kind, NodeKind::Spacer))
|
||||
.count();
|
||||
let growth = if spacers > 0 { spare } else { 0 };
|
||||
let spare = spare - growth;
|
||||
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);
|
||||
let between = if gaps == 0 { 0 } else { between };
|
||||
let mut gap_shares = Shares::new(between, gaps);
|
||||
let mut spacer_shares = Shares::new(growth, spacers);
|
||||
let mut reserved = children
|
||||
.iter()
|
||||
.map(|c| bounded(c.widths.minimum))
|
||||
.sum::<usize>()
|
||||
+ gap * gaps
|
||||
+ between;
|
||||
let mut offset = leading;
|
||||
let aligned =
|
||||
spacers == 0 && matches!(props.justify, Some(RowJustify::Center | RowJustify::End));
|
||||
let background_width = if width.fill_background && props.background.is_some() {
|
||||
width.cells.min(width.visible)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let suppress_blank = aligned && !width.in_aligned_row && background_width == 0;
|
||||
let placements = children.iter().map(move |child| {
|
||||
let minimum = bounded(child.widths.minimum);
|
||||
reserved -= minimum;
|
||||
let available = if matches!(child.kind, NodeKind::Spacer) {
|
||||
spacer_shares.take()
|
||||
} else {
|
||||
bounded(child.widths.preferred)
|
||||
.min(width.cells.saturating_sub(offset + reserved))
|
||||
.max(minimum)
|
||||
};
|
||||
let child_width = AvailableWidth {
|
||||
cells: available.min(width.cells),
|
||||
visible: width.visible.saturating_sub(offset),
|
||||
in_aligned_row: width.in_aligned_row || aligned,
|
||||
fill_background: true,
|
||||
height: Height::Grow(0),
|
||||
};
|
||||
let placement = (offset, available, child, child_width);
|
||||
let next_gap = gap + gap_shares.take();
|
||||
offset += available + next_gap;
|
||||
reserved = reserved.saturating_sub(next_gap);
|
||||
placement
|
||||
});
|
||||
let intrinsic = |cap| {
|
||||
placements.clone().map(move |(_, _, child, mut w)| {
|
||||
w.height = Height::Measure;
|
||||
layout_node(child, w, cap, &mut |_, _| {})
|
||||
})
|
||||
};
|
||||
if matches!(width.height, Height::Measure) {
|
||||
return intrinsic(limit).max().unwrap_or_default();
|
||||
}
|
||||
// A column with spacers can stretch to the tallest sibling in its band.
|
||||
// Measure before viewport clipping so offscreen lines still affect positioning.
|
||||
let extra = width.height.extra();
|
||||
let stretch = (children.len() > 1 || extra > 0) && children.iter().any(|c| c.stretches);
|
||||
let heights: Vec<_> = if stretch {
|
||||
intrinsic(usize::MAX).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let band_height = if stretch {
|
||||
heights.iter().copied().max().unwrap_or_default()
|
||||
} else if spacers > 0 || extra > 0 {
|
||||
intrinsic(limit).max().unwrap_or_default()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let band_height = band_height.saturating_add(extra);
|
||||
let mut lines = Vec::new();
|
||||
for (i, (offset, available, child, mut child_width)) in placements.enumerate() {
|
||||
let mut place = |y: usize, part: Fragment<'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
|
||||
&& !matches!(part, Fragment::Padding(..) | Fragment::Gap(..))
|
||||
&& let Some(gaps) = pending.take()
|
||||
{
|
||||
for gap in gaps {
|
||||
visit(y, gap);
|
||||
}
|
||||
}
|
||||
let mut emit = |fragment: Fragment<'a>| {
|
||||
if let Some(gaps) = pending
|
||||
&& fragment.width() > 0
|
||||
{
|
||||
gaps.push(fragment);
|
||||
} else {
|
||||
visit(y, fragment);
|
||||
}
|
||||
};
|
||||
// A gap before an empty fragment can paint to the edge, but
|
||||
// only content beyond that edge should trigger overflow.
|
||||
let start = if part.width() == 0 {
|
||||
offset.min(width.visible).min(width.cells)
|
||||
} else {
|
||||
offset.min(width.cells + 1)
|
||||
};
|
||||
if *end == 0 && leading > 0 && start > 0 {
|
||||
let padding = leading.min(start);
|
||||
emit(if padding == background_width {
|
||||
Fragment::Background(padding, &paint.leading)
|
||||
} else {
|
||||
Fragment::Padding(padding, &paint.leading)
|
||||
});
|
||||
*end = padding;
|
||||
}
|
||||
if start > *end {
|
||||
emit(if background_width > 0 {
|
||||
Fragment::Background(start - *end, &paint.gap)
|
||||
} else {
|
||||
Fragment::Gap(start - *end, &paint.gap)
|
||||
});
|
||||
*end = start;
|
||||
}
|
||||
// Forward blank lines so ancestors count them toward the height limit.
|
||||
emit(part);
|
||||
*end += part.width();
|
||||
};
|
||||
if matches!(child.kind, NodeKind::Spacer) {
|
||||
for y in 0..band_height.min(limit) {
|
||||
place(y, Fragment::Padding(available, &paint.leading));
|
||||
}
|
||||
} else {
|
||||
if stretch && child.stretches {
|
||||
child_width.height = Height::Grow(band_height - heights[i]);
|
||||
}
|
||||
layout_node(child, child_width, limit, &mut place);
|
||||
}
|
||||
}
|
||||
// Fill the rest of each visible line of an explicitly colored flex item,
|
||||
// including blank continuations. Never take cells from the next sibling.
|
||||
if background_width > 0 {
|
||||
for (y, (end, _)) in lines.iter().enumerate() {
|
||||
if *end < background_width {
|
||||
visit(
|
||||
y,
|
||||
Fragment::Background(background_width - end, &paint.leading),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.len().max(band_height.min(limit))
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub(super) struct RowPaint {
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct PreparedNode {
|
||||
pub(super) kind: NodeKind,
|
||||
pub(super) stretches: bool,
|
||||
pub(super) widths: Widths,
|
||||
}
|
||||
|
||||
@@ -38,12 +39,14 @@ pub(super) enum NodeKind {
|
||||
Col {
|
||||
children: Vec<PreparedNode>,
|
||||
gap: u64,
|
||||
spacers: usize,
|
||||
},
|
||||
Row {
|
||||
children: Vec<PreparedNode>,
|
||||
props: RowProps,
|
||||
paint: RowPaint,
|
||||
},
|
||||
Spacer,
|
||||
Empty,
|
||||
}
|
||||
|
||||
@@ -77,6 +80,10 @@ impl Flow {
|
||||
|
||||
impl PreparedNode {
|
||||
pub(super) fn from_node(node: UiNode, paint: Paint) -> Option<Self> {
|
||||
let container = matches!(
|
||||
node,
|
||||
UiNode::Col { .. } | UiNode::Box { .. } | UiNode::Row { .. }
|
||||
);
|
||||
let mut flow = Flow {
|
||||
paint: paint.clone(),
|
||||
..Flow::default()
|
||||
@@ -85,14 +92,19 @@ impl PreparedNode {
|
||||
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))
|
||||
let mut node = if flow.blocks.is_empty() {
|
||||
last?
|
||||
} else {
|
||||
flow.blocks.extend(last);
|
||||
if flow.blocks.len() == 1 {
|
||||
flow.blocks.pop()?
|
||||
} else {
|
||||
Self::col(flow.blocks, /*gap*/ 0)
|
||||
}
|
||||
};
|
||||
// An inline wrapper interrupts cross-axis stretch.
|
||||
node.stretches &= container;
|
||||
Some(node)
|
||||
}
|
||||
|
||||
// Emergency word breaks allow each chunk to fit independently. Flex rows
|
||||
@@ -111,9 +123,10 @@ impl PreparedNode {
|
||||
.map(Self::breakable_minimum)
|
||||
.max()
|
||||
.unwrap_or_default(),
|
||||
NodeKind::Clamped { .. } | NodeKind::Row { .. } | NodeKind::Empty => {
|
||||
self.widths.minimum
|
||||
}
|
||||
NodeKind::Clamped { .. }
|
||||
| NodeKind::Row { .. }
|
||||
| NodeKind::Spacer
|
||||
| NodeKind::Empty => self.widths.minimum,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,9 +136,18 @@ impl PreparedNode {
|
||||
widths.minimum = widths.minimum.max(child.widths.minimum);
|
||||
widths.preferred = widths.preferred.max(child.widths.preferred);
|
||||
}
|
||||
let spacers = children
|
||||
.iter()
|
||||
.filter(|c| matches!(c.kind, NodeKind::Spacer))
|
||||
.count();
|
||||
Self {
|
||||
stretches: spacers > 0,
|
||||
widths,
|
||||
kind: NodeKind::Col { children, gap },
|
||||
kind: NodeKind::Col {
|
||||
children,
|
||||
gap,
|
||||
spacers,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +172,7 @@ impl PreparedNode {
|
||||
widths.preferred = widths.preferred.max(width as u64);
|
||||
}
|
||||
Some(Self {
|
||||
stretches: false,
|
||||
kind: NodeKind::Text(text),
|
||||
widths,
|
||||
})
|
||||
@@ -181,6 +204,9 @@ impl PreparedNode {
|
||||
};
|
||||
Some(Self {
|
||||
widths,
|
||||
stretches: children.iter().any(|c| {
|
||||
c.stretches || (props.wrap == RowWrap::Wrap && matches!(c.kind, NodeKind::Spacer))
|
||||
}),
|
||||
kind: NodeKind::Row {
|
||||
children,
|
||||
props,
|
||||
@@ -214,7 +240,15 @@ impl PreparedNode {
|
||||
}
|
||||
|
||||
fn flex_item(child: UiNode, paint: &Paint) -> Self {
|
||||
if matches!(child, UiNode::Spacer { .. }) {
|
||||
return Self {
|
||||
stretches: false,
|
||||
kind: NodeKind::Spacer,
|
||||
widths: Widths::default(),
|
||||
};
|
||||
}
|
||||
Self::from_node(child, paint.clone()).unwrap_or_else(|| Self {
|
||||
stretches: false,
|
||||
kind: NodeKind::Empty,
|
||||
widths: Widths::default(),
|
||||
})
|
||||
@@ -227,6 +261,16 @@ impl PreparedNode {
|
||||
inline.push_leaf(raw, paint);
|
||||
return;
|
||||
}
|
||||
UiNode::Spacer { .. } => {
|
||||
// Outside a flex container the empty div interrupts inline flow.
|
||||
flow.finish_line(inline);
|
||||
flow.blocks.push(Self {
|
||||
stretches: false,
|
||||
kind: NodeKind::Empty,
|
||||
widths: Widths::default(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
UiNode::Code { children } => {
|
||||
paint.inline_code = true;
|
||||
paint.preserve_whitespace = true;
|
||||
@@ -264,7 +308,12 @@ impl PreparedNode {
|
||||
if let Some(color) = props.background {
|
||||
paint.background = Some(color);
|
||||
}
|
||||
let children = if props.justify.is_some() {
|
||||
let children = if props.justify.is_some()
|
||||
|| children
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|n| matches!(n, UiNode::Spacer { .. }))
|
||||
{
|
||||
Self::flex_items(children, &paint)
|
||||
} else {
|
||||
// Existing providers apply the gap to each authored child.
|
||||
@@ -293,6 +342,7 @@ impl PreparedNode {
|
||||
minimum: content.breakable_minimum(),
|
||||
preferred: content.widths.preferred,
|
||||
},
|
||||
stretches: false,
|
||||
kind: NodeKind::Clamped {
|
||||
content: Box::new(content),
|
||||
max_lines,
|
||||
|
||||
@@ -1492,6 +1492,20 @@ fn clamped_blank_text_keeps_its_height_in_a_zero_width_slot() {
|
||||
assert_eq!(painted_rows(&node, Size::new(1, 3)), ["A", ""]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacer_only_wrapping_row_stays_in_its_zero_width_slot() {
|
||||
let spacer = json!({"type": "spacer"});
|
||||
for children in [json!([spacer]), json!([spacer, spacer])] {
|
||||
let node = tree(json!({
|
||||
"type": "row", "props": {"gap": 0}, "children": [
|
||||
{"type": "row", "props": {"gap": 1, "wrap": "wrap"}, "children": children},
|
||||
"A"
|
||||
]
|
||||
}));
|
||||
assert_eq!(painted_rows(&node, Size::new(1, 1)), ["A"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_gap_keeps_the_aligned_glyph_at_the_viewport_edge() {
|
||||
let node = tree(json!({
|
||||
@@ -1594,3 +1608,114 @@ fn clipped_code_tab_styles_the_marker_only_when_it_paints_cells() {
|
||||
assert_eq!(marker.style(), buf[(width - 2, 0)].style());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacer_is_an_empty_leaf() {
|
||||
for input in [
|
||||
json!({"type":"spacer"}),
|
||||
json!({"type":"spacer","children":[]}),
|
||||
] {
|
||||
let node = parse(input).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&node).unwrap(),
|
||||
json!({"type":"spacer"})
|
||||
);
|
||||
assert_eq!(node.prepare().measure(Size::new(8, 3)), Size::default());
|
||||
}
|
||||
for input in [
|
||||
json!({"type":"spacer","children":[null]}),
|
||||
json!({"type":"spacer","children":["text"]}),
|
||||
json!({"type":"spacer","props":{"minSize":1}}),
|
||||
] {
|
||||
assert!(parse(input).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacers_share_each_bands_spare_width_before_justification() {
|
||||
let spacer = json!({"type":"spacer"});
|
||||
let node = tree(
|
||||
json!({"type":"box","props":{"direction":"row","gap":1,"wrap":"wrap","justify":"end"},
|
||||
"children":["A",spacer,"B",spacer,"C"]}),
|
||||
);
|
||||
insta::assert_snapshot!(painted_rows(&node, Size::new(10, 3)).join("\n"), @"A B C");
|
||||
assert_eq!(painted_rows(&node, Size::new(7, 3)), ["A B C"]);
|
||||
assert_eq!(painted_rows(&node, Size::new(4, 3)), ["A B", " C"]);
|
||||
let row = tree(json!({"type":"row","props":{"gap":0},"children":["a", "b", spacer, "界\nx"]}));
|
||||
assert_eq!(painted_rows(&row, Size::new(8, 1)), ["ab 界…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacers_share_height_only_in_stretched_columns() {
|
||||
let spacer = json!({"type":"spacer"});
|
||||
let col = json!({"type":"col","props":{"gap":0},"children":["A",spacer,"B",spacer,"C"]});
|
||||
assert_eq!(
|
||||
painted_rows(&tree(col.clone()), Size::new(8, 8)),
|
||||
["A", "B", "C"]
|
||||
);
|
||||
let row = tree(json!({"type":"row","props":{"gap":0},"children":[col,"1\n2\n3\n4\n5\n6"]}));
|
||||
assert_eq!(
|
||||
painted_rows(&row, Size::new(8, 6)),
|
||||
["A1", " 2", " 3", "B4", " 5", "C6"]
|
||||
);
|
||||
assert_eq!(painted_rows(&row, Size::new(8, 3)), ["A1", " 2", " 3…"]);
|
||||
let huge = tree(json!({"type":"row","props":{"gap":0},"children":[col,
|
||||
{"type":"col","props":{"gap":MAX_SAFE_INTEGER},"children":["1",spacer,"2"]}]}));
|
||||
assert_eq!(painted_rows(&huge, Size::new(8, 3)), ["A1", "", "…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacer_paints_the_row_fill_through_its_allocated_width() {
|
||||
let node = tree(
|
||||
json!({"type":"row","props":{"gap":1,"background":"red"},"children":["A",{"type":"spacer"}]}),
|
||||
);
|
||||
let area = Rect::new(0, 0, 8, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
assert!(
|
||||
buf.content()
|
||||
.iter()
|
||||
.all(|c| c.bg == ratatui::style::Color::Red)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_width_spacer_keeps_vertical_overflow_safe() {
|
||||
let s = json!({"type":"spacer"});
|
||||
let node = tree(json!({"type":"row","props":{"gap":0},"children":[s,"界\nx",s]}));
|
||||
assert_eq!(painted_rows(&node, Size::new(2, 1)), ["…"]);
|
||||
assert_eq!(painted_rows(&node, Size::new(3, 1)), ["界…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretch_reaches_columns_through_nested_row_bands() {
|
||||
let col = json!({"type":"col","props":{"gap":0},"children":["A",{"type":"spacer"},"B"]});
|
||||
let nested = json!({"type":"row","props":{"gap":0,"wrap":"wrap"},"children":[col,col]});
|
||||
let node = tree(json!({"type":"row","props":{"gap":0},"children":[nested,"1\n2\n3\n4\n5\n6"]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(2, 6)),
|
||||
["A1", " 2", "B3", "A4", " 5", "B6"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_spacer_bands_share_a_taller_siblings_height() {
|
||||
let spacer = json!({"type":"spacer"});
|
||||
let inner = json!({"type":"row","props":{"gap":0,"wrap":"wrap"},"children":["A",spacer,"B",spacer,"C"]});
|
||||
let node = tree(json!({"type":"row","props":{"gap":0},"children":[inner,"1\n2\n3\n4\n5\n6"]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(2, 6)),
|
||||
["A1", " 2", "B3", " 4", "C5", " 6"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacer_keeps_ordinary_gaps_on_authored_blank_lines() {
|
||||
let node = tree(
|
||||
json!({"type":"row","props":{"gap":1,"background":"red"},"children":["A\n\nB",{"type":"spacer"},"C\n\nD"]}),
|
||||
);
|
||||
let area = Rect::new(0, 0, 8, 3);
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
assert_eq!(buf[(4, 1)].bg, ratatui::style::Color::Red);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
CodeElement,
|
||||
ColElement,
|
||||
BoxElement,
|
||||
SpacerElement,
|
||||
Color,
|
||||
RowElement,
|
||||
StatuslineItemId,
|
||||
@@ -49,6 +50,11 @@ const indented: UiTree = { type: "text", props: { preserveWhitespace: true }, ch
|
||||
|
||||
const summary: UiTree = { type: "text", props: { maxLines: 2 }, children: ["build results"] };
|
||||
|
||||
const spacer: SpacerElement = { type: "spacer" };
|
||||
const emptySpacer: SpacerElement = { ...spacer, children: [] };
|
||||
// @ts-expect-error A spacer has no contents.
|
||||
const invalidSpacer: SpacerElement = { ...spacer, children: ["x"] };
|
||||
|
||||
const stacked: BoxElement = { type: "box", props: { gap: 1 }, children: [summary, indented] };
|
||||
const horizontal: BoxElement = { ...stacked, props: { gap: 0, direction: "row", justify: "end" } };
|
||||
const responsive = (compact: boolean): BoxElement => ({
|
||||
|
||||
Reference in New Issue
Block a user