Skip to main content

waft_markdown/
render.rs

1//! The default rendering of a document into widgets, one public function per element, so a
2//! renderer that replaces some elements can fall back on these for the rest.
3
4use std::any::Any;
5use std::fmt;
6use std::rc::Rc;
7
8use waft_embedder::valo::{FillRule, Point};
9use waft_embedder::{
10    Canvas, Clip, Color, Paint, PathBuilder, PlaceholderAlignment, RRect, Size, TextAlign,
11    TextBaseline, rrect_radii_elliptical,
12};
13use waft_foundation::{App, Handle, Listener, Ref};
14use waft_gestures::{RecognizerRef, TapGestureRecognizer};
15use waft_painting::{
16    Axis, EdgeInsets, InlineSpanRef, K_DEFAULT_FONT_SIZE, TextSpan, TextStyle, draw_drrect,
17};
18use waft_rendering::{
19    CrossAxisAlignment, CustomPainter, FixedColumnWidth, FlexFit, IntrinsicColumnWidth,
20    MainAxisSize,
21};
22use waft_widgets::{
23    BuildContext, Column, Container, CustomPaint, DecoratedBox, Flexible, GestureDetector,
24    IntoWidget, Padding, RawScrollbar, Row, ScrollController, ScrollControllerLeaf,
25    SingleChildScrollView, SizedBox, State, StateData, StatefulWidget, Table, TableCell, TableRow,
26    Text, WidgetRef, WidgetSpan,
27};
28
29use crate::document::{Alignment, Block, Cell, Inline, ListItem};
30use crate::style_sheet::MarkdownStyleSheet;
31use crate::widget::MarkdownHooks;
32
33/// What a list item's bullet stands for, given to [`bullet`] and to a widget's bullet hook.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct Bullet {
36    /// The item's number in an ordered list, counted from the list's start; `None` in a
37    /// bulleted list.
38    pub number: Option<u64>,
39    /// The item's position in its list, from 0.
40    pub index: usize,
41    /// How many lists enclose the item's list: 0 for a list at the top.
42    pub depth: usize,
43}
44
45/// What the render functions read and record while they turn one document into widgets.
46pub struct RenderContext<'a> {
47    style_sheet: &'a MarkdownStyleSheet,
48    hooks: &'a MarkdownHooks,
49    fit_content: bool,
50    /// The style of body text here: the sheet's, merged with each enclosing quote's.
51    text: TextStyle,
52    list_depth: usize,
53    /// Every recognizer made for a link. Whoever made the context disposes of them once the
54    /// spans holding them are replaced.
55    recognizers: &'a mut Vec<RecognizerRef>,
56}
57
58impl<'a> RenderContext<'a> {
59    pub(crate) fn new(
60        style_sheet: &'a MarkdownStyleSheet,
61        hooks: &'a MarkdownHooks,
62        fit_content: bool,
63        recognizers: &'a mut Vec<RecognizerRef>,
64    ) -> RenderContext<'a> {
65        RenderContext {
66            style_sheet,
67            hooks,
68            fit_content,
69            text: style_sheet.text.clone(),
70            list_depth: 0,
71            recognizers,
72        }
73    }
74
75    /// What tapping a link does, or `None` when the widget has no link hook.
76    fn link_tap(&mut self, app: &mut App, url: &str, title: &str) -> Option<LinkTap> {
77        let on_tap_link = self.hooks.on_tap_link.clone()?;
78        let (url, title) = (url.to_owned(), title.to_owned());
79        let on_tap = Listener::new(move |app| on_tap_link(app, &url, &title));
80        let recognizer = TapGestureRecognizer::new(app);
81        recognizer.set_on_tap(app, Some(on_tap.clone()));
82        let recognizer: RecognizerRef = recognizer.into_erased();
83        self.recognizers.push(recognizer.clone());
84        Some(LinkTap { recognizer, on_tap })
85    }
86}
87
88/// The widgets of `blocks`, `spacing` apart.
89pub fn blocks(
90    cx: &mut RenderContext,
91    app: &mut App,
92    blocks: &[Block],
93    spacing: f64,
94) -> Vec<WidgetRef> {
95    spaced(
96        blocks.iter().map(|block| self::block(cx, app, block)),
97        spacing,
98    )
99}
100
101/// The widget of one block.
102pub fn block(cx: &mut RenderContext, app: &mut App, block: &Block) -> WidgetRef {
103    match block {
104        Block::Paragraph(content) => paragraph(cx, app, content),
105        Block::Heading { level, content } => heading(cx, app, *level, content),
106        Block::Quote(blocks) => quote(cx, app, blocks),
107        Block::List { start, items, .. } => list(cx, app, *start, items),
108        Block::CodeBlock { language, text } => code_block(cx, app, language.as_deref(), text),
109        Block::Table {
110            alignments,
111            head,
112            rows,
113        } => table(cx, app, alignments, head, rows),
114        Block::Rule => rule(cx),
115    }
116}
117
118/// One text of the paragraph's spans.
119pub fn paragraph(cx: &mut RenderContext, app: &mut App, content: &[Inline]) -> WidgetRef {
120    let style = cx.text.clone();
121    rich_text(spans(cx, app, content, &style), style, TextAlign::Start)
122}
123
124/// The heading's text in its level's style.
125pub fn heading(cx: &mut RenderContext, app: &mut App, level: u8, content: &[Inline]) -> WidgetRef {
126    let heading = &cx.style_sheet.headings[usize::from(level.clamp(1, 6)) - 1];
127    let style = cx.text.merge(Some(&heading.text));
128    padded(
129        heading.padding,
130        rich_text(spans(cx, app, content, &style), style, TextAlign::Start),
131    )
132}
133
134/// The quote's blocks, padded inside its decoration.
135pub fn quote(cx: &mut RenderContext, app: &mut App, blocks: &[Block]) -> WidgetRef {
136    let sheet = cx.style_sheet;
137    let quoted = cx.text.merge(Some(&sheet.quote.text));
138    let outer = std::mem::replace(&mut cx.text, quoted);
139    let children = self::blocks(cx, app, blocks, sheet.block_spacing);
140    cx.text = outer;
141    DecoratedBox::new(sheet.quote.decoration.clone())
142        .child(Padding::new(sheet.quote.padding).child(column(children, cx.fit_content)))
143        .into_widget()
144}
145
146/// A row per item, its bullet, number or checkbox in the indent before its blocks, the items
147/// [`block_spacing`](MarkdownStyleSheet::block_spacing) apart whether the list is tight or
148/// loose, as flutter_markdown spaces them.
149pub fn list(
150    cx: &mut RenderContext,
151    app: &mut App,
152    start: Option<u64>,
153    items: &[ListItem],
154) -> WidgetRef {
155    let (sheet, hooks) = (cx.style_sheet, cx.hooks);
156    let spacing = sheet.block_spacing;
157    let depth = cx.list_depth;
158    cx.list_depth += 1;
159    let mut rows = Vec::with_capacity(items.len());
160    for (index, item) in items.iter().enumerate() {
161        let marker = match item.checked {
162            Some(checked) => match &hooks.checkbox {
163                Some(hook) => hook(app, checked),
164                None => checkbox(cx, checked),
165            },
166            None => {
167                let marker = Bullet {
168                    number: start.map(|start| start + index as u64),
169                    index,
170                    depth,
171                };
172                match &hooks.bullet {
173                    Some(hook) => hook(app, &marker),
174                    None => bullet(cx, &marker),
175                }
176            }
177        };
178        let content = column(
179            self::blocks(cx, app, &item.content, spacing),
180            cx.fit_content,
181        );
182        rows.push(list_item(cx, marker, content));
183    }
184    cx.list_depth = depth;
185    column(spaced(rows, spacing), cx.fit_content)
186}
187
188/// The default bullet: a dot, or the item's number and a full stop.
189pub fn bullet(cx: &RenderContext, bullet: &Bullet) -> WidgetRef {
190    let style = cx.text.merge(Some(&cx.style_sheet.list.bullet));
191    let (text, text_align) = match bullet.number {
192        None => ("•".to_owned(), TextAlign::Center),
193        Some(number) => (format!("{number}."), TextAlign::Right),
194    };
195    Text::new(text)
196        .style(style)
197        .text_align(text_align)
198        .into_widget()
199}
200
201/// The default checkbox: Material's checkbox glyph, ticked or empty, drawn in the middle of a
202/// line of the sheet's checkbox style.
203pub fn checkbox(cx: &RenderContext, checked: bool) -> WidgetRef {
204    let style = cx.text.merge(Some(&cx.style_sheet.list.checkbox));
205    let size = style.font_size.unwrap_or(K_DEFAULT_FONT_SIZE);
206    let color = style
207        .color
208        .as_deref()
209        .copied()
210        .unwrap_or(Color::new(0xFF000000));
211    let glyph = CustomPaint::new()
212        .painter(CheckboxPainter { checked, color })
213        .size(Size::new(size, size));
214    let line = TextSpan::new().children(vec![
215        WidgetSpan::new(glyph)
216            .alignment(PlaceholderAlignment::Middle)
217            .into_span(),
218    ]);
219    Text::rich(line.style(style).into_span()).into_widget()
220}
221
222/// The code in the code block's style, or as the widget's highlighter spans it, scrolling
223/// sideways inside the block's decoration.
224pub fn code_block(
225    cx: &mut RenderContext,
226    app: &mut App,
227    language: Option<&str>,
228    text: &str,
229) -> WidgetRef {
230    let block = &cx.style_sheet.code_block;
231    let code = match &cx.hooks.highlight_code {
232        Some(highlight) => {
233            TextSpan::new().children(vec![highlight(app, language, text).into_span()])
234        }
235        None => TextSpan::new().text(text),
236    };
237    let style = cx.text.merge(Some(&block.text));
238    Container::new()
239        .clip_behavior(Clip::HardEdge)
240        .decoration(block.decoration.clone())
241        .child(SidewaysScroll {
242            padding: block.padding,
243            child: Text::rich(code.style(style).into_span()).into_widget(),
244        })
245        .into_widget()
246}
247
248/// A [`Table`] of the head row and the body rows, each cell aligned as its column; it scrolls
249/// sideways when its columns size to their content.
250pub fn table(
251    cx: &mut RenderContext,
252    app: &mut App,
253    alignments: &[Alignment],
254    head: &[Cell],
255    rows: &[Vec<Cell>],
256) -> WidgetRef {
257    let table = &cx.style_sheet.table;
258    let head_style = cx.text.merge(Some(&table.head));
259    let body_style = cx.text.merge(Some(&table.body));
260    let mut table_rows = Vec::with_capacity(rows.len() + 1);
261    table_rows.push(TableRow::new().children(table_cells(
262        cx,
263        app,
264        alignments,
265        head,
266        &head_style,
267        table.head_align,
268    )));
269    for (index, row) in rows.iter().enumerate() {
270        let mut table_row = TableRow::new().children(table_cells(
271            cx,
272            app,
273            alignments,
274            row,
275            &body_style,
276            TextAlign::Start,
277        ));
278        if index % 2 == 1
279            && let Some(stripe) = &table.stripe
280        {
281            table_row = table_row.decoration(stripe.clone());
282        }
283        table_rows.push(table_row);
284    }
285    let widget = Table::new()
286        .default_column_width(Rc::clone(&table.column_width))
287        .default_vertical_alignment(table.vertical_alignment)
288        .border(table.border)
289        .children(table_rows)
290        .into_widget();
291    let column_width = table.column_width.as_any();
292    if column_width.is::<IntrinsicColumnWidth>() || column_width.is::<FixedColumnWidth>() {
293        return SidewaysScroll {
294            padding: EdgeInsets::ZERO,
295            child: widget,
296        }
297        .into_widget();
298    }
299    widget
300}
301
302/// A line across the full width, the sheet's rule decoration on a box of no height.
303pub fn rule(cx: &RenderContext) -> WidgetRef {
304    Container::new()
305        .decoration(cx.style_sheet.rule.clone())
306        .into_widget()
307}
308
309/// The spans of `content` in text of `style`. A link's spans carry a recognizer that calls the
310/// widget's link hook; an image is the widget's image hook's widget, or its alt text.
311pub fn spans(
312    cx: &mut RenderContext,
313    app: &mut App,
314    content: &[Inline],
315    style: &TextStyle,
316) -> Vec<InlineSpanRef> {
317    let mut spans = Vec::new();
318    push_spans(cx, app, content, style, None, &mut spans);
319    spans
320}
321
322/// What tapping a link's text or image does.
323struct LinkTap {
324    recognizer: RecognizerRef,
325    on_tap: Listener,
326}
327
328fn push_spans(
329    cx: &mut RenderContext,
330    app: &mut App,
331    content: &[Inline],
332    style: &TextStyle,
333    link: Option<&LinkTap>,
334    spans: &mut Vec<InlineSpanRef>,
335) {
336    let (sheet, hooks) = (cx.style_sheet, cx.hooks);
337    for inline in content {
338        match inline {
339            Inline::Text(text) => spans.push(text_span(text, style, link)),
340            Inline::Emphasis(content) => {
341                let style = MarkdownStyleSheet::emphasis(style);
342                push_spans(cx, app, content, &style, link, spans);
343            }
344            Inline::Strong(content) => {
345                let style = MarkdownStyleSheet::strong(style);
346                push_spans(cx, app, content, &style, link, spans);
347            }
348            Inline::Strikethrough(content) => {
349                let style = MarkdownStyleSheet::strikethrough(style);
350                push_spans(cx, app, content, &style, link, spans);
351            }
352            Inline::Code(code) => {
353                spans.push(text_span(
354                    code,
355                    &style.merge(Some(&sheet.inline_code)),
356                    link,
357                ));
358            }
359            Inline::Link {
360                url,
361                title,
362                content,
363            } => {
364                if content.is_empty() {
365                    continue;
366                }
367                let style = style.merge(Some(&sheet.link));
368                let tap = cx.link_tap(app, url, title);
369                push_spans(cx, app, content, &style, tap.as_ref(), spans);
370            }
371            Inline::Image(image) => match &hooks.image {
372                Some(hook) => {
373                    let mut child = hook(app, image);
374                    if let Some(link) = link {
375                        child = GestureDetector::new()
376                            .on_tap(link.on_tap.clone())
377                            .child(child)
378                            .into_widget();
379                    }
380                    spans.push(WidgetSpan::new(child).into_span());
381                }
382                None if !image.alt.is_empty() => spans.push(text_span(&image.alt, style, link)),
383                None => {}
384            },
385            Inline::LineBreak => spans.push(text_span("\n", style, link)),
386        }
387    }
388}
389
390fn text_span(text: &str, style: &TextStyle, link: Option<&LinkTap>) -> InlineSpanRef {
391    let mut span = TextSpan::new().text(text).style(style.clone());
392    if let Some(link) = link {
393        span = span.recognizer(link.recognizer.clone());
394    }
395    span.into_span()
396}
397
398fn rich_text(spans: Vec<InlineSpanRef>, style: TextStyle, text_align: TextAlign) -> WidgetRef {
399    Text::rich(TextSpan::new().style(style).children(spans).into_span())
400        .text_align(text_align)
401        .into_widget()
402}
403
404fn table_cells(
405    cx: &mut RenderContext,
406    app: &mut App,
407    alignments: &[Alignment],
408    cells: &[Cell],
409    style: &TextStyle,
410    unaligned: TextAlign,
411) -> Vec<WidgetRef> {
412    let padding = cx.style_sheet.table.cell_padding;
413    alignments
414        .iter()
415        .enumerate()
416        .map(|(column, alignment)| {
417            let text_align = match alignment {
418                Alignment::None => unaligned,
419                Alignment::Left => TextAlign::Left,
420                Alignment::Center => TextAlign::Center,
421                Alignment::Right => TextAlign::Right,
422            };
423            let content = cells.get(column).map_or(&[][..], |cell| &cell.content);
424            let text = rich_text(spans(cx, app, content, style), style.clone(), text_align);
425            TableCell::new(Padding::new(padding).child(text)).into_widget()
426        })
427        .collect()
428}
429
430fn list_item(cx: &RenderContext, marker: WidgetRef, content: WidgetRef) -> WidgetRef {
431    let list = &cx.style_sheet.list;
432    let padding = list.bullet_padding;
433    Row::new()
434        .main_axis_size(if cx.fit_content {
435            MainAxisSize::Min
436        } else {
437            MainAxisSize::Max
438        })
439        .cross_axis_alignment(CrossAxisAlignment::Baseline)
440        .text_baseline(TextBaseline::Alphabetic)
441        .children([
442            SizedBox::new()
443                .width(list.indent + padding.left + padding.right)
444                .child(Padding::new(padding).child(marker))
445                .into_widget(),
446            Flexible::new(content)
447                .fit(if cx.fit_content {
448                    FlexFit::Loose
449                } else {
450                    FlexFit::Tight
451                })
452                .into_widget(),
453        ])
454        .into_widget()
455}
456
457/// `children` in a column that takes their width when `fit_content`, the full width otherwise.
458pub(crate) fn column(children: Vec<WidgetRef>, fit_content: bool) -> WidgetRef {
459    Column::new()
460        .main_axis_size(MainAxisSize::Min)
461        .cross_axis_alignment(if fit_content {
462            CrossAxisAlignment::Start
463        } else {
464            CrossAxisAlignment::Stretch
465        })
466        .children(children)
467        .into_widget()
468}
469
470fn spaced(children: impl IntoIterator<Item = WidgetRef>, spacing: f64) -> Vec<WidgetRef> {
471    let mut spaced = Vec::new();
472    for child in children {
473        if !spaced.is_empty() {
474            spaced.push(SizedBox::new().height(spacing).into_widget());
475        }
476        spaced.push(child);
477    }
478    spaced
479}
480
481fn padded(padding: EdgeInsets, child: WidgetRef) -> WidgetRef {
482    if padding == EdgeInsets::ZERO {
483        return child;
484    }
485    Padding::new(padding).child(child).into_widget()
486}
487
488/// Material's `check_box` and `check_box_outline_blank` icons, drawn on their 24-unit grid.
489#[derive(PartialEq)]
490struct CheckboxPainter {
491    checked: bool,
492    color: Color,
493}
494
495impl CustomPainter for CheckboxPainter {
496    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
497        let unit = size.width().min(size.height()) / 24.0;
498        let square = |inset: f64, radius: f64| {
499            RRect::from_ltrbxy(
500                inset * unit,
501                inset * unit,
502                (24.0 - inset) * unit,
503                (24.0 - inset) * unit,
504                radius * unit,
505                radius * unit,
506            )
507        };
508        let paint = Paint::from_color(self.color.into());
509        let outer = square(3.0, 2.0);
510        if !self.checked {
511            draw_drrect(canvas, outer, square(5.0, 0.0), &paint);
512            return;
513        }
514        // The tick is a hole in the filled square.
515        let mut path = PathBuilder::new();
516        path.rrect_radii_elliptical(outer.outer_rect(), rrect_radii_elliptical(outer));
517        let point = |x: f64, y: f64| Point::new((x * unit) as f32, (y * unit) as f32);
518        path.move_to(point(10.0, 17.0));
519        for (x, y) in [
520            (5.0, 12.0),
521            (6.41, 10.59),
522            (10.0, 14.17),
523            (17.59, 6.58),
524            (19.0, 8.0),
525        ] {
526            path.line_to(point(x, y));
527        }
528        path.close();
529        canvas.draw_path(&path.build(), FillRule::EvenOdd, &paint);
530    }
531
532    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
533        old_delegate.as_any().downcast_ref::<CheckboxPainter>() != Some(self)
534    }
535
536    fn as_any(&self) -> &dyn Any {
537        self
538    }
539}
540
541/// `child` scrolling sideways under a [`RawScrollbar`], with a scroll controller of its own.
542struct SidewaysScroll {
543    padding: EdgeInsets,
544    child: WidgetRef,
545}
546
547impl fmt::Debug for SidewaysScroll {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        f.debug_struct("SidewaysScroll")
550            .field("child", &self.child)
551            .finish_non_exhaustive()
552    }
553}
554
555impl StatefulWidget for SidewaysScroll {
556    type State = SidewaysScrollState;
557
558    fn create_state(&self) -> SidewaysScrollState {
559        SidewaysScrollState {
560            state: StateData::new(),
561            controller: None,
562        }
563    }
564}
565
566struct SidewaysScrollState {
567    state: StateData<SidewaysScroll>,
568    /// Made in `init_state`, disposed of in `dispose`.
569    controller: Option<Ref<ScrollController>>,
570}
571
572impl State for SidewaysScrollState {
573    type Widget = SidewaysScroll;
574    waft_widgets::state_accessors!();
575
576    fn init_state(self: Handle<Self>, app: &mut App) {
577        let controller = ScrollController::default(app);
578        app.get_mut(self).controller = Some(controller);
579    }
580
581    fn dispose(self: Handle<Self>, app: &mut App) {
582        if let Some(controller) = app.get_mut(self).controller.take() {
583            controller.dispose(app);
584        }
585    }
586
587    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
588        let controller: waft_widgets::ScrollControllerRef = app
589            .get(self)
590            .controller
591            .as_ref()
592            .expect("made in init_state")
593            .erase();
594        let widget = self.widget(app);
595        let scroll_view = SingleChildScrollView::new()
596            .controller(controller.clone())
597            .scroll_direction(Axis::Horizontal)
598            .padding(widget.padding)
599            .child(widget.child.clone());
600        RawScrollbar::new(scroll_view)
601            .controller(controller)
602            .into_widget()
603    }
604}