Add named icons to custom statuslines (#64774)

## What changed

Render named `icon` elements inline with terminal text. Badges can
display an icon on its own or place it before or after a label. For
example, a success badge can show a `check` icon next to “passing”.

Keep icons intact when wrapping or truncating text, including icons
that span multiple cells such as `code` (`</>`). Expose the new
element and badge combinations in the bundled TypeScript contract.

## Testing

Add coverage for icon and badge rendering, whole-icon truncation,
invalid icon payloads, and badge children counting toward the UI tree
node limit. Update the TypeScript contract fixture to exercise a badge
with a leading icon.

GitOrigin-RevId: 8a5afb0662a71cf1b5d16400b9866cb414c11646
This commit is contained in:
Joe Savona
2026-11-30 17:43:15 +00:00
committed by copyberry
parent f57352c536
commit e860a98090
8 changed files with 284 additions and 39 deletions
@@ -14,8 +14,12 @@ export type ApprovalPolicy = "untrusted" | "on-request" | "granular" | "never";
export type ApprovalReviewer = "user" | "auto-review";
export type BadgeChildren = [string] | [BadgeIcon] | [BadgeIcon, string] | [string, BadgeIcon];
export type BadgeColor = "secondary" | "info" | "success" | "warning" | "danger";
export type BadgeIcon = { "type": "icon" } & IconNode;
export type BadgeProps = { color?: BadgeColor, };
/**
@@ -43,7 +47,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": "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 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": "icon" } & IconNode | { "type": "badge", props?: BadgeProps, children: BadgeChildren, } | { "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" };
@@ -52,6 +56,16 @@ export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" };
*/
export type HexRgb = `#${string}`;
export type IconName = "check" | "x" | "error" | "warning" | "info" | "clock" | "circle" | "empty-circle" | "circle-dashed" | "arrow-up" | "arrow-down" | "arrow-left" | "arrow-right" | "timer" | "branch" | "code";
export type IconNode = { props: IconProps, children?: [], };
export type IconProps = { name: IconName,
/**
* Terminal icons always align with surrounding text.
*/
inline?: boolean, };
/**
* An absolute HTTP(S) URL without control characters, at most 8 KiB in UTF-8.
*/
@@ -135,6 +149,7 @@ 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 IconElement = Extract<Element, { type: "icon" }>;
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 };
@@ -33,6 +33,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
"ListElement",
"ListItemElement",
"BadgeElement",
"IconElement",
"SpacerElement",
"CodeElement",
"StatuslineItemId",
@@ -77,6 +78,7 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
"List",
"ListItem",
"Badge",
"Icon",
"Spacer",
"Code",
] {
+80 -1
View File
@@ -63,12 +63,13 @@ pub(crate) enum UiNode {
#[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))]
children: [(); 0],
},
Icon(IconNode),
/// 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],
children: BadgeChildren,
},
Box {
props: BoxProps,
@@ -95,6 +96,84 @@ pub(crate) enum UiNode {
String(String),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(deny_unknown_fields)]
pub(crate) struct IconNode {
#[serde(deserialize_with = "decode::icon_props")]
props: IconProps,
#[serde(default, skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))]
children: [(); 0],
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(deny_unknown_fields)]
pub(crate) struct IconProps {
#[serde(deserialize_with = "decode::token")]
name: IconName,
/// Terminal icons always align with surrounding text.
#[serde(default, skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<bool>", optional))]
inline: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(rename_all = "kebab-case")]
pub(crate) enum IconName {
Check,
X,
Error,
Warning,
Info,
Clock,
Circle,
EmptyCircle,
CircleDashed,
ArrowUp,
ArrowDown,
ArrowLeft,
ArrowRight,
Timer,
Branch,
Code,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(tag = "type", rename_all = "kebab-case")]
pub(crate) enum BadgeIcon {
Icon(IconNode),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(untagged)]
pub(crate) enum BadgeChildren {
Label([String; 1]),
Icon([BadgeIcon; 1]),
Leading(BadgeIcon, String),
Trailing(String, BadgeIcon),
}
impl BadgeChildren {
fn count(&self) -> usize {
match self {
Self::Label(_) | Self::Icon(_) => 1,
Self::Leading(..) | Self::Trailing(..) => 2,
}
}
fn label(&self) -> &str {
match self {
Self::Label([label]) | Self::Leading(_, label) | Self::Trailing(label, _) => label,
Self::Icon(_) => "",
}
}
}
#[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"))]
+33 -14
View File
@@ -1,5 +1,6 @@
//! Enforce the input byte limit before parsing and the UI tree limits after deserialization.
use super::IconProps;
use super::MAX_SAFE_INTEGER;
use super::MAX_TEXT_BYTES;
use super::UiNode;
@@ -22,26 +23,21 @@ impl std::str::FromStr for UiTree {
let mut nodes = 0;
let mut text_bytes = 0;
while let Some((node, depth)) = pending.pop() {
// A badge stores its string child directly in the node.
let label = usize::from(matches!(node, UiNode::Badge { .. }));
if depth + label > 16 {
let badge_children = match node {
UiNode::Badge { children, .. } => children.count(),
_ => 0,
};
if depth + usize::from(badge_children > 0) > 16 {
return Err(Self::Err::custom("UI tree exceeds maximum depth 16"));
}
nodes += 1 + label;
nodes += 1 + badge_children;
if nodes > 256 {
return Err(Self::Err::custom("UI tree exceeds 256 non-null nodes"));
}
match node {
UiNode::Spacer { .. } => {}
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"));
}
}
UiNode::Spacer { .. } | UiNode::Icon(_) => {}
UiNode::String(text) => text_bytes += text.len(),
UiNode::Badge { children, .. } => text_bytes += children.label().len(),
UiNode::List { children, .. } => {
pending.extend(children.iter().map(|child| (child, depth + 1)));
}
@@ -59,10 +55,33 @@ impl std::str::FromStr for UiTree {
}
}
}
if text_bytes > MAX_TEXT_BYTES {
return Err(Self::Err::custom("UI tree exceeds 16 KiB of text"));
}
Ok(Self(root))
}
}
// A derived struct also accepts positional arrays. Require an object while
// retaining IconProps' checks for duplicate and unknown fields.
pub(super) fn icon_props<'de, D: Deserializer<'de>>(d: D) -> Result<IconProps, D::Error> {
struct Object;
impl<'de> serde::de::Visitor<'de> for Object {
type Value = IconProps;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an icon props object")
}
fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<IconProps, M::Error> {
IconProps::deserialize(serde::de::value::MapAccessDeserializer::new(map))
}
}
d.deserialize_map(Object)
}
pub(super) fn optional_token<'de, D: Deserializer<'de>, T: DeserializeOwned>(
d: D,
) -> Result<Option<T>, D::Error> {
+6 -5
View File
@@ -391,11 +391,12 @@ impl PreparedNode {
));
return;
}
UiNode::Badge {
props,
children: [label],
} => {
inline.push_badge(label, props.color, paint);
UiNode::Icon(icon) => {
inline.push_icon(icon.props.name, paint);
return;
}
UiNode::Badge { props, children } => {
inline.push_badge(children, props.color, paint);
return;
}
UiNode::Code { children } => {
+80 -17
View File
@@ -6,7 +6,10 @@ use super::RenderTheme;
use super::Visit;
use super::sanitize_leaf;
use crate::line_truncation::span_width;
use crate::ui_tree::BadgeChildren;
use crate::ui_tree::BadgeColor;
use crate::ui_tree::BadgeIcon;
use crate::ui_tree::IconName;
use crate::ui_tree::theme::Color;
use ratatui::buffer::CellWidth;
use ratatui::style::Style;
@@ -60,6 +63,7 @@ struct Run {
// Splitting a leaf at style, whitespace or wrap boundaries shares its original buffer.
#[derive(Debug)]
enum RunText {
Icon(&'static str),
Slice(Arc<String>, Range<usize>),
Space,
}
@@ -76,6 +80,7 @@ impl RunText {
Arc::clone(text),
bytes.start + range.start..bytes.start + range.end,
),
Self::Icon(text) => Self::Icon(&text[range]),
Self::Space => Self::Space,
}
}
@@ -87,6 +92,7 @@ impl Deref for RunText {
fn deref(&self) -> &str {
match self {
Self::Slice(text, bytes) => &text[bytes.clone()],
Self::Icon(text) => text,
Self::Space => " ",
}
}
@@ -94,7 +100,7 @@ impl Deref for RunText {
impl PartialEq for RunText {
fn eq(&self, other: &Self) -> bool {
**self == **other
matches!(self, Self::Icon(_)) == matches!(other, Self::Icon(_)) && **self == **other
}
}
@@ -129,6 +135,29 @@ pub(super) struct InlineText {
space: Option<Paint>,
}
impl IconName {
fn glyph(&self) -> &'static str {
match self {
Self::Check => "✓",
Self::X => "✗",
Self::Error => "!",
Self::Warning => "⚠",
Self::Info => "ⓘ",
Self::Clock => "◷",
Self::Circle => "●",
Self::EmptyCircle => "○",
Self::CircleDashed => "◌",
Self::ArrowUp => "↑",
Self::ArrowDown => "↓",
Self::ArrowLeft => "←",
Self::ArrowRight => "→",
Self::Timer => "⏱",
Self::Branch => "⑂",
Self::Code => "</>",
}
}
}
impl InlineText {
/// Returning to normal prose allows a break before a sibling’s first literal space.
pub(super) fn end_span(&mut self) {
@@ -148,31 +177,61 @@ 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);
pub(super) fn push_icon(&mut self, name: IconName, paint: Paint) {
self.push_box([RunText::Icon(name.glyph())], paint);
}
pub(super) fn push_badge(
&mut self,
children: BadgeChildren,
color: BadgeColor,
mut paint: Paint,
) {
let label = sanitize_leaf(children.label().replace('\r', " "));
let label = label.split_ascii_whitespace().collect::<Vec<_>>().join(" ");
let text = RunText::new(format!(" {label} "));
let gap = if label.is_empty() { "" } else { " " };
paint.badge = Some(color);
// An inline-flex badge forms one unbreakable box with a break on either side.
let glyph = |BadgeIcon::Icon(icon): BadgeIcon| RunText::Icon(icon.props.name.glyph());
match children {
BadgeChildren::Label(_) => self.push_box([RunText::new(format!(" {label} "))], paint),
BadgeChildren::Icon([icon]) => {
self.push_box([RunText::Space, glyph(icon), RunText::Space], paint);
}
BadgeChildren::Leading(icon, _) => self.push_box(
[
RunText::Space,
glyph(icon),
RunText::new(format!("{gap}{label} ")),
],
paint,
),
BadgeChildren::Trailing(_, icon) => self.push_box(
[
RunText::new(format!(" {label}{gap}")),
glyph(icon),
RunText::Space,
],
paint,
),
}
}
fn push_box(&mut self, parts: impl IntoIterator<Item = RunText>, paint: Paint) {
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 {
let mut chunk = Chunk::default();
for text in parts {
chunk.width_cells += span_width(&Span::raw(&*text));
chunk.runs.push(Run {
break_before: false,
text,
paint,
}],
..Chunk::default()
});
paint: paint.clone(),
});
}
self.completed.push(chunk);
}
fn finish_line(&mut self) {
@@ -617,6 +676,10 @@ pub(super) fn visit_chunks<'a>(
cells += w;
bytes += g.len();
}
// An icon can span multiple graphemes (e.g. </>) yet represents one glyph.
if bytes < text.len() && matches!(run.text, RunText::Icon(_)) {
return used;
}
if bytes > 0 && (used < limit || bytes == text.len()) {
draw(used, &text[..bytes], cells, &run.paint);
}
+64
View File
@@ -2121,3 +2121,67 @@ fn list_markers_preserve_the_surface_under_each_cell() {
}
}
}
#[test]
fn icon_and_badge_compositions_wrap_as_units() {
let icons = [
"circle",
"empty-circle",
"circle-dashed",
"arrow-up",
"arrow-down",
"arrow-left",
"arrow-right",
]
.map(|name| json!({"type":"icon","props":{"name":name}}));
let group = tree(json!({"type":"text","children":icons}));
assert_eq!(painted_rows(&group, Size::new(7, 1)), ["●○◌↑↓←→"]);
let code = json!({"type":"icon","props":{"name":"code","inline":true}});
let node = tree(json!({"type":"text","children":["AB",code]}));
assert_eq!(painted_rows(&node, Size::new(4, 2)), ["AB", "</>"]);
let icon = json!({"type":"icon","props":{"name":"arrow-right","inline":true}});
let node = tree(json!({"type":"text","children":["AB",icon]}));
assert_eq!(painted_rows(&node, Size::new(3, 1)), ["AB→"]);
for (children, expected) in [
(json!([icon]), " →"),
(json!([icon, " ok "]), " → ok"),
(json!(["ok", icon]), " ok →"),
] {
let node = tree(json!({"type":"badge","children":children}));
assert_eq!(painted_rows(&node, Size::new(12, 1)), [expected]);
}
}
#[test]
fn icons_require_a_supported_name_and_empty_children() {
for icon in [
json!({"type":"icon","props":["check",false]}),
json!({"type":"icon","props":{"name":"terminal"}}),
json!({"type":"icon","props":{"name":"spinner"}}),
json!({"type":"icon","props":{"name":"x-circle"}}),
json!({"type":"icon","props":{"name":"check"},"children":["x"]}),
json!({"type":"icon","props":{"name":{"check":null}}}),
] {
assert!(parse(icon.clone()).is_err());
assert!(parse(json!({"type":"badge","children":[icon,"ok"]})).is_err());
}
let icon = json!({"type":"icon","props":{"name":"check"},"children":[]});
let badge = json!({"type":"badge","children":[icon,"ok"]});
assert!(parse(json!({"type":"text","children":vec![badge.clone();85]})).is_ok());
assert!(parse(json!({"type":"text","children":vec![badge;86]})).is_err());
}
#[test]
fn ellipsis_never_splits_a_multi_cell_icon() {
let icon = json!({"type":"icon","props":{"name":"code","inline":true}});
for props in [json!({"maxLines":1}), json!({})] {
let node = tree(json!({"type":"text","props":props,"children":["A",icon,"B"]}));
assert_eq!(painted_rows(&node, Size::new(4, 1)), ["A…"]);
assert_eq!(painted_rows(&node, Size::new(5, 1)), ["A</>B"]);
}
let node = tree(json!({"type":"text","props":{"maxLines":1},"children":[icon,"B"]}));
assert_eq!(painted_rows(&node, Size::new(3, 1)), ["…"]);
let badge = tree(json!({"type":"badge","children":["A",icon]}));
assert_eq!(painted_rows(&badge, Size::new(5, 1)), [" A …"]);
assert_eq!(painted_rows(&badge, Size::new(6, 1)), [" A </>"]);
}
+3 -1
View File
@@ -3,6 +3,7 @@ import type {
ColElement,
BoxElement,
BadgeElement,
IconElement,
ListElement,
ListItemElement,
SpacerElement,
@@ -59,7 +60,8 @@ const emptySpacer: SpacerElement = { ...spacer, children: [] };
const invalidSpacer: SpacerElement = { ...spacer, children: ["x"] };
const badge: BadgeElement = { type: "badge", children: ["queued"] };
const passing: BadgeElement = { ...badge, props: { color: "success" }, children: ["passing"] };
const check: IconElement = { type: "icon", props: { name: "check", inline: true } };
const passing: BadgeElement = { ...badge, props: { color: "success" }, children: [check, "passing"] };
// @ts-expect-error Badges accept semantic colors.
const invalidBadge: BadgeElement = { ...badge, props: { color: "red" } };