Skip to main content

fc_ui/capabilities/content/
rich_text.rs

1use std::rc::Rc;
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::*;
5
6use crate::capabilities::content::code_block::CodeBlock;
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::primitives::separator::Separator;
9use crate::capabilities::primitives::text::TextVariant;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum TableAlignment {
13    Left,
14    Center,
15    Right,
16}
17
18#[derive(Debug, Clone)]
19pub enum RichInline {
20    Text(String),
21    Bold(Vec<RichInline>),
22    Italic(Vec<RichInline>),
23    Strikethrough(Vec<RichInline>),
24    Code(String),
25    Link {
26        text: Vec<RichInline>,
27        url: String,
28    },
29    Image {
30        alt: String,
31        url: String,
32    },
33    LineBreak,
34    Html(String),
35    Styled {
36        children: Vec<RichInline>,
37        color: Option<Hsla>,
38        background_color: Option<Hsla>,
39        bold: Option<bool>,
40        italic: Option<bool>,
41        font_size: Option<f32>,
42    },
43}
44
45#[derive(Debug, Clone)]
46pub struct ListItem {
47    pub checked: Option<bool>,
48    pub content: Vec<RichInline>,
49    pub children: Vec<ListItem>,
50}
51
52#[derive(Debug, Clone)]
53pub enum RichBlock {
54    Paragraph(Vec<RichInline>),
55    Heading {
56        level: u8,
57        content: Vec<RichInline>,
58    },
59    CodeBlock {
60        language: Option<String>,
61        code: String,
62    },
63    BlockQuote(Vec<RichBlock>),
64    OrderedList {
65        start: u64,
66        items: Vec<ListItem>,
67    },
68    UnorderedList {
69        items: Vec<ListItem>,
70    },
71    Table {
72        headers: Vec<Vec<RichInline>>,
73        alignments: Vec<TableAlignment>,
74        rows: Vec<Vec<Vec<RichInline>>>,
75    },
76    HorizontalRule,
77    Image {
78        alt: String,
79        url: String,
80    },
81}
82
83#[derive(Clone)]
84pub struct LinkInfo {
85    pub range: std::ops::Range<usize>,
86    pub url: String,
87}
88
89struct FlattenResult {
90    text: String,
91    runs: Vec<TextRun>,
92    links: Vec<LinkInfo>,
93}
94
95struct InlineFlattener {
96    text: String,
97    runs: Vec<TextRun>,
98    links: Vec<LinkInfo>,
99    font_family: SharedString,
100    font_mono: SharedString,
101    text_color: Hsla,
102    link_color: Hsla,
103    code_bg: Hsla,
104    bold: bool,
105    italic: bool,
106    strikethrough: bool,
107    in_link: Option<String>,
108    color_override: Option<Hsla>,
109    bg_override: Option<Hsla>,
110}
111
112impl InlineFlattener {
113    fn new(
114        font_family: SharedString,
115        font_mono: SharedString,
116        text_color: Hsla,
117        link_color: Hsla,
118        code_bg: Hsla,
119    ) -> Self {
120        Self {
121            text: String::new(),
122            runs: Vec::new(),
123            links: Vec::new(),
124            font_family,
125            font_mono,
126            text_color,
127            link_color,
128            code_bg,
129            bold: false,
130            italic: false,
131            strikethrough: false,
132            in_link: None,
133            color_override: None,
134            bg_override: None,
135        }
136    }
137
138    fn flatten(mut self, inlines: &[RichInline]) -> FlattenResult {
139        self.walk(inlines);
140        FlattenResult {
141            text: self.text,
142            runs: self.runs,
143            links: self.links,
144        }
145    }
146
147    fn walk(&mut self, inlines: &[RichInline]) {
148        for inline in inlines {
149            match inline {
150                RichInline::Text(s) => self.push_text(s, false),
151                RichInline::Bold(children) => {
152                    let prev = self.bold;
153                    self.bold = true;
154                    self.walk(children);
155                    self.bold = prev;
156                }
157                RichInline::Italic(children) => {
158                    let prev = self.italic;
159                    self.italic = true;
160                    self.walk(children);
161                    self.italic = prev;
162                }
163                RichInline::Strikethrough(children) => {
164                    let prev = self.strikethrough;
165                    self.strikethrough = true;
166                    self.walk(children);
167                    self.strikethrough = prev;
168                }
169                RichInline::Code(code) => self.push_text(code, true),
170                RichInline::Link { text, url } => {
171                    let prev = self.in_link.take();
172                    self.in_link = Some(url.clone());
173                    self.walk(text);
174                    self.in_link = prev;
175                }
176                RichInline::Image { alt, .. } => {
177                    if !alt.is_empty() {
178                        self.push_text(alt, false);
179                    }
180                }
181                RichInline::LineBreak => self.push_text("\n", false),
182                RichInline::Html(_) => {}
183                RichInline::Styled {
184                    children,
185                    color,
186                    background_color,
187                    bold,
188                    italic,
189                    font_size: _,
190                } => {
191                    let prev_bold = self.bold;
192                    let prev_italic = self.italic;
193                    let prev_color = self.color_override;
194                    let prev_bg = self.bg_override;
195                    if let Some(true) = bold {
196                        self.bold = true;
197                    }
198                    if let Some(true) = italic {
199                        self.italic = true;
200                    }
201                    if color.is_some() {
202                        self.color_override = *color;
203                    }
204                    if background_color.is_some() {
205                        self.bg_override = *background_color;
206                    }
207                    self.walk(children);
208                    self.bold = prev_bold;
209                    self.italic = prev_italic;
210                    self.color_override = prev_color;
211                    self.bg_override = prev_bg;
212                }
213            }
214        }
215    }
216
217    fn push_text(&mut self, text: &str, is_code: bool) {
218        if text.is_empty() {
219            return;
220        }
221
222        let start = self.text.len();
223        self.text.push_str(text);
224        let len = text.len();
225
226        let is_link = self.in_link.is_some();
227
228        let font = if is_code {
229            Font {
230                family: self.font_mono.clone(),
231                features: FontFeatures::default(),
232                weight: FontWeight::default(),
233                style: FontStyle::default(),
234                fallbacks: None,
235            }
236        } else {
237            Font {
238                family: self.font_family.clone(),
239                features: FontFeatures::default(),
240                weight: if self.bold {
241                    FontWeight::BOLD
242                } else {
243                    FontWeight::default()
244                },
245                style: if self.italic {
246                    FontStyle::Italic
247                } else {
248                    FontStyle::Normal
249                },
250                fallbacks: None,
251            }
252        };
253
254        let color = if is_link {
255            self.link_color
256        } else if let Some(c) = self.color_override {
257            c
258        } else {
259            self.text_color
260        };
261
262        let underline = if is_link {
263            Some(UnderlineStyle {
264                thickness: px(1.0),
265                color: Some(self.link_color),
266                wavy: false,
267            })
268        } else {
269            None
270        };
271
272        let strikethrough = if self.strikethrough {
273            Some(StrikethroughStyle {
274                thickness: px(1.0),
275                color: Some(self.text_color),
276            })
277        } else {
278            None
279        };
280
281        let background_color = if is_code {
282            Some(self.code_bg)
283        } else {
284            self.bg_override
285        };
286
287        self.runs.push(TextRun {
288            len,
289            font,
290            color,
291            background_color,
292            underline,
293            strikethrough,
294        });
295
296        if let Some(ref url) = self.in_link {
297            self.links.push(LinkInfo {
298                range: start..(start + len),
299                url: url.clone(),
300            });
301        }
302    }
303}
304
305pub type LinkClickHandler = Rc<dyn Fn(&str, &mut Window, &mut App) + 'static>;
306
307fn dispatch_link_click(
308    handler: &Option<LinkClickHandler>,
309    url: &str,
310    window: &mut Window,
311    cx: &mut App,
312) {
313    if !is_allowed_link_scheme(url) {
314        return;
315    }
316    match handler.as_ref() {
317        Some(handler) => handler(url, window, cx),
318        None => cx.open_url(url),
319    }
320}
321
322fn is_allowed_link_scheme(url: &str) -> bool {
323    let url = url.trim_start();
324    ["http://", "https://", "mailto:"].iter().any(|scheme| {
325        url.get(..scheme.len())
326            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(scheme))
327    })
328}
329
330pub fn render_inlines(
331    inlines: &[RichInline],
332    base_size: Pixels,
333    link_handler: Option<&LinkClickHandler>,
334    element_id: Option<ElementId>,
335    cx: &App,
336) -> AnyElement {
337    render_inline_content(
338        inlines,
339        base_size,
340        link_handler.cloned(),
341        element_id,
342        true,
343        cx,
344    )
345}
346
347pub fn render_inlines_with_handler(
348    inlines: &[RichInline],
349    base_size: Pixels,
350    _link_urls: &[LinkInfo],
351    on_link_click: &Option<LinkClickHandler>,
352    element_id: Option<ElementId>,
353    cx: &App,
354) -> AnyElement {
355    render_inline_content(
356        inlines,
357        base_size,
358        on_link_click.clone(),
359        element_id,
360        false,
361        cx,
362    )
363}
364
365fn render_inline_content(
366    inlines: &[RichInline],
367    base_size: Pixels,
368    link_handler: Option<LinkClickHandler>,
369    element_id: Option<ElementId>,
370    debug_links: bool,
371    cx: &App,
372) -> AnyElement {
373    let theme = use_theme(cx);
374    let font_family = theme.tokens.font_family.clone();
375    let font_mono = theme.tokens.font_mono.clone();
376    let text_color = theme.tokens.foreground;
377    let link_color = theme.tokens.primary;
378    let code_bg = theme.tokens.muted.opacity(0.3);
379
380    let flattened = InlineFlattener::new(font_family, font_mono, text_color, link_color, code_bg)
381        .flatten(inlines);
382
383    if flattened.text.is_empty() {
384        return div().into_any_element();
385    }
386
387    let styled = StyledText::new(SharedString::from(flattened.text)).with_runs(flattened.runs);
388
389    if !flattened.links.is_empty() {
390        let id = element_id.unwrap_or_else(|| ElementId::Name("rich-text-inline".into()));
391        let click_ranges: Vec<std::ops::Range<usize>> =
392            flattened.links.iter().map(|l| l.range.clone()).collect();
393        let link_urls: Vec<String> = flattened.links.iter().map(|l| l.url.clone()).collect();
394        let mut container = div().text_size(base_size).line_height(relative(1.5));
395
396        if debug_links {
397            container = container.debug_selector(|| "rich-text-link".into());
398        }
399
400        return container
401            .child(InteractiveText::new(id, styled).on_click(
402                click_ranges,
403                move |idx, window, cx| {
404                    if let Some(url) = link_urls.get(idx) {
405                        dispatch_link_click(&link_handler, url, window, cx);
406                    }
407                },
408            ))
409            .into_any_element();
410    }
411
412    div()
413        .text_size(base_size)
414        .line_height(relative(1.5))
415        .child(styled)
416        .into_any_element()
417}
418
419pub fn render_blocks(
420    blocks: &[RichBlock],
421    base_size: Pixels,
422    on_link_click: &Option<LinkClickHandler>,
423    id_prefix: &str,
424    cx: &App,
425) -> Vec<AnyElement> {
426    let mut elements = Vec::new();
427    let mut block_idx = 0u32;
428
429    for block in blocks {
430        let el = render_block(
431            block,
432            base_size,
433            on_link_click,
434            id_prefix,
435            &mut block_idx,
436            cx,
437        );
438        elements.push(el);
439    }
440
441    elements
442}
443
444fn render_block(
445    block: &RichBlock,
446    base_size: Pixels,
447    on_link_click: &Option<LinkClickHandler>,
448    id_prefix: &str,
449    block_idx: &mut u32,
450    cx: &App,
451) -> AnyElement {
452    let theme = use_theme(cx);
453    *block_idx += 1;
454    let idx = *block_idx;
455
456    match block {
457        RichBlock::Paragraph(inlines) => {
458            let id = ElementId::Name(format!("{}-p-{}", id_prefix, idx).into());
459            let el = render_inline_element(inlines, base_size, on_link_click, Some(id), cx);
460            div().mb(px(12.0)).child(el).into_any_element()
461        }
462
463        RichBlock::Heading { level, content } => {
464            let variant = match level {
465                1 => TextVariant::H1,
466                2 => TextVariant::H2,
467                3 => TextVariant::H3,
468                4 => TextVariant::H4,
469                5 => TextVariant::H5,
470                _ => TextVariant::H6,
471            };
472            let size = variant.size();
473            let weight = variant.weight();
474            let id = ElementId::Name(format!("{}-h{}-{}", id_prefix, level, idx).into());
475
476            let top_margin = match level {
477                1 => px(24.0),
478                2 => px(20.0),
479                3 => px(16.0),
480                _ => px(12.0),
481            };
482
483            let el = render_inline_element(content, size, on_link_click, Some(id), cx);
484            div()
485                .mt(top_margin)
486                .mb(px(8.0))
487                .font_weight(weight)
488                .child(el)
489                .into_any_element()
490        }
491
492        RichBlock::CodeBlock { language, code } => {
493            let mut cb = CodeBlock::new(code.clone())
494                .show_line_numbers(true)
495                .show_copy_button(true);
496            if let Some(lang) = language {
497                cb = cb.language(lang.clone());
498            }
499            div().mb(px(12.0)).child(cb).into_any_element()
500        }
501
502        RichBlock::BlockQuote(inner_blocks) => {
503            let children = render_blocks(inner_blocks, base_size, on_link_click, id_prefix, cx);
504            div()
505                .mb(px(12.0))
506                .pl(px(16.0))
507                .border_l(px(4.0))
508                .border_color(theme.tokens.border)
509                .bg(theme.tokens.muted.opacity(0.15))
510                .py(px(4.0))
511                .text_color(theme.tokens.muted_foreground)
512                .children(children)
513                .into_any_element()
514        }
515
516        RichBlock::UnorderedList { items } => {
517            let mut render_context = RichBlockRenderContext {
518                base_size,
519                on_link_click,
520                id_prefix,
521                block_idx,
522                cx,
523            };
524            let children = render_list_items(items, &mut render_context, false, 1);
525            div().mb(px(12.0)).children(children).into_any_element()
526        }
527
528        RichBlock::OrderedList { start, items } => {
529            let mut render_context = RichBlockRenderContext {
530                base_size,
531                on_link_click,
532                id_prefix,
533                block_idx,
534                cx,
535            };
536            let children = render_list_items(items, &mut render_context, true, *start);
537            div().mb(px(12.0)).children(children).into_any_element()
538        }
539
540        RichBlock::Table {
541            headers,
542            alignments,
543            rows,
544        } => {
545            let mut render_context = RichBlockRenderContext {
546                base_size,
547                on_link_click,
548                id_prefix,
549                block_idx,
550                cx,
551            };
552            render_table(headers, alignments, rows, &mut render_context)
553        }
554
555        RichBlock::HorizontalRule => div()
556            .my(px(16.0))
557            .child(Separator::new())
558            .into_any_element(),
559
560        RichBlock::Image { alt: _, url } => div()
561            .mb(px(12.0))
562            .child(img(SharedString::from(url.clone())).max_w(px(600.0)))
563            .into_any_element(),
564    }
565}
566
567fn render_inline_element(
568    inlines: &[RichInline],
569    base_size: Pixels,
570    on_link_click: &Option<LinkClickHandler>,
571    element_id: Option<ElementId>,
572    cx: &App,
573) -> AnyElement {
574    let theme = use_theme(cx);
575    let font_family = theme.tokens.font_family.clone();
576    let font_mono = theme.tokens.font_mono.clone();
577    let text_color = theme.tokens.foreground;
578    let link_color = theme.tokens.primary;
579    let code_bg = theme.tokens.muted.opacity(0.3);
580
581    let flattened = InlineFlattener::new(font_family, font_mono, text_color, link_color, code_bg)
582        .flatten(inlines);
583
584    if flattened.text.is_empty() {
585        return div().into_any_element();
586    }
587
588    let styled = StyledText::new(SharedString::from(flattened.text)).with_runs(flattened.runs);
589
590    if !flattened.links.is_empty() {
591        let id = element_id.unwrap_or_else(|| ElementId::Name("rich-inline".into()));
592        let click_ranges: Vec<std::ops::Range<usize>> =
593            flattened.links.iter().map(|l| l.range.clone()).collect();
594        let urls: Vec<String> = flattened.links.iter().map(|l| l.url.clone()).collect();
595        let handler = on_link_click.clone();
596
597        return div()
598            .text_size(base_size)
599            .line_height(relative(1.5))
600            .debug_selector(|| "rich-text-link".into())
601            .child(InteractiveText::new(id, styled).on_click(
602                click_ranges,
603                move |idx, window, cx| {
604                    if let Some(url) = urls.get(idx) {
605                        dispatch_link_click(&handler, url, window, cx);
606                    }
607                },
608            ))
609            .into_any_element();
610    }
611
612    div()
613        .text_size(base_size)
614        .line_height(relative(1.5))
615        .child(styled)
616        .into_any_element()
617}
618
619struct RichBlockRenderContext<'a> {
620    base_size: Pixels,
621    on_link_click: &'a Option<LinkClickHandler>,
622    id_prefix: &'a str,
623    block_idx: &'a mut u32,
624    cx: &'a App,
625}
626
627fn render_list_items(
628    items: &[ListItem],
629    context: &mut RichBlockRenderContext<'_>,
630    ordered: bool,
631    start: u64,
632) -> Vec<AnyElement> {
633    let theme = use_theme(context.cx);
634    let mut elements = Vec::new();
635
636    for (i, item) in items.iter().enumerate() {
637        *context.block_idx += 1;
638        let idx = *context.block_idx;
639
640        let bullet = if let Some(checked) = item.checked {
641            if checked {
642                SharedString::from("[x] ")
643            } else {
644                SharedString::from("[ ] ")
645            }
646        } else if ordered {
647            SharedString::from(format!("{}. ", start + i as u64))
648        } else {
649            SharedString::from("\u{2022} ")
650        };
651
652        let id = ElementId::Name(format!("{}-li-{}", context.id_prefix, idx).into());
653        let content_el = render_inline_element(
654            &item.content,
655            context.base_size,
656            context.on_link_click,
657            Some(id),
658            context.cx,
659        );
660
661        let row = div()
662            .flex()
663            .flex_row()
664            .pl(px(20.0))
665            .mb(px(4.0))
666            .child(
667                div()
668                    .flex_shrink_0()
669                    .w(px(24.0))
670                    .text_size(context.base_size)
671                    .text_color(theme.tokens.muted_foreground)
672                    .child(bullet),
673            )
674            .child(div().flex_1().child(content_el));
675
676        elements.push(row.into_any_element());
677
678        if !item.children.is_empty() {
679            let children = render_list_items(&item.children, context, false, 1);
680            elements.push(div().pl(px(20.0)).children(children).into_any_element());
681        }
682    }
683
684    elements
685}
686
687fn render_table(
688    headers: &[Vec<RichInline>],
689    alignments: &[TableAlignment],
690    rows: &[Vec<Vec<RichInline>>],
691    context: &mut RichBlockRenderContext<'_>,
692) -> AnyElement {
693    let theme = use_theme(context.cx);
694    let col_count = headers.len();
695    if col_count == 0 {
696        return div().into_any_element();
697    }
698
699    let mut table = div()
700        .mb(px(12.0))
701        .w_full()
702        .rounded(theme.tokens.radius_sm)
703        .border_1()
704        .border_color(theme.tokens.border)
705        .overflow_hidden();
706
707    *context.block_idx += 1;
708    let header_row = {
709        let mut row = div()
710            .flex()
711            .flex_row()
712            .bg(theme.tokens.muted.opacity(0.3))
713            .border_b_1()
714            .border_color(theme.tokens.border);
715
716        for (ci, header) in headers.iter().enumerate() {
717            *context.block_idx += 1;
718            let id =
719                ElementId::Name(format!("{}-th-{}", context.id_prefix, *context.block_idx).into());
720            let el = render_inline_element(
721                header,
722                context.base_size,
723                context.on_link_click,
724                Some(id),
725                context.cx,
726            );
727            let mut cell = div()
728                .flex_1()
729                .px(px(12.0))
730                .py(px(8.0))
731                .font_weight(FontWeight::SEMIBOLD)
732                .text_size(context.base_size)
733                .child(el);
734
735            if ci < alignments.len() {
736                cell = match &alignments[ci] {
737                    TableAlignment::Center => cell.items_center(),
738                    TableAlignment::Right => cell.items_end(),
739                    TableAlignment::Left => cell,
740                };
741            }
742
743            row = row.child(cell);
744        }
745        row
746    };
747    table = table.child(header_row);
748
749    for (ri, row_data) in rows.iter().enumerate() {
750        *context.block_idx += 1;
751        let mut row = div()
752            .flex()
753            .flex_row()
754            .when(ri < rows.len() - 1, |this| {
755                this.border_b_1().border_color(theme.tokens.border)
756            })
757            .when(ri % 2 == 1, |this| this.bg(theme.tokens.muted.opacity(0.1)));
758
759        for (ci, cell_data) in row_data.iter().enumerate() {
760            *context.block_idx += 1;
761            let id =
762                ElementId::Name(format!("{}-td-{}", context.id_prefix, *context.block_idx).into());
763            let el = render_inline_element(
764                cell_data,
765                context.base_size,
766                context.on_link_click,
767                Some(id),
768                context.cx,
769            );
770            let mut cell = div()
771                .flex_1()
772                .px(px(12.0))
773                .py(px(6.0))
774                .text_size(context.base_size)
775                .child(el);
776
777            if ci < alignments.len() {
778                cell = match &alignments[ci] {
779                    TableAlignment::Center => cell.items_center(),
780                    TableAlignment::Right => cell.items_end(),
781                    TableAlignment::Left => cell,
782                };
783            }
784
785            row = row.child(cell);
786        }
787        table = table.child(row);
788    }
789
790    table.into_any_element()
791}
792
793#[cfg(test)]
794mod tests {
795    use super::{dispatch_link_click, LinkClickHandler};
796    use gpui::{Empty, TestApp};
797    use std::{cell::Cell, rc::Rc};
798
799    #[gpui::test]
800    fn custom_link_handler_is_invoked() {
801        let calls = Rc::new(Cell::new(0));
802        let calls_for_handler = calls.clone();
803        let handler: Option<LinkClickHandler> = Some(Rc::new(move |url, _, _| {
804            assert_eq!(url, "https://example.com");
805            calls_for_handler.set(calls_for_handler.get() + 1);
806        }));
807        let mut app = TestApp::new();
808        let mut window = app.open_window(|_, _| Empty);
809
810        window.update(|_, window, cx| {
811            dispatch_link_click(&handler, "https://example.com", window, cx);
812        });
813
814        assert_eq!(calls.get(), 1);
815    }
816
817    #[gpui::test]
818    fn disallowed_link_schemes_are_ignored() {
819        let calls = Rc::new(Cell::new(0));
820        let calls_for_handler = calls.clone();
821        let handler: Option<LinkClickHandler> = Some(Rc::new(move |_, _, _| {
822            calls_for_handler.set(calls_for_handler.get() + 1);
823        }));
824        let none_handler: Option<LinkClickHandler> = None;
825        let mut app = TestApp::new();
826        let mut window = app.open_window(|_, _| Empty);
827
828        window.update(|_, window, cx| {
829            dispatch_link_click(&handler, "javascript:alert(1)", window, cx);
830            dispatch_link_click(&handler, "ftp://example.com/file", window, cx);
831            dispatch_link_click(&none_handler, "file:///etc/passwd", window, cx);
832            dispatch_link_click(&handler, "mailto:user@example.com", window, cx);
833        });
834
835        assert_eq!(calls.get(), 1);
836    }
837}