use super::form::rem;
use super::overlay::floating_shadow;
use super::scroll_area::{ScrollArea, ScrollAxes, ScrollFocusRing};
use crate::{
icons::{CarbonIcon, Icon, IconSize},
motion::{self, Curve, Motion, Speed},
theme::{LayerLevel, color},
tokens::{ColorRole, FontFamilyKey, TypeStyle},
typography::{TypeStyled as _, font},
};
use gpui_kit::{
AnyElement, App, ClipboardItem, CursorStyle, ElementId, FocusHandle, Hsla,
InteractiveElement as _, IntoElement, ParentElement, RenderOnce, ScrollHandle, SharedString,
StatefulInteractiveElement as _, Styled, Window, deferred, div, prelude::FluentBuilder as _,
px, relative,
};
use std::time::{Duration, Instant};
pub const FEEDBACK_TIMEOUT: Duration = Duration::from_millis(2000);
pub const FEEDBACK_FADE: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);
const HOVER: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast01);
pub const COPY_FEEDBACK_BELOW: bool = true;
pub const MAX_COLLAPSED_ROWS: usize = 15;
pub const ROW: f32 = 16.;
pub fn feedback_opacity(elapsed: Duration) -> Option<f32> {
let fade = FEEDBACK_FADE.speed.duration().as_secs_f32();
let t = elapsed.as_secs_f32();
let hold = FEEDBACK_TIMEOUT.as_secs_f32();
let ease = |x: f32| FEEDBACK_FADE.curve.ease(x);
if t < fade {
Some(ease(t / fade))
} else if t < hold {
Some(1.)
} else if t < hold + fade {
Some(1. - ease((t - hold) / fade))
} else {
None
}
}
pub fn button_background(level: LayerLevel, hovered: bool, pressed: bool) -> Hsla {
color(if pressed {
level.layer_active()
} else if hovered {
level.layer_hover()
} else {
level.layer()
})
}
#[derive(Default)]
struct CopyState {
hovered: bool,
pressed: bool,
copied_at: Option<Instant>,
}
fn feedback_box(text: SharedString, opacity: f32, below: bool) -> impl IntoElement {
let bubble = div()
.flex_none()
.px(rem(16.))
.py(rem(3.))
.rounded(px(2.))
.bg(color(ColorRole::BackgroundInverse))
.text_color(color(ColorRole::TextInverse))
.type_style(TypeStyle::BodyCompact01)
.whitespace_nowrap()
.shadow(floating_shadow())
.opacity(opacity)
.child(text);
let anchor = div()
.absolute()
.left(relative(0.5))
.w(px(0.))
.flex()
.flex_col()
.items_center()
.map(|this| {
if below {
this.top(relative(1.)).pt(rem(4.))
} else {
this.bottom(relative(1.)).pb(rem(4.))
}
})
.child(bubble);
deferred(anchor).with_priority(6000)
}
fn keyed_focus(
id: &ElementId,
key: &'static str,
window: &mut Window,
cx: &mut App,
) -> FocusHandle {
window
.use_keyed_state((id.clone(), key), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone()
}
fn copy_state(
id: &ElementId,
window: &mut Window,
cx: &mut App,
) -> (gpui_kit::Entity<CopyState>, Option<f32>) {
let state = window.use_keyed_state((id.clone(), "copy"), cx, |_, _| CopyState::default());
let opacity = state
.read(cx)
.copied_at
.and_then(|at| feedback_opacity(at.elapsed()));
if opacity.is_some() {
window.request_animation_frame();
}
(state, opacity)
}
fn press_handlers(
el: gpui_kit::Stateful<gpui_kit::Div>,
state: &gpui_kit::Entity<CopyState>,
) -> gpui_kit::Stateful<gpui_kit::Div> {
let (a, b, c) = (state.clone(), state.clone(), state.clone());
el.on_hover(move |h, _, cx| {
a.update(cx, |s, cx| {
s.hovered = *h;
if !*h {
s.pressed = false;
}
cx.notify();
})
})
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, _, cx| {
b.update(cx, |s, cx| {
s.pressed = true;
cx.notify();
})
})
.on_mouse_up(gpui_kit::MouseButton::Left, move |_, _, cx| {
c.update(cx, |s, cx| {
s.pressed = false;
cx.notify();
})
})
}
#[derive(IntoElement)]
pub struct CopyButton {
id: ElementId,
text: SharedString,
label: SharedString,
feedback: SharedString,
size: f32,
level: LayerLevel,
disabled: bool,
quiet: bool,
focus: Option<FocusHandle>,
}
impl CopyButton {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
label: SharedString::default(),
feedback: SharedString::default(),
size: 40.,
level: LayerLevel::One,
disabled: false,
quiet: false,
focus: None,
}
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus = Some(handle.clone());
self
}
pub fn quiet(mut self, quiet: bool) -> Self {
self.quiet = quiet;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn feedback(mut self, feedback: impl Into<SharedString>) -> Self {
self.feedback = feedback.into();
self
}
pub fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
pub fn layer(mut self, level: LayerLevel) -> Self {
self.level = level;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl RenderOnce for CopyButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let (state, opacity) = copy_state(&id, window, cx);
let focus = self
.focus
.clone()
.unwrap_or_else(|| keyed_focus(&id, "focus", window, cx));
let focused = focus.is_focused(window);
let (hovered, pressed) = {
let s = state.read(cx);
(s.hovered && !self.disabled, s.pressed && !self.disabled)
};
let bg = if self.quiet && !pressed {
if hovered && !self.disabled {
color(ColorRole::BackgroundHover)
} else {
gpui_kit::transparent_black()
}
} else if self.disabled {
color(self.level.layer())
} else {
button_background(self.level, hovered, pressed)
};
let bg = motion::animate_color((id.clone(), "bg"), bg, HOVER, window, cx);
let text = self.text.clone();
let on_copy = state.clone();
let button = gpui_kit::base::Button::new(id.clone())
.track_focus(&focus)
.disabled(self.disabled)
.accessibility_label(self.label.clone())
.relative()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(rem(self.size))
.bg(bg)
.cursor(if self.disabled {
CursorStyle::OperationNotAllowed
} else {
CursorStyle::PointingHand
})
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(text.to_string()));
on_copy.update(cx, |s, cx| {
s.copied_at = Some(Instant::now());
cx.notify();
});
})
.child(
Icon::carbon(CarbonIcon::Copy)
.size(IconSize::S16)
.color(color(if self.disabled {
ColorRole::IconDisabled
} else {
ColorRole::IconPrimary
})),
)
.when(focused, |this| {
this.child(
div()
.absolute()
.top_0()
.left_0()
.size_full()
.border_2()
.border_color(color(ColorRole::Focus)),
)
})
.when_some(opacity, |this, opacity| {
this.child(feedback_box(
self.feedback.clone(),
opacity,
COPY_FEEDBACK_BELOW,
))
});
press_handlers(div().id((id, "press")), &state)
.flex_none()
.child(button)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LineVariant {
Added,
Removed,
Highlighted,
}
#[derive(Clone, Debug, PartialEq)]
pub struct CodeLine {
pub text: SharedString,
pub variant: Option<LineVariant>,
}
impl CodeLine {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: text.into(),
variant: None,
}
}
pub fn added(text: impl Into<SharedString>) -> Self {
Self {
variant: Some(LineVariant::Added),
..Self::new(text)
}
}
pub fn removed(text: impl Into<SharedString>) -> Self {
Self {
variant: Some(LineVariant::Removed),
..Self::new(text)
}
}
pub fn highlighted(text: impl Into<SharedString>) -> Self {
Self {
variant: Some(LineVariant::Highlighted),
..Self::new(text)
}
}
}
pub fn split_code(code: &str) -> Vec<CodeLine> {
code.strip_suffix('\n')
.unwrap_or(code)
.split('\n')
.map(|l| CodeLine::new(l.to_string()))
.collect()
}
pub fn line_colors(variant: Option<LineVariant>) -> (Option<Hsla>, Hsla) {
use ColorRole::*;
match variant {
Some(LineVariant::Added) => (Some(color(DiffAddedBackground)), color(SupportSuccess)),
Some(LineVariant::Removed) => (Some(color(DiffRemovedBackground)), color(SupportError)),
Some(LineVariant::Highlighted) => (Some(color(Highlight)), color(TextSecondary)),
None => (None, color(TextSecondary)),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CodeBlockSize {
#[default]
Default,
Sm,
}
impl CodeBlockSize {
pub const ALL: [CodeBlockSize; 2] = [Self::Default, Self::Sm];
pub const fn name(self) -> &'static str {
match self {
Self::Default => "default",
Self::Sm => "sm",
}
}
pub const fn metrics(self) -> (f32, f32, f32) {
match self {
Self::Default => (14., 20., 16.),
Self::Sm => (12., 16., 8.),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CodeBlockVariant {
#[default]
Default,
Destructive,
}
impl CodeBlockVariant {
pub const ALL: [CodeBlockVariant; 2] = [Self::Default, Self::Destructive];
pub const fn name(self) -> &'static str {
match self {
Self::Default => "default",
Self::Destructive => "destructive",
}
}
}
#[derive(IntoElement)]
pub struct CodeBlock {
id: ElementId,
title: Option<SharedString>,
language: Option<SharedString>,
lines: Vec<CodeLine>,
line_numbers: bool,
start_line: usize,
wrap: bool,
size: CodeBlockSize,
variant: CodeBlockVariant,
footer: Option<AnyElement>,
copy_label: SharedString,
copy_feedback: SharedString,
}
impl CodeBlock {
pub fn new(id: impl Into<ElementId>, code: &str) -> Self {
Self {
id: id.into(),
title: None,
language: None,
lines: split_code(code),
line_numbers: false,
start_line: 1,
wrap: false,
size: CodeBlockSize::Default,
variant: CodeBlockVariant::Default,
footer: None,
copy_label: SharedString::default(),
copy_feedback: SharedString::default(),
}
}
pub fn lines(mut self, lines: impl IntoIterator<Item = CodeLine>) -> Self {
self.lines = lines.into_iter().collect();
self
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn language(mut self, language: impl Into<SharedString>) -> Self {
self.language = Some(language.into());
self
}
pub fn line_numbers(mut self, on: bool) -> Self {
self.line_numbers = on;
self
}
pub fn start_line(mut self, start: usize) -> Self {
self.start_line = start;
self
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
pub fn size(mut self, size: CodeBlockSize) -> Self {
self.size = size;
self
}
pub fn variant(mut self, variant: CodeBlockVariant) -> Self {
self.variant = variant;
self
}
pub fn footer(mut self, footer: impl IntoElement) -> Self {
self.footer = Some(footer.into_any_element());
self
}
pub fn copy_texts(
mut self,
label: impl Into<SharedString>,
feedback: impl Into<SharedString>,
) -> Self {
self.copy_label = label.into();
self.copy_feedback = feedback.into();
self
}
pub fn raw(&self) -> String {
self.lines
.iter()
.map(|l| l.text.as_ref())
.collect::<Vec<_>>()
.join("\n")
}
}
impl RenderOnce for CodeBlock {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let raw = self.raw();
let (font_size, line_height, pad_y) = self.size.metrics();
let has_header = self.title.is_some() || self.language.is_some();
let marks = self.line_numbers || self.lines.iter().any(|l| l.variant.is_some());
let copy = CopyButton::new((self.id.clone(), "copy"), raw.clone())
.label(self.copy_label.clone())
.feedback(self.copy_feedback.clone())
.layer(LayerLevel::One);
let rule = color(ColorRole::BorderSubtle01);
let mono = font(FontFamilyKey::Mono, 400);
let header = has_header.then(|| {
div()
.flex()
.flex_row()
.items_center()
.gap(rem(8.))
.h(rem(40.))
.pl(rem(16.))
.border_b_1()
.border_color(rule)
.child(
div()
.flex_1()
.min_w_0()
.font(font(FontFamilyKey::Sans, 600))
.text_size(rem(14.))
.line_height(rem(18.))
.overflow_hidden()
.text_ellipsis()
.whitespace_nowrap()
.children(self.title.clone()),
)
.when_some(self.language.clone(), |this, lang| {
this.child(
div()
.type_style(TypeStyle::Label01)
.text_color(color(ColorRole::TextSecondary))
.child(lang),
)
})
.child(copy)
});
let start = self.start_line;
let line_numbers = self.line_numbers;
let wrap = self.wrap;
let rows = self.lines.into_iter().enumerate().map(move |(i, line)| {
let (bg, mark_color) = line_colors(line.variant);
let mark = match line.variant {
Some(LineVariant::Added) => "+",
Some(LineVariant::Removed) => "−",
_ => "",
};
div()
.flex()
.flex_row()
.px(rem(16.))
.when(!wrap, |this| this.min_w_full().flex_none())
.when_some(bg, |this, bg| this.bg(bg))
.when(line_numbers, |this| {
this.child(
div()
.flex_none()
.w(rem(40.))
.pr(rem(12.))
.flex()
.justify_end()
.text_color(color(ColorRole::TextHelper))
.child(SharedString::from((start + i).to_string())),
)
})
.when(marks, |this| {
this.child(
div()
.flex_none()
.w(rem(16.))
.text_color(mark_color)
.child(mark),
)
})
.child(
div()
.when(wrap, |this| this.flex_1().min_w_0())
.when(!wrap, |this| this.whitespace_nowrap())
.child(if line.text.is_empty() {
SharedString::from(" ")
} else {
line.text
}),
)
});
let pre = code_scroller((self.id.clone(), "pre")).child(
div()
.flex()
.flex_col()
.py(rem(pad_y))
.font(mono)
.text_size(rem(font_size))
.line_height(rem(line_height))
.children(rows),
);
div()
.relative()
.flex()
.flex_col()
.w_full()
.bg(color(ColorRole::Layer01))
.text_color(color(ColorRole::TextPrimary))
.children(header)
.child(pre)
.when(!has_header, |this| {
this.child(
div().absolute().top_0().right_0().child(
CopyButton::new((self.id.clone(), "copy-float"), raw)
.label(self.copy_label.clone())
.feedback(self.copy_feedback.clone()),
),
)
})
.when_some(self.footer, |this, footer| {
this.child(
div()
.px(rem(16.))
.py(rem(8.))
.border_t_1()
.border_color(rule)
.type_style(TypeStyle::Label01)
.text_color(color(ColorRole::TextSecondary))
.child(footer),
)
})
.when(self.variant == CodeBlockVariant::Destructive, |this| {
this.child(
div()
.absolute()
.top_0()
.left_0()
.h_full()
.w(px(3.))
.bg(color(ColorRole::SupportError)),
)
})
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SnippetType {
#[default]
Single,
Multi,
Inline,
}
impl SnippetType {
pub const ALL: [SnippetType; 3] = [Self::Single, Self::Multi, Self::Inline];
pub const fn name(self) -> &'static str {
match self {
Self::Single => "single",
Self::Multi => "multi",
Self::Inline => "inline",
}
}
}
pub fn collapsed_height(rows: usize) -> Option<f32> {
(rows > MAX_COLLAPSED_ROWS).then_some(MAX_COLLAPSED_ROWS as f32 * ROW)
}
pub fn container_height(rows: usize, expanded: bool) -> f32 {
let natural = rows as f32 * ROW + 24.;
match collapsed_height(rows) {
Some(c) if !expanded => c,
Some(_) => natural + 16.,
None => natural,
}
}
#[derive(IntoElement)]
pub struct CodeSnippet {
id: ElementId,
kind: SnippetType,
code: SharedString,
level: LayerLevel,
disabled: bool,
wrap: bool,
copy_label: SharedString,
copy_feedback: SharedString,
show_more: SharedString,
show_less: SharedString,
focus: Option<FocusHandle>,
scroll: Option<ScrollHandle>,
}
impl CodeSnippet {
pub fn new(id: impl Into<ElementId>, kind: SnippetType, code: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
kind,
code: code.into(),
level: LayerLevel::One,
disabled: false,
wrap: false,
copy_label: SharedString::default(),
copy_feedback: SharedString::default(),
show_more: SharedString::default(),
show_less: SharedString::default(),
focus: None,
scroll: None,
}
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus = Some(handle.clone());
self
}
pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
self.scroll = Some(handle.clone());
self
}
pub fn layer(mut self, level: LayerLevel) -> Self {
self.level = level;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
pub fn copy_texts(
mut self,
label: impl Into<SharedString>,
feedback: impl Into<SharedString>,
) -> Self {
self.copy_label = label.into();
self.copy_feedback = feedback.into();
self
}
pub fn expand_texts(
mut self,
more: impl Into<SharedString>,
less: impl Into<SharedString>,
) -> Self {
self.show_more = more.into();
self.show_less = less.into();
self
}
}
fn code_01() -> (gpui_kit::Font, gpui_kit::Rems, gpui_kit::Rems) {
(font(FontFamilyKey::Mono, 400), rem(12.), rem(16.))
}
impl RenderOnce for CodeSnippet {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let (mono, size, lh) = code_01();
let text_color = color(if self.disabled {
ColorRole::TextDisabled
} else {
ColorRole::TextPrimary
});
let layer = color(self.level.layer());
match self.kind {
SnippetType::Inline => {
let (state, opacity) = copy_state(&id, window, cx);
let focus = window
.use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let focused = focus.is_focused(window);
let (h, p) = {
let s = state.read(cx);
(s.hovered && !self.disabled, s.pressed && !self.disabled)
};
let bg = motion::animate_color(
(id.clone(), "bg"),
button_background(self.level, h, p),
HOVER,
window,
cx,
);
let code = self.code.clone();
let on_copy = state.clone();
let chip = gpui_kit::base::Button::new(id.clone())
.track_focus(&focus)
.disabled(self.disabled)
.accessibility_label(self.copy_label.clone())
.relative()
.flex()
.items_center()
.h(rem(20.))
.px(rem(8.))
.rounded(px(4.))
.border_1()
.border_color(if focused {
color(ColorRole::Focus)
} else {
Hsla::transparent_black()
})
.bg(bg)
.text_color(text_color)
.font(mono)
.text_size(size)
.line_height(lh)
.whitespace_nowrap()
.cursor(CursorStyle::PointingHand)
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(code.to_string()));
on_copy.update(cx, |s, cx| {
s.copied_at = Some(Instant::now());
cx.notify();
});
})
.child(self.code.clone())
.when_some(opacity, |this, o| {
this.child(feedback_box(self.copy_feedback.clone(), o, true))
});
press_handlers(div().id((id, "press")), &state)
.flex_none()
.child(chip)
.into_any_element()
}
SnippetType::Single => {
let focus = self
.focus
.clone()
.unwrap_or_else(|| keyed_focus(&id, "code-focus", window, cx));
let copy_focus = keyed_focus(&id, "copy-focus", window, cx);
let focus_within = focus.is_focused(window) || copy_focus.is_focused(window);
let container = code_scroller((id.clone(), "scroll"))
.focusable(!self.disabled)
.track_focus(&focus)
.focus_ring(ScrollFocusRing::Focus)
.when_some(self.scroll.clone(), |this, handle| {
this.track_scroll(&handle)
})
.flex_1()
.min_w_0()
.h_full()
.child(
div()
.flex_1()
.flex()
.items_center()
.pl(rem(16.))
.pr(rem(32.))
.font(mono)
.text_size(size)
.line_height(lh)
.whitespace_nowrap()
.child(self.code.clone()),
);
div()
.relative()
.flex()
.items_center()
.w_full()
.max_w(rem(768.))
.h(rem(40.))
.pr(rem(40.))
.bg(layer)
.text_color(text_color)
.child(container)
.when(!focus_within, |this| this.child(fade_end(layer)))
.child(
div().absolute().top_0().right_0().child(
CopyButton::new((id.clone(), "copy"), self.code.clone())
.track_focus(©_focus)
.label(self.copy_label.clone())
.feedback(self.copy_feedback.clone())
.layer(self.level)
.disabled(self.disabled),
),
)
.into_any_element()
}
SnippetType::Multi => {
let lines: Vec<SharedString> = self
.code
.split('\n')
.map(|l| SharedString::from(l.to_string()))
.collect();
let collapsed = collapsed_height(lines.len());
let expanded_state =
window.use_keyed_state((id.clone(), "expanded"), cx, |_, _| false);
let expanded = *expanded_state.read(cx);
let height = motion::animate(
(id.clone(), "height"),
container_height(lines.len(), expanded),
Motion::new(Curve::ProductiveStandard, Speed::Moderate01).spatial(true),
window,
cx,
);
let rotation = motion::animate(
(id.clone(), "chevron"),
if expanded { std::f32::consts::PI } else { 0. },
if expanded {
Motion::new(Curve::ProductiveStandard, Speed::Moderate02).spatial(true)
} else {
Motion::new(Curve::ProductiveStandard, Speed::Moderate01).spatial(true)
},
window,
cx,
);
let wrap = self.wrap;
let disabled = self.disabled;
let focus = self
.focus
.clone()
.unwrap_or_else(|| keyed_focus(&id, "code-focus", window, cx));
let code_focused = focus.is_focused(window);
let expand_button = collapsed.map(|_| {
let expand_focus = keyed_focus(&id, "expand-focus", window, cx);
let expand_focused = expand_focus.is_focused(window);
let hovered =
window.use_keyed_state((id.clone(), "expand-hover"), cx, |_, _| false);
let bg = motion::animate_color(
(id.clone(), "expand-bg"),
button_background(self.level, *hovered.read(cx), false),
HOVER,
window,
cx,
);
let toggle = expanded_state.clone();
gpui_kit::base::Button::new((id.clone(), "expand"))
.track_focus(&expand_focus)
.disabled(disabled)
.absolute()
.bottom_0()
.right_0()
.flex()
.items_center()
.h(rem(32.))
.px(rem(16.))
.bg(bg)
.text_color(color(ColorRole::TextPrimary))
.type_style(TypeStyle::BodyCompact01)
.cursor(CursorStyle::PointingHand)
.on_hover(move |h, _, cx| {
hovered.update(cx, |v, cx| {
*v = *h;
cx.notify();
})
})
.on_click(move |_, _, cx| {
toggle.update(cx, |v, cx| {
*v = !*v;
cx.notify();
})
})
.child(if expanded {
self.show_less.clone()
} else {
self.show_more.clone()
})
.child(
div().ml(rem(8.)).child(
Icon::carbon(CarbonIcon::ChevronDown)
.size(IconSize::S16)
.color(color(ColorRole::IconPrimary))
.rotate(gpui_kit::radians(rotation)),
),
)
.when(expand_focused, |this| {
this.child(
div()
.absolute()
.top_0()
.left_0()
.size_full()
.border_2()
.border_color(color(ColorRole::Focus)),
)
})
});
div()
.relative()
.w_full()
.max_w(rem(768.))
.p(rem(16.))
.bg(layer)
.text_color(text_color)
.child(
div()
.relative()
.w_full()
.child(
div()
.w_full()
.h(rem(height))
.overflow_hidden()
.flex()
.flex_col()
.child(
code_scroller((id.clone(), "scroll"))
.focusable(!disabled)
.track_focus(&focus)
.focus_ring(ScrollFocusRing::Hidden)
.when_some(self.scroll.clone(), |this, handle| {
this.track_scroll(&handle)
})
.h_full()
.child(
div()
.flex()
.flex_col()
.pr(rem(24.))
.font(mono)
.text_size(size)
.line_height(lh)
.children(lines.into_iter().map(move |l| {
div()
.when(!wrap, |this| {
this.whitespace_nowrap()
})
.child(if l.is_empty() {
SharedString::from(" ")
} else {
l
})
})),
),
),
)
.when(code_focused, |this| {
this.child(
div()
.absolute()
.top(px(-2.))
.left(px(-2.))
.right(px(-2.))
.bottom(px(-2.))
.border_2()
.border_color(color(ColorRole::Focus)),
)
}),
)
.child(
div().absolute().top(rem(8.)).right(rem(8.)).child(
CopyButton::new((id.clone(), "copy"), self.code.clone())
.size(32.)
.label(self.copy_label.clone())
.feedback(self.copy_feedback.clone())
.layer(self.level)
.disabled(self.disabled),
),
)
.children(expand_button)
.into_any_element()
}
}
}
}
fn code_scroller(id: impl Into<ElementId>) -> ScrollArea {
ScrollArea::new(id)
.axes(ScrollAxes::Horizontal)
.focusable(false)
.restrict_wheel_to_axis()
.w_full()
}
fn fade_end(layer: Hsla) -> impl IntoElement {
div()
.absolute()
.top_0()
.right(rem(40.))
.h_full()
.w(rem(32.))
.bg(gpui_kit::linear_gradient(
90.,
gpui_kit::linear_color_stop(layer.opacity(0.), 0.),
gpui_kit::linear_color_stop(layer, 1.),
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn code_splits_like_index_jsx() {
let lines = split_code("npm install @carbon/react\nnpm install carbon-ui\n");
assert_eq!(lines.len(), 2);
let block = CodeBlock::new("c", "a\nb");
assert_eq!(block.raw(), "a\nb");
assert_eq!(CodeBlockSize::Default.metrics(), (14., 20., 16.));
assert_eq!(CodeBlockSize::Sm.metrics(), (12., 16., 8.));
}
#[test]
fn colors_follow_css() {
crate::theme::tests_set(CarbonTheme::White);
let (bg, mark) = line_colors(Some(LineVariant::Added));
assert!(bg.is_some());
assert_eq!(hex(mark), "#24a148");
let (_, mark) = line_colors(Some(LineVariant::Removed));
assert_eq!(hex(mark), "#da1e28");
assert_eq!(
hex(button_background(LayerLevel::One, false, false)),
"#f4f4f4"
);
assert_eq!(
hex(button_background(LayerLevel::One, true, false)),
"#e8e8e8"
);
assert_eq!(
hex(button_background(LayerLevel::One, true, true)),
"#c6c6c6"
);
}
#[test]
fn feedback_timing_and_collapse() {
assert_eq!(feedback_opacity(Duration::ZERO), Some(0.));
assert_eq!(feedback_opacity(Duration::from_millis(500)), Some(1.));
let out = feedback_opacity(Duration::from_millis(2055)).unwrap();
assert!(out > 0. && out < 1.);
assert_eq!(feedback_opacity(Duration::from_millis(2111)), None);
assert_eq!(collapsed_height(10), None);
assert_eq!(collapsed_height(20), Some(240.));
assert_eq!(container_height(20, false), 15. * ROW);
assert_eq!(container_height(20, true), 20. * ROW + 24. + 16.);
assert_eq!(container_height(4, false), 4. * ROW + 24.);
}
#[test]
fn copy_feedback_shows_below_like_carbon() {
const { assert!(COPY_FEEDBACK_BELOW) };
}
}