1use 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
30const MARKER_WIDTH: f64 = 22.0;
32const LIST_INDENT: f64 = MARKER_WIDTH + ROW_GAP;
34const ROW_GAP: f64 = 8.0;
36
37#[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
53type CodeAccessory = Rc<dyn Fn(MarkdownCode) -> AnyPiece>;
55
56pub 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#[derive(Clone, Copy)]
91pub struct MarkdownCode {
92 block: Signal<MarkdownBlock>,
93}
94
95impl MarkdownCode {
96 #[must_use]
98 pub fn text(&self) -> String {
99 self.block.with(|b| b.text.clone())
100 }
101 #[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 pub fn font(mut self, font: Font) -> Self {
116 self.font = font;
117 self
118 }
119 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 pub fn spacing(mut self, spacing: impl Into<f64>) -> Self {
128 self.spacing = spacing.into();
129 self
130 }
131 pub fn selectable_text(mut self) -> Self {
134 self.selectable = true;
135 self
136 }
137 pub fn on_link(mut self, f: impl Fn(&str) + 'static) -> Self {
140 self.on_link = Some(Rc::new(f));
141 self
142 }
143 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 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#[derive(Clone, Debug, PartialEq)]
164struct RowShape {
165 kind: ShapeKind,
166 quote_depth: u8,
167 list_depth: u8,
168 marker: ListStyle,
169 gap: f64,
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174enum ShapeKind {
175 Paragraph,
176 Heading(u8),
177 Code {
179 header: bool,
180 },
181 Rule,
182}
183
184struct BlockRow {
186 shape: RowShape,
187 block: Signal<MarkdownBlock>,
188 scope: Scope,
189 root: RNode,
190}
191
192struct 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 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 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 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 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
370struct TextLook {
372 font: Font,
373 inline: bool,
375 bold: bool,
376 monospace: bool,
377}
378
379fn 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 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 if row.block.with_untracked(|b| b != block) {
444 row.block.set(block.clone());
445 }
446 continue;
447 }
448 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#[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 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 #[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 d.assert_missing("md_block:7").await?;
534 d.assert_text("md_block:8", "The end.").await
535 })
536 }
537
538 #[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 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 #[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}