use crate::{
icons::{CarbonIcon, Icon},
motion,
t3::{
base::{
active_after_close, endless_phase, radio_step, reduced_pulse_opacity, visually_hidden,
},
craft::{mono, rem, sans},
},
theme::color,
tokens::{self, ColorRole},
u0::primitives::parts::{
focus_ring, focus_slot, focus_visible, insert_slot_anchor, keyed_focus, vacate_slot,
},
};
use gpui_kit::{
Animation, AnimationExt as _, AnyElement, App, CursorStyle, ElementId, FocusHandle, FontWeight,
HighlightStyle, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, StyledText,
TestSupportExt as _, Window, div, prelude::FluentBuilder as _, px, relative,
};
use std::ops::Range;
use std::rc::Rc;
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AnsiColor {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
}
impl AnsiColor {
const BASE: [AnsiColor; 8] = [
Self::Black,
Self::Red,
Self::Green,
Self::Yellow,
Self::Blue,
Self::Magenta,
Self::Cyan,
Self::White,
];
const BRIGHT: [AnsiColor; 8] = [
Self::BrightBlack,
Self::BrightRed,
Self::BrightGreen,
Self::BrightYellow,
Self::BrightBlue,
Self::BrightMagenta,
Self::BrightCyan,
Self::BrightWhite,
];
pub const fn role(self) -> ColorRole {
match self {
Self::Black => ColorRole::AnsiBlack,
Self::Red => ColorRole::AnsiRed,
Self::Green => ColorRole::AnsiGreen,
Self::Yellow => ColorRole::AnsiYellow,
Self::Blue => ColorRole::AnsiBlue,
Self::Magenta => ColorRole::AnsiMagenta,
Self::Cyan => ColorRole::AnsiCyan,
Self::White => ColorRole::AnsiWhite,
Self::BrightBlack => ColorRole::AnsiBrightBlack,
Self::BrightRed => ColorRole::AnsiBrightRed,
Self::BrightGreen => ColorRole::AnsiBrightGreen,
Self::BrightYellow => ColorRole::AnsiBrightYellow,
Self::BrightBlue => ColorRole::AnsiBrightBlue,
Self::BrightMagenta => ColorRole::AnsiBrightMagenta,
Self::BrightCyan => ColorRole::AnsiBrightCyan,
Self::BrightWhite => ColorRole::AnsiBrightWhite,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AnsiRun {
pub text: String,
pub fg: Option<AnsiColor>,
pub bold: bool,
}
pub fn parse_ansi(s: &str) -> Vec<AnsiRun> {
let mut out = Vec::new();
let (mut fg, mut bold) = (None, false);
let mut push = |text: &str, fg: Option<AnsiColor>, bold: bool| {
if !text.is_empty() {
out.push(AnsiRun {
text: text.to_string(),
fg,
bold,
});
}
};
let mut last = 0;
let mut i = 0;
while let Some(at) = s[i..].find("\x1b[").map(|p| p + i) {
let params_start = at + 2;
let params_end = params_start
+ s[params_start..]
.find(|c: char| !(c.is_ascii_digit() || c == ';'))
.unwrap_or(s.len() - params_start);
if !s[params_end..].starts_with('m') {
i = at + 2;
continue;
}
push(&s[last..at], fg, bold);
let params = &s[params_start..params_end];
let params = if params.is_empty() { "0" } else { params };
for code in params.split(';').map(|p| p.parse::<u32>().unwrap_or(0)) {
match code {
0 => {
fg = None;
bold = false;
}
1 => bold = true,
30..=37 => fg = Some(AnsiColor::BASE[(code - 30) as usize]),
90..=97 => fg = Some(AnsiColor::BRIGHT[(code - 90) as usize]),
39 => fg = None,
_ => {}
}
}
last = params_end + 1;
i = last;
}
push(&s[last..], fg, bold);
out
}
pub fn ansi_highlights(runs: &[AnsiRun]) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
let mut text = String::new();
let mut styles = Vec::new();
for run in runs {
let start = text.len();
text.push_str(&run.text);
if run.fg.is_some() || run.bold {
styles.push((
start..text.len(),
HighlightStyle {
color: run.fg.map(|c| color(c.role())),
font_weight: run.bold.then_some(FontWeight::SEMIBOLD),
..Default::default()
},
));
}
}
(text, styles)
}
pub const LINE: f32 = 16.;
pub const SCREEN_PAD: (f32, f32) = (8., 12.);
pub const BLINK_PERIOD: Duration = Duration::from_millis(1000);
pub const REDUCED_PULSE: Duration = Duration::from_millis(1400);
pub fn rows_height(rows: usize) -> f32 {
rows as f32 * LINE + 16.
}
pub fn blink_opacity(t: f32) -> f32 {
if t.rem_euclid(1.) < 0.5 { 1. } else { 0. }
}
pub fn is_selected(i: usize, selection: Option<(usize, usize)>) -> bool {
selection.is_some_and(|(from, to)| i >= from && i <= to)
}
#[derive(Clone)]
pub struct TerminalTexts {
pub name: SharedString,
pub exited: Rc<dyn Fn(i32) -> SharedString>,
}
impl Default for TerminalTexts {
fn default() -> Self {
Self {
name: "Terminal".into(),
exited: Rc::new(|n| format!("[process exited with code {n}]").into()),
}
}
}
#[derive(IntoElement)]
pub struct TerminalView {
id: ElementId,
lines: Vec<SharedString>,
cursor: bool,
selection: Option<(usize, usize)>,
title: Option<SharedString>,
exited: Option<i32>,
rows: Option<usize>,
texts: TerminalTexts,
}
impl TerminalView {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
lines: Vec::new(),
cursor: true,
selection: None,
title: None,
exited: None,
rows: None,
texts: TerminalTexts::default(),
}
}
pub fn lines(mut self, lines: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.lines = lines.into_iter().map(Into::into).collect();
self
}
pub fn cursor(mut self, cursor: bool) -> Self {
self.cursor = cursor;
self
}
pub fn selection(mut self, from: usize, to: usize) -> Self {
self.selection = Some((from, to));
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn exited(mut self, code: i32) -> Self {
self.exited = Some(code);
self
}
pub fn rows(mut self, rows: usize) -> Self {
self.rows = Some(rows);
self
}
pub fn texts(mut self, texts: TerminalTexts) -> Self {
self.texts = texts;
self
}
}
pub type Highlights = Vec<(Range<usize>, HighlightStyle)>;
pub const BREAK: char = '\u{200B}';
fn holds_together(prev: char, next: char) -> bool {
prev.is_whitespace()
|| next.is_whitespace()
|| prev == '\u{200D}'
|| matches!(next,
'\u{0300}'..='\u{036F}'
| '\u{1AB0}'..='\u{1AFF}'
| '\u{1DC0}'..='\u{1DFF}'
| '\u{20D0}'..='\u{20FF}'
| '\u{200C}'..='\u{200D}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{FE20}'..='\u{FE2F}'
| '\u{1F3FB}'..='\u{1F3FF}'
| '\u{E0020}'..='\u{E007F}'
| '\u{E0100}'..='\u{E01EF}')
}
pub fn break_all(
text: &str,
styles: Vec<(Range<usize>, HighlightStyle)>,
) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
let mut out = String::with_capacity(text.len() * 2);
let mut at = vec![0; text.len() + 1];
let mut prev = None;
for (i, c) in text.char_indices() {
if prev.is_some_and(|p| !holds_together(p, c)) {
out.push(BREAK);
}
at[i] = out.len();
out.push(c);
prev = Some(c);
}
at[text.len()] = out.len();
let styles = styles
.into_iter()
.map(|(r, s)| (at[r.start]..at[r.end], s))
.collect();
(out, styles)
}
pub fn screen_line(line: &str, cursor: bool) -> (String, Highlights, Option<Range<usize>>) {
let (text, styles) = ansi_highlights(&parse_ansi(line));
let (mut text, styles) = break_all(&text, styles);
if !cursor {
return (text, styles, None);
}
if !text.is_empty() {
text.push(BREAK);
}
let at = text.len();
text.push(' ');
(text, styles, Some(at..at + 1))
}
fn line_text(
text: SharedString,
styles: &[(Range<usize>, HighlightStyle)],
cursor: Option<Range<usize>>,
opacity: f32,
) -> StyledText {
let mut styles = styles.to_vec();
if let Some(range) = cursor
&& opacity > 0.
{
let mut c = color(ColorRole::TerminalCursor);
c.a *= opacity;
styles.push((
range,
HighlightStyle {
background_color: Some(c),
..Default::default()
},
));
}
StyledText::new(text).with_highlights(styles)
}
fn cursor_line(
id: ElementId,
text: SharedString,
styles: Vec<(Range<usize>, HighlightStyle)>,
cursor: Range<usize>,
pulse: Option<f32>,
) -> AnyElement {
if let Some(opacity) = pulse {
line_text(text, &styles, Some(cursor), opacity).into_any_element()
} else {
line_text(text.clone(), &styles, Some(cursor.clone()), 1.)
.with_animation(id, Animation::new(BLINK_PERIOD).repeat(), move |_, t| {
line_text(
text.clone(),
&styles,
Some(cursor.clone()),
blink_opacity(t),
)
})
.into_any_element()
}
}
impl RenderOnce for TerminalView {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let focus = keyed_focus((id.clone(), "focus"), window, cx);
let ring = focus_visible(&focus, window);
let reduced = motion::reduced_motion(cx);
let last = self.lines.len().saturating_sub(1);
let cursor_pulse = (reduced && self.cursor && self.exited.is_none())
.then(|| reduced_pulse_opacity(endless_phase(REDUCED_PULSE, window)));
let show_cursor = self.cursor && self.exited.is_none();
let lines = self
.lines
.iter()
.enumerate()
.map(|(i, line)| {
let (text, styles, cursor) = screen_line(line, show_cursor && i == last);
let text: SharedString = text.into();
div()
.id((id.clone(), SharedString::from(format!("line-{i}"))))
.test_support()
.min_h(rem(LINE))
.when(is_selected(i, self.selection), |d| {
d.bg(color(ColorRole::TerminalSelection))
})
.child(match cursor {
Some(range) => cursor_line(
(id.clone(), "cursor").into(),
text,
styles,
range,
cursor_pulse,
),
None => StyledText::new(text)
.with_highlights(styles)
.into_any_element(),
})
})
.collect::<Vec<_>>();
let exit = self.exited.map(|code| {
div()
.mt(tokens::SPACING_03)
.text_color(color(if code != 0 {
ColorRole::AnsiRed
} else {
ColorRole::AnsiBrightBlack
}))
.child((self.texts.exited)(code))
});
let name = self.title.clone().unwrap_or(self.texts.name.clone());
div()
.relative()
.min_w_0()
.when_some(self.rows, |d, r| d.h(rem(rows_height(r))))
.child(
mono(div(), 12., 400)
.id(id)
.track_focus(&focus.clone().tab_index(0).tab_stop(true))
.size_full()
.overflow_y_scroll()
.bg(color(ColorRole::TerminalBackground))
.text_color(color(ColorRole::TerminalText))
.line_height(rem(LINE))
.child(visually_hidden(name))
.child(
div()
.flex()
.flex_col()
.py(rem(SCREEN_PAD.0))
.px(rem(SCREEN_PAD.1))
.children(lines)
.when_some(exit, |d, e| d.child(e)),
),
)
.when(ring, |d| d.child(focus_ring()))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TerminalTab {
pub title: SharedString,
pub running: bool,
pub exited: bool,
pub cwd: Option<SharedString>,
}
impl TerminalTab {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
..Default::default()
}
}
pub fn running(mut self, running: bool) -> Self {
self.running = running;
self
}
pub fn exited(mut self, exited: bool) -> Self {
self.exited = exited;
self
}
pub fn cwd(mut self, cwd: impl Into<SharedString>) -> Self {
self.cwd = Some(cwd.into());
self
}
}
pub fn terminal_tint(pct: f32) -> Hsla {
let mut c = color(ColorRole::TerminalText);
c.a *= pct / 100.;
c
}
#[derive(Clone)]
pub struct TerminalTabsTexts {
pub list: SharedString,
pub running: SharedString,
pub exited: SharedString,
pub close: Rc<dyn Fn(&str) -> SharedString>,
pub new_terminal: SharedString,
}
impl Default for TerminalTabsTexts {
fn default() -> Self {
Self {
list: "Terminals".into(),
running: "(running)".into(),
exited: " · exited".into(),
close: Rc::new(|t| format!("Close {t}").into()),
new_terminal: "New terminal".into(),
}
}
}
type IndexHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type Handler = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct TerminalTabs {
id: ElementId,
tabs: Vec<TerminalTab>,
value: Option<usize>,
default_value: usize,
on_value_change: Option<IndexHandler>,
on_new: Option<Handler>,
on_close: Option<IndexHandler>,
texts: TerminalTabsTexts,
}
impl TerminalTabs {
pub fn new(id: impl Into<ElementId>, tabs: impl IntoIterator<Item = TerminalTab>) -> Self {
Self {
id: id.into(),
tabs: tabs.into_iter().collect(),
value: None,
default_value: 0,
on_value_change: None,
on_new: None,
on_close: None,
texts: TerminalTabsTexts::default(),
}
}
pub fn value(mut self, value: usize) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, value: usize) -> Self {
self.default_value = value;
self
}
pub fn on_value_change(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_value_change = Some(Rc::new(f));
self
}
pub fn on_new(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_new = Some(Rc::new(f));
self
}
pub fn on_close(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
self.on_close = Some(Rc::new(f));
self
}
pub fn texts(mut self, texts: TerminalTabsTexts) -> Self {
self.texts = texts;
self
}
}
fn hover_state(
id: ElementId,
window: &mut Window,
cx: &mut App,
) -> (bool, impl Fn(&bool, &mut Window, &mut App) + 'static) {
let store = window.use_keyed_state(id, cx, |_, _| false);
let over = *store.read(cx);
(over, move |h: &bool, _: &mut Window, cx: &mut App| {
store.update(cx, |v, cx| {
if *v != *h {
*v = *h;
cx.notify();
}
})
})
}
impl RenderOnce for TerminalTabs {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let n = self.tabs.len();
let default = self.default_value;
let store = window.use_keyed_state((id.clone(), "value"), cx, |_, _| default);
let controlled = self.value.is_some();
let current = self
.value
.unwrap_or(*store.read(cx))
.min(n.saturating_sub(1));
let handles: Vec<FocusHandle> = (0..n)
.map(|i| {
keyed_focus(
(id.clone(), SharedString::from(format!("tab-{i}"))),
window,
cx,
)
})
.collect();
let x_handles: Vec<FocusHandle> = (0..n)
.map(|i| {
let tid: ElementId = (id.clone(), SharedString::from(format!("t{i}"))).into();
keyed_focus((tid, "x-focus"), window, cx)
})
.collect();
let slot = focus_slot((id.clone(), "slot"), window, cx);
let select: IndexHandler = {
let store = store.clone();
let on_change = self.on_value_change.clone();
Rc::new(move |i, window, cx| {
store.update(cx, |v, cx| {
*v = i;
cx.notify();
});
if let Some(f) = &on_change {
f(i, window, cx);
}
})
};
let on_close: Option<IndexHandler> = self.on_close.clone().map(|f| {
let store = store.clone();
let slot = slot.clone();
let parts: Vec<[FocusHandle; 2]> = handles
.iter()
.cloned()
.zip(x_handles.iter().cloned())
.map(|(t, x)| [t, x])
.collect();
Rc::new(move |i, window: &mut Window, cx: &mut App| {
if let Some(p) = parts.get(i) {
vacate_slot(&slot, i, p, window, cx);
}
if !controlled {
store.update(cx, |v, cx| {
*v = active_after_close(current, i, n);
cx.notify();
});
}
f(i, window, cx)
}) as IndexHandler
});
let rule = terminal_tint(14.);
let tabs = self
.tabs
.iter()
.enumerate()
.map(|(i, tab)| {
let tid: ElementId = (id.clone(), SharedString::from(format!("t{i}"))).into();
let on = i == current;
let focus = handles[i].clone();
let ring = focus_visible(&focus, window);
let (x_over, x_hover) = hover_state((tid.clone(), "x-hover").into(), window, cx);
let x_focus = x_handles[i].clone();
let x_ring = focus_visible(&x_focus, window);
let pick = select.clone();
let keys = select.clone();
let handles = handles.clone();
let close = on_close.clone();
let close_key = on_close.clone();
let glyph: AnyElement = if tab.running {
div()
.flex_none()
.size(px(6.))
.rounded_full()
.bg(color(ColorRole::AnsiGreen))
.into_any_element()
} else {
Icon::carbon(CarbonIcon::Terminal)
.size_length(rem(14.))
.color(color(ColorRole::TerminalText))
.into_any_element()
};
div()
.relative()
.flex()
.flex_none()
.items_center()
.border_r_1()
.border_color(rule)
.when(on, |d| {
d.bg(terminal_tint(9.)).child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.h(px(2.))
.bg(color(ColorRole::AnsiBlue)),
)
})
.child(
sans(gpui_kit::base::Button::new(tid.clone()), 12., 400)
.track_focus(&focus)
.tab_stop(on)
.aria_selected(on)
.relative()
.flex()
.items_center()
.h_full()
.gap(tokens::SPACING_02)
.pl(tokens::SPACING_04)
.pr(tokens::SPACING_02)
.opacity(if on { 1. } else { 0.7 })
.cursor(CursorStyle::PointingHand)
.on_click(move |_, w, cx| pick(i, w, cx))
.on_key_down(move |e: &KeyDownEvent, window, cx| {
let key = e.keystroke.key.as_str();
let step = match key {
"right" | "left" => radio_step(key, n, Some(i)),
_ => None,
};
if let Some(next) = step {
keys(next, window, cx);
window.focus(&handles[next], cx);
cx.stop_propagation();
} else if key == "delete"
&& let Some(f) = &close_key
{
f(i, window, cx);
cx.stop_propagation();
}
})
.child(glyph)
.child(tab.title.clone())
.when(tab.running, |b| {
b.child(visually_hidden(self.texts.running.clone()))
})
.when(tab.exited, |b| {
b.child(div().opacity(0.6).child(self.texts.exited.clone()))
})
.when(ring, |b| b.child(focus_ring())),
)
.child(
gpui_kit::base::Button::new((tid.clone(), "x"))
.track_focus(&x_focus)
.tab_stop(false)
.accessibility_label((self.texts.close)(&tab.title))
.relative()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(rem(20.))
.mr(tokens::SPACING_02)
.opacity(if x_over { 1. } else { 0.6 })
.when(x_over, |b| b.bg(rule))
.cursor(CursorStyle::PointingHand)
.on_hover(x_hover)
.on_click(move |_, w, cx| {
if let Some(f) = &close {
f(i, w, cx);
}
})
.child(
Icon::carbon(CarbonIcon::Close)
.size_length(rem(12.))
.color(color(ColorRole::TerminalText)),
)
.when(x_ring, |b| b.child(focus_ring())),
)
})
.map(IntoElement::into_any_element)
.collect::<Vec<_>>();
let mut tabs = tabs;
insert_slot_anchor(&mut tabs, (id.clone(), "anchor"), &slot, cx);
let (new_over, new_hover) = hover_state((id.clone(), "new-hover").into(), window, cx);
let new_focus = keyed_focus((id.clone(), "new-focus"), window, cx);
let new_ring = focus_visible(&new_focus, window);
let on_new = self.on_new.clone();
let row = crate::density::current().row();
let cwd = self.tabs.get(current).and_then(|t| t.cwd.clone());
div()
.id(id.clone())
.flex()
.items_stretch()
.h(row)
.min_w_0()
.bg(color(ColorRole::TerminalBackground))
.text_color(color(ColorRole::TerminalText))
.border_b_1()
.border_color(rule)
.child(visually_hidden(self.texts.list.clone()))
.child(
div()
.id((id.clone(), "list"))
.flex()
.items_stretch()
.min_w_0()
.overflow_x_scroll()
.children(tabs),
)
.child(
gpui_kit::base::Button::new((id.clone(), "new"))
.track_focus(&new_focus)
.accessibility_label(self.texts.new_terminal.clone())
.relative()
.flex()
.flex_none()
.items_center()
.justify_center()
.w(row)
.h(row)
.when(new_over, |b| b.bg(terminal_tint(9.)))
.cursor(CursorStyle::PointingHand)
.on_hover(new_hover)
.on_click(move |_, w, cx| {
if let Some(f) = &on_new {
f(w, cx);
}
})
.child(
Icon::carbon(CarbonIcon::Add)
.size_length(rem(16.))
.color(color(ColorRole::TerminalText)),
)
.when(new_ring, |b| b.child(focus_ring())),
)
.child(div().flex_1())
.when_some(cwd, |d, cwd| {
d.child(
mono(div(), 12., 400)
.self_center()
.min_w_0()
.max_w(relative(0.4))
.pr(tokens::SPACING_04)
.opacity(0.6)
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis_start()
.child(cwd),
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn run(text: &str, fg: Option<AnsiColor>, bold: bool) -> AnsiRun {
AnsiRun {
text: text.into(),
fg,
bold,
}
}
#[test]
fn parse_ansi_follows_the_reference() {
use AnsiColor::*;
assert_eq!(
parse_ansi(" \x1b[32mVITE\x1b[0m v6.0.3 ready in \x1b[1m412\x1b[0m ms"),
vec![
run(" ", None, false),
run("VITE", Some(Green), false),
run(" v6.0.3 ready in ", None, false),
run("412", None, true),
run(" ms", None, false),
]
);
assert_eq!(
parse_ansi("\x1b[90m10:42\x1b[39m x \x1b[1;33mw\x1b[m!"),
vec![
run("10:42", Some(BrightBlack), false),
run(" x ", None, false),
run("w", Some(Yellow), true),
run("!", None, false),
]
);
assert_eq!(parse_ansi("\x1b[1;ma"), vec![run("a", None, false)]);
assert_eq!(parse_ansi("\x1b[2Kx"), vec![run("\x1b[2Kx", None, false)]);
assert_eq!(parse_ansi(""), vec![]);
}
#[test]
fn ansi_colors_use_their_tokens() {
assert_eq!(AnsiColor::Red.role(), ColorRole::AnsiRed);
assert_eq!(AnsiColor::BrightCyan.role(), ColorRole::AnsiBrightCyan);
let (text, styles) = ansi_highlights(&parse_ansi("a\x1b[36mb\x1b[0m"));
assert_eq!(text, "ab");
assert_eq!(styles.len(), 1);
assert_eq!(styles[0].0, 1..2);
}
#[test]
fn break_all_puts_a_break_between_characters() {
let b = BREAK;
let (text, _) = break_all("ab cd", vec![]);
assert_eq!(text, format!("a{b}b c{b}d"));
let style = HighlightStyle::default();
let (text, styles) = break_all("xyz", vec![(1..3, style)]);
assert_eq!(&text[styles[0].0.clone()], format!("y{b}z"));
assert_eq!(break_all("e\u{301}", vec![]).0, "e\u{301}");
assert_eq!(break_all("❤\u{fe0f}", vec![]).0, "❤\u{fe0f}");
assert_eq!(break_all("", vec![]).0, "");
}
#[test]
fn screen_line_ends_in_the_cursor() {
crate::theme::tests_set(crate::CarbonTheme::White);
let b = BREAK;
let (text, styles, cursor) = screen_line("\x1b[32mok\x1b[0m", true);
assert_eq!(text, format!("o{b}k{b} "));
assert_eq!(&text[styles[0].0.clone()], format!("o{b}k"));
assert_eq!(cursor, Some(text.len() - 1..text.len()));
let (text, _, _) = screen_line("$ ", true);
assert_eq!(text, format!("$ {b} "));
assert_eq!(screen_line("", true).0, " ");
assert_eq!(screen_line("ab", false).2, None);
}
#[test]
fn geometry_and_timing() {
assert_eq!(rows_height(10), 176.);
assert_eq!(blink_opacity(0.2), 1.);
assert_eq!(blink_opacity(0.6), 0.);
assert!(is_selected(2, Some((2, 3))));
assert!(is_selected(3, Some((2, 3))));
assert!(!is_selected(4, Some((2, 3))));
assert!(!is_selected(0, None));
}
#[test]
fn tints_mix_terminal_text() {
crate::theme::tests_set(crate::CarbonTheme::White);
let t = terminal_tint(14.);
let base = color(ColorRole::TerminalText);
assert_eq!((t.h, t.s, t.l), (base.h, base.s, base.l));
assert!((t.a - base.a * 0.14).abs() < 1e-6);
}
}