Add inline badges to custom statuslines (#64010)

Add a `badge` element to the statusline UI tree and TypeScript contract.
It renders one string as a padded, single-line label with normalized
whitespace. The optional `color` accepts `secondary` (the default),
`info`, `success`, `warning`, or `danger`. The renderer uses the
active theme for the label and blends the fill with the surrounding
background when its color is known.

Badges wrap as a unit. When a line limit requires an ellipsis after
earlier content, a trailing badge that cannot fit is dropped. At the
viewport edge, the right padding can clip while the full label remains
visible.

## Testing

Add rendering tests for wrapping, clipping, theme colors, and linked
badges, along with checks for UI tree limits and the TypeScript contract.

GitOrigin-RevId: be9e9799d6832976d325ba5fda48f5793dbbc722
This commit is contained in:
Joe Savona
2026-11-25 22:51:53 +00:00
committed by copyberry
parent 8d8de8f693
commit 09b1cfd337
11 changed files with 493 additions and 23 deletions
@@ -14,6 +14,10 @@ export type ApprovalPolicy = "untrusted" | "on-request" | "granular" | "never";
export type ApprovalReviewer = "user" | "auto-review";
export type BadgeColor = "secondary" | "info" | "success" | "warning" | "danger";
export type BadgeProps = { color?: BadgeColor, };
/**
* A box defaults to a column when direction is omitted.
* Horizontal boxes group adjacent strings even without justify. Use separate elements for a gap.
@@ -39,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": "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": "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" };
@@ -124,6 +128,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 BadgeElement = Extract<Element, { type: "badge" }>;
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 };
@@ -30,6 +30,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
"RowElement",
"ColElement",
"BoxElement",
"BadgeElement",
"SpacerElement",
"CodeElement",
"StatuslineItemId",
@@ -71,6 +72,7 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
"Row",
"Col",
"Box",
"Badge",
"Spacer",
"Code",
] {
+2 -2
View File
@@ -178,14 +178,14 @@ pub(crate) fn hover_foreground(foreground: Color, background: Color) -> Option<C
})
}
fn background_rgb(background: Option<Color>) -> Option<(u8, u8, u8)> {
pub(crate) fn background_rgb(background: Option<Color>) -> Option<(u8, u8, u8)> {
match background {
None | Some(Color::Reset) => default_bg(),
Some(color) => explicit_rgb(color),
}
}
fn explicit_rgb(color: Color) -> Option<(u8, u8, u8)> {
pub(crate) fn explicit_rgb(color: Color) -> Option<(u8, u8, u8)> {
match color {
Color::Rgb(r, g, b) => Some((r, g, b)),
Color::Indexed(index) if index >= 16 => {
+32
View File
@@ -53,6 +53,13 @@ pub(crate) enum UiNode {
#[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))]
children: [(); 0],
},
/// A compact, single-line state label.
Badge {
#[serde(default, skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<BadgeProps>", optional))]
props: BadgeProps,
children: [String; 1],
},
Box {
props: BoxProps,
children: Vec<Option<UiNode>>,
@@ -78,6 +85,31 @@ 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 BadgeProps {
#[serde(
default,
deserialize_with = "decode::token",
skip_serializing_if = "is_default"
)]
#[cfg_attr(test, ts(as = "Option<BadgeColor>", optional))]
color: BadgeColor,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum BadgeColor {
#[default]
Secondary,
Info,
Success,
Warning,
Danger,
}
/// A box defaults to a column when direction is omitted.
/// Horizontal boxes group adjacent strings even without justify. Use separate elements for a gap.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+8 -3
View File
@@ -22,16 +22,21 @@ impl std::str::FromStr for UiTree {
let mut nodes = 0;
let mut text_bytes = 0;
while let Some((node, depth)) = pending.pop() {
if depth > 16 {
// A badge stores its string child directly in the node.
let label = usize::from(matches!(node, UiNode::Badge { .. }));
if depth + label > 16 {
return Err(Self::Err::custom("UI tree exceeds maximum depth 16"));
}
nodes += 1;
nodes += 1 + label;
if nodes > 256 {
return Err(Self::Err::custom("UI tree exceeds 256 non-null nodes"));
}
match node {
UiNode::Spacer { .. } => {}
UiNode::String(text) => {
UiNode::String(text)
| UiNode::Badge {
children: [text], ..
} => {
text_bytes += text.len();
if text_bytes > MAX_TEXT_BYTES {
return Err(Self::Err::custom("UI tree exceeds 16 KiB of text"));
+42 -10
View File
@@ -98,12 +98,22 @@ impl<'a> Fragment<'a> {
}
}
fn prefix(self, limit: usize) -> Self {
fn has_content(self) -> bool {
self.width() > 0
&& !matches!(
self,
Self::Padding(..) | Self::Gap(..) | Self::Background(..)
)
}
fn prefix(self, limit: usize, cut: text::Cut) -> Self {
if self.width() <= limit {
return self;
}
match self {
Self::Text(chunks, _) => Self::Text(chunks, self.visit(limit, |_, _, _, _| {})),
Self::Text(chunks, _) => {
Self::Text(chunks, visit_chunks(chunks, limit, cut, |_, _, _, _| {}))
}
Self::Padding(_, paint) => Self::Padding(limit, paint),
Self::Gap(_, paint) => Self::Gap(limit, paint),
Self::Background(_, paint) => Self::Background(limit, paint),
@@ -111,7 +121,12 @@ impl<'a> Fragment<'a> {
}
}
fn visit(self, limit: usize, mut draw: impl FnMut(usize, &str, usize, &'a Paint)) -> usize {
fn visit(
self,
limit: usize,
cut: text::Cut,
mut draw: impl FnMut(usize, &str, usize, &'a Paint),
) -> usize {
match self {
Self::Ellipsis(paint) => {
if limit > 0 {
@@ -121,7 +136,7 @@ impl<'a> Fragment<'a> {
0
}
}
Self::Text(chunks, width) => visit_chunks(chunks, limit.min(width), draw),
Self::Text(chunks, width) => visit_chunks(chunks, limit.min(width), cut, draw),
Self::BlankLine => 0,
Self::Padding(width, paint)
| Self::Gap(width, paint)
@@ -144,6 +159,7 @@ type Visit<'a, 'b> = dyn FnMut(usize, Fragment<'a>) + 'b;
#[derive(Default)]
struct Row<'a> {
ends_in_marker: bool,
content_before_edge: bool,
width: usize,
edge: Option<(usize, Fragment<'a>)>,
last_paint: Option<&'a Paint>,
@@ -217,14 +233,21 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
if fragment.width() > 0 {
row.ends_in_marker = matches!(fragment, Fragment::Ellipsis(_));
}
if row.width < width {
row.content_before_edge |= fragment.has_content();
}
if start < width {
if row.width >= width {
row.edge = Some((start, fragment));
} else if let Some(draw) = draw.as_deref_mut() {
fragment.visit(usize::MAX, |offset, text, cells, paint| {
draw(y, start + offset, text, cells, paint);
row.last_paint = Some(paint);
});
fragment.visit(
usize::MAX,
text::Cut::Viewport,
|offset, text, cells, paint| {
draw(y, start + offset, text, cells, paint);
row.last_paint = Some(paint);
},
);
}
}
},
@@ -242,8 +265,15 @@ fn layout(root: Option<&PreparedNode>, bounds: Size, mut draw: Option<&mut Draw<
&& (clipped || draw.is_some())
{
let limit = width - usize::from(clipped) - start;
let cut = if clipped {
text::Cut::LineClamp {
prior_content: row.content_before_edge,
}
} else {
text::Cut::Viewport
};
end = start
+ edge.visit(limit, |offset, text, cells, paint| {
+ edge.visit(limit, cut, |offset, text, cells, paint| {
if let Some(draw) = draw.as_deref_mut() {
draw(y, start + offset, text, cells, paint);
}
@@ -306,8 +336,10 @@ fn layout_visible<'a>(
}
if let Some(marker) = marker.filter(|_| clipped && width.cells > 0) {
let mut remaining = width.cells - 1;
let mut prior_content = false;
for fragment in tail {
let prefix = fragment.prefix(remaining);
let prefix = fragment.prefix(remaining, text::Cut::LineClamp { prior_content });
prior_content |= prefix.has_content();
visit(height - 1, prefix);
remaining -= prefix.width();
if prefix.width() < fragment.width() {
@@ -271,6 +271,13 @@ impl PreparedNode {
});
return;
}
UiNode::Badge {
props,
children: [label],
} => {
inline.push_badge(label, props.color, paint);
return;
}
UiNode::Code { children } => {
paint.inline_code = true;
paint.preserve_whitespace = true;
+86 -7
View File
@@ -6,6 +6,7 @@ use super::RenderTheme;
use super::Visit;
use super::sanitize_leaf;
use crate::line_truncation::span_width;
use crate::ui_tree::BadgeColor;
use crate::ui_tree::theme::Color;
use ratatui::buffer::CellWidth;
use ratatui::style::Style;
@@ -25,6 +26,7 @@ pub(super) struct Paint {
pub(super) foreground: Option<Color>,
pub(super) background: Option<Color>,
pub(super) href: Option<Arc<String>>,
pub(super) badge: Option<BadgeColor>,
pub(super) inline_code: bool,
pub(super) preserve_whitespace: bool,
pub(super) break_long_words: bool,
@@ -36,10 +38,15 @@ impl Paint {
style.fg = self.foreground.map(|c| theme.resolve(c));
style.bg = self.background.map(|c| theme.resolve(c));
if self.inline_code {
theme.inline_code_style(style)
} else {
style
style = theme.inline_code_style(style);
}
if let Some(color) = self.badge {
style = style.patch(theme.badge_style(color, style.bg));
if self.href.is_some() {
style = style.add_modifier(ratatui::style::Modifier::UNDERLINED);
}
}
style
}
}
@@ -117,6 +124,7 @@ pub(super) struct PreparedText {
pub(super) struct InlineText {
after_span: bool,
text: PreparedText,
completed: Vec<Chunk>,
line: Vec<Run>,
space: Option<Paint>,
}
@@ -140,6 +148,44 @@ impl InlineText {
self.push_sanitized(sanitize_leaf(raw), paint);
}
pub(super) fn push_badge(&mut self, label: String, color: BadgeColor, mut paint: Paint) {
let label = if label.contains('\r') {
label.replace('\r', " ")
} else {
label
};
let label = sanitize_leaf(label);
let label = label.split_ascii_whitespace().collect::<Vec<_>>().join(" ");
let text = RunText::new(format!(" {label} "));
paint.badge = Some(color);
// An inline-flex badge forms one unbreakable box with a break on either side.
self.completed
.extend(chunks(std::mem::take(&mut self.line)));
if let Some(last) = self.completed.last_mut() {
last.trailing_space = self.space.take();
}
self.completed.push(Chunk {
width_cells: span_width(&Span::raw(&*text)),
runs: vec![Run {
break_before: false,
text,
paint,
}],
..Chunk::default()
});
}
fn finish_line(&mut self) {
let mut line = std::mem::take(&mut self.completed);
let rest = chunks(std::mem::take(&mut self.line));
if line.is_empty() {
line = rest;
} else {
line.extend(rest);
}
self.text.lines.push(line);
}
fn push_sanitized(&mut self, raw: String, paint: Paint) {
let after_span = !raw.is_empty() && std::mem::take(&mut self.after_span);
let break_before = after_span && paint.preserve_whitespace && raw.starts_with([' ', '\t']);
@@ -155,6 +201,11 @@ impl InlineText {
.chain(std::iter::once((text.len(), "")))
{
if start < end {
if self.line.is_empty()
&& let Some(last) = self.completed.last_mut()
{
last.trailing_space = self.space.take();
}
if let Some(paint) = self.space.take() {
self.line.push(Run {
break_before: false,
@@ -169,9 +220,9 @@ impl InlineText {
});
}
if ch == "\n" {
self.text.lines.push(chunks(std::mem::take(&mut self.line)));
self.finish_line();
self.space = None;
} else if !ch.is_empty() && !self.line.is_empty() {
} else if !ch.is_empty() && (!self.line.is_empty() || !self.completed.is_empty()) {
self.space.get_or_insert_with(|| paint.clone());
}
start = end + ch.len();
@@ -180,8 +231,8 @@ impl InlineText {
pub(super) fn finish(mut self) -> PreparedText {
self.text.has_authored_break = !self.text.lines.is_empty();
if !self.line.is_empty() {
self.text.lines.push(chunks(self.line));
if !self.line.is_empty() || !self.completed.is_empty() {
self.finish_line();
}
self.text
}
@@ -411,6 +462,12 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
const TAB_SPACES: &str = " ";
impl Chunk {
fn is_badge(&self) -> bool {
self.runs
.first()
.is_some_and(|run| run.paint.badge.is_some())
}
pub(super) fn prefers_break_before(&self, index_in_line: usize) -> bool {
match self.break_before {
BreakBefore::Preferred => true,
@@ -464,6 +521,7 @@ impl PreparedText {
limit: usize,
visit: &mut Visit<'a, '_>,
) -> usize {
let visible = width.visible;
let width = width.cells;
let mut y = 0;
for line in &self.lines {
@@ -471,6 +529,13 @@ impl PreparedText {
loop {
let (end, cells) = fit_visual_line(remaining, width);
let (fitted, rest) = remaining.split_at(end);
// Keep both gutters for wrapping. At the viewport edge the
// decorative right gutter can clip while the entire label fits.
let cells = if cells == visible + 1 && fitted.last().is_some_and(Chunk::is_badge) {
visible
} else {
cells
};
visit(y, Fragment::Text(fitted, cells));
y += 1;
if y == limit {
@@ -510,14 +575,28 @@ fn fit_visual_line(line: &[Chunk], width: usize) -> (usize, usize) {
(line.len(), used)
}
#[derive(Clone, Copy)]
pub(super) enum Cut {
Viewport,
LineClamp { prior_content: bool },
}
pub(super) fn visit_chunks<'a>(
chunks: &'a [Chunk],
limit: usize,
cut: Cut,
mut draw: impl FnMut(usize, &str, usize, &'a Paint),
) -> usize {
let mut used = 0;
for (index, chunk) in chunks.iter().enumerate() {
if let Cut::LineClamp { prior_content } = cut
&& (prior_content || used > 0)
&& chunk.is_badge()
&& chunk.width_cells > limit - used
{
return used;
}
if let Some(paint) = chunk.tab_paint() {
let cells = chunk.width_at(used).min(limit.saturating_sub(used));
if cells == 0 {
+84
View File
@@ -5,8 +5,11 @@ use ratatui::style::Style;
use serde::Deserialize;
use serde::Serialize;
use super::BadgeColor;
use crate::bottom_pane::StatusLineAccent;
use crate::render::highlight;
use crate::style;
use crate::style::StatusTone;
use crate::terminal_palette;
use crate::terminal_palette::StdoutColorLevel;
use std::cell::OnceCell;
@@ -20,6 +23,7 @@ pub(super) struct RenderTheme<'a> {
highlighter: OnceCell<Highlighter<'a>>,
inline_code: OnceCell<(TerminalColor, TerminalColor)>,
resolved: HashMap<Color, TerminalColor>,
badges: HashMap<(BadgeColor, Option<TerminalColor>), Style>,
}
impl<'a> RenderTheme<'a> {
@@ -29,6 +33,7 @@ impl<'a> RenderTheme<'a> {
highlighter: OnceCell::new(),
inline_code: OnceCell::new(),
resolved: HashMap::new(),
badges: HashMap::new(),
}
}
@@ -77,6 +82,85 @@ impl<'a> RenderTheme<'a> {
style.fg(fg).bg(bg)
}
fn semantic_foreground(&mut self, role: BadgeColor) -> TerminalColor {
// TextMate also matches parent scopes, e.g. markup.inserted for markup.inserted.diff.
let scopes: &[&str] = match role {
BadgeColor::Secondary => &["codex.secondary"],
BadgeColor::Info => &["codex.info", "token.info-token"],
BadgeColor::Success => &["codex.success", "markup.inserted.diff"],
BadgeColor::Warning => &["codex.warning", "token.warn-token", "markup.changed.diff"],
BadgeColor::Danger => &["codex.danger", "token.error-token", "markup.deleted.diff"],
};
let fg = terminal_color(
highlight::foreground_color_for_scopes(self.highlighter(), scopes),
TerminalColor::Reset,
);
if fg != TerminalColor::Reset {
return fg;
}
match role {
BadgeColor::Secondary => match self.resolve(Color::Primary) {
TerminalColor::Reset => style::secondary_text_style().fg.unwrap_or_default(),
fg => fg,
},
BadgeColor::Info => match self.resolve(Color::Accent) {
TerminalColor::Reset => style::accent_color(),
fg => fg,
},
BadgeColor::Success => style::status_style(StatusTone::Success)
.fg
.unwrap_or_default(),
BadgeColor::Warning => style::status_style(StatusTone::Attention)
.fg
.unwrap_or_default(),
BadgeColor::Danger => style::status_style(StatusTone::Failure)
.fg
.unwrap_or_default(),
}
}
pub(super) fn badge_style(&mut self, role: BadgeColor, parent: Option<TerminalColor>) -> Style {
let key = (role, parent);
if let Some(&style) = self.badges.get(&key) {
return style;
}
let style = self.resolve_badge_style(role, parent);
self.badges.insert(key, style);
style
}
fn resolve_badge_style(&mut self, role: BadgeColor, parent: Option<TerminalColor>) -> Style {
let base = Style::default()
.fg(TerminalColor::Reset)
.bg(TerminalColor::Reset)
.remove_modifier(ratatui::style::Modifier::BOLD | ratatui::style::Modifier::UNDERLINED);
let level = terminal_palette::effective_stdout_color_level();
if matches!(level, StdoutColorLevel::Unknown) {
return base;
}
let fg = self.semantic_foreground(role);
// Pair ANSI foregrounds with the terminal background they were chosen for.
let Some(tint) = style::explicit_rgb(fg) else {
return base.fg(fg);
};
// A named ANSI parent has no known RGB. Compositing onto a known surface
// lets the contrast check use the exact fill the terminal will paint.
let Some(surface) = style::background_rgb(parent)
.or_else(terminal_palette::default_bg)
.or_else(|| style::explicit_rgb(self.resolve(Color::Surface)))
else {
return base;
};
const BADGE_TINT_ALPHA: f32 = 0.15;
let bg = terminal_palette::best_color_for_level(
crate::color::blend(tint, surface, BADGE_TINT_ALPHA),
level,
);
let fg = style::readable_color_on(fg, Some(bg));
base.fg(fg).bg(bg)
}
// Plain text and literal colors need no TextMate scope matching.
fn highlighter(&self) -> &Highlighter<'a> {
self.highlighter
+218
View File
@@ -1719,3 +1719,221 @@ fn spacer_keeps_ordinary_gaps_on_authored_blank_lines() {
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
assert_eq!(buf[(4, 1)].bg, ratatui::style::Color::Red);
}
#[test]
fn badge_is_one_sanitized_inline_box() {
let badge = json!({"type":"badge","children":[" \u{1b}[31mok\u{1b}[0m \t \n"]});
let node = tree(json!({"type":"text","children":["A",badge,"B"]}));
insta::assert_snapshot!(painted_rows(&node,Size::new(6,3)).join("\n"), @"A ok B");
assert_eq!(painted_rows(&node, Size::new(4, 3)), ["A", " ok", "B"]);
let node = tree(
json!({"type":"code","children":["a",{"type":"badge","children":[" a\t \nb "]},"c"]}),
);
assert_eq!(painted_rows(&node, Size::new(7, 1)), ["a a b c"]);
let node = tree(
json!({"type":"row","props":{"gap":0},"children":[{"type":"badge","children":[""]},"X"]}),
);
assert_eq!(painted_rows(&node, Size::new(3, 1)), [" X"]);
}
#[test]
fn badge_labels_count_toward_tree_limits() {
let badge = |children: Value| json!({"type":"badge","children":children});
for children in [
json!([]),
json!(["a", "b"]),
json!([null]),
json!(["a".repeat(MAX_TEXT_BYTES + 1)]),
] {
assert!(parse(badge(children)).is_err());
}
let mut node = badge(json!(["ok"]));
for _ in 0..15 {
node = json!({"type":"bold","children":[node]});
}
assert!(parse(node.clone()).is_ok());
assert!(parse(json!({"type":"bold","children":[node]})).is_err());
let badges = vec![badge(json!(["ok"])); 128];
assert!(parse(json!({"type":"text","children":badges})).is_err());
}
#[test]
fn semantic_badge_paints_its_gutters_and_keeps_the_surrounding_style() {
let palette = crate::terminal_probe::DefaultColors {
fg: (255, 255, 255),
bg: (0, 0, 0),
};
crate::terminal_palette::with_test_default_colors(palette, || {
let mut styles = Vec::new();
for color in ["secondary", "info", "success", "warning", "danger"] {
let node = tree(
json!({"type":"bold","children":["A",{"type":"badge","props":{"color":color},"children":["ok"]},"B"]}),
);
let area = Rect::new(0, 0, 6, 1);
let mut buf = Buffer::empty(area);
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
let style = buf[(2, 0)].style();
for x in 1..5 {
assert_eq!(buf[(x, 0)].style(), style);
}
assert_eq!(buf[(0, 0)].style(), buf[(5, 0)].style());
assert_ne!(style.fg, style.bg);
assert!(!styles.contains(&style));
styles.push(style);
}
});
}
#[test]
fn linked_and_plain_badges_share_colors_but_keep_distinct_underlines() {
use ratatui::style::Modifier;
let badge = json!({"type":"badge","children":["ok"]});
let link = json!({"type":"link","props":{"href":"https://example.com"},"children":[badge]});
for (children, linked, plain) in [(json!([link, badge]), 1, 5), (json!([badge, link]), 5, 1)] {
let node = tree(json!({"type":"text","children":children}));
let area = Rect::new(0, 0, 8, 1);
let mut buf = Buffer::empty(area);
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
let linked = &buf[(linked, 0)];
let plain = &buf[(plain, 0)];
assert_eq!((linked.fg, linked.bg), (plain.fg, plain.bg));
assert!(linked.modifier.contains(Modifier::UNDERLINED));
assert!(!plain.modifier.contains(Modifier::UNDERLINED));
}
}
#[test]
fn badge_uses_a_measurable_surface_for_its_fill() {
use ratatui::style::Color as TermColor;
let mut theme = Theme::default();
theme.settings.foreground = Some("#cdd6f4".parse().unwrap());
theme.settings.background = Some("#1e1e2e".parse().unwrap());
let colors = |theme: &Theme, background: Option<&str>, role: &str| {
let badge = json!({"type":"badge","props":{"color":role},"children":["X"]});
let node = match background {
Some(bg) => {
tree(json!({"type":"row","props":{"gap":0,"background":bg},"children":[badge]}))
}
None => tree(badge),
};
let area = Rect::new(0, 0, 3, 1);
let mut buf = Buffer::empty(area);
node.render(area, theme, &mut buf, /*plain_style*/ None);
let cell = &buf[(1, 0)];
(cell.fg, cell.bg)
};
let palette = crate::terminal_probe::DefaultColors {
fg: (255, 255, 255),
bg: (16, 16, 16),
};
for (palette, surface) in [(Some(palette), "#101010"), (None, "#1e1e2e")] {
crate::terminal_palette::with_test_default_colors(palette, || {
let secondary = |bg| colors(&theme, bg, "secondary");
assert_eq!(secondary(Some("white")), secondary(Some(surface)));
assert_eq!(secondary(None), secondary(Some(surface)));
assert_ne!(secondary(Some("white")), secondary(Some("#c0c0c0")));
assert_eq!(
colors(&theme, Some("#008000"), "success"),
(TermColor::Green, TermColor::Reset)
);
});
}
theme.settings.background = None;
crate::terminal_palette::with_test_default_colors(/*colors*/ None, || {
assert_eq!(
colors(&theme, Some("white"), "secondary"),
(TermColor::Reset, TermColor::Reset)
);
});
}
#[test]
fn badge_text_and_fill_follow_theme_changes_on_the_painted_surface() {
use crate::terminal_palette::rgb_color;
use syntect::highlighting::StyleModifier;
use syntect::highlighting::ThemeItem;
let palette = crate::terminal_probe::DefaultColors {
fg: (0, 0, 0),
bg: (255, 255, 255),
};
crate::terminal_palette::with_test_default_colors(palette, || {
for (role, scope) in [
("secondary", None),
("info", Some("codex.accent")),
("success", Some("markup.inserted.diff")),
("warning", Some("markup.changed.diff")),
("danger", Some("markup.deleted")),
] {
let node = tree(
json!({"type":"row","props":{"gap":0,"background":"#101010"},"children":[
{"type":"badge","props":{"color":role},"children":["X"]}
]}),
);
let mut theme = Theme::default();
let name = format!("codex.{role}");
// Paint with a conventional scope, then override it on the same prepared tree.
for (scope, value) in [(scope, "#ffcc88"), (Some(name.as_str()), "#88ccff")] {
let color: syntect::highlighting::Color = value.parse().unwrap();
if let Some(scope) = scope {
theme.scopes.push(ThemeItem {
scope: scope.parse().unwrap(),
style: StyleModifier {
foreground: Some(color),
..Default::default()
},
});
} else {
theme.settings.foreground = Some(color);
}
let area = Rect::new(0, 0, 3, 1);
let mut buf = Buffer::empty(area);
node.render(area, &theme, &mut buf, /*plain_style*/ None);
let rgb = (color.r, color.g, color.b);
let fill = crate::color::blend(rgb, (16, 16, 16), /*alpha*/ 0.15);
let cell = &buf[(1, 0)];
assert_eq!(
(cell.fg, cell.bg),
(rgb_color(rgb), rgb_color(fill)),
"{role}"
);
}
}
});
}
#[test]
fn clamped_text_reserves_room_for_a_whole_trailing_badge() {
let node = tree(
json!({"type":"text","props":{"maxLines":1},"children":["A",{"type":"badge","children":["ok"]},"B"]}),
);
assert_eq!(painted_rows(&node, Size::new(5, 1)), ["A…"]);
assert_eq!(painted_rows(&node, Size::new(6, 1)), ["A ok B"]);
let node = tree(json!({"type":"badge","children":["A\rB"]}));
assert_eq!(painted_rows(&node, Size::new(8, 1)), [" A B"]);
}
#[test]
fn clipped_badge_accounts_for_previous_row_children() {
let badge = json!({"type":"badge","children":["ok"]});
let row = json!({"type":"row","props":{"gap":0},"children":["A",badge]});
let centered = json!({"type":"row","props":{"gap":0,"justify":"center"},"children":[badge]});
for (line, width, expected) in [(row, 5, "A…"), (centered, 6, " ok …")] {
let col = json!({"type":"col","props":{"gap":0},"children":[line,"B"]});
let footer = tree(col.clone());
let clamped = tree(json!({"type":"text","props":{"maxLines":1},"children":[col]}));
assert_eq!(painted_rows(&footer, Size::new(width, 1)), [expected]);
assert_eq!(painted_rows(&clamped, Size::new(width, 2)), [expected]);
}
}
#[test]
fn clipping_only_the_badge_gutter_keeps_the_whole_label() {
let badge = json!({"type":"badge","children":["界"]});
assert_eq!(painted_rows(&tree(badge.clone()), Size::new(3, 1)), [" 界"]);
let row = tree(json!({"type":"row","props":{"gap":0},"children":["A",badge]}));
assert_eq!(painted_rows(&row, Size::new(4, 1)), ["A 界"]);
assert_eq!(painted_rows(&row, Size::new(3, 1)), ["A…"]);
}
@@ -2,6 +2,7 @@ import type {
CodeElement,
ColElement,
BoxElement,
BadgeElement,
SpacerElement,
Color,
RowElement,
@@ -55,6 +56,11 @@ const emptySpacer: SpacerElement = { ...spacer, children: [] };
// @ts-expect-error A spacer has no contents.
const invalidSpacer: SpacerElement = { ...spacer, children: ["x"] };
const badge: BadgeElement = { type: "badge", children: ["queued"] };
const passing: BadgeElement = { ...badge, props: { color: "success" }, children: ["passing"] };
// @ts-expect-error Badges accept semantic colors.
const invalidBadge: BadgeElement = { ...badge, props: { color: "red" } };
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 => ({