Skip to main content

arc_ui/data/
code_block.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/code-block/code-block.tsx` & `.module.css`
3//!
4//! P6 Component #10: `code-block`
5//!
6//! - Framed syntax-highlighted source code viewer with file header, language badge, built-in
7//!   `CopyButton` writing directly to the OS clipboard, and optional `max_lines` collapse/expand
8//!   bar with rotating vector chevron (`SpringSpec::SNAPPY`).
9
10use std::{cell::RefCell, rc::Rc};
11
12use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
13use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
14use gpui_kit::{
15    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, PathBuilder, RenderOnce, Role,
16    SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
17};
18
19use crate::actions::copy_button::CopyButton;
20
21/// Lightweight syntax token category matching `code-block.tsx`.
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub enum CodeTokenKind {
24    Plain,
25    Comment,
26    String,
27    Number,
28    Keyword,
29    Type,
30    Function,
31    Property,
32    Punctuation,
33}
34
35/// One tokenized text span on a line of source code.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct CodeSpan {
38    pub kind: CodeTokenKind,
39    pub text: String,
40}
41
42const KEYWORDS: &[&str] = &[
43    "abstract",
44    "as",
45    "async",
46    "await",
47    "break",
48    "case",
49    "catch",
50    "class",
51    "const",
52    "continue",
53    "crate",
54    "default",
55    "delete",
56    "do",
57    "else",
58    "enum",
59    "export",
60    "extends",
61    "extern",
62    "false",
63    "finally",
64    "fn",
65    "for",
66    "from",
67    "function",
68    "get",
69    "if",
70    "impl",
71    "implements",
72    "import",
73    "in",
74    "instanceof",
75    "interface",
76    "let",
77    "loop",
78    "match",
79    "mod",
80    "move",
81    "mut",
82    "new",
83    "null",
84    "of",
85    "private",
86    "protected",
87    "pub",
88    "public",
89    "readonly",
90    "ref",
91    "return",
92    "self",
93    "Self",
94    "set",
95    "static",
96    "struct",
97    "super",
98    "switch",
99    "throw",
100    "trait",
101    "true",
102    "try",
103    "type",
104    "typeof",
105    "undefined",
106    "unsafe",
107    "use",
108    "var",
109    "void",
110    "where",
111    "while",
112    "with",
113    "yield",
114    "SELECT",
115    "FROM",
116    "WHERE",
117    "INSERT",
118    "UPDATE",
119    "DELETE",
120];
121
122const TYPES: &[&str] = &[
123    "Array",
124    "Boolean",
125    "Date",
126    "Error",
127    "Map",
128    "Number",
129    "Promise",
130    "Record",
131    "Set",
132    "String",
133    "Vec",
134    "Option",
135    "Result",
136    "Box",
137    "Rc",
138    "Arc",
139    "HashMap",
140    "HashSet",
141    "SharedString",
142    "ElementId",
143    "Window",
144    "App",
145    "Context",
146    "usize",
147    "isize",
148    "u8",
149    "u16",
150    "u32",
151    "u64",
152    "i8",
153    "i16",
154    "i32",
155    "i64",
156    "f32",
157    "f64",
158    "bool",
159    "str",
160    "boolean",
161    "number",
162    "string",
163    "object",
164    "unknown",
165    "never",
166];
167
168/// Tokenizes a single line of source code into colored spans (Rust / TS / JS / JSON / SQL / CSS).
169pub fn tokenize_code_line(line: &str, language: &str) -> Vec<CodeSpan> {
170    let lang = language.to_lowercase();
171    let bytes = line.as_bytes();
172    let len = bytes.len();
173    let mut i = 0usize;
174    let mut out = Vec::new();
175
176    let push = |out: &mut Vec<CodeSpan>, kind: CodeTokenKind, slice: &str| {
177        if slice.is_empty() {
178            return;
179        }
180        if let Some(last) = out.last_mut()
181            && last.kind == kind
182        {
183            last.text.push_str(slice);
184            return;
185        }
186        out.push(CodeSpan {
187            kind,
188            text: slice.to_string(),
189        });
190    };
191
192    while i < len {
193        // Line comment `//` or `#` (for toml/py/sh)
194        if (i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'/')
195            || (bytes[i] == b'#'
196                && matches!(
197                    lang.as_str(),
198                    "toml" | "sh" | "bash" | "py" | "python" | "yaml"
199                ))
200        {
201            push(&mut out, CodeTokenKind::Comment, &line[i..]);
202            break;
203        }
204        // Inline block comment `/* ... */`
205        if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
206            let start = i;
207            i += 2;
208            while i + 1 < len && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
209                i += 1;
210            }
211            if i + 1 < len {
212                i += 2;
213            } else {
214                i = len;
215            }
216            push(&mut out, CodeTokenKind::Comment, &line[start..i]);
217            continue;
218        }
219        // Quoted strings
220        let b = bytes[i];
221        if b == b'"' || b == b'\'' || b == b'`' {
222            let quote = b;
223            let start = i;
224            i += 1;
225            while i < len {
226                if bytes[i] == b'\\' && i + 1 < len {
227                    i += 2;
228                    continue;
229                }
230                if bytes[i] == quote {
231                    i += 1;
232                    break;
233                }
234                i += 1;
235            }
236            let slice = &line[start..i];
237            let rest = line[i..].trim_start();
238            let kind = if lang == "json" && rest.starts_with(':') {
239                CodeTokenKind::Property
240            } else {
241                CodeTokenKind::String
242            };
243            push(&mut out, kind, slice);
244            continue;
245        }
246        // Numbers
247        if b.is_ascii_digit() {
248            let start = i;
249            while i < len
250                && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'.' || bytes[i] == b'_')
251            {
252                i += 1;
253            }
254            push(&mut out, CodeTokenKind::Number, &line[start..i]);
255            continue;
256        }
257        // Identifiers / keywords / types / functions
258        if b.is_ascii_alphabetic() || b == b'_' || b == b'$' {
259            let start = i;
260            while i < len
261                && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'$')
262            {
263                i += 1;
264            }
265            let word = &line[start..i];
266            let after = line[i..].trim_start();
267            let kind = if KEYWORDS.contains(&word) {
268                CodeTokenKind::Keyword
269            } else if TYPES.contains(&word) {
270                CodeTokenKind::Type
271            } else if after.starts_with('(') && lang != "json" {
272                CodeTokenKind::Function
273            } else if matches!(lang.as_str(), "css" | "tsx" | "jsx" | "toml")
274                && (after.starts_with(':') || after.starts_with('='))
275            {
276                CodeTokenKind::Property
277            } else {
278                CodeTokenKind::Plain
279            };
280            push(&mut out, kind, word);
281            continue;
282        }
283        // Punctuation
284        if b"{}[]();,.<>:=+*/!?|&-".contains(&b) {
285            push(&mut out, CodeTokenKind::Punctuation, &line[i..i + 1]);
286            i += 1;
287            continue;
288        }
289        // Other UTF-8 char (whitespace or non-ASCII)
290        let ch = line[i..].chars().next().unwrap();
291        let ch_len = ch.len_utf8();
292        push(&mut out, CodeTokenKind::Plain, &line[i..i + ch_len]);
293        i += ch_len;
294    }
295
296    if out.is_empty() {
297        out.push(CodeSpan {
298            kind: CodeTokenKind::Plain,
299            text: " ".to_string(),
300        });
301    }
302    out
303}
304
305fn paint_file_code_icon(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
306    let mut page = PathBuilder::stroke(px(1.4));
307    page.move_to(point(px(cx - 5.0), px(cy - 6.5)));
308    page.line_to(point(px(cx + 1.5), px(cy - 6.5)));
309    page.line_to(point(px(cx + 5.0), px(cy - 3.0)));
310    page.line_to(point(px(cx + 5.0), px(cy + 6.5)));
311    page.line_to(point(px(cx - 5.0), px(cy + 6.5)));
312    page.line_to(point(px(cx - 5.0), px(cy - 6.5)));
313    if let Ok(p) = page.build() {
314        window.paint_path(p, color);
315    }
316    let mut left = PathBuilder::stroke(px(1.3));
317    left.move_to(point(px(cx - 1.2), px(cy - 0.5)));
318    left.line_to(point(px(cx - 3.0), px(cy + 1.5)));
319    left.line_to(point(px(cx - 1.2), px(cy + 3.5)));
320    if let Ok(p) = left.build() {
321        window.paint_path(p, color);
322    }
323    let mut right = PathBuilder::stroke(px(1.3));
324    right.move_to(point(px(cx + 1.2), px(cy - 0.5)));
325    right.line_to(point(px(cx + 3.0), px(cy + 1.5)));
326    right.line_to(point(px(cx + 1.2), px(cy + 3.5)));
327    if let Ok(p) = right.build() {
328        window.paint_path(p, color);
329    }
330}
331
332fn paint_chevron_down(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
333    let rad = angle_deg.to_radians();
334    let (c, s) = (rad.cos(), rad.sin());
335    let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
336    let mut pb = PathBuilder::stroke(px(1.6));
337    pb.move_to(rot(-3.8, -1.8));
338    pb.line_to(rot(0.0, 2.2));
339    pb.line_to(rot(3.8, -1.8));
340    if let Ok(path) = pb.build() {
341        window.paint_path(path, color);
342    }
343}
344
345/// Syntax-highlighted source code viewer with copy button & collapsible footer (`code-block`).
346#[derive(IntoElement)]
347pub struct CodeBlock {
348    id: ElementId,
349    code: SharedString,
350    filename: Option<SharedString>,
351    language: SharedString,
352    max_lines: Option<usize>,
353    show_line_numbers: bool,
354}
355
356impl CodeBlock {
357    pub fn new(id: impl Into<ElementId>, code: impl Into<SharedString>) -> Self {
358        Self {
359            id: id.into(),
360            code: code.into(),
361            filename: None,
362            language: SharedString::from("rs"),
363            max_lines: None,
364            show_line_numbers: true,
365        }
366    }
367
368    pub fn filename(mut self, filename: impl Into<SharedString>) -> Self {
369        self.filename = Some(filename.into());
370        self
371    }
372
373    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
374        self.language = SharedString::from(language.into().trim_start_matches('.').to_lowercase());
375        self
376    }
377
378    pub fn max_lines(mut self, max_lines: usize) -> Self {
379        self.max_lines = Some(max_lines);
380        self
381    }
382
383    pub fn show_line_numbers(mut self, show: bool) -> Self {
384        self.show_line_numbers = show;
385        self
386    }
387}
388
389impl RenderOnce for CodeBlock {
390    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
391        let theme = cx.arc_theme().clone();
392        let colors = theme.colors;
393        let _reduced = is_reduced_motion(cx);
394
395        let lines: Vec<&str> = self.code.lines().collect();
396        let total_lines = lines.len().max(1);
397        let collapsible = self.max_lines.is_some_and(|m| m > 0 && total_lines > m);
398
399        let expanded_cell = window
400            .use_keyed_state(
401                ElementId::NamedChild(self.id.clone().into(), SharedString::from("cb-expanded")),
402                cx,
403                |_, _| Rc::new(RefCell::new(false)),
404            )
405            .read(cx)
406            .clone();
407        let expanded = *expanded_cell.borrow();
408        let visible_count = if collapsible && !expanded {
409            self.max_lines.unwrap_or(total_lines).min(total_lines)
410        } else {
411            total_lines
412        };
413
414        let chev_deg = arc_spring_with_options(
415            (self.id.clone(), "cb-chev"),
416            if expanded { 180.0 } else { 0.0 },
417            SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
418            window,
419            cx,
420        )
421        .value;
422
423        let kw_color = colors.accent;
424        let str_color = colors.success;
425        let num_color = colors.warning;
426        let type_color = oklab_mix(colors.info, colors.foreground, 0.72);
427        let fn_color = oklab_mix(colors.accent, colors.foreground, 0.76);
428        let prop_color = oklab_mix(colors.warning, colors.foreground, 0.65);
429        let comment_color = colors.text_muted;
430        let punct_color = colors.text_secondary;
431
432        let span_color = |kind: CodeTokenKind| -> Hsla {
433            match kind {
434                CodeTokenKind::Plain => colors.foreground,
435                CodeTokenKind::Comment => comment_color,
436                CodeTokenKind::String => str_color,
437                CodeTokenKind::Number => num_color,
438                CodeTokenKind::Keyword => kw_color,
439                CodeTokenKind::Type => type_color,
440                CodeTokenKind::Function => fn_color,
441                CodeTokenKind::Property => prop_color,
442                CodeTokenKind::Punctuation => punct_color,
443            }
444        };
445
446        let file_label = self
447            .filename
448            .clone()
449            .unwrap_or_else(|| SharedString::from("Source code"));
450        let icon_col = colors.text_muted;
451
452        let header = div()
453            .w_full()
454            .px(Spacing::S4)
455            .py(Spacing::S2)
456            .bg(colors.surface_muted)
457            .border_b_1()
458            .border_color(colors.border)
459            .flex()
460            .flex_row()
461            .items_center()
462            .justify_between()
463            .gap(Spacing::S3)
464            .child(
465                div()
466                    .flex()
467                    .flex_row()
468                    .items_center()
469                    .gap(Spacing::S2)
470                    .child(
471                        div().w(px(16.0)).h(px(16.0)).child(
472                            canvas(
473                                |_, _, _| {},
474                                move |bounds, _, window, _| {
475                                    let cx_p = f32::from(bounds.origin.x)
476                                        + f32::from(bounds.size.width) * 0.5;
477                                    let cy_p = f32::from(bounds.origin.y)
478                                        + f32::from(bounds.size.height) * 0.5;
479                                    paint_file_code_icon(cx_p, cy_p, icon_col, window);
480                                },
481                            )
482                            .w_full()
483                            .h_full(),
484                        ),
485                    )
486                    .child(
487                        div()
488                            .text_size(Typography::TEXT_SM)
489                            .font_medium()
490                            .text_color(colors.foreground)
491                            .child(file_label),
492                    )
493                    .child(
494                        div()
495                            .px(px(6.0))
496                            .py(px(1.0))
497                            .rounded(Radii::CONTROL)
498                            .bg(colors.surface)
499                            .border_1()
500                            .border_color(colors.border)
501                            .text_size(px(11.0))
502                            .text_color(colors.text_muted)
503                            .child(self.language.clone()),
504                    ),
505            )
506            .child(
507                CopyButton::new(
508                    ElementId::NamedChild(self.id.clone().into(), SharedString::from("cb-copy")),
509                    self.code.clone(),
510                )
511                .label("Copy"),
512            );
513
514        let mut code_body = div()
515            .w_full()
516            .px(Spacing::S4)
517            .py(Spacing::S3)
518            .flex()
519            .flex_col()
520            .gap(px(2.0));
521
522        for (idx, raw_line) in lines.iter().take(visible_count).enumerate() {
523            let tokens = tokenize_code_line(raw_line, self.language.as_ref());
524            let mut spans_row = div()
525                .flex_1()
526                .min_w(px(0.0))
527                .flex()
528                .flex_row()
529                .flex_wrap()
530                .items_baseline();
531            for span in tokens {
532                spans_row = spans_row.child(
533                    div()
534                        .text_size(px(13.0))
535                        .line_height(px(20.0))
536                        .text_color(span_color(span.kind))
537                        .child(span.text),
538                );
539            }
540            let line_row = div()
541                .w_full()
542                .flex()
543                .flex_row()
544                .items_start()
545                .gap(Spacing::S3)
546                .when(self.show_line_numbers, |this| {
547                    this.child(
548                        div()
549                            .w(px(28.0))
550                            .flex_none()
551                            .text_size(px(12.0))
552                            .line_height(px(20.0))
553                            .text_color(colors.text_muted)
554                            .child(format!("{:>2}", idx + 1)),
555                    )
556                })
557                .child(spans_row);
558            code_body = code_body.child(line_row);
559        }
560
561        let mut root = div()
562            .id(self.id.clone())
563            .w_full()
564            .rounded(Radii::PANEL)
565            .border_1()
566            .border_color(colors.border)
567            .bg(colors.surface)
568            .overflow_hidden()
569            .flex()
570            .flex_col()
571            .role(Role::Region)
572            .child(header)
573            .child(code_body);
574
575        if collapsible {
576            let exp_toggle = expanded_cell.clone();
577            let chev_col = colors.text_secondary;
578            let footer_label = if expanded {
579                SharedString::from("Show fewer lines")
580            } else {
581                SharedString::from(format!("Show all {total_lines} lines"))
582            };
583            root = root.child(
584                div()
585                    .w_full()
586                    .h(px(36.0))
587                    .border_t_1()
588                    .border_color(colors.border)
589                    .bg(colors.surface_muted)
590                    .cursor_pointer()
591                    .hover(|h| h.bg(oklab_mix(colors.foreground, colors.surface_muted, 0.05)))
592                    .flex()
593                    .flex_row()
594                    .items_center()
595                    .justify_center()
596                    .gap(Spacing::S2)
597                    .on_mouse_down(MouseButton::Left, move |_, window, _| {
598                        let mut flag = exp_toggle.borrow_mut();
599                        *flag = !*flag;
600                        window.refresh();
601                    })
602                    .child(
603                        div()
604                            .text_size(Typography::TEXT_XS)
605                            .font_medium()
606                            .text_color(colors.text_secondary)
607                            .child(footer_label),
608                    )
609                    .child(
610                        div().w(px(14.0)).h(px(14.0)).child(
611                            canvas(
612                                |_, _, _| {},
613                                move |bounds, _, window, _| {
614                                    let cx_p = f32::from(bounds.origin.x)
615                                        + f32::from(bounds.size.width) * 0.5;
616                                    let cy_p = f32::from(bounds.origin.y)
617                                        + f32::from(bounds.size.height) * 0.5;
618                                    paint_chevron_down(cx_p, cy_p, chev_deg, chev_col, window);
619                                },
620                            )
621                            .w_full()
622                            .h_full(),
623                        ),
624                    ),
625            );
626        }
627
628        root
629    }
630}
631
632#[cfg(test)]
633mod tests {
634    use super::*;
635
636    #[test]
637    fn tokenizes_keywords_strings_numbers_and_comments() {
638        let spans = tokenize_code_line("pub fn count() -> usize { 42 } // ok", "rs");
639        assert!(
640            spans
641                .iter()
642                .any(|s| s.kind == CodeTokenKind::Keyword && s.text == "pub")
643        );
644        assert!(
645            spans
646                .iter()
647                .any(|s| s.kind == CodeTokenKind::Function && s.text == "count")
648        );
649        assert!(
650            spans
651                .iter()
652                .any(|s| s.kind == CodeTokenKind::Type && s.text == "usize")
653        );
654        assert!(
655            spans
656                .iter()
657                .any(|s| s.kind == CodeTokenKind::Number && s.text == "42")
658        );
659        assert!(
660            spans
661                .iter()
662                .any(|s| s.kind == CodeTokenKind::Comment && s.text.contains("ok"))
663        );
664
665        let json = tokenize_code_line(r#"  "name": "arc-ui""#, "json");
666        assert!(
667            json.iter()
668                .any(|s| s.kind == CodeTokenKind::Property && s.text == "\"name\"")
669        );
670        assert!(
671            json.iter()
672                .any(|s| s.kind == CodeTokenKind::String && s.text == "\"arc-ui\"")
673        );
674    }
675}