Skip to main content

markdown/
render.rs

1//! [`Doc`] → gpui elements.
2//!
3//! Numbers drive layout (sizes, line heights, paddings — the constants here);
4//! colors are paint, read from [`Theme`]. Blocks are a flat list, so nesting is
5//! left padding rather than nested containers, and the gap between two blocks
6//! is decided by the pair: list items sit tight, everything else breathes.
7//!
8//! Ported from zeronsh/comet (MIT) and rebuilt against the flat block model.
9
10use crate::AppExt as _;
11use std::{
12    cell::RefCell,
13    collections::HashMap,
14    hash::{DefaultHasher, Hash, Hasher},
15    ops::Range,
16    path::Path,
17    rc::Rc,
18};
19use ui::AppExt as _;
20use ui::widgets::Layout as _;
21
22use gpui::{
23    AnyElement, App, BorderStyle, Bounds, CursorStyle, ElementId, FontStyle, FontWeight, Hsla,
24    ImageSource, InteractiveText, MouseButton, ObjectFit, Pixels, Point, SharedString,
25    StrikethroughStyle, StyledImage as _, StyledText, TextLayout, TextRun, UnderlineStyle, Window,
26    canvas, div, font, img, point, prelude::*, px, quad, size,
27};
28use theme::{TextStyle, Theme, Typeset};
29
30use crate::{
31    block,
32    doc::{Align, Block, BlockKind, Doc, Form, Mark, Part, QuoteKind, Text},
33    preview,
34    select::{Affinity, Cursor, Selection},
35    typography::Typography,
36};
37
38/// Space between two ordinary blocks, and the tighter space inside a list.
39mod code;
40mod column;
41mod layouts;
42mod media;
43mod table;
44mod text;
45
46pub use code::*;
47use column::*;
48pub use layouts::*;
49use media::*;
50use table::*;
51pub use text::*;
52
53const BLOCK_GAP: f32 = 12.0;
54const LIST_GAP: f32 = 4.0;
55/// One indent level. Wide enough to clear a marker and read as a level.
56const INDENT_WIDTH: f32 = 22.0;
57/// The marker column of a list row.
58const MARKER_WIDTH: f32 = 18.0;
59const MARKER_GAP: f32 = 8.0;
60/// What a fence holds its code in, inside its border.
61const CODE_PADDING_X: f32 = 12.0;
62const CODE_PADDING_Y: f32 = 10.0;
63/// What a fence with no info string calls itself, in its header and in a
64/// picker — one spelling, so the label and the menu row cannot disagree.
65pub const PLAIN_LANGUAGE: &str = "Plain";
66/// Width of the caret. Wider than a hairline, because it has to read at a
67/// glance against the text it sits in.
68const CARET_WIDTH: f32 = 1.5;
69/// Inline code's wash is a rounded quad painted under the glyphs: a run's
70/// `background_color` can only ever be a square box.
71const INLINE_CODE_RADIUS: f32 = 4.5;
72const INLINE_CODE_PAD_X: f32 = 2.0;
73const INLINE_CODE_INSET_Y: f32 = 2.0;
74/// A mention's hover card.
75const MENTION_CARD_WIDTH: f32 = 320.0;
76/// Bookmark metrics. Notion's card: 180px of image beside the text, and a
77/// height that fits a title, two lines of blurb and a footer. A cover moves
78/// that image above the text and gives it the card's full width.
79const CARD_HEIGHT: f32 = 116.0;
80const CARD_IMAGE_WIDTH: f32 = 180.0;
81const CARD_COVER_HEIGHT: f32 = 200.0;
82const CARD_PADDING: f32 = 14.0;
83const CARD_BORDER: f32 = 1.0;
84const CARD_ICON: f32 = 16.0;
85const CARD_COVER: f32 = 44.0;
86/// Image metrics.
87const IMAGE_EMPTY_HEIGHT: f32 = 52.0;
88const CAPTION_GAP: f32 = 4.0;
89/// What an image with no URL yet says, and what its caption says while empty.
90const IMAGE_EMPTY: &str = "Add an image";
91const CAPTION_HINT: &str = "Write a caption";
92/// Table metrics. The design is frameless: hairlines between rows are the only
93/// chrome — no outer box, no header fill, no rounding.
94const TABLE_CELL_PADDING: f32 = 12.0;
95/// Reserved lane for editor table controls, inside the block bounds.
96pub const TABLE_CONTROL_SIZE: f32 = 16.0;
97const TABLE_DIVIDER: f32 = 1.0;
98/// Floor for a column's max-content share, so a short column ("1k") beside a
99/// prose column keeps a readable width.
100const TABLE_MIN_COLUMN_CONTENT: f32 = 48.0;
101/// Narrowest a column wraps down to before the table scrolls instead.
102const TABLE_MIN_COLUMN_WIDTH: f32 = 96.0;
103
104/// What an image's one authored string is doing on the page.
105///
106/// SwiftUI keeps three things apart — `accessibilityLabel` for a reader that
107/// cannot see, `.help` for the pointer, and a caption you compose out of a
108/// `Text` under the picture. Markdown has one slot for all three, so this says
109/// which of them it is playing here rather than in the document, where it is
110/// the same string either way.
111///
112/// A named choice rather than a `bool`, so a surface that wants a third answer
113/// gets a variant instead of a second flag.
114#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
115pub enum Caption {
116    /// Under the picture, where a caret can sit in it. The editor's shape.
117    #[default]
118    Shown,
119    /// Kept by the document and painted nowhere — a picture on its own.
120    Hidden,
121}
122
123/// Whether a fence paints the button that copies its text.
124///
125/// A named choice rather than a `bool`, the way [`Caption`] is.
126#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
127pub enum CopyButton {
128    /// Floating at the top right of the band, on the pointer and off it.
129    #[default]
130    Shown,
131    /// Painted nowhere. A document with this and no [`Editing::toggle`] holds
132    /// no listener at all.
133    Hidden,
134}
135
136/// A range the caller wants washed, and which wash it gets.
137///
138/// None of what a comment or a highlight *says* is here: the caller keeps it
139/// and hands over the range, the way it hands over a [`crate::Preview`]. A
140/// closed set rather than a color, so the environment keeps deciding the paint.
141#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
142#[non_exhaustive]
143pub enum Annotation {
144    /// A thread still waiting on someone.
145    #[default]
146    Open,
147    /// Answered, and kept for the record.
148    Resolved,
149    /// The one whose thread the reader has in front of them.
150    Active,
151    /// A reader's highlight, in the wash [`crate::AppExt::set_highlight_paint`]
152    /// gives its colour.
153    Highlight(crate::HighlightColor),
154    /// A find hit.
155    Match,
156    /// The find hit the reader is on.
157    Current,
158}
159
160impl Annotation {
161    fn wash(self, theme: &Theme, highlight: crate::HighlightPaint, find: crate::FindPaint) -> Hsla {
162        match self {
163            Self::Open => theme.warning.opacity(0.20),
164            Self::Resolved => theme.warning.opacity(0.08),
165            Self::Active => theme.warning.opacity(0.38),
166            Self::Highlight(color) => highlight(color, theme),
167            Self::Match => find(theme).0,
168            Self::Current => find(theme).1,
169        }
170    }
171}
172
173/// Handed the block whose checkbox was clicked — see [`Toggle::Handled`].
174///
175/// Shared rather than borrowed: the press listener it is cloned into outlives
176/// the frame that built it.
177pub type OnToggle = Rc<dyn Fn(usize, &mut Window, &mut App)>;
178
179/// Handed the image block whose picture was clicked — see [`Editing::image`].
180pub type OnImage = Rc<dyn Fn(usize, &mut Window, &mut App)>;
181
182/// Handed the heading block a clicked `#fragment` link names — see
183/// [`Editing::jump`].
184pub type OnJump = Rc<dyn Fn(usize, &mut Window, &mut App)>;
185
186/// Builds a picture's hover control from its block index and original URL.
187pub type ImageOverlay = Rc<dyn Fn(usize, &str, &mut Window, &mut App) -> Option<AnyElement>>;
188
189/// Handed a fence's block index and its new code — see [`FenceHost::rewrite`].
190pub type OnRewrite = Rc<dyn Fn(usize, String, &mut Window, &mut App)>;
191
192/// Handed the block a painted fence is leaving — see [`FenceHost::leave`].
193pub type OnLeave = Rc<dyn Fn(usize, &mut Window, &mut App)>;
194
195/// Handed a resizable painted block's index and where its grip was pressed —
196/// see [`FenceHost::resize`].
197pub type OnResize = Rc<dyn Fn(usize, Pixels, &mut Window, &mut App)>;
198
199/// What an editor lends the blocks an installed [`crate::BlockRenderer`]
200/// paints — see [`Editing::fence`].
201#[derive(Clone)]
202pub struct FenceHost {
203    /// Replaces the code of the fence at a block index, as an edit of the
204    /// document.
205    pub rewrite: OnRewrite,
206    /// Hands the keyboard back to the document from inside the painted block
207    /// at a block index. Dispatched by [`LeaveBlock`].
208    pub leave: OnLeave,
209    /// Starts a height drag off the grip along a resizable painted block's
210    /// foot, from the press's window `y`. `None` paints no grip.
211    pub resize: Option<OnResize>,
212}
213
214/// The key context around every painted fence. An editor's bindings stop at
215/// it, so keys typed into a control the block paints stay that control's.
216pub const PAINTED_CONTEXT: &str = "MarkdownPaintedBlock";
217
218gpui::actions!(
219    markdown,
220    [
221        /// Return focus from inside a painted fence to the document around it.
222        LeaveBlock
223    ]
224);
225
226/// The picture corner holding an app's hover control.
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
228pub enum ImageOverlayCorner {
229    TopLeft,
230    TopRight,
231    BottomLeft,
232    #[default]
233    BottomRight,
234}
235
236/// Who answers a press on a task block's checkbox.
237///
238/// Either variant paints the box as a control — the pointer over it is a hand.
239/// [`Editing::toggle`] left unset paints it as a mark, and the press goes
240/// wherever it would on any other glyph.
241#[derive(Clone)]
242pub enum Toggle {
243    /// The box takes the press, stops it, and calls this with the block it
244    /// belongs to. For a caller holding the [`Doc`] it renders itself.
245    Handled(OnToggle),
246    /// The box takes no press. The caller hit-tests
247    /// [`BlockLayouts::checkbox_bounds`] in its own handler, which is what an
248    /// editor does: the press it swallows is the one that also takes focus and
249    /// closes an open menu, and the toggle belongs in the undo history beside
250    /// the rest of its edits.
251    HitTested,
252}
253
254/// What an editor paints over a document.
255///
256/// One value rather than six parameters, and the reason it is public: the
257/// caret, the selection, the comment washes and the layout sink all arrive
258/// together or not at all, and a read-only [`render`] sets none of them.
259#[derive(Clone)]
260pub struct Editing<'a> {
261    /// The caret and what it has selected. `None` paints neither — a document
262    /// nobody is editing.
263    pub selection: Option<Selection>,
264    /// The blink's lit half. A caret painted on every frame reads as frozen,
265    /// and the phase belongs to whoever owns the focus.
266    pub caret_on: bool,
267    /// Filled as the document paints, for a caller resolving clicks against it.
268    ///
269    /// Given, only the blocks near the part of the window the document shows
270    /// are built, and it answers for those alone. The rest are placed at their
271    /// last measured height, or a guess at one, and held in it across frames.
272    pub layouts: Option<&'a BlockLayouts>,
273    /// Ranges washed under the text, in the order given.
274    pub annotations: &'a [(Selection, Annotation)],
275    /// Shown on the caret's block while it holds nothing.
276    pub placeholder: Option<SharedString>,
277    pub caption: Caption,
278    /// What to set the document in. `None` takes the installed
279    /// [`Typography`] — a caller sizing one document apart from the rest
280    /// passes [`Typography::scaled`].
281    pub typography: Option<Typography>,
282    /// Makes a task block's checkbox a control, and says who answers the
283    /// press. `None` paints a mark.
284    pub toggle: Option<Toggle>,
285    /// Handles a picture click with its block index, keeping the arrow cursor. A
286    /// press and release more than a couple of pixels apart is a drag and
287    /// calls nothing. The press still reaches whatever is under the picture.
288    pub image: Option<OnImage>,
289    /// An app control inset at `image_overlay_corner`, visible on hover.
290    /// Its presses do not reach the picture. `None` adds no listeners.
291    pub image_overlay: Option<ImageOverlay>,
292    /// Corner for the picture control; defaults to bottom-right.
293    pub image_overlay_corner: ImageOverlayCorner,
294    /// Lets a painted fence rewrite its own code and give the keyboard back.
295    /// `None` paints a fence that can do neither.
296    pub fence: Option<FenceHost>,
297    /// A painted block held at a height while its resize handle is dragged:
298    /// the block index and the height, in place of the one the document says.
299    pub sizing: Option<(usize, u32)>,
300    /// Reserves lanes around tables for editor controls.
301    pub table_controls: bool,
302    /// Whether a fence offers to copy itself.
303    pub copy: CopyButton,
304    /// The directory a relative image path is joined onto. `None` leaves it
305    /// relative, which gpui reads against the process's working directory.
306    pub base: Option<&'a Path>,
307    /// Blocks built wherever they are, alongside the ones near the part of the
308    /// window the document shows — source lines, for [`render_source`]. The
309    /// caret's and the selection anchor's are built without being named. Only
310    /// read with `layouts` given.
311    pub keep: &'a [usize],
312    /// The scroll container the document sits in. When blocks above the text
313    /// showing come out taller or shorter than they were placed at, its offset
314    /// moves by the difference. Only read with `layouts` given.
315    pub scroll: Option<&'a gpui::ScrollHandle>,
316    /// Scrolls to the heading a clicked `#fragment` link names, matched by
317    /// [`crate::link::heading`]. `None`, or a fragment naming no heading,
318    /// makes the click do nothing.
319    pub jump: Option<OnJump>,
320}
321
322impl Default for Editing<'_> {
323    fn default() -> Self {
324        Self {
325            selection: None,
326            // Lit, so that a caller setting a selection and nothing else gets a
327            // caret rather than a mystery.
328            caret_on: true,
329            layouts: None,
330            annotations: &[],
331            placeholder: None,
332            caption: Caption::default(),
333            typography: None,
334            toggle: None,
335            image: None,
336            image_overlay: None,
337            image_overlay_corner: ImageOverlayCorner::BottomRight,
338            fence: None,
339            sizing: None,
340            table_controls: false,
341            copy: CopyButton::default(),
342            base: None,
343            keep: &[],
344            scroll: None,
345            jump: None,
346        }
347    }
348}
349
350/// What the editor needs painted into one text: which text it is, where the
351/// caret sits, and where to record the layout a click resolves against.
352///
353/// One bundle rather than four parameters threaded through every block arm —
354/// a read-only render builds it with no caret and no sink, and pays nothing.
355#[derive(Clone, Copy)]
356struct Overlay<'a> {
357    block: usize,
358    part: Part,
359    selection: Option<Selection>,
360    caret_on: bool,
361    caret_shape: ui::input::CaretShape,
362    caret_height: ui::input::CaretHeight,
363    caret_inactive: ui::input::InactiveCaret,
364    /// A block caret is hollow, and cuts no glyph out, while this is false.
365    window_active: bool,
366    layouts: Option<&'a BlockLayouts>,
367    /// Ranges washed under the text, in the order the caller gave them.
368    annotations: &'a [(Selection, Annotation)],
369    /// Shown on the caret's block while it holds nothing. The renderer is the
370    /// only thing that knows where that text sits, so the string comes to it.
371    placeholder: Option<&'a SharedString>,
372    caption: Caption,
373    /// Borrowed so [`Overlay`] stays `Copy` — the clone is made at the one
374    /// press listener that needs an owned handle.
375    toggle: Option<&'a Toggle>,
376    image: Option<&'a OnImage>,
377    image_overlay: Option<&'a ImageOverlay>,
378    image_overlay_corner: ImageOverlayCorner,
379    fence: Option<&'a FenceHost>,
380    sizing: Option<(usize, u32)>,
381    table_controls: bool,
382    copy: CopyButton,
383    base: Option<&'a Path>,
384    highlight: crate::HighlightPaint,
385    find: crate::FindPaint,
386    jump: Option<&'a crate::link::Jump>,
387}
388
389/// What a resizable painted block carries besides itself: where it landed,
390/// for the height drag, and the grip along its foot that starts one, shown
391/// while the block is hovered or being sized.
392fn resizable(overlay: &Overlay, theme: &Theme) -> Vec<AnyElement> {
393    let ix = overlay.block;
394    let mut parts = Vec::new();
395    if let Some(layouts) = overlay.layouts {
396        let layouts = layouts.clone();
397        parts.push(
398            canvas(
399                move |bounds, _, _| layouts.record_painted(ix, bounds),
400                |_, _, _, _| (),
401            )
402            .absolute()
403            .size_full()
404            .into_any_element(),
405        );
406    }
407    if let Some(resize) = overlay.fence.and_then(|host| host.resize.clone()) {
408        let dragging = overlay.held_height().is_some();
409        // Inside the block's foot rather than across its edge: the grip is
410        // shown while the block is hovered, and the pointer has to stay over
411        // the block to reach it. A strip only as wide as it needs, so the
412        // controls a block keeps in its corners stay pressable.
413        parts.push(
414            div()
415                .absolute()
416                .left_0()
417                .right_0()
418                .bottom_0()
419                .flex()
420                .justify_center()
421                .child(
422                    theme
423                        .grip_handle()
424                        .id(ElementId::named_usize("painted-grip", ix))
425                        .debug_selector(|| "painted-grip".into())
426                        .w(px(PAINTED_GRIP_WIDTH))
427                        .when(!dragging, |el| {
428                            el.invisible()
429                                .group_hover(painted_group(ix), |el| el.visible())
430                        })
431                        .on_mouse_down(MouseButton::Left, move |event, window, cx| {
432                            cx.stop_propagation();
433                            resize(ix, event.position.y, window, cx);
434                        }),
435                )
436                .into_any_element(),
437        );
438    }
439    parts
440}
441
442/// How wide the grip along a resizable painted block's foot can be pressed.
443const PAINTED_GRIP_WIDTH: f32 = 120.0;
444
445fn painted_group(ix: usize) -> SharedString {
446    SharedString::from(format!("painted-{ix}"))
447}
448
449impl<'a> Overlay<'a> {
450    fn at(self, part: Part) -> Self {
451        Self { part, ..self }
452    }
453
454    /// The height this block's resize handle is holding it at, if it is.
455    fn held_height(&self) -> Option<u32> {
456        self.sizing
457            .filter(|(ix, _)| *ix == self.block)
458            .map(|(_, height)| height)
459    }
460
461    fn here(&self) -> Cursor {
462        Cursor::new(self.block, self.part, 0)
463    }
464
465    /// The caret to paint: where it is, only on the blink's lit half, and
466    /// never over a non-empty selection.
467    ///
468    /// Separate from [`Self::caret`] because the blink must not reach anything
469    /// but the quad — a block whose paint depends on holding the caret would
470    /// otherwise swap itself out twice a second.
471    fn caret_painted(&self) -> Option<usize> {
472        let collapsed = self.selection.is_some_and(|s| s.is_collapsed());
473        let shown = self
474            .caret_shape
475            .shown(self.window_active, self.caret_inactive);
476        (self.caret_on && collapsed && shown)
477            .then(|| self.caret())
478            .flatten()
479    }
480
481    /// The caret's row at a soft wrap.
482    fn affinity(&self) -> Affinity {
483        self.selection
484            .map_or_else(Affinity::default, |selection| selection.affinity)
485    }
486
487    /// The grapheme after the caret, which a solid block covers. None at the
488    /// end of a row before a wrap, where that grapheme starts the next row.
489    fn covered(&self, text: &str, offset: usize) -> Option<Range<usize>> {
490        (self.affinity() == Affinity::Downstream)
491            .then(|| glyph_at(text, offset))
492            .flatten()
493    }
494
495    fn caret_hollow(&self) -> bool {
496        !self.window_active
497    }
498
499    /// The caret's byte offset, if the head is in *this* text.
500    fn caret(&self) -> Option<usize> {
501        self.selection
502            .map(|selection| selection.head)
503            .filter(|head| head.block == self.block && head.part == self.part)
504            .map(|head| head.offset)
505    }
506
507    /// The selected slice of this text, clipped to it.
508    fn selected(&self, len: usize) -> Option<Range<usize>> {
509        self.clip(self.selection?, len)
510    }
511
512    /// The annotated slices of this text, already resolved to their paint —
513    /// the wash goes into a `move` closure that the theme does not travel into.
514    fn annotated(&self, len: usize, theme: &Theme) -> Vec<(Range<usize>, Hsla)> {
515        self.annotations
516            .iter()
517            .filter_map(|(range, kind)| {
518                Some((
519                    self.clip(*range, len)?,
520                    kind.wash(theme, self.highlight, self.find),
521                ))
522            })
523            .collect()
524    }
525
526    /// A range clipped to this text, and `None` when it does not reach it.
527    ///
528    /// The comparison is on `(block, part)` alone: a range covers this text
529    /// entirely when it starts before and ends after, and the offsets only
530    /// matter at the two ends.
531    fn clip(&self, selection: Selection, len: usize) -> Option<Range<usize>> {
532        if selection.is_collapsed() {
533            return None;
534        }
535        let (start, end) = selection.ordered();
536        let here = self.here();
537        let (first, last) = (
538            Cursor::new(start.block, start.part, 0),
539            Cursor::new(end.block, end.part, 0),
540        );
541        if here < first || here > last {
542            return None;
543        }
544        let from = if here == first { start.offset } else { 0 };
545        let to = if here == last { end.offset } else { len };
546        (from < to).then_some(from..to.min(len))
547    }
548
549    /// Whether a block painting something a caret cannot enter — a rule, a
550    /// picture — falls inside the selection, and so should show that it is
551    /// going to be taken.
552    fn covers_block(&self) -> bool {
553        let Some(selection) = self.selection.filter(|s| !s.is_collapsed()) else {
554            return false;
555        };
556        let (start, end) = selection.ordered();
557        start.block < self.block && self.block < end.block
558    }
559}
560
561/// What gpui loads for an image URL as written in a document.
562///
563/// Anything with `://` is fetched as it stands. Anything else is a file: an
564/// absolute path as it stands, a relative one joined onto `base` when there is
565/// one.
566pub fn image_source(url: &str, base: Option<&Path>) -> ImageSource {
567    if url.contains("://") {
568        return SharedString::from(url.to_string()).into();
569    }
570    // gpui reads a file only from a `PathBuf` — handed a string it looks for
571    // an asset built into the binary and paints nothing.
572    match base {
573        Some(base) => base.join(url).into(),
574        None => std::path::PathBuf::from(url).into(),
575    }
576}
577
578/// Parse and render in one step — the common case for read-only content.
579pub fn markdown(source: &str, window: &mut Window, cx: &mut App) -> AnyElement {
580    let doc = crate::parse_with(source, &cx.marks());
581    render(&doc, Caption::default(), window, cx)
582}
583
584/// Render a document.
585pub fn render(doc: &Doc, caption: Caption, window: &mut Window, cx: &mut App) -> AnyElement {
586    render_with(
587        doc,
588        Editing {
589            caption,
590            ..Editing::default()
591        },
592        window,
593        cx,
594    )
595}
596
597/// Render a document with a caret and a selection in it.
598///
599/// Both are paint-time concerns and nothing else: they read their positions off
600/// the shaped text's own layout handle, the same way the inline-code wash does,
601/// so nothing about layout depends on where the caret sits. An editor supplies
602/// the selection and owns the focus and the keys; painting a caret and a few
603/// quads is not worth a second renderer.
604pub fn render_with(doc: &Doc, editing: Editing, window: &mut Window, cx: &mut App) -> AnyElement {
605    let Editing {
606        selection,
607        caret_on,
608        layouts,
609        annotations,
610        placeholder,
611        caption,
612        typography,
613        toggle,
614        image,
615        image_overlay,
616        image_overlay_corner,
617        fence,
618        sizing,
619        table_controls,
620        copy,
621        base,
622        keep,
623        scroll,
624        jump,
625    } = editing;
626    // Cloned once so the theme is readable while `cx` stays free for the
627    // element state the copy button needs.
628    let theme = Theme::of(cx).clone();
629    let typography = typography.unwrap_or_else(|| cx.typography());
630    let highlight = crate::marks::highlight_paint_of(cx);
631    let find = crate::find::find_paint_of(cx);
632    let jump = jump.map(|to| crate::link::Jump::new(doc, to));
633    let gaps: Vec<Pixels> = doc
634        .blocks
635        .iter()
636        .enumerate()
637        .map(|(ix, block)| {
638            px(match doc.blocks.get(ix.wrapping_sub(1)) {
639                None => 0.0,
640                Some(previous) if tight(previous, block) => LIST_GAP,
641                Some(_) => BLOCK_GAP,
642            })
643        })
644        .collect();
645
646    let Some(layouts) = layouts else {
647        let mut column = div().flex().flex_col();
648        for (ix, block) in doc.blocks.iter().enumerate() {
649            let overlay = Overlay {
650                block: ix,
651                part: Part::Body,
652                selection,
653                caret_on,
654                caret_shape: cx.caret_shape(),
655                caret_height: cx.caret_height(),
656                caret_inactive: cx.inactive_caret(),
657                window_active: window.is_window_active(),
658                layouts: None,
659                annotations,
660                placeholder: placeholder.as_ref(),
661                caption,
662                toggle: toggle.as_ref(),
663                image: image.as_ref(),
664                image_overlay: image_overlay.as_ref(),
665                image_overlay_corner,
666                fence: fence.as_ref(),
667                sizing,
668                table_controls,
669                copy,
670                base,
671                highlight,
672                find,
673                jump: jump.as_ref(),
674            };
675            column = column
676                .child(block_box(block, overlay, &typography, &theme, window, cx).mt(gaps[ix]));
677        }
678        return column.into_any_element();
679    };
680
681    let keys: Vec<u64> = doc
682        .blocks
683        .iter()
684        .map(|block| block_key(block, &typography, table_controls))
685        .collect();
686    layouts.prune(&keys);
687    let guesses: Vec<Guess> = doc
688        .blocks
689        .iter()
690        .map(|block| {
691            let mut guess = guess(block, &typography);
692            if table_controls && matches!(block.kind, BlockKind::Table { .. }) {
693                guess.extra += px(2.0 * TABLE_CONTROL_SIZE);
694            }
695            guess
696        })
697        .collect();
698    let mut kept = keep.to_vec();
699    kept.extend(selection.map(|selection| selection.head.block));
700    kept.extend(selection.map(|selection| selection.anchor.block));
701    let owned = Owned {
702        blocks: doc.blocks.clone(),
703        selection,
704        caret_on,
705        layouts: layouts.clone(),
706        annotations: annotations.to_vec(),
707        placeholder,
708        caption,
709        toggle,
710        image,
711        image_overlay,
712        image_overlay_corner,
713        fence,
714        sizing,
715        table_controls,
716        copy,
717        base: base.map(Path::to_path_buf),
718        highlight,
719        find,
720        jump,
721        typography,
722        theme,
723    };
724    Column {
725        layouts: layouts.clone(),
726        keys: keys.into(),
727        gaps: gaps.into(),
728        guesses: guesses.into(),
729        keep: kept,
730        scroll: scroll.cloned(),
731        item_of: Box::new(|at| at.block),
732        build: Box::new(move |ix, window, cx| {
733            let overlay = Overlay {
734                block: ix,
735                part: Part::Body,
736                selection: owned.selection,
737                caret_on: owned.caret_on,
738                caret_shape: cx.caret_shape(),
739                caret_height: cx.caret_height(),
740                caret_inactive: cx.inactive_caret(),
741                window_active: window.is_window_active(),
742                layouts: Some(&owned.layouts),
743                annotations: &owned.annotations,
744                placeholder: owned.placeholder.as_ref(),
745                caption: owned.caption,
746                toggle: owned.toggle.as_ref(),
747                image: owned.image.as_ref(),
748                image_overlay: owned.image_overlay.as_ref(),
749                image_overlay_corner: owned.image_overlay_corner,
750                fence: owned.fence.as_ref(),
751                sizing: owned.sizing,
752                table_controls: owned.table_controls,
753                copy: owned.copy,
754                base: owned.base.as_deref(),
755                highlight: owned.highlight,
756                find: owned.find,
757                jump: owned.jump.as_ref(),
758            };
759            block_box(
760                &owned.blocks[ix],
761                overlay,
762                &owned.typography,
763                &owned.theme,
764                window,
765                cx,
766            )
767            .into_any_element()
768        }),
769    }
770    .into_any_element()
771}
772
773/// What [`Column`] builds a block from, owned so it can build one at prepaint.
774struct Owned {
775    blocks: Vec<Block>,
776    selection: Option<Selection>,
777    caret_on: bool,
778    layouts: BlockLayouts,
779    annotations: Vec<(Selection, Annotation)>,
780    placeholder: Option<SharedString>,
781    caption: Caption,
782    toggle: Option<Toggle>,
783    image: Option<OnImage>,
784    image_overlay: Option<ImageOverlay>,
785    image_overlay_corner: ImageOverlayCorner,
786    fence: Option<FenceHost>,
787    sizing: Option<(usize, u32)>,
788    table_controls: bool,
789    copy: CopyButton,
790    base: Option<std::path::PathBuf>,
791    highlight: crate::HighlightPaint,
792    find: crate::FindPaint,
793    jump: Option<crate::link::Jump>,
794    typography: Typography,
795    theme: Theme,
796}
797
798/// A block's box: its indent outside, and inside it the recorder and the
799/// block itself.
800fn block_box(
801    block: &Block,
802    overlay: Overlay,
803    typography: &Typography,
804    theme: &Theme,
805    window: &mut Window,
806    cx: &mut App,
807) -> gpui::Div {
808    let ix = overlay.block;
809    // The block's own box, recorded for a gutter handle and a drop target.
810    // A rule and an image hold no text, so a layout would not find them.
811    let frame = overlay.layouts.map(|layouts| {
812        let layouts = layouts.clone();
813        canvas(
814            move |bounds, _, _| layouts.record_block(ix, bounds),
815            |_, _, _, _| (),
816        )
817        .absolute()
818        .size_full()
819    });
820    // The indent sits on the outside and the recorder on the inside, so what
821    // is recorded is the box the block's text actually occupies. Recorded
822    // outside the padding, every level answered with the same left edge, and a
823    // gutter handle placed from it stayed at the margin while the block it
824    // belongs to moved right.
825    div()
826        .w_full()
827        // Everything a block draws — cards, bands, captions — is set in the
828        // document's face unless it names its own.
829        .font_family(theme.font_body.clone())
830        .pl(px(block.indent as f32 * INDENT_WIDTH))
831        .child(
832            div()
833                .w_full()
834                .relative()
835                .children(frame)
836                // What a caret cannot enter still has to show it is inside the
837                // selection, or a rule between two paragraphs looks untouched
838                // right up until it disappears.
839                .when(overlay.covers_block() && block.opaque(), |el| {
840                    el.rounded(px(4.0)).bg(theme.selection)
841                })
842                .child(block_element(block, overlay, typography, theme, window, cx)),
843        )
844}
845
846/// What a block's height is cached under: its content and the type it is set
847/// in, so an edit elsewhere that shifts its index keeps the height.
848fn block_key(block: &Block, typography: &Typography, table_controls: bool) -> u64 {
849    let mut hasher = DefaultHasher::new();
850    table_controls.hash(&mut hasher);
851    block.hash(&mut hasher);
852    typography.body.size().to_bits().hash(&mut hasher);
853    typography.body.line_height().to_bits().hash(&mut hasher);
854    hasher.finish()
855}
856
857/// What a block is placed at before it has ever been built.
858fn guess(block: &Block, typography: &Typography) -> Guess {
859    let body = px(typography.body.line_height());
860    let prose = |chars: usize, line: Pixels| Guess {
861        chars,
862        line,
863        rows: 0,
864        extra: px(0.0),
865        indent: px(0.0),
866    };
867    let guess = match &block.kind {
868        BlockKind::Paragraph(text)
869        | BlockKind::Bullet(text)
870        | BlockKind::Ordered { text, .. }
871        | BlockKind::Task { text, .. }
872        | BlockKind::Quote { text, .. } => prose(text.text.len(), body),
873        BlockKind::Heading { level, text } => prose(
874            text.text.len(),
875            px(typography.heading(*level).line_height()),
876        ),
877        BlockKind::Code { code, .. } => Guess {
878            rows: code.text.lines().count().max(1),
879            line: px(typography.code.line_height()),
880            extra: px(2.0 * CODE_PADDING_Y) + body,
881            ..prose(0, body)
882        },
883        BlockKind::Table { rows, .. } => Guess {
884            rows: rows.len() + 1,
885            extra: px(2.0 * TABLE_CELL_PADDING + TABLE_DIVIDER) * (rows.len() + 1) as f32,
886            ..prose(0, body)
887        },
888        BlockKind::Image { alt, .. } => Guess {
889            extra: px(240.0),
890            ..prose(alt.text.len(), px(typography.caption.line_height()))
891        },
892        BlockKind::Bookmark { .. } => Guess {
893            extra: body * 3.0,
894            ..prose(0, body)
895        },
896        BlockKind::Rule => Guess {
897            extra: body,
898            ..prose(0, px(0.0))
899        },
900    };
901    Guess {
902        indent: px(block.indent as f32 * INDENT_WIDTH),
903        ..guess
904    }
905}
906
907/// Whether two adjacent blocks belong to the same list and should sit close.
908fn tight(previous: &Block, next: &Block) -> bool {
909    let marker = |block: &Block| {
910        matches!(
911            block.kind,
912            BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
913        )
914    };
915    marker(previous) && (marker(next) || next.indent > previous.indent)
916}
917
918fn block_element(
919    block: &Block,
920    overlay: Overlay,
921    typography: &Typography,
922    theme: &Theme,
923    window: &mut Window,
924    cx: &mut App,
925) -> AnyElement {
926    let body = overlay.at(Part::Body);
927    match &block.kind {
928        BlockKind::Paragraph(text) => text_element(
929            text,
930            typography.body.size(),
931            typography.body.line_height(),
932            FontWeight::NORMAL,
933            body,
934            theme,
935            cx,
936        ),
937        BlockKind::Heading { level, text } => {
938            let heading = typography.heading(*level);
939            text_element(
940                text,
941                heading.size(),
942                heading.line_height(),
943                heading.weight,
944                body,
945                theme,
946                cx,
947            )
948        }
949        BlockKind::Bullet(text) => {
950            marker_row(disc(typography, theme), text, body, typography, theme, cx)
951        }
952        BlockKind::Ordered { number, text } => marker_row(
953            div()
954                .flex_none()
955                .w(px(MARKER_WIDTH))
956                .text_size(px(typography.body.size()))
957                .line_height(px(typography.body.line_height()))
958                .text_color(theme.text_muted)
959                .child(SharedString::from(format!("{number}.")))
960                .into_any_element(),
961            text,
962            body,
963            typography,
964            theme,
965            cx,
966        ),
967        BlockKind::Task { checked, text } => marker_row(
968            checkbox(*checked, overlay, typography, theme),
969            text,
970            body,
971            typography,
972            theme,
973            cx,
974        ),
975        BlockKind::Quote { kind, text } => div()
976            .border_l_2()
977            .border_color(kind.map_or(theme.border_strong, |kind| alert_color(kind, theme)))
978            .pl(px(12.0))
979            .pr(px(10.0))
980            .py(px(2.0))
981            .text_color(theme.text_muted)
982            .children(kind.map(|kind| {
983                div()
984                    .pb(px(2.0))
985                    .text_size(px(typography.body.size()))
986                    .line_height(px(typography.body.line_height()))
987                    .font_weight(FontWeight::SEMIBOLD)
988                    .text_color(alert_color(kind, theme))
989                    .child(kind.label())
990            }))
991            .child(text_element(
992                text,
993                typography.body.size(),
994                typography.body.line_height(),
995                FontWeight::NORMAL,
996                body,
997                theme,
998                cx,
999            ))
1000            .into_any_element(),
1001        BlockKind::Code {
1002            language,
1003            code,
1004            height,
1005        } => {
1006            let overlay = overlay.at(Part::Code);
1007            let height = overlay.held_height().or(*height);
1008            // The caret in the fence gives the source back. A painted block is
1009            // still an editable one, and typing into it otherwise edits what
1010            // the reader cannot see.
1011            let painted = overlay
1012                .caret()
1013                .is_none()
1014                .then(|| {
1015                    let fence = block::Fence {
1016                        language: language.as_deref()?,
1017                        code: &code.text,
1018                        height,
1019                        rewrite: overlay.fence.map(|host| {
1020                            let (rewrite, ix) = (host.rewrite.clone(), overlay.block);
1021                            Rc::new(move |code: String, window: &mut Window, cx: &mut App| {
1022                                rewrite(ix, code, window, cx)
1023                            }) as block::Rewrite
1024                        }),
1025                    };
1026                    block::render(&fence, window, cx)
1027                })
1028                .flatten();
1029            match painted {
1030                // Painted, there is no text under the selection to carry it —
1031                // the wash an opaque block gets at the container comes here.
1032                Some(element) => div()
1033                    .key_context(PAINTED_CONTEXT)
1034                    .relative()
1035                    .when_some(overlay.fence, |el, host| {
1036                        let (leave, ix) = (host.leave.clone(), overlay.block);
1037                        el.on_action(move |_: &LeaveBlock, window, cx| leave(ix, window, cx))
1038                    })
1039                    .when(overlay.covers_block(), |el| {
1040                        el.rounded(px(4.0)).bg(theme.selection)
1041                    })
1042                    .group(painted_group(overlay.block))
1043                    .child(element)
1044                    .children(resizable(&overlay, theme))
1045                    .into_any_element(),
1046                None => code_block(
1047                    language.as_deref(),
1048                    &code.text,
1049                    overlay,
1050                    typography,
1051                    theme,
1052                    window,
1053                    cx,
1054                ),
1055            }
1056        }
1057        BlockKind::Image { url, alt, width } => {
1058            image(url, alt, *width, overlay, typography, theme, window, cx)
1059        }
1060        BlockKind::Bookmark { url, form } => match crate::preview::card(
1061            url,
1062            match (*form, overlay.held_height()) {
1063                (Form::Embed(_), Some(held)) => Form::Embed(Some(held)),
1064                (form, _) => form,
1065            },
1066            window,
1067            cx,
1068        ) {
1069            // The app's own, painted where a fence's would be and kept apart
1070            // from the editor's keys the same way.
1071            Some(element) => div()
1072                .key_context(PAINTED_CONTEXT)
1073                .relative()
1074                .when_some(overlay.fence, |el, host| {
1075                    let (leave, ix) = (host.leave.clone(), overlay.block);
1076                    el.on_action(move |_: &LeaveBlock, window, cx| leave(ix, window, cx))
1077                })
1078                .when(overlay.covers_block(), |el| {
1079                    el.rounded(px(4.0)).bg(theme.selection)
1080                })
1081                .group(painted_group(overlay.block))
1082                .child(element)
1083                .children(match form {
1084                    Form::Embed(_) => resizable(&overlay, theme),
1085                    _ => Vec::new(),
1086                })
1087                .into_any_element(),
1088            None => bookmark(overlay.block, url, *form, typography, theme, cx),
1089        },
1090        BlockKind::Table {
1091            align,
1092            header,
1093            rows,
1094        } => table(align, header, rows, overlay, typography, theme, window, cx),
1095        BlockKind::Rule => div()
1096            .h(px(1.0))
1097            .w_full()
1098            .bg(theme.border)
1099            .into_any_element(),
1100    }
1101}
1102
1103/// A real 5px disc rather than the "•" glyph, which reads too small at body size.
1104fn disc(typography: &Typography, theme: &Theme) -> AnyElement {
1105    div()
1106        .flex_none()
1107        .w(px(MARKER_WIDTH))
1108        .h(px(typography.body.line_height()))
1109        .flex()
1110        .items_center()
1111        .child(
1112            div()
1113                .ml(px(1.0))
1114                .w(px(5.0))
1115                .h(px(5.0))
1116                .rounded_full()
1117                .bg(theme.text_faint),
1118        )
1119        .into_any_element()
1120}
1121
1122fn checkbox(checked: bool, overlay: Overlay, typography: &Typography, theme: &Theme) -> AnyElement {
1123    let ix = overlay.block;
1124    let mut box_ = div()
1125        .relative()
1126        .w(px(13.0))
1127        .h(px(13.0))
1128        .rounded(px(3.5))
1129        .border_1()
1130        .flex()
1131        .items_center()
1132        .justify_center();
1133    box_ = if checked {
1134        box_.bg(theme.solid)
1135            .border_color(theme.solid)
1136            .text_style(TextStyle::Caption)
1137            .text_color(theme.on_solid)
1138            .child("✓")
1139    } else {
1140        box_.border_color(theme.border_strong)
1141    };
1142    // The box's own bounds rather than the marker column's: a caller hit-tests
1143    // these to tell a toggle from a caret placed in the gutter beside it.
1144    box_ = box_.children(overlay.layouts.map(|layouts| {
1145        let layouts = layouts.clone();
1146        canvas(
1147            move |bounds, _, _| layouts.record_checkbox(ix, bounds),
1148            |_, _, _, _| (),
1149        )
1150        .absolute()
1151        .size_full()
1152    }));
1153    // The cursor answers to either variant: a box an editor hit-tests is as
1154    // pressable as one the renderer listens to, and only the pointer says so.
1155    if overlay.toggle.is_some() {
1156        box_ = box_.cursor_pointer();
1157    }
1158    if let Some(Toggle::Handled(toggle)) = overlay.toggle.cloned() {
1159        box_ = box_.on_mouse_down(MouseButton::Left, move |_, window, cx| {
1160            // Stopped, or the press goes on to whatever placed a caret
1161            // under it and the toggle reads as a click that moved the
1162            // caret as well.
1163            cx.stop_propagation();
1164            toggle(ix, window, cx);
1165        });
1166    }
1167
1168    div()
1169        .flex_none()
1170        .w(px(MARKER_WIDTH))
1171        .h(px(typography.body.line_height()))
1172        .flex()
1173        .items_center()
1174        .child(box_)
1175        .into_any_element()
1176}
1177
1178/// What an alert paints its rule and its label in.
1179fn alert_color(kind: QuoteKind, theme: &Theme) -> Hsla {
1180    match kind {
1181        QuoteKind::Note => theme.accent,
1182        QuoteKind::Tip => theme.success,
1183        QuoteKind::Important => theme.busy,
1184        QuoteKind::Warning => theme.warning,
1185        QuoteKind::Caution => theme.danger,
1186    }
1187}
1188
1189fn marker_row(
1190    marker: AnyElement,
1191    text: &Text,
1192    overlay: Overlay,
1193    typography: &Typography,
1194    theme: &Theme,
1195    cx: &App,
1196) -> AnyElement {
1197    div()
1198        .flex()
1199        .flex_row()
1200        .gap(px(MARKER_GAP))
1201        .child(marker)
1202        .child(div().flex_auto().min_w_0().child(text_element(
1203            text,
1204            typography.body.size(),
1205            typography.body.line_height(),
1206            FontWeight::NORMAL,
1207            overlay,
1208            theme,
1209            cx,
1210        )))
1211        .into_any_element()
1212}