Skip to main content

waft_markdown/
widget.rs

1//! The Markdown widgets: [`MarkdownBody`], and [`Markdown`], which scrolls.
2
3use std::fmt;
4use std::rc::Rc;
5
6use pulldown_cmark::Options;
7use waft_foundation::{App, Handle};
8use waft_gestures::RecognizerRef;
9use waft_painting::{EdgeInsets, TextSpan};
10use waft_widgets::{
11    BuildContext, IntoWidget, KeyRef, ListView, ScrollControllerRef, ScrollPhysicsRef, State,
12    StateData, StatefulWidget, StatelessWidget, WidgetRef,
13};
14
15use crate::document::{self, Block, GITHUB_FLAVORED, Image};
16use crate::render::{self, Bullet, RenderContext};
17use crate::style_sheet::{DefaultMarkdownStyle, MarkdownStyleSheet};
18
19/// Called with a tapped link's address and title.
20pub type TapLinkHook = Rc<dyn Fn(&mut App, &str, &str)>;
21/// Builds the widget of an image.
22pub type ImageHook = Rc<dyn Fn(&mut App, &Image) -> WidgetRef>;
23/// Builds a task item's checkbox from whether it is ticked.
24pub type CheckboxHook = Rc<dyn Fn(&mut App, bool) -> WidgetRef>;
25/// Builds a list item's bullet.
26pub type BulletHook = Rc<dyn Fn(&mut App, &Bullet) -> WidgetRef>;
27/// Builds the spans of a code block's text from its language.
28pub type HighlightCodeHook = Rc<dyn Fn(&mut App, Option<&str>, &str) -> TextSpan>;
29
30/// The closures that replace parts of the default rendering; an element without one renders as
31/// the [`render`] module's function for it does.
32#[derive(Clone, Default)]
33pub struct MarkdownHooks {
34    /// Without it a link is styled but does nothing when tapped.
35    pub on_tap_link: Option<TapLinkHook>,
36    /// Without it an image shows its alt text.
37    pub image: Option<ImageHook>,
38    pub checkbox: Option<CheckboxHook>,
39    pub bullet: Option<BulletHook>,
40    /// Its spans go inside the code block's text style, box and sideways scrolling.
41    pub highlight_code: Option<HighlightCodeHook>,
42}
43
44/// What [`MarkdownBody`] and [`Markdown`] share: the text, how it is parsed, how it looks.
45#[derive(Clone)]
46pub struct MarkdownConfig {
47    pub data: String,
48    /// The extensions [`data`](Self::data) is parsed with, [`GITHUB_FLAVORED`] by default.
49    pub options: Options,
50    /// When given, replaces the inherited [`DefaultMarkdownStyle`] whole.
51    pub style_sheet: Option<MarkdownStyleSheet>,
52    /// Whether a block takes its content's width rather than the full width.
53    pub fit_content: bool,
54    pub hooks: MarkdownHooks,
55}
56
57impl MarkdownConfig {
58    fn new(data: String, fit_content: bool) -> MarkdownConfig {
59        MarkdownConfig {
60            data,
61            options: GITHUB_FLAVORED,
62            style_sheet: None,
63            fit_content,
64            hooks: MarkdownHooks::default(),
65        }
66    }
67}
68
69/// The setters of what [`MarkdownConfig`] holds, for each widget built on it.
70macro_rules! markdown_setters {
71    ($name:ident) => {
72        impl $name {
73            /// Sets the key.
74            pub fn key(mut self, key: KeyRef) -> $name {
75                self.key = Some(key);
76                self
77            }
78
79            /// Sets the extensions the text is parsed with.
80            pub fn options(mut self, options: Options) -> $name {
81                self.config.options = options;
82                self
83            }
84
85            /// Sets the look, in place of the inherited [`DefaultMarkdownStyle`].
86            pub fn style_sheet(mut self, style_sheet: MarkdownStyleSheet) -> $name {
87                self.config.style_sheet = Some(style_sheet);
88                self
89            }
90
91            /// Sets whether a block takes its content's width rather than the full width.
92            pub fn fit_content(mut self, fit_content: bool) -> $name {
93                self.config.fit_content = fit_content;
94                self
95            }
96
97            /// Calls `on_tap_link` with a tapped link's address and title.
98            pub fn on_tap_link(
99                mut self,
100                on_tap_link: impl Fn(&mut App, &str, &str) + 'static,
101            ) -> $name {
102                self.config.hooks.on_tap_link = Some(Rc::new(on_tap_link));
103                self
104            }
105
106            /// Builds each image with `image`.
107            pub fn image(
108                mut self,
109                image: impl Fn(&mut App, &Image) -> WidgetRef + 'static,
110            ) -> $name {
111                self.config.hooks.image = Some(Rc::new(image));
112                self
113            }
114
115            /// Builds each task item's checkbox with `checkbox`.
116            pub fn checkbox(
117                mut self,
118                checkbox: impl Fn(&mut App, bool) -> WidgetRef + 'static,
119            ) -> $name {
120                self.config.hooks.checkbox = Some(Rc::new(checkbox));
121                self
122            }
123
124            /// Builds each list item's bullet with `bullet`.
125            pub fn bullet(
126                mut self,
127                bullet: impl Fn(&mut App, &Bullet) -> WidgetRef + 'static,
128            ) -> $name {
129                self.config.hooks.bullet = Some(Rc::new(bullet));
130                self
131            }
132
133            /// Spans each code block's text with `highlight_code`.
134            pub fn highlight_code(
135                mut self,
136                highlight_code: impl Fn(&mut App, Option<&str>, &str) -> TextSpan + 'static,
137            ) -> $name {
138                self.config.hooks.highlight_code = Some(Rc::new(highlight_code));
139                self
140            }
141        }
142
143        impl fmt::Debug for $name {
144            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145                f.debug_struct(stringify!($name))
146                    .field("data", &self.config.data)
147                    .finish_non_exhaustive()
148            }
149        }
150    };
151}
152
153/// Markdown laid out in a column, for a parent that scrolls or sizes it.
154pub struct MarkdownBody {
155    pub key: Option<KeyRef>,
156    /// [`fit_content`](MarkdownConfig::fit_content) is true by default.
157    pub config: MarkdownConfig,
158}
159
160impl MarkdownBody {
161    /// Renders the Markdown `data`.
162    pub fn new(data: impl Into<String>) -> MarkdownBody {
163        MarkdownBody {
164            key: None,
165            config: MarkdownConfig::new(data.into(), true),
166        }
167    }
168}
169
170markdown_setters!(MarkdownBody);
171
172impl StatelessWidget for MarkdownBody {
173    fn key(&self) -> Option<&KeyRef> {
174        self.key.as_ref()
175    }
176
177    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
178        MarkdownView {
179            config: self.config.clone(),
180            layout: Layout::Column,
181        }
182        .into_widget()
183    }
184}
185
186/// Markdown in a scrolling list, one block per item.
187pub struct Markdown {
188    pub key: Option<KeyRef>,
189    /// [`fit_content`](MarkdownConfig::fit_content) is false by default.
190    pub config: MarkdownConfig,
191    /// Around the blocks, inside the scrolling area.
192    pub padding: EdgeInsets,
193    pub controller: Option<ScrollControllerRef>,
194    pub physics: Option<ScrollPhysicsRef>,
195    /// Whether the list takes its content's height rather than all the height it is given.
196    pub shrink_wrap: bool,
197}
198
199impl Markdown {
200    /// Renders the Markdown `data` in a scrolling list.
201    pub fn new(data: impl Into<String>) -> Markdown {
202        Markdown {
203            key: None,
204            config: MarkdownConfig::new(data.into(), false),
205            padding: EdgeInsets::all(16.0),
206            controller: None,
207            physics: None,
208            shrink_wrap: false,
209        }
210    }
211
212    /// Sets the padding around the blocks.
213    pub fn padding(mut self, padding: EdgeInsets) -> Markdown {
214        self.padding = padding;
215        self
216    }
217
218    /// Sets the controller of the list's scroll position.
219    pub fn controller(mut self, controller: ScrollControllerRef) -> Markdown {
220        self.controller = Some(controller);
221        self
222    }
223
224    /// Sets how the list responds to scrolling.
225    pub fn physics(mut self, physics: ScrollPhysicsRef) -> Markdown {
226        self.physics = Some(physics);
227        self
228    }
229
230    /// Sets whether the list takes its content's height.
231    pub fn shrink_wrap(mut self, shrink_wrap: bool) -> Markdown {
232        self.shrink_wrap = shrink_wrap;
233        self
234    }
235}
236
237markdown_setters!(Markdown);
238
239impl StatelessWidget for Markdown {
240    fn key(&self) -> Option<&KeyRef> {
241        self.key.as_ref()
242    }
243
244    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
245        MarkdownView {
246            config: self.config.clone(),
247            layout: Layout::List {
248                padding: self.padding,
249                controller: self.controller.clone(),
250                physics: self.physics.clone(),
251                shrink_wrap: self.shrink_wrap,
252            },
253        }
254        .into_widget()
255    }
256}
257
258/// How the blocks of a document are laid out.
259#[derive(Clone)]
260enum Layout {
261    Column,
262    List {
263        padding: EdgeInsets,
264        controller: Option<ScrollControllerRef>,
265        physics: Option<ScrollPhysicsRef>,
266        shrink_wrap: bool,
267    },
268}
269
270impl Layout {
271    fn lay_out(&self, blocks: Vec<WidgetRef>, fit_content: bool) -> WidgetRef {
272        match self {
273            Layout::Column => render::column(blocks, fit_content),
274            Layout::List {
275                padding,
276                controller,
277                physics,
278                shrink_wrap,
279            } => {
280                let mut list = ListView::new().padding(*padding).shrink_wrap(*shrink_wrap);
281                if let Some(controller) = controller {
282                    list = list.controller(controller.clone());
283                }
284                if let Some(physics) = physics {
285                    list = list.physics(Rc::clone(physics));
286                }
287                list.children(blocks).into_widget()
288            }
289        }
290    }
291}
292
293/// The widget both Markdown widgets build: it keeps the parsed document, the widgets made
294/// from it and their link recognizers between builds, as flutter_markdown's state does.
295struct MarkdownView {
296    config: MarkdownConfig,
297    layout: Layout,
298}
299
300impl fmt::Debug for MarkdownView {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        f.debug_struct("MarkdownView")
303            .field("data", &self.config.data)
304            .finish_non_exhaustive()
305    }
306}
307
308impl StatefulWidget for MarkdownView {
309    type State = MarkdownViewState;
310
311    fn create_state(&self) -> MarkdownViewState {
312        MarkdownViewState {
313            state: StateData::new(),
314            document: Rc::from([]),
315            blocks: Vec::new(),
316            recognizers: Vec::new(),
317        }
318    }
319}
320
321struct MarkdownViewState {
322    state: StateData<MarkdownView>,
323    /// Parsed from the widget's data and options whenever either changes.
324    document: Rc<[Block]>,
325    /// Made from the document when it, the style sheet or an inherited dependency changes, not
326    /// on every build, so a rebuild in the middle of a tap keeps the link's recognizer.
327    blocks: Vec<WidgetRef>,
328    /// The recognizers of the links in [`blocks`](Self::blocks): disposed of when the blocks are
329    /// made again, and on dispose.
330    recognizers: Vec<RecognizerRef>,
331}
332
333impl MarkdownViewState {
334    fn parse(self: Handle<Self>, app: &mut App) {
335        let config = &self.widget(app).config;
336        let document = document::parse(&config.data, config.options);
337        app.get_mut(self).document = document.into();
338    }
339
340    fn dispose_recognizers(self: Handle<Self>, app: &mut App) {
341        for recognizer in std::mem::take(&mut app.get_mut(self).recognizers) {
342            recognizer.dispose(app);
343        }
344    }
345
346    fn render(self: Handle<Self>, app: &mut App) {
347        let (style_sheet, mut hooks, fit_content) = {
348            let config = &self.widget(app).config;
349            (
350                config.style_sheet.clone(),
351                config.hooks.clone(),
352                config.fit_content,
353            )
354        };
355        let style_sheet = match style_sheet {
356            Some(style_sheet) => style_sheet,
357            None => DefaultMarkdownStyle::of(app, self.context(app)),
358        };
359        if hooks.on_tap_link.is_some() {
360            // flutter_markdown's link calls `widget.onTapLink`: the current widget's, at tap time.
361            hooks.on_tap_link = Some(Rc::new(move |app: &mut App, url: &str, title: &str| {
362                if let Some(on_tap_link) = self.widget(app).config.hooks.on_tap_link.clone() {
363                    on_tap_link(app, url, title);
364                }
365            }));
366        }
367        self.dispose_recognizers(app);
368        let document = Rc::clone(&app.get(self).document);
369        let mut recognizers = Vec::new();
370        let mut cx = RenderContext::new(&style_sheet, &hooks, fit_content, &mut recognizers);
371        let blocks = render::blocks(&mut cx, app, &document, style_sheet.block_spacing);
372        let state = app.get_mut(self);
373        state.blocks = blocks;
374        state.recognizers = recognizers;
375    }
376}
377
378impl State for MarkdownViewState {
379    type Widget = MarkdownView;
380    waft_widgets::state_accessors!();
381
382    fn init_state(self: Handle<Self>, app: &mut App) {
383        self.parse(app);
384    }
385
386    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
387        self.render(app);
388    }
389
390    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MarkdownView) {
391        let config = &self.widget(app).config;
392        let parse =
393            config.data != old_widget.config.data || config.options != old_widget.config.options;
394        let restyle = config.style_sheet != old_widget.config.style_sheet;
395        if parse {
396            self.parse(app);
397        }
398        if parse || restyle {
399            self.render(app);
400        }
401    }
402
403    fn dispose(self: Handle<Self>, app: &mut App) {
404        self.dispose_recognizers(app);
405    }
406
407    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
408        let (layout, fit_content) = {
409            let widget = self.widget(app);
410            (widget.layout.clone(), widget.config.fit_content)
411        };
412        let blocks = app.get(self).blocks.clone();
413        layout.lay_out(blocks, fit_content)
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use std::cell::RefCell;
420
421    use waft_embedder::{
422        Brightness, Color, FontStyle, FontWeight, Offset, TextAlign, TextBaseline, TextDecoration,
423    };
424    use waft_foundation::AppCell;
425    use waft_painting::{AlignmentGeometry, BoxDecoration, TextStyle};
426    use waft_rendering::{
427        AnyRenderAbstractViewport, AnyRenderObject, RenderBox, RenderCustomPaint,
428        RenderDecoratedBox, RenderParagraph, RenderTable,
429    };
430    use waft_widgets::{
431        Align, Builder, Directionality, GlobalKey, Padding, SizedBox, TextDirection,
432    };
433
434    use super::*;
435    use crate::test_support::{
436        build, descendants, find_all, global_rect_of_text, paragraph_texts, pump, render_object_of,
437        span_with_text, tap_at, test_cell,
438    };
439
440    /// An agent's chat reply using every element the app shows.
441    const REPLY: &str = "\
442# Poster plan
443
444Here is a **bold** idea, an *italic* one, a ~~struck~~ one and `inline code`.
445See [Seede](https://seede.ai \"home\") for more.
446
447## Steps
448
449- first
450- second
451  - nested
452- third
453
4541. one
4552. two
456
457> Keep the title short.
458
459```rust
460fn main() {}
461```
462
463---
464
465| Name | Size |
466|:-----|-----:|
467| Poster | A2 |
468| Deck | 16:9 |
469";
470
471    /// Mounts `child` as the first item of a list in a side panel `width` wide, and returns
472    /// the root render object of the item.
473    fn mount_in_panel<K>(cell: &AppCell, width: f64, child: impl IntoWidget<K>) -> AnyRenderObject {
474        let key = GlobalKey::new();
475        let item_key: KeyRef = key.clone().into();
476        let panel = SizedBox::new().width(width).height(600.0).child(
477            ListView::new().children([
478                Padding::new(EdgeInsets::all(8.0))
479                    .key(item_key)
480                    .child(child)
481                    .into_widget(),
482                SizedBox::new().height(40.0).into_widget(),
483            ]),
484        );
485        build(
486            cell,
487            Directionality::new(
488                TextDirection::Ltr,
489                Align::new()
490                    .alignment(AlignmentGeometry::TOP_LEFT)
491                    .child(panel),
492            )
493            .into_widget(),
494        );
495        render_object_of(&mut cell.borrow_mut(), &key)
496    }
497
498    /// The sheet the widgets fall back on in the test app: the empty ambient text style, light.
499    fn fallback_sheet() -> MarkdownStyleSheet {
500        MarkdownStyleSheet::from_text_style(TextStyle::new(), Brightness::Light)
501    }
502
503    #[test]
504    fn a_reply_lays_out_in_a_narrow_side_panel() {
505        for width in [320.0, 480.0] {
506            let cell = test_cell();
507            let item = mount_in_panel(&cell, width, MarkdownBody::new(REPLY));
508            let app = cell.borrow();
509            let item_box = item.as_box().expect("a box");
510            assert_eq!(item_box.size(&app).width(), width);
511            assert!(item_box.size(&app).height() > 200.0);
512
513            let texts = paragraph_texts(&app, item).join("\n");
514            for expected in [
515                "Poster plan",
516                "Steps",
517                "bold",
518                "inline code",
519                "Seede",
520                "•",
521                "first",
522                "nested",
523                "1.",
524                "2.",
525                "Keep the title short.",
526                "fn main() {}",
527                "Poster",
528                "16:9",
529            ] {
530                assert!(texts.contains(expected), "{expected:?} at {width}: {texts}");
531            }
532            for paragraph in find_all::<RenderParagraph>(&app, item) {
533                assert!(
534                    paragraph.size(&app).width() <= width,
535                    "no text overflows the panel"
536                );
537            }
538        }
539    }
540
541    #[test]
542    fn each_element_takes_its_style_from_the_sheet() {
543        let cell = test_cell();
544        let item = mount_in_panel(&cell, 400.0, MarkdownBody::new(REPLY));
545        let app = cell.borrow();
546        let sheet = fallback_sheet();
547
548        let (_, bold) = span_with_text(&app, item, "bold");
549        assert_eq!(bold.style.unwrap().font_weight, Some(FontWeight::BOLD));
550        let (_, italic) = span_with_text(&app, item, "italic");
551        assert_eq!(italic.style.unwrap().font_style, Some(FontStyle::Italic));
552        let (_, struck) = span_with_text(&app, item, "struck");
553        assert_eq!(
554            struck.style.unwrap().decoration,
555            Some(TextDecoration::LINE_THROUGH)
556        );
557        let (_, code) = span_with_text(&app, item, "inline code");
558        assert_eq!(
559            code.style.unwrap().font_family.as_deref(),
560            Some("monospace")
561        );
562        let (_, title) = span_with_text(&app, item, "Poster plan");
563        let title_style = title.style.unwrap();
564        assert_eq!(title_style.font_size, sheet.headings[0].text.font_size);
565        assert_eq!(title_style.font_weight, Some(FontWeight::W500));
566        let (_, steps) = span_with_text(&app, item, "Steps");
567        assert_eq!(
568            steps.style.unwrap().font_size,
569            sheet.headings[1].text.font_size
570        );
571        let (_, link) = span_with_text(&app, item, "Seede");
572        assert_eq!(link.style.unwrap().color, sheet.link.color);
573        assert!(
574            link.recognizer.is_none(),
575            "without a hook a link has nothing to call"
576        );
577    }
578
579    #[test]
580    fn a_tapped_link_calls_on_tap_link_with_its_url_and_title() {
581        let cell = test_cell();
582        let taps: Rc<RefCell<Vec<(String, String)>>> = Rc::default();
583        let sink = Rc::clone(&taps);
584        let body = MarkdownBody::new(REPLY).on_tap_link(move |_app, url, title| {
585            sink.borrow_mut().push((url.to_owned(), title.to_owned()))
586        });
587        let item = mount_in_panel(&cell, 400.0, body);
588        let mut app = cell.borrow_mut();
589        let link = global_rect_of_text(&mut app, item, "Seede");
590        tap_at(&mut app, link.center());
591        assert_eq!(
592            *taps.borrow(),
593            [("https://seede.ai".to_owned(), "home".to_owned())]
594        );
595        let text = global_rect_of_text(&mut app, item, "for more");
596        tap_at(&mut app, text.center());
597        assert_eq!(taps.borrow().len(), 1, "plain text is not a link");
598    }
599
600    /// Bullets come before each item, numbers count from the list's start, and a nested
601    /// item is indented past its parent.
602    #[test]
603    fn lists_have_bullets_numbers_and_nesting() {
604        let cell = test_cell();
605        let item = mount_in_panel(
606            &cell,
607            400.0,
608            MarkdownBody::new("- outer\n  - inner\n\n3. three\n4. four\n"),
609        );
610        let mut app = cell.borrow_mut();
611        let texts = paragraph_texts(&app, item);
612        assert_eq!(texts.iter().filter(|text| *text == "•").count(), 2);
613        assert!(texts.contains(&"3.".to_owned()) && texts.contains(&"4.".to_owned()));
614        let outer = global_rect_of_text(&mut app, item, "outer");
615        let inner = global_rect_of_text(&mut app, item, "inner");
616        assert!(inner.left > outer.left, "the nested item is indented");
617        assert!(inner.top > outer.top);
618    }
619
620    #[test]
621    fn tight_and_loose_list_items_are_one_block_spacing_apart() {
622        let gap = |markdown: &str| {
623            let cell = test_cell();
624            let item = mount_in_panel(&cell, 400.0, MarkdownBody::new(markdown));
625            let mut app = cell.borrow_mut();
626            let first = global_rect_of_text(&mut app, item, "first");
627            let second = global_rect_of_text(&mut app, item, "second");
628            second.top - first.bottom
629        };
630        let sheet = fallback_sheet();
631        let tight = gap("- first\n- second\n");
632        let loose = gap("- first\n\n- second\n");
633        assert!((tight - sheet.block_spacing).abs() < 1e-9, "{tight}");
634        assert!((loose - sheet.block_spacing).abs() < 1e-9, "{loose}");
635    }
636
637    /// A bullet larger than its text sits on the text's baseline, not on its top.
638    #[test]
639    fn a_bullet_sits_on_the_baseline_of_its_text() {
640        let cell = test_cell();
641        let mut sheet = MarkdownStyleSheet::from_text_style(
642            TextStyle::new().font_size(12.0),
643            Brightness::Light,
644        );
645        sheet.list.bullet = TextStyle::new().font_size(32.0);
646        let item = mount_in_panel(
647            &cell,
648            400.0,
649            MarkdownBody::new("- item\n").style_sheet(sheet),
650        );
651        let mut app = cell.borrow_mut();
652        let global_baseline = |app: &mut App, text: &str| {
653            let (paragraph, _) = span_with_text(app, item, text);
654            let paragraph = paragraph.as_box();
655            let baseline = paragraph
656                .get_distance_to_baseline(app, TextBaseline::Alphabetic, true)
657                .expect("a paragraph has a baseline");
658            let top = paragraph.local_to_global(app, Offset::ZERO, None).dy();
659            (top, top + baseline)
660        };
661        let (bullet_top, bullet_baseline) = global_baseline(&mut app, "•");
662        let (text_top, text_baseline) = global_baseline(&mut app, "item");
663        assert!(bullet_top < text_top, "the larger bullet starts higher");
664        assert!((bullet_baseline - text_baseline).abs() < 1e-9);
665    }
666
667    #[test]
668    fn a_table_has_a_head_row_striped_body_rows_and_aligned_cells() {
669        let cell = test_cell();
670        let item = mount_in_panel(
671            &cell,
672            400.0,
673            MarkdownBody::new(
674                "| Name | Size |\n|------|-----:|\n| Poster | A2 |\n| Deck | 16:9 |\n| Card | A6 |\n",
675            ),
676        );
677        let app = cell.borrow();
678        let tables = find_all::<RenderTable>(&app, item);
679        assert_eq!(tables.len(), 1);
680        let table = tables[0];
681        assert_eq!((table.columns(&app), table.rows(&app)), (2, 4));
682        assert!(table.border(&app).is_some());
683        assert_eq!(table.size(&app).width(), 400.0 - 16.0);
684        let decorated: Vec<bool> = table
685            .row_decorations(&app)
686            .iter()
687            .map(Option::is_some)
688            .collect();
689        assert_eq!(decorated, [false, false, true, false]);
690
691        let (head, name) = span_with_text(&app, item, "Name");
692        assert_eq!(name.style.unwrap().font_weight, Some(FontWeight::W600));
693        assert_eq!(
694            head.text_align(&app),
695            TextAlign::Center,
696            "an unaligned head is centred"
697        );
698        let (size, _) = span_with_text(&app, item, "Size");
699        assert_eq!(size.text_align(&app), TextAlign::Right);
700        let (poster, _) = span_with_text(&app, item, "Poster");
701        assert_eq!(poster.text_align(&app), TextAlign::Start);
702        let (a2, _) = span_with_text(&app, item, "A2");
703        assert_eq!(a2.text_align(&app), TextAlign::Right);
704    }
705
706    /// The quote, the code block and the rule each paint their decoration, and the code
707    /// scrolls sideways.
708    #[test]
709    fn blocks_paint_their_decorations_and_code_scrolls_sideways() {
710        let cell = test_cell();
711        let item = mount_in_panel(&cell, 400.0, MarkdownBody::new(REPLY));
712        let app = cell.borrow();
713        assert!(find_all::<RenderDecoratedBox>(&app, item).len() >= 3);
714        let (code_paragraph, code) = span_with_text(&app, item, "fn main");
715        assert_eq!(code.text.as_deref(), Some("fn main() {}"));
716        assert!(
717            is_in_viewport(&app, item, code_paragraph.as_object()),
718            "a code block scrolls sideways"
719        );
720    }
721
722    fn is_in_viewport(app: &App, root: AnyRenderObject, object: AnyRenderObject) -> bool {
723        let viewports: Vec<AnyRenderObject> = descendants(app, root)
724            .into_iter()
725            .filter(|object| object.interface::<AnyRenderAbstractViewport>().is_some())
726            .collect();
727        let mut ancestor = object.parent(app);
728        while let Some(current) = ancestor {
729            if viewports.contains(&current) {
730                return true;
731            }
732            ancestor = current.parent(app);
733        }
734        false
735    }
736
737    #[test]
738    fn the_highlighter_spans_a_code_blocks_text() {
739        let cell = test_cell();
740        let red = Color::new(0xFFFF0000);
741        let languages: Rc<RefCell<Vec<Option<String>>>> = Rc::default();
742        let sink = Rc::clone(&languages);
743        let body = MarkdownBody::new("```rust\nfn main() {}\n```\n").highlight_code(
744            move |_app, language, code| {
745                sink.borrow_mut().push(language.map(str::to_owned));
746                let (keyword, rest) = code.split_at(2);
747                TextSpan::new().children(vec![
748                    TextSpan::new()
749                        .text(keyword)
750                        .style(TextStyle::new().color(red))
751                        .into_span(),
752                    TextSpan::new().text(rest).into_span(),
753                ])
754            },
755        );
756        let item = mount_in_panel(&cell, 400.0, body);
757        let app = cell.borrow();
758        assert_eq!(*languages.borrow(), [Some("rust".to_owned())]);
759        let (paragraph, keyword) = span_with_text(&app, item, "fn");
760        assert_eq!(keyword.style.unwrap().color.as_deref(), Some(&red));
761        assert_eq!(
762            paragraph.text(&app).to_plain_text(true, true),
763            "fn main() {}"
764        );
765        // `Text::rich` wraps the block's span in one carrying the ambient text style.
766        let text = paragraph.text(&app);
767        let wrapper = text
768            .as_any()
769            .downcast_ref::<TextSpan>()
770            .expect("a text span");
771        let block_span = wrapper.children.as_ref().expect("the block's span")[0].clone();
772        let block_style = block_span.style().cloned().expect("the block's style");
773        assert_eq!(block_style.font_family.as_deref(), Some("monospace"));
774        assert!(is_in_viewport(&app, item, paragraph.as_object()));
775    }
776
777    #[test]
778    fn a_default_markdown_style_above_sets_the_look() {
779        let red = Color::new(0xFFFF0000);
780        let blue = Color::new(0xFF0000FF);
781        let red_sheet =
782            MarkdownStyleSheet::from_text_style(TextStyle::new().color(red), Brightness::Light);
783        let cell = test_cell();
784        let item = mount_in_panel(
785            &cell,
786            400.0,
787            DefaultMarkdownStyle::new(red_sheet.clone(), MarkdownBody::new("plain words")),
788        );
789        let (_, span) = span_with_text(&cell.borrow(), item, "plain words");
790        assert_eq!(span.style.unwrap().color.as_deref(), Some(&red));
791
792        let mut blue_sheet = red_sheet.clone();
793        blue_sheet.text = TextStyle::new().color(blue);
794        let cell = test_cell();
795        let item = mount_in_panel(
796            &cell,
797            400.0,
798            DefaultMarkdownStyle::new(
799                red_sheet,
800                MarkdownBody::new("plain words").style_sheet(blue_sheet),
801            ),
802        );
803        let (_, span) = span_with_text(&cell.borrow(), item, "plain words");
804        assert_eq!(
805            span.style.unwrap().color.as_deref(),
806            Some(&blue),
807            "the widget's own sheet replaces the inherited one"
808        );
809    }
810
811    #[test]
812    fn the_hooks_build_images_checkboxes_and_bullets() {
813        let cell = test_cell();
814        let images: Rc<RefCell<Vec<Image>>> = Rc::default();
815        let checkboxes: Rc<RefCell<Vec<bool>>> = Rc::default();
816        let bullets: Rc<RefCell<Vec<Bullet>>> = Rc::default();
817        let (image_sink, checkbox_sink, bullet_sink) = (
818            Rc::clone(&images),
819            Rc::clone(&checkboxes),
820            Rc::clone(&bullets),
821        );
822        let body = MarkdownBody::new(
823            "![a cat](cat.png \"Cat\")\n\n- [x] done\n- [ ] todo\n\n2. two\n   - under\n",
824        )
825        .image(move |_app, image| {
826            image_sink.borrow_mut().push(image.clone());
827            SizedBox::new().width(100.0).height(50.0).into_widget()
828        })
829        .checkbox(move |_app, checked| {
830            checkbox_sink.borrow_mut().push(checked);
831            SizedBox::new().width(10.0).height(10.0).into_widget()
832        })
833        .bullet(move |_app, bullet| {
834            bullet_sink.borrow_mut().push(*bullet);
835            SizedBox::new().width(10.0).height(10.0).into_widget()
836        });
837        mount_in_panel(&cell, 400.0, body);
838        assert_eq!(
839            *images.borrow(),
840            [Image {
841                url: "cat.png".to_owned(),
842                title: "Cat".to_owned(),
843                alt: "a cat".to_owned(),
844            }]
845        );
846        assert_eq!(*checkboxes.borrow(), [true, false]);
847        assert_eq!(
848            *bullets.borrow(),
849            [
850                Bullet {
851                    number: Some(2),
852                    index: 0,
853                    depth: 0
854                },
855                Bullet {
856                    number: None,
857                    index: 0,
858                    depth: 1
859                },
860            ]
861        );
862    }
863
864    #[test]
865    fn without_hooks_an_image_shows_its_alt_text_and_a_task_its_checkbox() {
866        let cell = test_cell();
867        let item = mount_in_panel(
868            &cell,
869            400.0,
870            MarkdownBody::new("![a cat](cat.png)\n\n- [x] done\n- [ ] todo\n"),
871        );
872        let app = cell.borrow();
873        let texts = paragraph_texts(&app, item);
874        assert!(texts.contains(&"a cat".to_owned()), "{texts:?}");
875        assert_eq!(find_all::<RenderCustomPaint>(&app, item).len(), 2);
876    }
877
878    #[test]
879    fn link_recognizers_are_disposed_when_the_text_changes_and_on_unmount() {
880        let cell = test_cell();
881        let text = cell
882            .borrow_mut()
883            .new_entity(|_cx| Some("[one](https://one.example)".to_owned()));
884        let tree = Builder::new({
885            let text = text.clone();
886            move |app, _context| match text.read(app).clone() {
887                Some(text) => MarkdownBody::new(text)
888                    .on_tap_link(|_app, _url, _title| {})
889                    .into_widget(),
890                None => SizedBox::new().into_widget(),
891            }
892        });
893        let item = mount_in_panel(&cell, 400.0, tree);
894        let recognizer_of = |app: &App, link: &str| {
895            span_with_text(app, item, link)
896                .1
897                .recognizer
898                .expect("a link with a hook has a recognizer")
899                .handle()
900        };
901        let is_gone = |app: &App, recognizer: waft_gestures::AnyGestureRecognizer| {
902            !app.contains(recognizer.id()) || app.is_disposed(recognizer.id())
903        };
904
905        let first = recognizer_of(&cell.borrow(), "one");
906        text.update(&mut cell.borrow_mut(), |text, cx| {
907            *text = Some("[two](https://two.example)".to_owned());
908            cx.notify();
909        });
910        pump(&mut cell.borrow_mut(), std::time::Duration::from_millis(16));
911        let second = recognizer_of(&cell.borrow(), "two");
912        assert!(is_gone(&cell.borrow(), first));
913        assert!(!is_gone(&cell.borrow(), second));
914
915        text.update(&mut cell.borrow_mut(), |text, cx| {
916            *text = None;
917            cx.notify();
918        });
919        pump(&mut cell.borrow_mut(), std::time::Duration::from_millis(32));
920        assert!(is_gone(&cell.borrow(), second));
921    }
922
923    /// A rebuild with the same text keeps the links' recognizers, and a tap calls the newest
924    /// `on_tap_link`, as flutter_markdown's link calls `widget.onTapLink`.
925    #[test]
926    fn a_rebuild_with_the_same_text_keeps_the_link_and_calls_the_newest_hook() {
927        let cell = test_cell();
928        let generation = cell.borrow_mut().new_entity(|_cx| 1u32);
929        let taps: Rc<RefCell<Vec<u32>>> = Rc::default();
930        let tree = Builder::new({
931            let (generation, taps) = (generation.clone(), Rc::clone(&taps));
932            move |app, _context| {
933                let current = *generation.read(app);
934                let taps = Rc::clone(&taps);
935                MarkdownBody::new("[link](https://example.com)")
936                    .on_tap_link(move |_app, _url, _title| taps.borrow_mut().push(current))
937                    .into_widget()
938            }
939        });
940        let item = mount_in_panel(&cell, 400.0, tree);
941        let recognizer_of = |app: &App| {
942            span_with_text(app, item, "link")
943                .1
944                .recognizer
945                .expect("a link with a hook has a recognizer")
946                .handle()
947        };
948        let first = recognizer_of(&cell.borrow());
949
950        generation.update(&mut cell.borrow_mut(), |generation, cx| {
951            *generation = 2;
952            cx.notify();
953        });
954        pump(&mut cell.borrow_mut(), std::time::Duration::from_millis(16));
955
956        let mut app = cell.borrow_mut();
957        assert_eq!(recognizer_of(&app).id(), first.id());
958        let link = global_rect_of_text(&mut app, item, "link");
959        tap_at(&mut app, link.center());
960        assert_eq!(*taps.borrow(), [2]);
961    }
962
963    #[test]
964    fn the_scrolling_widget_lists_the_blocks() {
965        let cell = test_cell();
966        let key = GlobalKey::new();
967        let markdown_key: KeyRef = key.clone().into();
968        build(
969            &cell,
970            Directionality::new(
971                TextDirection::Ltr,
972                Markdown::new("# Title\n\nOne paragraph.\n\nAnother.").key(markdown_key),
973            )
974            .into_widget(),
975        );
976        let mut app = cell.borrow_mut();
977        let root = render_object_of(&mut app, &key);
978        assert_eq!(
979            paragraph_texts(&app, root),
980            ["Title", "One paragraph.", "Another."]
981        );
982        let title = global_rect_of_text(&mut app, root, "Title");
983        assert_eq!((title.left, title.top), (16.0, 16.0), "the default padding");
984    }
985
986    #[test]
987    fn a_quote_paints_its_decoration_with_the_sheets_colour() {
988        let cell = test_cell();
989        let green = Color::new(0xFF00FF00);
990        let mut sheet = fallback_sheet();
991        sheet.quote.decoration = BoxDecoration::new().color(green);
992        let item = mount_in_panel(
993            &cell,
994            400.0,
995            MarkdownBody::new("> quoted").style_sheet(sheet),
996        );
997        let app = cell.borrow();
998        let decorations: Vec<_> = find_all::<RenderDecoratedBox>(&app, item)
999            .into_iter()
1000            .filter_map(|decorated| {
1001                decorated
1002                    .decoration(&app)
1003                    .as_any()
1004                    .downcast_ref::<BoxDecoration>()
1005                    .cloned()
1006            })
1007            .collect();
1008        assert!(decorations.contains(&BoxDecoration::new().color(green)));
1009    }
1010}