mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add list elements to custom status lines (#64773)
## Why Custom status lines need a way to display grouped entries with automatic numbering and keep wrapped lines aligned with the item text. ## What changed Add `list` and `list-item` to the UI tree and the bundled TypeScript contract. Each direct child of a `list` is an item. Use `list-item` to combine multiple elements under one marker. Lists use bullets by default and accept `number` or `none` as alternatives. Wrapped lines align with the item text, and nested numbered lists start their own count. ## Testing Add renderer tests for wrapping, nested numbering, marker placement in rows, clipping, and background preservation. Extend the decoding and TypeScript contract tests to cover invalid markers. GitOrigin-RevId: 991d230357f035ccbe7e52956ef1cbfe5b1e2174
This commit is contained in:
+7
-1
@@ -43,7 +43,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": "spacer", children?: [], } | { "type": "badge", props?: BadgeProps, children: [string], } | { "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": "list", props?: ListProps, children: Array<Element>, } | { "type": "list-item", children: Array<Element | null>, } | { "type": "spacer", children?: [], } | { "type": "badge", props?: BadgeProps, children: [string], } | { "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" };
|
||||
|
||||
@@ -59,6 +59,10 @@ export type LinkHref = string;
|
||||
|
||||
export type LinkProps = { href: LinkHref, title?: string | null, };
|
||||
|
||||
export type ListMarker = "bullet" | "number" | "none";
|
||||
|
||||
export type ListProps = { marker?: ListMarker, };
|
||||
|
||||
export type Model = { access_program?: "standard" | "daybreak_blue" | "daybreak_red", display_name: string, id?: string, provider: string, reasoning_level?: string, service_tier?: string, service_tier_display_name?: string, };
|
||||
|
||||
export type Permissions = { display_name: string, profile_id?: string, } & ({ "type": "managed", file_system: FileSystem, network: "restricted" | "enabled", } | { "type": "disabled" } | { "type": "external", network: "restricted" | "enabled", });
|
||||
@@ -128,6 +132,8 @@ 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 ListElement = Extract<Element, { type: "list" }>;
|
||||
export type ListItemElement = Extract<Element, { type: "list-item" }>;
|
||||
export type BadgeElement = Extract<Element, { type: "badge" }>;
|
||||
export type SpacerElement = Extract<Element, { type: "spacer" }>;
|
||||
export type CodeElement = Extract<Element, { type: "code" }>;
|
||||
|
||||
@@ -30,6 +30,8 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
|
||||
"RowElement",
|
||||
"ColElement",
|
||||
"BoxElement",
|
||||
"ListElement",
|
||||
"ListItemElement",
|
||||
"BadgeElement",
|
||||
"SpacerElement",
|
||||
"CodeElement",
|
||||
@@ -72,11 +74,17 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
|
||||
"Row",
|
||||
"Col",
|
||||
"Box",
|
||||
"List",
|
||||
"ListItem",
|
||||
"Badge",
|
||||
"Spacer",
|
||||
"Code",
|
||||
] {
|
||||
let tag = name.to_ascii_lowercase();
|
||||
let tag = if name == "ListItem" {
|
||||
"list-item".to_owned()
|
||||
} else {
|
||||
name.to_ascii_lowercase()
|
||||
};
|
||||
writeln!(
|
||||
generated,
|
||||
"export type {name}Element = Extract<Element, {{ type: \"{tag}\" }}>;"
|
||||
|
||||
@@ -47,6 +47,16 @@ pub(crate) enum UiNode {
|
||||
props: RowProps,
|
||||
children: Vec<Option<UiNode>>,
|
||||
},
|
||||
/// Each direct child is one item. Use list-item to compose an item from siblings.
|
||||
List {
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
#[cfg_attr(test, ts(as = "Option<ListProps>", optional))]
|
||||
props: ListProps,
|
||||
children: Vec<UiNode>,
|
||||
},
|
||||
ListItem {
|
||||
children: Vec<Option<UiNode>>,
|
||||
},
|
||||
/// Empty flex item sharing spare space on its parent's main axis.
|
||||
Spacer {
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
@@ -85,6 +95,29 @@ pub(crate) enum UiNode {
|
||||
String(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
|
||||
pub(crate) struct ListProps {
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "decode::token",
|
||||
skip_serializing_if = "is_default"
|
||||
)]
|
||||
#[cfg_attr(test, ts(as = "Option<ListMarker>", optional))]
|
||||
marker: ListMarker,
|
||||
}
|
||||
|
||||
#[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 ListMarker {
|
||||
#[default]
|
||||
Bullet,
|
||||
Number,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
|
||||
|
||||
@@ -42,7 +42,11 @@ impl std::str::FromStr for UiTree {
|
||||
return Err(Self::Err::custom("UI tree exceeds 16 KiB of text"));
|
||||
}
|
||||
}
|
||||
UiNode::Text { children, .. }
|
||||
UiNode::List { children, .. } => {
|
||||
pending.extend(children.iter().map(|child| (child, depth + 1)));
|
||||
}
|
||||
UiNode::ListItem { children }
|
||||
| UiNode::Text { children, .. }
|
||||
| UiNode::Code { children }
|
||||
| UiNode::Bold { children }
|
||||
| UiNode::Italic { children }
|
||||
|
||||
@@ -20,7 +20,9 @@ use ratatui::layout::Rect;
|
||||
use ratatui::layout::Size;
|
||||
use ratatui::style::Modifier;
|
||||
use ratatui::style::Style;
|
||||
use std::borrow::Cow;
|
||||
use syntect::highlighting::Theme;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use vtparse::CollectingVTActor;
|
||||
use vtparse::VTAction;
|
||||
use vtparse::VTParser;
|
||||
@@ -77,6 +79,9 @@ impl PreparedUiTree {
|
||||
#[derive(Clone, Copy)]
|
||||
enum Fragment<'a> {
|
||||
Text(&'a [Chunk], usize),
|
||||
/// An outside marker is positioned by the nearest list.
|
||||
ListMarker(&'a str, &'a Paint),
|
||||
MarkerCell(&'a str, &'a Paint, &'a Paint),
|
||||
Padding(usize, &'a Paint),
|
||||
Gap(usize, &'a Paint),
|
||||
/// The visible background of a flex item counts even on an otherwise blank line.
|
||||
@@ -93,16 +98,20 @@ impl<'a> Fragment<'a> {
|
||||
| Self::Padding(width, _)
|
||||
| Self::Gap(width, _)
|
||||
| Self::Background(width, _) => width,
|
||||
Self::BlankLine => 0,
|
||||
Self::Ellipsis(_) => 1,
|
||||
Self::ListMarker(..) | Self::BlankLine => 0,
|
||||
Self::MarkerCell(..) | Self::Ellipsis(_) => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn occupies_line(self) -> bool {
|
||||
self.width() > 0 || matches!(self, Self::ListMarker(..))
|
||||
}
|
||||
|
||||
fn has_content(self) -> bool {
|
||||
self.width() > 0
|
||||
&& !matches!(
|
||||
self,
|
||||
Self::Padding(..) | Self::Gap(..) | Self::Background(..)
|
||||
Self::Padding(..) | Self::Gap(..) | Self::Background(..) | Self::MarkerCell(..)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,7 +126,9 @@ impl<'a> Fragment<'a> {
|
||||
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,
|
||||
Self::MarkerCell(..) | Self::ListMarker(..) | Self::Ellipsis(_) | Self::BlankLine => {
|
||||
Self::BlankLine
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,19 +136,39 @@ impl<'a> Fragment<'a> {
|
||||
self,
|
||||
limit: usize,
|
||||
cut: text::Cut,
|
||||
mut draw: impl FnMut(usize, &str, usize, &'a Paint),
|
||||
mut draw: impl FnMut(usize, &str, usize, Cow<'a, Paint>),
|
||||
) -> usize {
|
||||
match self {
|
||||
Self::Ellipsis(paint) => {
|
||||
if limit > 0 {
|
||||
draw(0, "…", 1, paint);
|
||||
draw(0, "…", 1, Cow::Borrowed(paint));
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Self::Text(chunks, width) => visit_chunks(chunks, limit.min(width), cut, draw),
|
||||
Self::BlankLine => 0,
|
||||
Self::MarkerCell(glyph, paint, surface) => {
|
||||
if limit == 0 {
|
||||
return 0;
|
||||
}
|
||||
draw(
|
||||
0,
|
||||
glyph,
|
||||
1,
|
||||
Cow::Owned(Paint {
|
||||
background: surface.background,
|
||||
inline_code: surface.inline_code,
|
||||
..paint.clone()
|
||||
}),
|
||||
);
|
||||
1
|
||||
}
|
||||
Self::Text(chunks, width) => {
|
||||
visit_chunks(chunks, limit.min(width), cut, |x, text, cells, paint| {
|
||||
draw(x, text, cells, Cow::Borrowed(paint))
|
||||
})
|
||||
}
|
||||
Self::ListMarker(..) | Self::BlankLine => 0,
|
||||
Self::Padding(width, paint)
|
||||
| Self::Gap(width, paint)
|
||||
| Self::Background(width, paint) => {
|
||||
@@ -145,7 +176,7 @@ impl<'a> Fragment<'a> {
|
||||
let end = width.min(limit);
|
||||
for start in (0..end).step_by(SPACES.len()) {
|
||||
let n = (end - start).min(SPACES.len());
|
||||
draw(start, &SPACES[..n], n, paint);
|
||||
draw(start, &SPACES[..n], n, Cow::Borrowed(paint));
|
||||
}
|
||||
end
|
||||
}
|
||||
@@ -153,6 +184,36 @@ impl<'a> Fragment<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reclaim the marker lane from a list indent, flex gap or alignment padding.
|
||||
/// Preserve preceding text when the browser would paint over it.
|
||||
fn place_marker<'a>(line: &mut Vec<Fragment<'a>>, label: &'a str, paint: &'a Paint) {
|
||||
// Bullets, digits, periods and the separator each occupy a single cell.
|
||||
let mut glyphs = std::iter::once(" ")
|
||||
.chain(label.graphemes(true).rev())
|
||||
.peekable();
|
||||
let mut cells = Vec::new();
|
||||
for i in (0..line.len()).rev() {
|
||||
let surface = match line[i] {
|
||||
Fragment::Background(_, paint)
|
||||
| Fragment::Gap(_, paint)
|
||||
| Fragment::Padding(_, paint)
|
||||
| Fragment::MarkerCell(_, _, paint) => paint,
|
||||
_ => return,
|
||||
};
|
||||
for remaining in (0..line[i].width()).rev() {
|
||||
if let Some(glyph) = glyphs.next() {
|
||||
cells.push(Fragment::MarkerCell(glyph, paint, surface));
|
||||
}
|
||||
if glyphs.peek().is_none() {
|
||||
line[i] = line[i].prefix(remaining, text::Cut::Viewport);
|
||||
line.truncate(i + usize::from(remaining > 0));
|
||||
line.extend(cells.into_iter().rev());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Visit<'a, 'b> = dyn FnMut(usize, Fragment<'a>) + 'b;
|
||||
|
||||
/// Only the fragment that reaches the right edge must wait until overflow is known.
|
||||
@@ -162,7 +223,7 @@ struct Row<'a> {
|
||||
content_before_edge: bool,
|
||||
width: usize,
|
||||
edge: Option<(usize, Fragment<'a>)>,
|
||||
last_paint: Option<&'a Paint>,
|
||||
last_paint: Option<Cow<'a, Paint>>,
|
||||
}
|
||||
|
||||
type Draw<'a> = dyn FnMut(usize, usize, &str, usize, &Paint) + 'a;
|
||||
@@ -244,7 +305,7 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
|
||||
usize::MAX,
|
||||
text::Cut::Viewport,
|
||||
|offset, text, cells, paint| {
|
||||
draw(y, start + offset, text, cells, paint);
|
||||
draw(y, start + offset, text, cells, &paint);
|
||||
row.last_paint = Some(paint);
|
||||
},
|
||||
);
|
||||
@@ -275,14 +336,14 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
|
||||
end = start
|
||||
+ edge.visit(limit, cut, |offset, text, cells, paint| {
|
||||
if let Some(draw) = draw.as_deref_mut() {
|
||||
draw(y, start + offset, text, cells, paint);
|
||||
draw(y, start + offset, text, cells, &paint);
|
||||
}
|
||||
last_paint = Some(paint);
|
||||
});
|
||||
}
|
||||
if clipped {
|
||||
if let Some(draw) = draw.as_deref_mut() {
|
||||
let mut paint = last_paint.cloned().unwrap_or_default();
|
||||
let mut paint = last_paint.map(Cow::into_owned).unwrap_or_default();
|
||||
paint.href = None;
|
||||
draw(y, end, "…", 1, &paint);
|
||||
}
|
||||
@@ -363,6 +424,62 @@ fn layout_node<'a>(
|
||||
) -> usize {
|
||||
match &node.kind {
|
||||
NodeKind::Empty | NodeKind::Spacer => 0,
|
||||
NodeKind::ListItem {
|
||||
prefix,
|
||||
body,
|
||||
paint,
|
||||
} => {
|
||||
if !prefix.is_empty() {
|
||||
visit(0, Fragment::ListMarker(prefix, paint));
|
||||
}
|
||||
layout_node(body, width, limit, visit).max(usize::from(!prefix.is_empty()))
|
||||
}
|
||||
NodeKind::List {
|
||||
indent,
|
||||
body,
|
||||
paint,
|
||||
} => {
|
||||
let content = AvailableWidth {
|
||||
cells: width.cells.saturating_sub(*indent),
|
||||
visible: width.visible.saturating_sub(*indent),
|
||||
..width
|
||||
};
|
||||
if matches!(width.height, Height::Measure) || *indent == 0 {
|
||||
return layout_node(body, content, limit, visit);
|
||||
}
|
||||
// Position outside markers in the free cells immediately before
|
||||
// each label, including labels placed side by side in a row.
|
||||
let mut lines = Vec::new();
|
||||
let total = layout_node(body, content, limit, &mut |y, part| {
|
||||
if y >= lines.len() {
|
||||
lines.resize_with(y + 1, Vec::new);
|
||||
}
|
||||
if !part.occupies_line() {
|
||||
return;
|
||||
}
|
||||
let line = &mut lines[y];
|
||||
if line.is_empty() {
|
||||
line.push(Fragment::Gap(*indent, paint));
|
||||
}
|
||||
if let Fragment::ListMarker(label, paint) = part {
|
||||
place_marker(line, label, paint);
|
||||
} else {
|
||||
line.push(part);
|
||||
}
|
||||
});
|
||||
for (y, mut line) in lines.into_iter().enumerate() {
|
||||
if matches!(line.last(), Some(Fragment::MarkerCell(" ", ..))) {
|
||||
line.pop();
|
||||
}
|
||||
if line.is_empty() {
|
||||
visit(y, Fragment::BlankLine);
|
||||
}
|
||||
for part in line {
|
||||
visit(y, part);
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
NodeKind::Clamped {
|
||||
content,
|
||||
max_lines,
|
||||
|
||||
@@ -237,7 +237,7 @@ fn layout_band<'a>(
|
||||
}
|
||||
// Unpainted alignment and gaps alone do not make a blank line visible.
|
||||
let (end, pending) = &mut lines[y];
|
||||
if part.width() > 0
|
||||
if part.occupies_line()
|
||||
&& !matches!(part, Fragment::Padding(..) | Fragment::Gap(..))
|
||||
&& let Some(gaps) = pending.take()
|
||||
{
|
||||
@@ -256,7 +256,7 @@ fn layout_band<'a>(
|
||||
};
|
||||
// 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 {
|
||||
let start = if !part.occupies_line() {
|
||||
offset.min(width.visible).min(width.cells)
|
||||
} else {
|
||||
offset.min(width.cells + 1)
|
||||
|
||||
@@ -5,9 +5,11 @@ use super::text::Paint;
|
||||
use super::text::PreparedText;
|
||||
use crate::ui_tree::BoxProps;
|
||||
use crate::ui_tree::DirectedBox;
|
||||
use crate::ui_tree::ListMarker;
|
||||
use crate::ui_tree::RowProps;
|
||||
use crate::ui_tree::RowWrap;
|
||||
use crate::ui_tree::UiNode;
|
||||
use crate::ui_tree::theme::Color;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct RowPaint {
|
||||
@@ -31,6 +33,16 @@ pub(super) struct Widths {
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) enum NodeKind {
|
||||
Text(PreparedText),
|
||||
List {
|
||||
indent: usize,
|
||||
body: Box<PreparedNode>,
|
||||
paint: Paint,
|
||||
},
|
||||
ListItem {
|
||||
prefix: String,
|
||||
body: Box<PreparedNode>,
|
||||
paint: Paint,
|
||||
},
|
||||
Clamped {
|
||||
content: Box<PreparedNode>,
|
||||
max_lines: u64,
|
||||
@@ -123,7 +135,9 @@ impl PreparedNode {
|
||||
.map(Self::breakable_minimum)
|
||||
.max()
|
||||
.unwrap_or_default(),
|
||||
NodeKind::ListItem { body, .. } => body.breakable_minimum(),
|
||||
NodeKind::Clamped { .. }
|
||||
| NodeKind::List { .. }
|
||||
| NodeKind::Row { .. }
|
||||
| NodeKind::Spacer
|
||||
| NodeKind::Empty => self.widths.minimum,
|
||||
@@ -254,6 +268,95 @@ impl PreparedNode {
|
||||
})
|
||||
}
|
||||
|
||||
fn list_item(child: UiNode, paint: Paint) -> Self {
|
||||
let body = Self::flex_item(child, &paint);
|
||||
Self {
|
||||
stretches: false,
|
||||
widths: body.widths,
|
||||
kind: NodeKind::ListItem {
|
||||
prefix: String::new(),
|
||||
body: Box::new(body),
|
||||
paint,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit descendants participate in the nearest list's counter, even
|
||||
// through another item or an intervening layout container.
|
||||
fn collect_items<'a>(&'a mut self, items: &mut Vec<(&'a mut String, &'a mut Paint)>) {
|
||||
match &mut self.kind {
|
||||
NodeKind::ListItem {
|
||||
prefix,
|
||||
body,
|
||||
paint,
|
||||
} => {
|
||||
items.push((prefix, paint));
|
||||
body.collect_items(items);
|
||||
}
|
||||
NodeKind::Row { children, .. } | NodeKind::Col { children, .. } => {
|
||||
for child in children {
|
||||
child.collect_items(items);
|
||||
}
|
||||
}
|
||||
NodeKind::Clamped { content, .. } => content.collect_items(items),
|
||||
NodeKind::List { .. } | NodeKind::Text(_) | NodeKind::Spacer | NodeKind::Empty => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn list(children: Vec<UiNode>, marker: ListMarker, mut paint: Paint) -> Self {
|
||||
// Prose replaces inline code’s emphasis while keeping its background.
|
||||
paint.foreground = paint.inline_code.then_some(Color::Primary);
|
||||
paint.break_long_words = true;
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|child| {
|
||||
if matches!(child, UiNode::ListItem { .. }) {
|
||||
Self::flex_item(child, &paint)
|
||||
} else {
|
||||
Self::list_item(child, paint.clone())
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut body = Self::col(children, /*gap*/ 0);
|
||||
let mut items = Vec::new();
|
||||
body.collect_items(&mut items);
|
||||
let digits = items.len().to_string().len();
|
||||
let mut indent = 0;
|
||||
for (index, (prefix, style)) in items.into_iter().enumerate() {
|
||||
*prefix = match marker {
|
||||
ListMarker::None => break,
|
||||
ListMarker::Bullet => {
|
||||
indent = 3;
|
||||
"•".to_owned()
|
||||
}
|
||||
ListMarker::Number => {
|
||||
indent = digits + 2;
|
||||
format!("{}.", index + 1)
|
||||
}
|
||||
};
|
||||
style.href = None;
|
||||
if marker == ListMarker::Number {
|
||||
style.modifiers = style.modifiers.bold();
|
||||
}
|
||||
}
|
||||
Self {
|
||||
stretches: false,
|
||||
widths: Widths {
|
||||
minimum: body.breakable_minimum().saturating_add(indent as u64),
|
||||
preferred: body.widths.preferred.saturating_add(indent as u64),
|
||||
},
|
||||
kind: NodeKind::List {
|
||||
indent,
|
||||
body: Box::new(body),
|
||||
paint: Paint {
|
||||
background: paint.background,
|
||||
inline_code: paint.inline_code,
|
||||
..Paint::default()
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_inline(flow: &mut Flow, inline: &mut InlineText, node: UiNode, mut paint: Paint) {
|
||||
let parent_preserves_spaces = paint.preserve_whitespace;
|
||||
let children = match node {
|
||||
@@ -271,6 +374,23 @@ impl PreparedNode {
|
||||
});
|
||||
return;
|
||||
}
|
||||
UiNode::List { props, children } => {
|
||||
flow.finish_line(inline);
|
||||
flow.blocks.push(Self::list(children, props.marker, paint));
|
||||
return;
|
||||
}
|
||||
UiNode::ListItem { children } => {
|
||||
paint.break_long_words = true;
|
||||
flow.finish_line(inline);
|
||||
flow.blocks.push(Self::list_item(
|
||||
UiNode::Text {
|
||||
props: Default::default(),
|
||||
children,
|
||||
},
|
||||
paint,
|
||||
));
|
||||
return;
|
||||
}
|
||||
UiNode::Badge {
|
||||
props,
|
||||
children: [label],
|
||||
|
||||
@@ -1937,3 +1937,187 @@ fn clipping_only_the_badge_gutter_keeps_the_whole_label() {
|
||||
assert_eq!(painted_rows(&row, Size::new(4, 1)), ["A 界"]);
|
||||
assert_eq!(painted_rows(&row, Size::new(3, 1)), ["A…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_markers_hang_beside_wrapped_and_composed_items() {
|
||||
let children = json!(["first", {"type":"list-item","children":["run ", {"type":"bold","children":["tests"]}]}]);
|
||||
for (props, expected) in [
|
||||
(json!({}), vec![" • first", " • run", " tests"]),
|
||||
(
|
||||
json!({"marker":"number"}),
|
||||
vec!["1. first", "2. run", " tests"],
|
||||
),
|
||||
(json!({"marker":"none"}), vec!["first", "run", "tests"]),
|
||||
] {
|
||||
let list = tree(json!({"type":"list","props":props,"children":children}));
|
||||
assert_eq!(painted_rows(&list, Size::new(8, 3)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_lists_restart_numbering_and_keep_their_indent() {
|
||||
let list = tree(
|
||||
json!({"type":"list","props":{"marker":"number"},"children":[
|
||||
{"type":"list-item","children":["outer", {"type":"list","props":{"marker":"number"},"children":["abcdef"]}]},
|
||||
"next"
|
||||
]}),
|
||||
);
|
||||
assert_eq!(
|
||||
painted_rows(&list, Size::new(10, 4)),
|
||||
["1. outer", " 1. abcd", " ef", "2. next"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_rejects_unknown_markers_and_counts_nested_items() {
|
||||
assert!(parse(json!({"type":"list","props":{"marker":"check"},"children":[]})).is_err());
|
||||
let items = vec![json!({"type":"list-item","children":["X"]}); 128];
|
||||
assert!(parse(json!({"type":"list","children":items})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_item_fills_the_remaining_width_with_one_indent_per_line() {
|
||||
let list = tree(json!({"type":"list","children":[
|
||||
{"type":"row","props":{"gap":0,"justify":"between"},"children":[
|
||||
{"type":"text","children":["a\nb"]}, {"type":"text","children":["c\nd"]}
|
||||
]}
|
||||
]}));
|
||||
insta::assert_snapshot!(painted_rows(&list, Size::new(9, 2)).join("\n"), @" • a c\n b d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_reserve_space_for_indivisible_labels_beside_wrapping_siblings() {
|
||||
let badge = json!({"type":"badge","children":["ok"]});
|
||||
for (marker, width, expected) in [("bullet", 10, "abc • ok"), ("none", 7, "abc ok")] {
|
||||
let row = tree(json!({"type":"row","props":{"gap":0},"children":[
|
||||
"abc d", {"type":"list","props":{"marker":marker},"children":[badge]}
|
||||
]}));
|
||||
assert_eq!(painted_rows(&row, Size::new(width, 2)), [expected, "d"]);
|
||||
}
|
||||
let row = tree(json!({"type":"row","props":{"gap":0},"children":[
|
||||
"abc", {"type":"list","children":["abcd"]}
|
||||
]}));
|
||||
assert_eq!(
|
||||
painted_rows(&row, Size::new(8, 2)),
|
||||
["abc • ab", " cd"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descendant_items_use_the_nearest_lists_marker_lane_and_counter() {
|
||||
let list = tree(
|
||||
json!({"type":"list","props":{"marker":"number"},"children":[
|
||||
{"type":"list-item","children":["A",{"type":"bold","children":[{"type":"list-item","children":["B"]}]},
|
||||
{"type":"list","props":{"marker":"none"},"children":[{"type":"list-item","children":["C"]}]},
|
||||
{"type":"list-item","children":["D"]}]},
|
||||
"E"
|
||||
]}),
|
||||
);
|
||||
assert_eq!(
|
||||
painted_rows(&list, Size::new(10, 5)),
|
||||
["1. A", "2. B", " C", "3. D", "4. E"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_color_resets_to_prose_and_accepts_local_overrides() {
|
||||
use ratatui::style::Color;
|
||||
let node = tree(json!({"type":"text","props":{"color":"red"},"children":[
|
||||
"A",{"type":"list","props":{"marker":"number"},"children":["B",{"type":"text","props":{"color":"red"},"children":["C"]}]}
|
||||
]}));
|
||||
let area = Rect::new(0, 0, 4, 3);
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
assert_eq!(
|
||||
[(0, 0), (0, 1), (3, 1), (0, 2), (3, 2)].map(|p| buf[p].fg),
|
||||
[
|
||||
Color::Red,
|
||||
Color::Reset,
|
||||
Color::Reset,
|
||||
Color::Reset,
|
||||
Color::Red
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_list_markers_use_the_free_space_before_each_label() {
|
||||
let item = |text| json!({"type":"list-item","children":[text]});
|
||||
for (marker, gap, children, expected) in [
|
||||
(
|
||||
"number",
|
||||
3,
|
||||
json!([item("B"), item("C")]),
|
||||
["1. A", "2. B3. C", "4. D"],
|
||||
),
|
||||
(
|
||||
"bullet",
|
||||
2,
|
||||
json!([item("B"), item("C")]),
|
||||
[" • A", " • B• C", " • D"],
|
||||
),
|
||||
(
|
||||
"number",
|
||||
0,
|
||||
json!(["L",{"type":"spacer"},item("R")]),
|
||||
["1. A", " L2. R", "3. D"],
|
||||
),
|
||||
] {
|
||||
let list = tree(json!({"type":"list","props":{"marker":marker},"children":[
|
||||
{"type":"list-item","children":["A", {"type":"col","props":{"gap":0},"children":[
|
||||
{"type":"row","props":{"gap":gap},"children":children}
|
||||
]}]}, "D"
|
||||
]}));
|
||||
assert_eq!(painted_rows(&list, Size::new(8, 3)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_in_code_uses_prose_on_the_surrounding_surface() {
|
||||
let node = tree(
|
||||
json!({"type":"code","children":[{"type":"text","props":{"color":"primary"},"children":["X"]},
|
||||
{"type":"list","props":{"marker":"number"},"children":["Y"]}]}),
|
||||
);
|
||||
let area = Rect::new(0, 0, 4, 2);
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
let style = |p: (u16, u16)| (buf[p].fg, buf[p].bg);
|
||||
assert_eq!([style((0, 1)), style((3, 1))], [style((0, 0)); 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipped_list_keeps_a_lone_badge_after_its_marker() {
|
||||
let node = tree(
|
||||
json!({"type":"list","props":{"marker":"number"},"children":[
|
||||
{"type":"badge","children":["ok"]}, "next"
|
||||
]}),
|
||||
);
|
||||
assert_eq!(painted_rows(&node, Size::new(7, 1)), ["1. ok…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_markers_preserve_the_surface_under_each_cell() {
|
||||
use ratatui::style::Color;
|
||||
let row = json!({"type":"row","props":{"gap":3,"background":"red"},"children":[
|
||||
{"type":"list-item","children":["B"]},
|
||||
{"type":"list-item","children":["C"]}
|
||||
]});
|
||||
let flex_item = json!({"type":"row","props":{"gap":0},"children":[row]});
|
||||
for child in [row, flex_item] {
|
||||
let list = tree(
|
||||
json!({"type":"list","props":{"marker":"number"},"children":[
|
||||
{"type":"list-item","children":["A", {"type":"col","props":{"gap":0},"children":[child]}]}
|
||||
]}),
|
||||
);
|
||||
let area = Rect::new(0, 0, 8, 2);
|
||||
let mut buf = Buffer::empty(area);
|
||||
list.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
assert_eq!(painted_rows(&list, area.as_size()), ["1. A", "2. B3. C"]);
|
||||
for x in 0..8 {
|
||||
assert_eq!(
|
||||
buf[(x, 1)].bg,
|
||||
if x < 3 { Color::Reset } else { Color::Red }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import type {
|
||||
ColElement,
|
||||
BoxElement,
|
||||
BadgeElement,
|
||||
ListElement,
|
||||
ListItemElement,
|
||||
SpacerElement,
|
||||
Color,
|
||||
RowElement,
|
||||
@@ -99,3 +101,8 @@ const missingColGap: ColElement = { type: "col", props: {}, children: [] };
|
||||
const invalidColor: Color = "ff00bb";
|
||||
|
||||
const groupedPositions: RowElement["props"]["justify"][] = ["center", "end"];
|
||||
|
||||
const item: ListItemElement = { type: "list-item", children: ["ci ", passing] };
|
||||
const checks: ListElement = { type: "list", props: { marker: "number" }, children: ["build", item] };
|
||||
// @ts-expect-error Markers are limited to bullet, number, and none.
|
||||
const invalidList: ListElement = { ...checks, props: { marker: "check" } };
|
||||
|
||||
Reference in New Issue
Block a user