use std::{cell::RefCell, rc::Rc};
use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, PathBuilder, RenderOnce, Role,
SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
use crate::actions::copy_button::CopyButton;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CodeTokenKind {
Plain,
Comment,
String,
Number,
Keyword,
Type,
Function,
Property,
Punctuation,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CodeSpan {
pub kind: CodeTokenKind,
pub text: String,
}
const KEYWORDS: &[&str] = &[
"abstract",
"as",
"async",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"crate",
"default",
"delete",
"do",
"else",
"enum",
"export",
"extends",
"extern",
"false",
"finally",
"fn",
"for",
"from",
"function",
"get",
"if",
"impl",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"new",
"null",
"of",
"private",
"protected",
"pub",
"public",
"readonly",
"ref",
"return",
"self",
"Self",
"set",
"static",
"struct",
"super",
"switch",
"throw",
"trait",
"true",
"try",
"type",
"typeof",
"undefined",
"unsafe",
"use",
"var",
"void",
"where",
"while",
"with",
"yield",
"SELECT",
"FROM",
"WHERE",
"INSERT",
"UPDATE",
"DELETE",
];
const TYPES: &[&str] = &[
"Array",
"Boolean",
"Date",
"Error",
"Map",
"Number",
"Promise",
"Record",
"Set",
"String",
"Vec",
"Option",
"Result",
"Box",
"Rc",
"Arc",
"HashMap",
"HashSet",
"SharedString",
"ElementId",
"Window",
"App",
"Context",
"usize",
"isize",
"u8",
"u16",
"u32",
"u64",
"i8",
"i16",
"i32",
"i64",
"f32",
"f64",
"bool",
"str",
"boolean",
"number",
"string",
"object",
"unknown",
"never",
];
pub fn tokenize_code_line(line: &str, language: &str) -> Vec<CodeSpan> {
let lang = language.to_lowercase();
let bytes = line.as_bytes();
let len = bytes.len();
let mut i = 0usize;
let mut out = Vec::new();
let push = |out: &mut Vec<CodeSpan>, kind: CodeTokenKind, slice: &str| {
if slice.is_empty() {
return;
}
if let Some(last) = out.last_mut()
&& last.kind == kind
{
last.text.push_str(slice);
return;
}
out.push(CodeSpan {
kind,
text: slice.to_string(),
});
};
while i < len {
if (i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'/')
|| (bytes[i] == b'#'
&& matches!(
lang.as_str(),
"toml" | "sh" | "bash" | "py" | "python" | "yaml"
))
{
push(&mut out, CodeTokenKind::Comment, &line[i..]);
break;
}
if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
let start = i;
i += 2;
while i + 1 < len && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
i += 1;
}
if i + 1 < len {
i += 2;
} else {
i = len;
}
push(&mut out, CodeTokenKind::Comment, &line[start..i]);
continue;
}
let b = bytes[i];
if b == b'"' || b == b'\'' || b == b'`' {
let quote = b;
let start = i;
i += 1;
while i < len {
if bytes[i] == b'\\' && i + 1 < len {
i += 2;
continue;
}
if bytes[i] == quote {
i += 1;
break;
}
i += 1;
}
let slice = &line[start..i];
let rest = line[i..].trim_start();
let kind = if lang == "json" && rest.starts_with(':') {
CodeTokenKind::Property
} else {
CodeTokenKind::String
};
push(&mut out, kind, slice);
continue;
}
if b.is_ascii_digit() {
let start = i;
while i < len
&& (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'.' || bytes[i] == b'_')
{
i += 1;
}
push(&mut out, CodeTokenKind::Number, &line[start..i]);
continue;
}
if b.is_ascii_alphabetic() || b == b'_' || b == b'$' {
let start = i;
while i < len
&& (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'$')
{
i += 1;
}
let word = &line[start..i];
let after = line[i..].trim_start();
let kind = if KEYWORDS.contains(&word) {
CodeTokenKind::Keyword
} else if TYPES.contains(&word) {
CodeTokenKind::Type
} else if after.starts_with('(') && lang != "json" {
CodeTokenKind::Function
} else if matches!(lang.as_str(), "css" | "tsx" | "jsx" | "toml")
&& (after.starts_with(':') || after.starts_with('='))
{
CodeTokenKind::Property
} else {
CodeTokenKind::Plain
};
push(&mut out, kind, word);
continue;
}
if b"{}[]();,.<>:=+*/!?|&-".contains(&b) {
push(&mut out, CodeTokenKind::Punctuation, &line[i..i + 1]);
i += 1;
continue;
}
let ch = line[i..].chars().next().unwrap();
let ch_len = ch.len_utf8();
push(&mut out, CodeTokenKind::Plain, &line[i..i + ch_len]);
i += ch_len;
}
if out.is_empty() {
out.push(CodeSpan {
kind: CodeTokenKind::Plain,
text: " ".to_string(),
});
}
out
}
fn paint_file_code_icon(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let mut page = PathBuilder::stroke(px(1.4));
page.move_to(point(px(cx - 5.0), px(cy - 6.5)));
page.line_to(point(px(cx + 1.5), px(cy - 6.5)));
page.line_to(point(px(cx + 5.0), px(cy - 3.0)));
page.line_to(point(px(cx + 5.0), px(cy + 6.5)));
page.line_to(point(px(cx - 5.0), px(cy + 6.5)));
page.line_to(point(px(cx - 5.0), px(cy - 6.5)));
if let Ok(p) = page.build() {
window.paint_path(p, color);
}
let mut left = PathBuilder::stroke(px(1.3));
left.move_to(point(px(cx - 1.2), px(cy - 0.5)));
left.line_to(point(px(cx - 3.0), px(cy + 1.5)));
left.line_to(point(px(cx - 1.2), px(cy + 3.5)));
if let Ok(p) = left.build() {
window.paint_path(p, color);
}
let mut right = PathBuilder::stroke(px(1.3));
right.move_to(point(px(cx + 1.2), px(cy - 0.5)));
right.line_to(point(px(cx + 3.0), px(cy + 1.5)));
right.line_to(point(px(cx + 1.2), px(cy + 3.5)));
if let Ok(p) = right.build() {
window.paint_path(p, color);
}
}
fn paint_chevron_down(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let (c, s) = (rad.cos(), rad.sin());
let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
let mut pb = PathBuilder::stroke(px(1.6));
pb.move_to(rot(-3.8, -1.8));
pb.line_to(rot(0.0, 2.2));
pb.line_to(rot(3.8, -1.8));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
#[derive(IntoElement)]
pub struct CodeBlock {
id: ElementId,
code: SharedString,
filename: Option<SharedString>,
language: SharedString,
max_lines: Option<usize>,
show_line_numbers: bool,
}
impl CodeBlock {
pub fn new(id: impl Into<ElementId>, code: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
code: code.into(),
filename: None,
language: SharedString::from("rs"),
max_lines: None,
show_line_numbers: true,
}
}
pub fn filename(mut self, filename: impl Into<SharedString>) -> Self {
self.filename = Some(filename.into());
self
}
pub fn language(mut self, language: impl Into<SharedString>) -> Self {
self.language = SharedString::from(language.into().trim_start_matches('.').to_lowercase());
self
}
pub fn max_lines(mut self, max_lines: usize) -> Self {
self.max_lines = Some(max_lines);
self
}
pub fn show_line_numbers(mut self, show: bool) -> Self {
self.show_line_numbers = show;
self
}
}
impl RenderOnce for CodeBlock {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let _reduced = is_reduced_motion(cx);
let lines: Vec<&str> = self.code.lines().collect();
let total_lines = lines.len().max(1);
let collapsible = self.max_lines.is_some_and(|m| m > 0 && total_lines > m);
let expanded_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("cb-expanded")),
cx,
|_, _| Rc::new(RefCell::new(false)),
)
.read(cx)
.clone();
let expanded = *expanded_cell.borrow();
let visible_count = if collapsible && !expanded {
self.max_lines.unwrap_or(total_lines).min(total_lines)
} else {
total_lines
};
let chev_deg = arc_spring_with_options(
(self.id.clone(), "cb-chev"),
if expanded { 180.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value;
let kw_color = colors.accent;
let str_color = colors.success;
let num_color = colors.warning;
let type_color = oklab_mix(colors.info, colors.foreground, 0.72);
let fn_color = oklab_mix(colors.accent, colors.foreground, 0.76);
let prop_color = oklab_mix(colors.warning, colors.foreground, 0.65);
let comment_color = colors.text_muted;
let punct_color = colors.text_secondary;
let span_color = |kind: CodeTokenKind| -> Hsla {
match kind {
CodeTokenKind::Plain => colors.foreground,
CodeTokenKind::Comment => comment_color,
CodeTokenKind::String => str_color,
CodeTokenKind::Number => num_color,
CodeTokenKind::Keyword => kw_color,
CodeTokenKind::Type => type_color,
CodeTokenKind::Function => fn_color,
CodeTokenKind::Property => prop_color,
CodeTokenKind::Punctuation => punct_color,
}
};
let file_label = self
.filename
.clone()
.unwrap_or_else(|| SharedString::from("Source code"));
let icon_col = colors.text_muted;
let header = div()
.w_full()
.px(Spacing::S4)
.py(Spacing::S2)
.bg(colors.surface_muted)
.border_b_1()
.border_color(colors.border)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(
div().w(px(16.0)).h(px(16.0)).child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_file_code_icon(cx_p, cy_p, icon_col, window);
},
)
.w_full()
.h_full(),
),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(file_label),
)
.child(
div()
.px(px(6.0))
.py(px(1.0))
.rounded(Radii::CONTROL)
.bg(colors.surface)
.border_1()
.border_color(colors.border)
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(self.language.clone()),
),
)
.child(
CopyButton::new(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("cb-copy")),
self.code.clone(),
)
.label("Copy"),
);
let mut code_body = div()
.w_full()
.px(Spacing::S4)
.py(Spacing::S3)
.flex()
.flex_col()
.gap(px(2.0));
for (idx, raw_line) in lines.iter().take(visible_count).enumerate() {
let tokens = tokenize_code_line(raw_line, self.language.as_ref());
let mut spans_row = div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_row()
.flex_wrap()
.items_baseline();
for span in tokens {
spans_row = spans_row.child(
div()
.text_size(px(13.0))
.line_height(px(20.0))
.text_color(span_color(span.kind))
.child(span.text),
);
}
let line_row = div()
.w_full()
.flex()
.flex_row()
.items_start()
.gap(Spacing::S3)
.when(self.show_line_numbers, |this| {
this.child(
div()
.w(px(28.0))
.flex_none()
.text_size(px(12.0))
.line_height(px(20.0))
.text_color(colors.text_muted)
.child(format!("{:>2}", idx + 1)),
)
})
.child(spans_row);
code_body = code_body.child(line_row);
}
let mut root = div()
.id(self.id.clone())
.w_full()
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.overflow_hidden()
.flex()
.flex_col()
.role(Role::Region)
.child(header)
.child(code_body);
if collapsible {
let exp_toggle = expanded_cell.clone();
let chev_col = colors.text_secondary;
let footer_label = if expanded {
SharedString::from("Show fewer lines")
} else {
SharedString::from(format!("Show all {total_lines} lines"))
};
root = root.child(
div()
.w_full()
.h(px(36.0))
.border_t_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.cursor_pointer()
.hover(|h| h.bg(oklab_mix(colors.foreground, colors.surface_muted, 0.05)))
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(Spacing::S2)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut flag = exp_toggle.borrow_mut();
*flag = !*flag;
window.refresh();
})
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.child(footer_label),
)
.child(
div().w(px(14.0)).h(px(14.0)).child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_chevron_down(cx_p, cy_p, chev_deg, chev_col, window);
},
)
.w_full()
.h_full(),
),
),
);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokenizes_keywords_strings_numbers_and_comments() {
let spans = tokenize_code_line("pub fn count() -> usize { 42 } // ok", "rs");
assert!(
spans
.iter()
.any(|s| s.kind == CodeTokenKind::Keyword && s.text == "pub")
);
assert!(
spans
.iter()
.any(|s| s.kind == CodeTokenKind::Function && s.text == "count")
);
assert!(
spans
.iter()
.any(|s| s.kind == CodeTokenKind::Type && s.text == "usize")
);
assert!(
spans
.iter()
.any(|s| s.kind == CodeTokenKind::Number && s.text == "42")
);
assert!(
spans
.iter()
.any(|s| s.kind == CodeTokenKind::Comment && s.text.contains("ok"))
);
let json = tokenize_code_line(r#" "name": "arc-ui""#, "json");
assert!(
json.iter()
.any(|s| s.kind == CodeTokenKind::Property && s.text == "\"name\"")
);
assert!(
json.iter()
.any(|s| s.kind == CodeTokenKind::String && s.text == "\"arc-ui\"")
);
}
}