markdown_preview_view.rs

  1use std::sync::Arc;
  2use std::time::Duration;
  3use std::{ops::Range, path::PathBuf};
  4
  5use anyhow::Result;
  6use editor::scroll::Autoscroll;
  7use editor::{Editor, EditorEvent, SelectionEffects};
  8use gpui::{
  9    App, ClickEvent, Context, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
 10    IntoElement, IsZero, ListState, ParentElement, Render, RetainAllImageCache, Styled,
 11    Subscription, Task, WeakEntity, Window, list,
 12};
 13use language::LanguageRegistry;
 14use settings::Settings;
 15use theme::ThemeSettings;
 16use ui::prelude::*;
 17use workspace::item::{Item, ItemHandle};
 18use workspace::{Pane, Workspace};
 19
 20use crate::markdown_elements::ParsedMarkdownElement;
 21use crate::markdown_renderer::CheckboxClickedEvent;
 22use crate::{
 23    MovePageDown, MovePageUp, OpenFollowingPreview, OpenPreview, OpenPreviewToTheSide,
 24    markdown_elements::ParsedMarkdown,
 25    markdown_parser::parse_markdown,
 26    markdown_renderer::{RenderContext, render_markdown_block},
 27};
 28
 29const REPARSE_DEBOUNCE: Duration = Duration::from_millis(200);
 30
 31pub struct MarkdownPreviewView {
 32    workspace: WeakEntity<Workspace>,
 33    image_cache: Entity<RetainAllImageCache>,
 34    active_editor: Option<EditorState>,
 35    focus_handle: FocusHandle,
 36    contents: Option<ParsedMarkdown>,
 37    selected_block: usize,
 38    list_state: ListState,
 39    language_registry: Arc<LanguageRegistry>,
 40    parsing_markdown_task: Option<Task<Result<()>>>,
 41    mode: MarkdownPreviewMode,
 42}
 43
 44#[derive(Clone, Copy, Debug, PartialEq)]
 45pub enum MarkdownPreviewMode {
 46    /// The preview will always show the contents of the provided editor.
 47    Default,
 48    /// The preview will "follow" the currently active editor.
 49    Follow,
 50}
 51
 52struct EditorState {
 53    editor: Entity<Editor>,
 54    _subscription: Subscription,
 55}
 56
 57impl MarkdownPreviewView {
 58    pub fn register(workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>) {
 59        workspace.register_action(move |workspace, _: &OpenPreview, window, cx| {
 60            if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
 61                let view = Self::create_markdown_view(workspace, editor.clone(), window, cx);
 62                workspace.active_pane().update(cx, |pane, cx| {
 63                    if let Some(existing_view_idx) =
 64                        Self::find_existing_independent_preview_item_idx(pane, &editor, cx)
 65                    {
 66                        pane.activate_item(existing_view_idx, true, true, window, cx);
 67                    } else {
 68                        pane.add_item(Box::new(view.clone()), true, true, None, window, cx)
 69                    }
 70                });
 71                cx.notify();
 72            }
 73        });
 74
 75        workspace.register_action(move |workspace, _: &OpenPreviewToTheSide, window, cx| {
 76            if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
 77                let view = Self::create_markdown_view(workspace, editor.clone(), window, cx);
 78                let pane = workspace
 79                    .find_pane_in_direction(workspace::SplitDirection::Right, cx)
 80                    .unwrap_or_else(|| {
 81                        workspace.split_pane(
 82                            workspace.active_pane().clone(),
 83                            workspace::SplitDirection::Right,
 84                            window,
 85                            cx,
 86                        )
 87                    });
 88                pane.update(cx, |pane, cx| {
 89                    if let Some(existing_view_idx) =
 90                        Self::find_existing_independent_preview_item_idx(pane, &editor, cx)
 91                    {
 92                        pane.activate_item(existing_view_idx, true, true, window, cx);
 93                    } else {
 94                        pane.add_item(Box::new(view.clone()), false, false, None, window, cx)
 95                    }
 96                });
 97                editor.focus_handle(cx).focus(window);
 98                cx.notify();
 99            }
100        });
101
102        workspace.register_action(move |workspace, _: &OpenFollowingPreview, window, cx| {
103            if let Some(editor) = Self::resolve_active_item_as_markdown_editor(workspace, cx) {
104                // Check if there's already a following preview
105                let existing_follow_view_idx = {
106                    let active_pane = workspace.active_pane().read(cx);
107                    active_pane
108                        .items_of_type::<MarkdownPreviewView>()
109                        .find(|view| view.read(cx).mode == MarkdownPreviewMode::Follow)
110                        .and_then(|view| active_pane.index_for_item(&view))
111                };
112
113                if let Some(existing_follow_view_idx) = existing_follow_view_idx {
114                    workspace.active_pane().update(cx, |pane, cx| {
115                        pane.activate_item(existing_follow_view_idx, true, true, window, cx);
116                    });
117                } else {
118                    let view =
119                        Self::create_following_markdown_view(workspace, editor.clone(), window, cx);
120                    workspace.active_pane().update(cx, |pane, cx| {
121                        pane.add_item(Box::new(view.clone()), true, true, None, window, cx)
122                    });
123                }
124                cx.notify();
125            }
126        });
127    }
128
129    fn find_existing_independent_preview_item_idx(
130        pane: &Pane,
131        editor: &Entity<Editor>,
132        cx: &App,
133    ) -> Option<usize> {
134        pane.items_of_type::<MarkdownPreviewView>()
135            .find(|view| {
136                let view_read = view.read(cx);
137                // Only look for independent (Default mode) previews, not Follow previews
138                view_read.mode == MarkdownPreviewMode::Default
139                    && view_read
140                        .active_editor
141                        .as_ref()
142                        .is_some_and(|active_editor| active_editor.editor == *editor)
143            })
144            .and_then(|view| pane.index_for_item(&view))
145    }
146
147    pub fn resolve_active_item_as_markdown_editor(
148        workspace: &Workspace,
149        cx: &mut Context<Workspace>,
150    ) -> Option<Entity<Editor>> {
151        if let Some(editor) = workspace
152            .active_item(cx)
153            .and_then(|item| item.act_as::<Editor>(cx))
154            && Self::is_markdown_file(&editor, cx) {
155                return Some(editor);
156            }
157        None
158    }
159
160    fn create_markdown_view(
161        workspace: &mut Workspace,
162        editor: Entity<Editor>,
163        window: &mut Window,
164        cx: &mut Context<Workspace>,
165    ) -> Entity<MarkdownPreviewView> {
166        let language_registry = workspace.project().read(cx).languages().clone();
167        let workspace_handle = workspace.weak_handle();
168        MarkdownPreviewView::new(
169            MarkdownPreviewMode::Default,
170            editor,
171            workspace_handle,
172            language_registry,
173            window,
174            cx,
175        )
176    }
177
178    fn create_following_markdown_view(
179        workspace: &mut Workspace,
180        editor: Entity<Editor>,
181        window: &mut Window,
182        cx: &mut Context<Workspace>,
183    ) -> Entity<MarkdownPreviewView> {
184        let language_registry = workspace.project().read(cx).languages().clone();
185        let workspace_handle = workspace.weak_handle();
186        MarkdownPreviewView::new(
187            MarkdownPreviewMode::Follow,
188            editor,
189            workspace_handle,
190            language_registry,
191            window,
192            cx,
193        )
194    }
195
196    pub fn new(
197        mode: MarkdownPreviewMode,
198        active_editor: Entity<Editor>,
199        workspace: WeakEntity<Workspace>,
200        language_registry: Arc<LanguageRegistry>,
201        window: &mut Window,
202        cx: &mut Context<Workspace>,
203    ) -> Entity<Self> {
204        cx.new(|cx| {
205            let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
206
207            let mut this = Self {
208                selected_block: 0,
209                active_editor: None,
210                focus_handle: cx.focus_handle(),
211                workspace: workspace.clone(),
212                contents: None,
213                list_state,
214                language_registry,
215                parsing_markdown_task: None,
216                image_cache: RetainAllImageCache::new(cx),
217                mode,
218            };
219
220            this.set_editor(active_editor, window, cx);
221
222            if mode == MarkdownPreviewMode::Follow {
223                if let Some(workspace) = &workspace.upgrade() {
224                    cx.observe_in(workspace, window, |this, workspace, window, cx| {
225                        let item = workspace.read(cx).active_item(cx);
226                        this.workspace_updated(item, window, cx);
227                    })
228                    .detach();
229                } else {
230                    log::error!("Failed to listen to workspace updates");
231                }
232            }
233
234            this
235        })
236    }
237
238    fn workspace_updated(
239        &mut self,
240        active_item: Option<Box<dyn ItemHandle>>,
241        window: &mut Window,
242        cx: &mut Context<Self>,
243    ) {
244        if let Some(item) = active_item
245            && item.item_id() != cx.entity_id()
246                && let Some(editor) = item.act_as::<Editor>(cx)
247                    && Self::is_markdown_file(&editor, cx) {
248                        self.set_editor(editor, window, cx);
249                    }
250    }
251
252    pub fn is_markdown_file<V>(editor: &Entity<Editor>, cx: &mut Context<V>) -> bool {
253        let buffer = editor.read(cx).buffer().read(cx);
254        if let Some(buffer) = buffer.as_singleton()
255            && let Some(language) = buffer.read(cx).language() {
256                return language.name() == "Markdown".into();
257            }
258        false
259    }
260
261    fn set_editor(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut Context<Self>) {
262        if let Some(active) = &self.active_editor
263            && active.editor == editor {
264                return;
265            }
266
267        let subscription = cx.subscribe_in(
268            &editor,
269            window,
270            |this, editor, event: &EditorEvent, window, cx| {
271                match event {
272                    EditorEvent::Edited { .. }
273                    | EditorEvent::DirtyChanged
274                    | EditorEvent::ExcerptsEdited { .. } => {
275                        this.parse_markdown_from_active_editor(true, window, cx);
276                    }
277                    EditorEvent::SelectionsChanged { .. } => {
278                        let selection_range = editor
279                            .update(cx, |editor, cx| editor.selections.last::<usize>(cx).range());
280                        this.selected_block = this.get_block_index_under_cursor(selection_range);
281                        this.list_state.scroll_to_reveal_item(this.selected_block);
282                        cx.notify();
283                    }
284                    _ => {}
285                };
286            },
287        );
288
289        self.active_editor = Some(EditorState {
290            editor,
291            _subscription: subscription,
292        });
293
294        self.parse_markdown_from_active_editor(false, window, cx);
295    }
296
297    fn parse_markdown_from_active_editor(
298        &mut self,
299        wait_for_debounce: bool,
300        window: &mut Window,
301        cx: &mut Context<Self>,
302    ) {
303        if let Some(state) = &self.active_editor {
304            self.parsing_markdown_task = Some(self.parse_markdown_in_background(
305                wait_for_debounce,
306                state.editor.clone(),
307                window,
308                cx,
309            ));
310        }
311    }
312
313    fn parse_markdown_in_background(
314        &mut self,
315        wait_for_debounce: bool,
316        editor: Entity<Editor>,
317        window: &mut Window,
318        cx: &mut Context<Self>,
319    ) -> Task<Result<()>> {
320        let language_registry = self.language_registry.clone();
321
322        cx.spawn_in(window, async move |view, cx| {
323            if wait_for_debounce {
324                // Wait for the user to stop typing
325                cx.background_executor().timer(REPARSE_DEBOUNCE).await;
326            }
327
328            let (contents, file_location) = view.update(cx, |_, cx| {
329                let editor = editor.read(cx);
330                let contents = editor.buffer().read(cx).snapshot(cx).text();
331                let file_location = MarkdownPreviewView::get_folder_for_active_editor(editor, cx);
332                (contents, file_location)
333            })?;
334
335            let parsing_task = cx.background_spawn(async move {
336                parse_markdown(&contents, file_location, Some(language_registry)).await
337            });
338            let contents = parsing_task.await;
339            view.update(cx, move |view, cx| {
340                let markdown_blocks_count = contents.children.len();
341                view.contents = Some(contents);
342                let scroll_top = view.list_state.logical_scroll_top();
343                view.list_state.reset(markdown_blocks_count);
344                view.list_state.scroll_to(scroll_top);
345                cx.notify();
346            })
347        })
348    }
349
350    fn move_cursor_to_block(
351        &self,
352        window: &mut Window,
353        cx: &mut Context<Self>,
354        selection: Range<usize>,
355    ) {
356        if let Some(state) = &self.active_editor {
357            state.editor.update(cx, |editor, cx| {
358                editor.change_selections(
359                    SelectionEffects::scroll(Autoscroll::center()),
360                    window,
361                    cx,
362                    |selections| selections.select_ranges(vec![selection]),
363                );
364                window.focus(&editor.focus_handle(cx));
365            });
366        }
367    }
368
369    /// The absolute path of the file that is currently being previewed.
370    fn get_folder_for_active_editor(editor: &Editor, cx: &App) -> Option<PathBuf> {
371        if let Some(file) = editor.file_at(0, cx) {
372            if let Some(file) = file.as_local() {
373                file.abs_path(cx).parent().map(|p| p.to_path_buf())
374            } else {
375                None
376            }
377        } else {
378            None
379        }
380    }
381
382    fn get_block_index_under_cursor(&self, selection_range: Range<usize>) -> usize {
383        let mut block_index = None;
384        let cursor = selection_range.start;
385
386        let mut last_end = 0;
387        if let Some(content) = &self.contents {
388            for (i, block) in content.children.iter().enumerate() {
389                let Some(Range { start, end }) = block.source_range() else {
390                    continue;
391                };
392
393                // Check if the cursor is between the last block and the current block
394                if last_end <= cursor && cursor < start {
395                    block_index = Some(i.saturating_sub(1));
396                    break;
397                }
398
399                if start <= cursor && end >= cursor {
400                    block_index = Some(i);
401                    break;
402                }
403                last_end = end;
404            }
405
406            if block_index.is_none() && last_end < cursor {
407                block_index = Some(content.children.len().saturating_sub(1));
408            }
409        }
410
411        block_index.unwrap_or_default()
412    }
413
414    fn should_apply_padding_between(
415        current_block: &ParsedMarkdownElement,
416        next_block: Option<&ParsedMarkdownElement>,
417    ) -> bool {
418        !(current_block.is_list_item() && next_block.map(|b| b.is_list_item()).unwrap_or(false))
419    }
420
421    fn scroll_page_up(&mut self, _: &MovePageUp, _window: &mut Window, cx: &mut Context<Self>) {
422        let viewport_height = self.list_state.viewport_bounds().size.height;
423        if viewport_height.is_zero() {
424            return;
425        }
426
427        self.list_state.scroll_by(-viewport_height);
428        cx.notify();
429    }
430
431    fn scroll_page_down(&mut self, _: &MovePageDown, _window: &mut Window, cx: &mut Context<Self>) {
432        let viewport_height = self.list_state.viewport_bounds().size.height;
433        if viewport_height.is_zero() {
434            return;
435        }
436
437        self.list_state.scroll_by(viewport_height);
438        cx.notify();
439    }
440}
441
442impl Focusable for MarkdownPreviewView {
443    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
444        self.focus_handle.clone()
445    }
446}
447
448impl EventEmitter<()> for MarkdownPreviewView {}
449
450impl Item for MarkdownPreviewView {
451    type Event = ();
452
453    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
454        Some(Icon::new(IconName::FileDoc))
455    }
456
457    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
458        self.active_editor
459            .as_ref()
460            .and_then(|editor_state| {
461                let buffer = editor_state.editor.read(cx).buffer().read(cx);
462                let buffer = buffer.as_singleton()?;
463                let file = buffer.read(cx).file()?;
464                let local_file = file.as_local()?;
465                local_file
466                    .abs_path(cx)
467                    .file_name()
468                    .map(|name| format!("Preview {}", name.to_string_lossy()).into())
469            })
470            .unwrap_or_else(|| SharedString::from("Markdown Preview"))
471    }
472
473    fn telemetry_event_text(&self) -> Option<&'static str> {
474        Some("Markdown Preview Opened")
475    }
476
477    fn to_item_events(_event: &Self::Event, _f: impl FnMut(workspace::item::ItemEvent)) {}
478}
479
480impl Render for MarkdownPreviewView {
481    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
482        let buffer_size = ThemeSettings::get_global(cx).buffer_font_size(cx);
483        let buffer_line_height = ThemeSettings::get_global(cx).buffer_line_height;
484
485        v_flex()
486            .image_cache(self.image_cache.clone())
487            .id("MarkdownPreview")
488            .key_context("MarkdownPreview")
489            .track_focus(&self.focus_handle(cx))
490            .on_action(cx.listener(MarkdownPreviewView::scroll_page_up))
491            .on_action(cx.listener(MarkdownPreviewView::scroll_page_down))
492            .size_full()
493            .bg(cx.theme().colors().editor_background)
494            .p_4()
495            .text_size(buffer_size)
496            .line_height(relative(buffer_line_height.value()))
497            .child(div().flex_grow().map(|this| {
498                this.child(
499                    list(
500                        self.list_state.clone(),
501                        cx.processor(|this, ix, window, cx| {
502                            let Some(contents) = &this.contents else {
503                                return div().into_any();
504                            };
505
506                            let mut render_cx =
507                                RenderContext::new(Some(this.workspace.clone()), window, cx)
508                                    .with_checkbox_clicked_callback(cx.listener(
509                                        move |this, e: &CheckboxClickedEvent, window, cx| {
510                                            if let Some(editor) = this
511                                                .active_editor
512                                                .as_ref()
513                                                .map(|s| s.editor.clone())
514                                            {
515                                                editor.update(cx, |editor, cx| {
516                                                    let task_marker =
517                                                        if e.checked() { "[x]" } else { "[ ]" };
518
519                                                    editor.edit(
520                                                        vec![(e.source_range(), task_marker)],
521                                                        cx,
522                                                    );
523                                                });
524                                                this.parse_markdown_from_active_editor(
525                                                    false, window, cx,
526                                                );
527                                                cx.notify();
528                                            }
529                                        },
530                                    ));
531
532                            let block = contents.children.get(ix).unwrap();
533                            let rendered_block = render_markdown_block(block, &mut render_cx);
534
535                            let should_apply_padding = Self::should_apply_padding_between(
536                                block,
537                                contents.children.get(ix + 1),
538                            );
539
540                            div()
541                                .id(ix)
542                                .when(should_apply_padding, |this| {
543                                    this.pb(render_cx.scaled_rems(0.75))
544                                })
545                                .group("markdown-block")
546                                .on_click(cx.listener(
547                                    move |this, event: &ClickEvent, window, cx| {
548                                        if event.click_count() == 2
549                                            && let Some(source_range) = this
550                                                .contents
551                                                .as_ref()
552                                                .and_then(|c| c.children.get(ix))
553                                                .and_then(|block: &ParsedMarkdownElement| {
554                                                    block.source_range()
555                                                })
556                                            {
557                                                this.move_cursor_to_block(
558                                                    window,
559                                                    cx,
560                                                    source_range.start..source_range.start,
561                                                );
562                                            }
563                                    },
564                                ))
565                                .map(move |container| {
566                                    let indicator = div()
567                                        .h_full()
568                                        .w(px(4.0))
569                                        .when(ix == this.selected_block, |this| {
570                                            this.bg(cx.theme().colors().border)
571                                        })
572                                        .group_hover("markdown-block", |s| {
573                                            if ix == this.selected_block {
574                                                s
575                                            } else {
576                                                s.bg(cx.theme().colors().border_variant)
577                                            }
578                                        })
579                                        .rounded_xs();
580
581                                    container.child(
582                                        div()
583                                            .relative()
584                                            .child(
585                                                div()
586                                                    .pl(render_cx.scaled_rems(1.0))
587                                                    .child(rendered_block),
588                                            )
589                                            .child(indicator.absolute().left_0().top_0()),
590                                    )
591                                })
592                                .into_any()
593                        }),
594                    )
595                    .size_full(),
596                )
597            }))
598    }
599}