Skip to main content

day_pieces/
markdown.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The Markdown view (docs/markdown-view.md): a read-only document that takes its height from
5//! its content.
6//!
7//! Composed here, once, from native labels and Day's containers, so it is the same piece on
8//! every toolkit and needs no toolkit duty: a paragraph or heading is a `label(…).markdown()`,
9//! a code block is a monospace label on the platform's card surface, a quote bar and a rule
10//! are dividers, and a list item is a marker label beside its content. The document is a
11//! column of such rows, one per [`MarkdownBlock`].
12//!
13//! The rows are kept, not rebuilt. When the text changes, [`MarkdownDocument::update`] parses
14//! from the last top-level block boundary before the change and says which block is the first
15//! to differ; rows below it are untouched, a row whose block kept its shape gets its new text
16//! through a signal (one label patch), and only rows whose shape changed are built again. A
17//! reply that streams in a token at a time therefore costs one block parse and one label patch
18//! per token, whatever the length of the text above it.
19
20use std::cell::RefCell;
21use std::rc::Rc;
22
23use day_core::*;
24use day_reactive::{Scope, Signal, watch};
25use day_spec::markdown::{MarkdownBlock, MarkdownBlockKind, MarkdownDocument};
26use day_spec::{Font, Insets, ListStyle, Role};
27
28use crate::*;
29
30/// The width a list marker takes before its item's text, and the gap after it.
31const MARKER_WIDTH: f64 = 22.0;
32/// How far each list level sits in from the one above: the marker and the gap after it.
33const LIST_INDENT: f64 = MARKER_WIDTH + ROW_GAP;
34/// The gap between a quote bar, a marker and the text.
35const ROW_GAP: f64 = 8.0;
36
37/// A read-only Markdown document that sizes to its content (docs/markdown-view.md).
38///
39/// Built by [`markdown()`]. It does not scroll and cannot be edited: put it in a chat bubble, a
40/// release note, a help page, or inside a `scroll` when the text can be long.
41#[must_use]
42pub struct Markdown {
43    text: TextSource,
44    font: Font,
45    color: Option<Reactive<day_spec::Ink>>,
46    spacing: f64,
47    selectable: bool,
48    on_link: Option<crate::leaves::LinkHandler>,
49    code_accessory: Option<CodeAccessory>,
50    block_id: Option<Rc<dyn Fn(usize) -> ElementId>>,
51}
52
53/// Builds the piece shown in a code block's header.
54type CodeAccessory = Rc<dyn Fn(MarkdownCode) -> AnyPiece>;
55
56/// Show block Markdown: headings, paragraphs with inline styles and links, bullet and numbered
57/// lists, block quotes, fenced code blocks and rules.
58///
59/// ```ignore
60/// markdown(res::str::release_notes())
61/// markdown(move || reply.get())          // a streamed reply: only the last block re-parses
62///     .code_accessory(|code| {
63///         button(res::str::copy())
64///             .icon(Symbol::Copy)
65///             .icon_only()
66///             .plain()
67///             .action(move || copy_text(code.text()))
68///     })
69/// ```
70///
71/// The text is a literal, a localized message, a `Signal<String>` or a closure. The view takes
72/// the width it is given and the height its content needs. Links open through [`open_link`]
73/// unless [`Markdown::on_link`] handles them.
74pub fn markdown<M>(text: impl IntoText<M>) -> Markdown {
75    Markdown {
76        text: text.into_text(),
77        font: Font::Body,
78        color: None,
79        spacing: Space::M.points(),
80        selectable: false,
81        on_link: None,
82        code_accessory: None,
83        block_id: None,
84    }
85}
86
87/// A fenced code block in a [`Markdown`] view, as its accessory sees it. `Copy`, and its reads
88/// are tracked, so a closure or an action that calls them always gets the current text, also
89/// while the block is still streaming in.
90#[derive(Clone, Copy)]
91pub struct MarkdownCode {
92    block: Signal<MarkdownBlock>,
93}
94
95impl MarkdownCode {
96    /// The code, verbatim, without the fences.
97    #[must_use]
98    pub fn text(&self) -> String {
99        self.block.with(|b| b.text.clone())
100    }
101    /// The language named after the opening fence; empty when there is none.
102    #[must_use]
103    pub fn language(&self) -> String {
104        self.block.with(|b| match &b.kind {
105            MarkdownBlockKind::Code { language } => language.clone(),
106            _ => String::new(),
107        })
108    }
109}
110
111#[day_macros::builder(MarkdownBuilder)]
112impl Markdown {
113    /// The font of paragraphs, list items, quotes and code (default [`Font::Body`]). Headings
114    /// take the semantic title styles whatever this is.
115    pub fn font(mut self, font: Font) -> Self {
116        self.font = font;
117        self
118    }
119    /// The text color of every block: a constant, a signal or a closure. Without it each block
120    /// draws in the platform's label color.
121    pub fn color<M>(mut self, color: impl IntoReactive<day_spec::Ink, M>) -> Self {
122        self.color = Some(color.into_reactive());
123        self
124    }
125    /// The gap between blocks: a [`Space`] step or points (default `Space::M`). Items of a
126    /// tight list sit closer, and a first- or second-level heading takes half again as much.
127    pub fn spacing(mut self, spacing: impl Into<f64>) -> Self {
128        self.spacing = spacing.into();
129        self
130    }
131    /// Let the reader select and copy the text of each block. Selection stays inside one
132    /// block: every block is its own native label.
133    pub fn selectable_text(mut self) -> Self {
134        self.selectable = true;
135        self
136    }
137    /// Handle a tapped link yourself. Without this a `#route` target navigates in-app and any
138    /// other target opens in the platform's default handler ([`open_link`]).
139    pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
140        self.on_link = Some(Rc::new(f));
141        self
142    }
143    /// Put a piece in the header of every code block, at its trailing edge: a copy button, a
144    /// "Run" button, a language badge of your own. The closure runs once per code block and
145    /// gets a [`MarkdownCode`] whose `text()` and `language()` read the block as it is now.
146    ///
147    /// Copying is the app's to do, because the clipboard is a part the app chooses to link
148    /// (`day-part-clipboard`).
149    pub fn code_accessory<P: Piece>(mut self, f: impl Fn(MarkdownCode) -> P + 'static) -> Self {
150        self.code_accessory = Some(Rc::new(move |code| AnyPiece::new(f(code))));
151        self
152    }
153    /// Give each block's text an element id for tests and `DayScript`, from its position in the
154    /// document: `.block_ids(|i| id!(reply_block, i))`. A rule has no text and takes no id.
155    pub fn block_ids(mut self, id: impl Fn(usize) -> ElementId + 'static) -> Self {
156        self.block_id = Some(Rc::new(id));
157        self
158    }
159}
160
161/// What decides how a block's row is built. A row whose block keeps its shape is updated
162/// through its signal; one whose shape changes is built again.
163#[derive(Clone, Debug, PartialEq)]
164struct RowShape {
165    kind: ShapeKind,
166    quote_depth: u8,
167    list_depth: u8,
168    marker: ListStyle,
169    /// The space above the row.
170    gap: f64,
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174enum ShapeKind {
175    Paragraph,
176    Heading(u8),
177    /// A code block, and whether it shows a header (a language or an accessory).
178    Code {
179        header: bool,
180    },
181    Rule,
182}
183
184/// One built row and the signal its labels read.
185struct BlockRow {
186    shape: RowShape,
187    block: Signal<MarkdownBlock>,
188    scope: Scope,
189    root: RNode,
190}
191
192/// The settings every row is built from.
193struct RowStyle {
194    font: Font,
195    color: Option<Reactive<day_spec::Ink>>,
196    spacing: f64,
197    selectable: bool,
198    on_link: Option<crate::leaves::LinkHandler>,
199    code_accessory: Option<CodeAccessory>,
200    block_id: Option<Rc<dyn Fn(usize) -> ElementId>>,
201}
202
203impl RowStyle {
204    fn shape(&self, block: &MarkdownBlock, previous: Option<&MarkdownBlock>) -> RowShape {
205        let kind = match &block.kind {
206            MarkdownBlockKind::Paragraph => ShapeKind::Paragraph,
207            MarkdownBlockKind::Heading(level) => ShapeKind::Heading(*level),
208            MarkdownBlockKind::Code { language } => ShapeKind::Code {
209                header: !language.is_empty() || self.code_accessory.is_some(),
210            },
211            MarkdownBlockKind::Rule => ShapeKind::Rule,
212        };
213        let gap = match previous {
214            None => 0.0,
215            // Items of a tight list, and the blocks inside one item, sit close together.
216            Some(prev) if !block.blank_before && block.list_depth > 0 && prev.list_depth > 0 => {
217                self.spacing / 3.0
218            }
219            Some(_) if matches!(kind, ShapeKind::Heading(1 | 2)) => self.spacing * 1.5,
220            Some(_) => self.spacing,
221        };
222        RowShape {
223            kind,
224            quote_depth: block.quote_depth,
225            list_depth: block.list_depth,
226            marker: block.marker,
227            gap,
228        }
229    }
230
231    /// A block's text as a label that follows its signal, with the view's color, link
232    /// handling, selection and id applied.
233    fn text(&self, block: Signal<MarkdownBlock>, index: usize, look: &TextLook) -> AnyPiece {
234        let mut text = label(move || block.with(|b| b.text.clone())).font(look.font);
235        if look.inline {
236            text = text.markdown();
237        }
238        if look.bold {
239            text = text.bold();
240        }
241        if look.monospace {
242            text = text.monospace();
243        }
244        text.color.clone_from(&self.color);
245        text.on_link.clone_from(&self.on_link);
246        let mut piece = text.any();
247        if self.selectable {
248            piece = piece.selectable().any();
249        }
250        if let Some(id) = &self.block_id {
251            piece = piece.id(id(index)).any();
252        }
253        piece
254    }
255
256    fn build(&self, shape: &RowShape, block: Signal<MarkdownBlock>, index: usize) -> AnyPiece {
257        let body = match shape.kind {
258            ShapeKind::Paragraph => self.text(
259                block,
260                index,
261                &TextLook {
262                    font: self.font,
263                    inline: true,
264                    bold: false,
265                    monospace: false,
266                },
267            ),
268            ShapeKind::Heading(level) => self
269                .text(
270                    block,
271                    index,
272                    &TextLook {
273                        font: heading_font(level),
274                        inline: true,
275                        // The two smallest levels share a size with body text and captions,
276                        // so weight is what marks them as headings.
277                        bold: level >= 5,
278                        monospace: false,
279                    },
280                )
281                .a11y(move |a| a.role(Role::Heading(level)))
282                .any(),
283            ShapeKind::Code { header } => self.code(block, index, header),
284            ShapeKind::Rule => divider().any(),
285        };
286        let top = Insets::top(shape.gap);
287        let mut cells: Vec<AnyPiece> = Vec::new();
288        for _ in 0..shape.quote_depth {
289            cells.push(divider().vertical().any());
290        }
291        let outer = f64::from(shape.list_depth.saturating_sub(1)) * LIST_INDENT;
292        let marker = match shape.marker {
293            ListStyle::None => None,
294            ListStyle::Bullet => Some("\u{2022}".to_owned()),
295            ListStyle::Ordered(n) => Some(format!("{n}.")),
296        };
297        let has_marker = marker.is_some();
298        let body_indent = if let Some(marker) = marker {
299            cells.push(
300                label(marker)
301                    .font(self.font)
302                    .secondary()
303                    .min_width(MARKER_WIDTH)
304                    .padding(Insets {
305                        top: shape.gap,
306                        leading: outer,
307                        ..Insets::default()
308                    })
309                    .any(),
310            );
311            0.0
312        } else {
313            f64::from(shape.list_depth) * LIST_INDENT
314        };
315        cells.push(
316            body.padding(Insets {
317                leading: body_indent,
318                ..top
319            })
320            .grow(Dimension::Width)
321            .any(),
322        );
323        row(cells)
324            .spacing(ROW_GAP)
325            .align(if has_marker {
326                VAlign::FirstBaseline
327            } else {
328                VAlign::Top
329            })
330            .any()
331    }
332
333    /// A code block: the code in the monospaced face on the platform's card surface, under a
334    /// header that names the language and holds the app's accessory.
335    fn code(&self, block: Signal<MarkdownBlock>, index: usize, header: bool) -> AnyPiece {
336        let code = self.text(
337            block,
338            index,
339            &TextLook {
340                font: self.font,
341                inline: false,
342                bold: false,
343                monospace: true,
344            },
345        );
346        let mut lines: Vec<AnyPiece> = Vec::new();
347        if header {
348            let handle = MarkdownCode { block };
349            let mut cells: Vec<AnyPiece> = vec![
350                label(move || handle.language())
351                    .font(Font::Caption)
352                    .secondary()
353                    .any(),
354                spacer().any(),
355            ];
356            if let Some(accessory) = &self.code_accessory {
357                cells.push(accessory(handle));
358            }
359            lines.push(row(cells).any());
360        }
361        lines.push(code);
362        column(lines)
363            .spacing(Space::XS)
364            .align(HAlign::Leading)
365            .card()
366            .any()
367    }
368}
369
370/// How one block's label is drawn.
371struct TextLook {
372    font: Font,
373    /// Read the text as inline Markdown (a paragraph or heading) or literally (code).
374    inline: bool,
375    bold: bool,
376    monospace: bool,
377}
378
379/// The semantic style a heading level takes, so headings follow the platform's type ramp and
380/// the reader's text size like every other label.
381fn heading_font(level: u8) -> Font {
382    match level {
383        1 => Font::Title,
384        2 => Font::Title2,
385        3 => Font::Title3,
386        4 => Font::Headline,
387        5 => Font::Subheadline,
388        _ => Font::Footnote,
389    }
390}
391
392impl Piece for Markdown {
393    fn build(self, cx: &mut BuildCx) -> RNode {
394        let Markdown {
395            text,
396            font,
397            color,
398            spacing,
399            selectable,
400            on_link,
401            code_accessory,
402            block_id,
403        } = self;
404        let style = Rc::new(RowStyle {
405            font,
406            color,
407            spacing,
408            selectable,
409            on_link,
410            code_accessory,
411            block_id,
412        });
413        let rows = piece_fn(move |cx| {
414            let anchor = cx.layout_only(
415                Rc::new(PassThrough),
416                Flex {
417                    is_group: true,
418                    ..Default::default()
419                },
420                Boundary::No,
421            );
422            // Rows are built from a reaction, where `Scope::child()` would parent them to the
423            // root scope; they belong to this piece (the same capture `each` makes).
424            let owner = Scope::current();
425            let document = Rc::new(RefCell::new(MarkdownDocument::new()));
426            let built: Rc<RefCell<Vec<BlockRow>>> = Rc::new(RefCell::new(Vec::new()));
427            let sync = move |source: &str| {
428                if !with_tree(|t| t.node_exists(anchor)) {
429                    return;
430                }
431                let first = document.borrow_mut().update(source);
432                let document = document.borrow();
433                let blocks = document.blocks();
434                let mut rows = built.borrow_mut();
435                for index in first..blocks.len() {
436                    let block = &blocks[index];
437                    let previous = index.checked_sub(1).and_then(|i| blocks.get(i));
438                    let shape = style.shape(block, previous);
439                    if let Some(row) = rows.get(index)
440                        && row.shape == shape
441                    {
442                        // Same shape: the row's labels follow the signal.
443                        if row.block.with_untracked(|b| b != block) {
444                            row.block.set(block.clone());
445                        }
446                        continue;
447                    }
448                    // The shape changed here: this row and the ones after it are built again,
449                    // so the rows stay in document order by appending.
450                    let stale = index.min(rows.len());
451                    for row in rows.drain(stale..) {
452                        row.scope.dispose();
453                        with_tree(|t| t.remove_subtree(row.root));
454                    }
455                    let scope = owner.enter(Scope::child);
456                    let (signal, root) = scope.enter(|| {
457                        let signal = Signal::new(block.clone());
458                        let mut cx = BuildCx::new(anchor);
459                        (signal, style.build(&shape, signal, index).build(&mut cx))
460                    });
461                    rows.push(BlockRow {
462                        shape,
463                        block: signal,
464                        scope,
465                        root,
466                    });
467                }
468                let extra = blocks.len().min(rows.len());
469                for row in rows.drain(extra..) {
470                    row.scope.dispose();
471                    with_tree(|t| t.remove_subtree(row.root));
472                }
473            };
474            sync(&text.initial());
475            if let TextSource::Dyn(source) = text {
476                watch(move || source(), move |now: &String, _| sync(now));
477            }
478            anchor
479        });
480        column((rows,)).align(HAlign::Leading).build(cx)
481    }
482}
483
484// ---------------------------------------------------------------------------
485// Conformance cases (docs/testing.md)
486// ---------------------------------------------------------------------------
487
488/// The Markdown view's `#[day::test]` cases. Compiled only under the `conformance` feature.
489#[cfg(feature = "conformance")]
490pub(crate) mod conformance {
491    use day_core::Piece;
492    use day_core::conformance::{Case, Drive, FrameExpect};
493    use day_reactive::Signal;
494    use day_spec::{Cap, kinds};
495
496    use crate::*;
497
498    /// A marker box, so a case can compare heights by where two markers sit.
499    fn foot(id: day_core::ElementId) -> impl Piece {
500        rectangle()
501            .fill(day_spec::Color::hex(0x0033_6699))
502            .frame(10.0, 4.0)
503            .id(id)
504    }
505
506    const DOCUMENT: &str = "# Release notes\n\nThis build is **faster** and has `fewer` \
507        [bugs](https://daybrite.dev/bugs).\n\n- First item\n- Second item\n  1. Nested step\n\n\
508        > A quoted line\n\n```rust\nfn main() {}\n```\n\n---\n\nThe end.";
509
510    /// Every block of a document becomes its own label, with the Markdown markers stripped
511    /// and the code left verbatim.
512    #[day_macros::test(day_core)]
513    fn markdown_view_blocks() -> Case {
514        Case::new()
515            .proves(kinds::LABEL)
516            .requires(Cap::TextRuns)
517            .page(|| {
518                markdown(DOCUMENT)
519                    .block_ids(|i| day_core::id!(md_block, i))
520                    .width(300.0)
521            })
522            .shot("default")
523            .drive(|d: Drive| async move {
524                d.assert_text("md_block:0", "Release notes").await?;
525                d.assert_text("md_block:1", "This build is faster and has fewer bugs.")
526                    .await?;
527                d.assert_text("md_block:2", "First item").await?;
528                d.assert_text("md_block:3", "Second item").await?;
529                d.assert_text("md_block:4", "Nested step").await?;
530                d.assert_text("md_block:5", "A quoted line").await?;
531                d.assert_text("md_block:6", "fn main() {}").await?;
532                // Block 7 is the rule, which has no text and no id.
533                d.assert_missing("md_block:7").await?;
534                d.assert_text("md_block:8", "The end.").await
535            })
536    }
537
538    /// The view takes its height from its content: what follows it sits directly under its
539    /// last block, and moves down when the text grows. A reply that arrives a piece at a time
540    /// updates the block being written and adds blocks as they start.
541    #[day_macros::test(day_core)]
542    fn markdown_view_streams() -> Case {
543        let reply = Signal::new("# Answer\n\nThe first".to_owned());
544        Case::new()
545            .proves(kinds::LABEL)
546            .requires(Cap::TextRuns)
547            .page(move || {
548                column((
549                    row((
550                        column((
551                            markdown(reply)
552                                .block_ids(|i| day_core::id!(mds_block, i))
553                                .width(200.0),
554                            foot(day_core::id!(mds_after)),
555                        ))
556                        .align(HAlign::Leading),
557                        column((
558                            label("Short").width(100.0),
559                            foot(day_core::id!(mds_reference)),
560                        ))
561                        .align(HAlign::Leading),
562                    ))
563                    .align(VAlign::Top),
564                    button("More")
565                        .action(move || reply.update(|r| r.push_str(" paragraph")))
566                        .id(day_core::id!(mds_more)),
567                    button("List")
568                        .action(move || reply.update(|r| r.push_str(".\n\n- one\n- two")))
569                        .id(day_core::id!(mds_list)),
570                    button("Replace")
571                        .action(move || reply.set("Short".into()))
572                        .id(day_core::id!(mds_replace)),
573                ))
574                .align(HAlign::Leading)
575            })
576            .drive(|d: Drive| async move {
577                d.assert_text("mds_block:0", "Answer").await?;
578                d.assert_text("mds_block:1", "The first").await?;
579                d.tap("mds_more").await?;
580                d.assert_text("mds_block:1", "The first paragraph").await?;
581                d.assert_text("mds_block:0", "Answer").await?;
582                d.tap("mds_list").await?;
583                d.assert_text("mds_block:1", "The first paragraph.").await?;
584                d.assert_text("mds_block:2", "one").await?;
585                d.assert_text("mds_block:3", "two").await?;
586                d.tap("mds_replace").await?;
587                d.wait_idle().await?;
588                d.assert_text("mds_block:0", "Short").await?;
589                d.assert_missing("mds_block:1").await?;
590                // One paragraph left: the view is as tall as a plain label with the same text,
591                // so what follows each sits at the same height.
592                d.assert_frame(
593                    "mds_after",
594                    FrameExpect {
595                        y: Some(0.0),
596                        relative_to: Some("mds_reference".into()),
597                        ..Default::default()
598                    },
599                )
600                .await
601            })
602    }
603
604    /// A code block's accessory reads the block's current code and language.
605    #[day_macros::test(day_core)]
606    fn markdown_view_code_accessory() -> Case {
607        let source = Signal::new("```swift\nlet day = 1\n```".to_owned());
608        let copied = Signal::new(String::new());
609        Case::new()
610            .proves(kinds::LABEL)
611            .page(move || {
612                column((
613                    markdown(source)
614                        .block_ids(|i| day_core::id!(mdc_block, i))
615                        .code_accessory(move |code| {
616                            button("Copy")
617                                .action(move || {
618                                    copied.set(format!("{}: {}", code.language(), code.text()));
619                                })
620                                .id(day_core::id!(mdc_copy))
621                        })
622                        .width(300.0),
623                    label(move || copied.get()).id(day_core::id!(mdc_copied)),
624                    button("Grow")
625                        .action(move || {
626                            source.set("```swift\nlet day = 1\nlet night = 2\n```".into());
627                        })
628                        .id(day_core::id!(mdc_grow)),
629                ))
630                .align(HAlign::Leading)
631                .spacing(8.0)
632            })
633            .shot("default")
634            .drive(|d: Drive| async move {
635                d.assert_text("mdc_block:0", "let day = 1").await?;
636                d.tap("mdc_copy").await?;
637                d.assert_text("mdc_copied", "swift: let day = 1").await?;
638                d.tap("mdc_grow").await?;
639                d.assert_text("mdc_block:0", "let day = 1\nlet night = 2")
640                    .await?;
641                d.tap("mdc_copy").await?;
642                d.assert_text("mdc_copied", "swift: let day = 1\nlet night = 2")
643                    .await
644            })
645    }
646}