markdown.rs

 1use gpui::{App, AppContext, ClipboardItem, Context, Entity, Window, div, prelude::*};
 2use language::Buffer;
 3use markdown::{Markdown, MarkdownElement, MarkdownFont, MarkdownStyle};
 4
 5use crate::outputs::OutputContent;
 6
 7pub struct MarkdownView {
 8    markdown: Entity<Markdown>,
 9}
10
11impl MarkdownView {
12    pub fn from(text: String, cx: &mut Context<Self>) -> Self {
13        let markdown = cx.new(|cx| Markdown::new(text.clone().into(), None, None, cx));
14
15        Self { markdown }
16    }
17}
18
19impl OutputContent for MarkdownView {
20    fn clipboard_content(&self, _window: &Window, cx: &App) -> Option<ClipboardItem> {
21        let source = self.markdown.read(cx).source().to_string();
22        Some(ClipboardItem::new_string(source))
23    }
24
25    fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
26        true
27    }
28
29    fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {
30        true
31    }
32
33    fn buffer_content(&mut self, _: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {
34        let source = self.markdown.read(cx).source().to_string();
35        let buffer = cx.new(|cx| {
36            let mut buffer =
37                Buffer::local(source.clone(), cx).with_language(language::PLAIN_TEXT.clone(), cx);
38            buffer.set_capability(language::Capability::ReadOnly, cx);
39            buffer
40        });
41        Some(buffer)
42    }
43}
44
45impl Render for MarkdownView {
46    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
47        let style = markdown_style(window, cx);
48        div()
49            .w_full()
50            .child(MarkdownElement::new(self.markdown.clone(), style))
51    }
52}
53
54fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
55    MarkdownStyle::themed(MarkdownFont::Editor, window, cx)
56}