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        {
156            return Some(editor);
157        }
158        None
159    }
160
161    fn create_markdown_view(
162        workspace: &mut Workspace,
163        editor: Entity<Editor>,
164        window: &mut Window,
165        cx: &mut Context<Workspace>,
166    ) -> Entity<MarkdownPreviewView> {
167        let language_registry = workspace.project().read(cx).languages().clone();
168        let workspace_handle = workspace.weak_handle();
169        MarkdownPreviewView::new(
170            MarkdownPreviewMode::Default,
171            editor,
172            workspace_handle,
173            language_registry,
174            window,
175            cx,
176        )
177    }
178
179    fn create_following_markdown_view(
180        workspace: &mut Workspace,
181        editor: Entity<Editor>,
182        window: &mut Window,
183        cx: &mut Context<Workspace>,
184    ) -> Entity<MarkdownPreviewView> {
185        let language_registry = workspace.project().read(cx).languages().clone();
186        let workspace_handle = workspace.weak_handle();
187        MarkdownPreviewView::new(
188            MarkdownPreviewMode::Follow,
189            editor,
190            workspace_handle,
191            language_registry,
192            window,
193            cx,
194        )
195    }
196
197    pub fn new(
198        mode: MarkdownPreviewMode,
199        active_editor: Entity<Editor>,
200        workspace: WeakEntity<Workspace>,
201        language_registry: Arc<LanguageRegistry>,
202        window: &mut Window,
203        cx: &mut Context<Workspace>,
204    ) -> Entity<Self> {
205        cx.new(|cx| {
206            let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
207
208            let mut this = Self {
209                selected_block: 0,
210                active_editor: None,
211                focus_handle: cx.focus_handle(),
212                workspace: workspace.clone(),
213                contents: None,
214                list_state,
215                language_registry,
216                parsing_markdown_task: None,
217                image_cache: RetainAllImageCache::new(cx),
218                mode,
219            };
220
221            this.set_editor(active_editor, window, cx);
222
223            if mode == MarkdownPreviewMode::Follow {
224                if let Some(workspace) = &workspace.upgrade() {
225                    cx.observe_in(workspace, window, |this, workspace, window, cx| {
226                        let item = workspace.read(cx).active_item(cx);
227                        this.workspace_updated(item, window, cx);
228                    })
229                    .detach();
230                } else {
231                    log::error!("Failed to listen to workspace updates");
232                }
233            }
234
235            this
236        })
237    }
238
239    fn workspace_updated(
240        &mut self,
241        active_item: Option<Box<dyn ItemHandle>>,
242        window: &mut Window,
243        cx: &mut Context<Self>,
244    ) {
245        if let Some(item) = active_item
246            && item.item_id() != cx.entity_id()
247            && let Some(editor) = item.act_as::<Editor>(cx)
248            && Self::is_markdown_file(&editor, cx)
249        {
250            self.set_editor(editor, window, cx);
251        }
252    }
253
254    pub fn is_markdown_file<V>(editor: &Entity<Editor>, cx: &mut Context<V>) -> bool {
255        let buffer = editor.read(cx).buffer().read(cx);
256        if let Some(buffer) = buffer.as_singleton()
257            && let Some(language) = buffer.read(cx).language()
258        {
259            return language.name() == "Markdown".into();
260        }
261        false
262    }
263
264    fn set_editor(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut Context<Self>) {
265        if let Some(active) = &self.active_editor
266            && active.editor == editor
267        {
268            return;
269        }
270
271        let subscription = cx.subscribe_in(
272            &editor,
273            window,
274            |this, editor, event: &EditorEvent, window, cx| {
275                match event {
276                    EditorEvent::Edited { .. }
277                    | EditorEvent::DirtyChanged
278                    | EditorEvent::ExcerptsEdited { .. } => {
279                        this.parse_markdown_from_active_editor(true, window, cx);
280                    }
281                    EditorEvent::SelectionsChanged { .. } => {
282                        let selection_range = editor
283                            .update(cx, |editor, cx| editor.selections.last::<usize>(cx).range());
284                        this.selected_block = this.get_block_index_under_cursor(selection_range);
285                        this.list_state.scroll_to_reveal_item(this.selected_block);
286                        cx.notify();
287                    }
288                    _ => {}
289                };
290            },
291        );
292
293        self.active_editor = Some(EditorState {
294            editor,
295            _subscription: subscription,
296        });
297
298        self.parse_markdown_from_active_editor(false, window, cx);
299    }
300
301    fn parse_markdown_from_active_editor(
302        &mut self,
303        wait_for_debounce: bool,
304        window: &mut Window,
305        cx: &mut Context<Self>,
306    ) {
307        if let Some(state) = &self.active_editor {
308            self.parsing_markdown_task = Some(self.parse_markdown_in_background(
309                wait_for_debounce,
310                state.editor.clone(),
311                window,
312                cx,
313            ));
314        }
315    }
316
317    fn parse_markdown_in_background(
318        &mut self,
319        wait_for_debounce: bool,
320        editor: Entity<Editor>,
321        window: &mut Window,
322        cx: &mut Context<Self>,
323    ) -> Task<Result<()>> {
324        let language_registry = self.language_registry.clone();
325
326        cx.spawn_in(window, async move |view, cx| {
327            if wait_for_debounce {
328                // Wait for the user to stop typing
329                cx.background_executor().timer(REPARSE_DEBOUNCE).await;
330            }
331
332            let (contents, file_location) = view.update(cx, |_, cx| {
333                let editor = editor.read(cx);
334                let contents = editor.buffer().read(cx).snapshot(cx).text();
335                let file_location = MarkdownPreviewView::get_folder_for_active_editor(editor, cx);
336                (contents, file_location)
337            })?;
338
339            let parsing_task = cx.background_spawn(async move {
340                parse_markdown(&contents, file_location, Some(language_registry)).await
341            });
342            let contents = parsing_task.await;
343            view.update(cx, move |view, cx| {
344                let markdown_blocks_count = contents.children.len();
345                view.contents = Some(contents);
346                let scroll_top = view.list_state.logical_scroll_top();
347                view.list_state.reset(markdown_blocks_count);
348                view.list_state.scroll_to(scroll_top);
349                cx.notify();
350            })
351        })
352    }
353
354    fn move_cursor_to_block(
355        &self,
356        window: &mut Window,
357        cx: &mut Context<Self>,
358        selection: Range<usize>,
359    ) {
360        if let Some(state) = &self.active_editor {
361            state.editor.update(cx, |editor, cx| {
362                editor.change_selections(
363                    SelectionEffects::scroll(Autoscroll::center()),
364                    window,
365                    cx,
366                    |selections| selections.select_ranges(vec![selection]),
367                );
368                window.focus(&editor.focus_handle(cx));
369            });
370        }
371    }
372
373    /// The absolute path of the file that is currently being previewed.
374    fn get_folder_for_active_editor(editor: &Editor, cx: &App) -> Option<PathBuf> {
375        if let Some(file) = editor.file_at(0, cx) {
376            if let Some(file) = file.as_local() {
377                file.abs_path(cx).parent().map(|p| p.to_path_buf())
378            } else {
379                None
380            }
381        } else {
382            None
383        }
384    }
385
386    fn get_block_index_under_cursor(&self, selection_range: Range<usize>) -> usize {
387        let mut block_index = None;
388        let cursor = selection_range.start;
389
390        let mut last_end = 0;
391        if let Some(content) = &self.contents {
392            for (i, block) in content.children.iter().enumerate() {
393                let Some(Range { start, end }) = block.source_range() else {
394                    continue;
395                };
396
397                // Check if the cursor is between the last block and the current block
398                if last_end <= cursor && cursor < start {
399                    block_index = Some(i.saturating_sub(1));
400                    break;
401                }
402
403                if start <= cursor && end >= cursor {
404                    block_index = Some(i);
405                    break;
406                }
407                last_end = end;
408            }
409
410            if block_index.is_none() && last_end < cursor {
411                block_index = Some(content.children.len().saturating_sub(1));
412            }
413        }
414
415        block_index.unwrap_or_default()
416    }
417
418    fn should_apply_padding_between(
419        current_block: &ParsedMarkdownElement,
420        next_block: Option<&ParsedMarkdownElement>,
421    ) -> bool {
422        !(current_block.is_list_item() && next_block.map(|b| b.is_list_item()).unwrap_or(false))
423    }
424
425    fn scroll_page_up(&mut self, _: &MovePageUp, _window: &mut Window, cx: &mut Context<Self>) {
426        let viewport_height = self.list_state.viewport_bounds().size.height;
427        if viewport_height.is_zero() {
428            return;
429        }
430
431        self.list_state.scroll_by(-viewport_height);
432        cx.notify();
433    }
434
435    fn scroll_page_down(&mut self, _: &MovePageDown, _window: &mut Window, cx: &mut Context<Self>) {
436        let viewport_height = self.list_state.viewport_bounds().size.height;
437        if viewport_height.is_zero() {
438            return;
439        }
440
441        self.list_state.scroll_by(viewport_height);
442        cx.notify();
443    }
444}
445
446impl Focusable for MarkdownPreviewView {
447    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
448        self.focus_handle.clone()
449    }
450}
451
452impl EventEmitter<()> for MarkdownPreviewView {}
453
454impl Item for MarkdownPreviewView {
455    type Event = ();
456
457    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
458        Some(Icon::new(IconName::FileDoc))
459    }
460
461    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
462        self.active_editor
463            .as_ref()
464            .and_then(|editor_state| {
465                let buffer = editor_state.editor.read(cx).buffer().read(cx);
466                let buffer = buffer.as_singleton()?;
467                let file = buffer.read(cx).file()?;
468                let local_file = file.as_local()?;
469                local_file
470                    .abs_path(cx)
471                    .file_name()
472                    .map(|name| format!("Preview {}", name.to_string_lossy()).into())
473            })
474            .unwrap_or_else(|| SharedString::from("Markdown Preview"))
475    }
476
477    fn telemetry_event_text(&self) -> Option<&'static str> {
478        Some("Markdown Preview Opened")
479    }
480
481    fn to_item_events(_event: &Self::Event, _f: impl FnMut(workspace::item::ItemEvent)) {}
482}
483
484impl Render for MarkdownPreviewView {
485    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
486        let buffer_size = ThemeSettings::get_global(cx).buffer_font_size(cx);
487        let buffer_line_height = ThemeSettings::get_global(cx).buffer_line_height;
488
489        v_flex()
490            .image_cache(self.image_cache.clone())
491            .id("MarkdownPreview")
492            .key_context("MarkdownPreview")
493            .track_focus(&self.focus_handle(cx))
494            .on_action(cx.listener(MarkdownPreviewView::scroll_page_up))
495            .on_action(cx.listener(MarkdownPreviewView::scroll_page_down))
496            .size_full()
497            .bg(cx.theme().colors().editor_background)
498            .p_4()
499            .text_size(buffer_size)
500            .line_height(relative(buffer_line_height.value()))
501            .child(div().flex_grow().map(|this| {
502                this.child(
503                    list(
504                        self.list_state.clone(),
505                        cx.processor(|this, ix, window, cx| {
506                            let Some(contents) = &this.contents else {
507                                return div().into_any();
508                            };
509
510                            let mut render_cx =
511                                RenderContext::new(Some(this.workspace.clone()), window, cx)
512                                    .with_checkbox_clicked_callback(cx.listener(
513                                        move |this, e: &CheckboxClickedEvent, window, cx| {
514                                            if let Some(editor) = this
515                                                .active_editor
516                                                .as_ref()
517                                                .map(|s| s.editor.clone())
518                                            {
519                                                editor.update(cx, |editor, cx| {
520                                                    let task_marker =
521                                                        if e.checked() { "[x]" } else { "[ ]" };
522
523                                                    editor.edit(
524                                                        vec![(e.source_range(), task_marker)],
525                                                        cx,
526                                                    );
527                                                });
528                                                this.parse_markdown_from_active_editor(
529                                                    false, window, cx,
530                                                );
531                                                cx.notify();
532                                            }
533                                        },
534                                    ));
535
536                            let block = contents.children.get(ix).unwrap();
537                            let rendered_block = render_markdown_block(block, &mut render_cx);
538
539                            let should_apply_padding = Self::should_apply_padding_between(
540                                block,
541                                contents.children.get(ix + 1),
542                            );
543
544                            div()
545                                .id(ix)
546                                .when(should_apply_padding, |this| {
547                                    this.pb(render_cx.scaled_rems(0.75))
548                                })
549                                .group("markdown-block")
550                                .on_click(cx.listener(
551                                    move |this, event: &ClickEvent, window, cx| {
552                                        if event.click_count() == 2
553                                            && let Some(source_range) = this
554                                                .contents
555                                                .as_ref()
556                                                .and_then(|c| c.children.get(ix))
557                                                .and_then(|block: &ParsedMarkdownElement| {
558                                                    block.source_range()
559                                                })
560                                        {
561                                            this.move_cursor_to_block(
562                                                window,
563                                                cx,
564                                                source_range.start..source_range.start,
565                                            );
566                                        }
567                                    },
568                                ))
569                                .map(move |container| {
570                                    let indicator = div()
571                                        .h_full()
572                                        .w(px(4.0))
573                                        .when(ix == this.selected_block, |this| {
574                                            this.bg(cx.theme().colors().border)
575                                        })
576                                        .group_hover("markdown-block", |s| {
577                                            if ix == this.selected_block {
578                                                s
579                                            } else {
580                                                s.bg(cx.theme().colors().border_variant)
581                                            }
582                                        })
583                                        .rounded_xs();
584
585                                    container.child(
586                                        div()
587                                            .relative()
588                                            .child(
589                                                div()
590                                                    .pl(render_cx.scaled_rems(1.0))
591                                                    .child(rendered_block),
592                                            )
593                                            .child(indicator.absolute().left_0().top_0()),
594                                    )
595                                })
596                                .into_any()
597                        }),
598                    )
599                    .size_full(),
600                )
601            }))
602    }
603}