Skip to main content

fc_ui/capabilities/content/
code_block.rs

1use gpui::*;
2
3use crate::capabilities::foundation::theme::use_theme;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum CodeBlockCopyState {
7    #[default]
8    Idle,
9    Copied,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13enum TokenKind {
14    Keyword,
15    StringLiteral,
16    Comment,
17    Number,
18    Plain,
19}
20
21#[derive(IntoElement)]
22pub struct CodeBlock {
23    base: Div,
24    code: SharedString,
25    language: Option<SharedString>,
26    show_line_numbers: bool,
27    show_copy_button: bool,
28    highlight_lines: Vec<usize>,
29    max_height: Option<Pixels>,
30}
31
32impl CodeBlock {
33    pub fn new(code: impl Into<SharedString>) -> Self {
34        Self {
35            base: div(),
36            code: code.into(),
37            language: None,
38            show_line_numbers: true,
39            show_copy_button: true,
40            highlight_lines: Vec::new(),
41            max_height: None,
42        }
43    }
44
45    pub fn language(mut self, lang: impl Into<SharedString>) -> Self {
46        self.language = Some(lang.into());
47        self
48    }
49
50    pub fn show_line_numbers(mut self, show: bool) -> Self {
51        self.show_line_numbers = show;
52        self
53    }
54
55    pub fn highlight_lines(mut self, lines: Vec<usize>) -> Self {
56        self.highlight_lines = lines;
57        self
58    }
59
60    pub fn max_height(mut self, height: Pixels) -> Self {
61        self.max_height = Some(height);
62        self
63    }
64
65    pub fn show_copy_button(mut self, show: bool) -> Self {
66        self.show_copy_button = show;
67        self
68    }
69}
70
71impl RenderOnce for CodeBlock {
72    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
73        let theme = use_theme(cx);
74        let lines: Vec<&str> = self.code.split('\n').collect();
75        let is_rust = self
76            .language
77            .as_ref()
78            .map(|l| l.as_ref() == "rust" || l.as_ref() == "rs")
79            .unwrap_or(false);
80
81        let keyword_color = theme.tokens.primary;
82        let string_color = hsla(0.4, 0.7, 0.5, 1.0);
83        let comment_color = theme.tokens.muted_foreground;
84        let number_color = hsla(0.08, 0.7, 0.6, 1.0);
85        let plain_color = theme.tokens.foreground;
86        let line_number_color = theme.tokens.muted_foreground;
87        let highlight_bg = theme.tokens.muted.opacity(0.5);
88
89        let gutter_width = px(40.0);
90
91        let code_for_copy = self.code.clone();
92        let show_copy = self.show_copy_button;
93
94        let mut outer = self
95            .base
96            .relative()
97            .bg(theme.tokens.muted.opacity(0.3))
98            .rounded(theme.tokens.radius_md)
99            .font_family(theme.tokens.font_mono.clone())
100            .text_size(px(13.0))
101            .overflow_hidden();
102
103        let max_h = self.max_height;
104
105        if show_copy {
106            let copy_btn = div()
107                .id("code-block-copy")
108                .absolute()
109                .top(px(8.0))
110                .right(px(8.0))
111                .px(px(8.0))
112                .py(px(4.0))
113                .rounded(theme.tokens.radius_sm)
114                .bg(theme.tokens.muted.opacity(0.6))
115                .text_color(theme.tokens.muted_foreground)
116                .text_size(px(11.0))
117                .cursor_pointer()
118                .hover(|s| s.bg(theme.tokens.muted))
119                .active(|s| s.opacity(0.7))
120                .child("Copy")
121                .on_click(move |_, _window, cx| {
122                    cx.write_to_clipboard(ClipboardItem::new_string(code_for_copy.to_string()));
123                });
124            outer = outer.child(copy_btn);
125        }
126
127        let mut content = div().flex().flex_col().py(px(12.0));
128
129        for (idx, line_text) in lines.iter().enumerate() {
130            let line_num = idx + 1;
131            let is_highlighted = self.highlight_lines.contains(&line_num);
132
133            let mut row = div().flex().flex_row().px(px(12.0));
134
135            if is_highlighted {
136                row = row.bg(highlight_bg);
137            }
138
139            if self.show_line_numbers {
140                row = row.child(
141                    div()
142                        .w(gutter_width)
143                        .flex_shrink_0()
144                        .text_color(line_number_color)
145                        .text_size(px(12.0))
146                        .text_right()
147                        .pr(px(12.0))
148                        .child(format!("{}", line_num)),
149                );
150            }
151
152            let mut code_row = div().flex().flex_row().flex_1().min_w_0();
153            let tokens = tokenize(line_text, is_rust);
154
155            for (kind, text) in tokens {
156                let color = match kind {
157                    TokenKind::Keyword => keyword_color,
158                    TokenKind::StringLiteral => string_color,
159                    TokenKind::Comment => comment_color,
160                    TokenKind::Number => number_color,
161                    TokenKind::Plain => plain_color,
162                };
163                code_row = code_row.child(div().text_color(color).child(text.to_string()));
164            }
165
166            row = row.child(code_row);
167            content = content.child(row);
168        }
169
170        if let Some(h) = max_h {
171            outer.child(
172                div()
173                    .id("code-block-scroll")
174                    .max_h(h)
175                    .overflow_y_scroll()
176                    .child(content),
177            )
178        } else {
179            outer.child(content)
180        }
181    }
182}
183
184fn tokenize(line: &str, is_rust: bool) -> Vec<(TokenKind, &str)> {
185    let mut tokens = Vec::new();
186    let bytes = line.as_bytes();
187    let len = bytes.len();
188    let mut pos = 0;
189
190    while pos < len {
191        if pos + 1 < len && bytes[pos] == b'/' && bytes[pos + 1] == b'/' {
192            tokens.push((TokenKind::Comment, &line[pos..]));
193            return tokens;
194        }
195
196        if bytes[pos] == b'"' {
197            let start = pos;
198            pos += 1;
199            while pos < len && bytes[pos] != b'"' {
200                if bytes[pos] == b'\\' && pos + 1 < len {
201                    pos += 1;
202                }
203                pos += 1;
204            }
205            if pos < len {
206                pos += 1;
207            }
208            tokens.push((TokenKind::StringLiteral, &line[start..pos]));
209            continue;
210        }
211
212        if bytes[pos] == b'\'' && is_rust {
213            let start = pos;
214            pos += 1;
215            if pos < len && bytes[pos] == b'\\' && pos + 1 < len {
216                pos += 2;
217            } else if pos < len {
218                // Advance a full UTF-8 character, not a single byte; slicing
219                // into a multi-byte character panics at runtime.
220                pos += line[pos..].chars().next().map_or(1, char::len_utf8);
221            }
222            if pos < len && bytes[pos] == b'\'' {
223                pos += 1;
224                tokens.push((TokenKind::StringLiteral, &line[start..pos]));
225                continue;
226            }
227            pos = start + 1;
228            tokens.push((TokenKind::Plain, &line[start..pos]));
229            continue;
230        }
231
232        if bytes[pos].is_ascii_digit()
233            || (bytes[pos] == b'-' && pos + 1 < len && bytes[pos + 1].is_ascii_digit())
234        {
235            let start = pos;
236            if bytes[pos] == b'-' {
237                pos += 1;
238            }
239            while pos < len
240                && (bytes[pos].is_ascii_digit() || bytes[pos] == b'.' || bytes[pos] == b'_')
241            {
242                pos += 1;
243            }
244            if pos < len && (bytes[pos] == b'e' || bytes[pos] == b'E') {
245                pos += 1;
246                if pos < len && (bytes[pos] == b'+' || bytes[pos] == b'-') {
247                    pos += 1;
248                }
249                while pos < len && bytes[pos].is_ascii_digit() {
250                    pos += 1;
251                }
252            }
253            tokens.push((TokenKind::Number, &line[start..pos]));
254            continue;
255        }
256
257        if bytes[pos].is_ascii_alphabetic() || bytes[pos] == b'_' {
258            let start = pos;
259            while pos < len && (bytes[pos].is_ascii_alphanumeric() || bytes[pos] == b'_') {
260                pos += 1;
261            }
262            let word = &line[start..pos];
263            if is_rust && is_rust_keyword(word) {
264                tokens.push((TokenKind::Keyword, word));
265            } else {
266                tokens.push((TokenKind::Plain, word));
267            }
268            continue;
269        }
270
271        if bytes[pos] == b' ' {
272            let start = pos;
273            while pos < len && bytes[pos] == b' ' {
274                pos += 1;
275            }
276            tokens.push((TokenKind::Plain, &line[start..pos]));
277            continue;
278        }
279
280        let start = pos;
281        // Advance a full UTF-8 character, not a single byte; slicing into a
282        // multi-byte character panics at runtime (CJK content in code blocks).
283        pos += line[start..].chars().next().map_or(1, char::len_utf8);
284        tokens.push((TokenKind::Plain, &line[start..pos]));
285    }
286
287    tokens
288}
289
290fn is_rust_keyword(word: &str) -> bool {
291    matches!(
292        word,
293        "fn" | "let"
294            | "mut"
295            | "pub"
296            | "struct"
297            | "enum"
298            | "impl"
299            | "use"
300            | "mod"
301            | "if"
302            | "else"
303            | "for"
304            | "while"
305            | "match"
306            | "return"
307            | "self"
308            | "Self"
309            | "crate"
310            | "super"
311            | "true"
312            | "false"
313            | "async"
314            | "await"
315            | "move"
316            | "ref"
317            | "where"
318            | "type"
319            | "trait"
320            | "const"
321            | "static"
322            | "loop"
323            | "break"
324            | "continue"
325            | "in"
326            | "as"
327            | "unsafe"
328            | "dyn"
329            | "extern"
330    )
331}
332
333impl Styled for CodeBlock {
334    fn style(&mut self) -> &mut StyleRefinement {
335        self.base.style()
336    }
337}
338
339impl InteractiveElement for CodeBlock {
340    fn interactivity(&mut self) -> &mut Interactivity {
341        self.base.interactivity()
342    }
343}
344
345impl StatefulInteractiveElement for CodeBlock {}
346
347impl ParentElement for CodeBlock {
348    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
349        self.base.extend(elements)
350    }
351}
352
353#[cfg(test)]
354mod cjk_tests {
355    // Absolute paths only: this crate's boundary checker forbids relative
356    // `super::` paths inside src/capabilities/.
357    use crate::capabilities::content::code_block::{tokenize, TokenKind};
358
359    // Regression: multi-byte UTF-8 content must not panic the tokenizer.
360    // Reported against fc-ui 0.8.1 via the Obelisk app: a code block whose
361    // first character is CJK (e.g. a Chinese note) panicked with
362    // "end byte index 1 is not a char boundary".
363    #[test]
364    fn tokenize_cjk_content_does_not_panic() {
365        // Plain CJK text (the reported crash: fallback branch).
366        let tokens = tokenize("读后感:这段代码很好", false);
367        assert_eq!(tokens[0].1.chars().next(), Some('读'));
368
369        // CJK inside a string literal.
370        let tokens = tokenize(r#"let s = "你好世界";"#, true);
371        assert!(tokens
372            .iter()
373            .any(|(kind, text)| *kind == TokenKind::StringLiteral && text.contains("你好世界")));
374
375        // A Rust char literal holding a CJK character.
376        let tokens = tokenize("let c = '读';", true);
377        assert!(tokens
378            .iter()
379            .any(|(kind, text)| *kind == TokenKind::StringLiteral && text.contains('读')));
380
381        // Mixed emoji + CJK + code.
382        let _ = tokenize("fn 計算(x: i32) -> i32 { x * 2 } // 🚀 加速", true);
383    }
384}