BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / render / blocks.rs

blocks.rs

blocks.rs 29.2 KiB Download Raw
1use std::ops::Range;
2
3use teams_core::Span;
4
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
6pub const CODE_PADDING: &str = "\u{2004}";
7const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
8const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
9
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
11pub struct StyleFlags {
12 pub bold: bool,
13 pub italic: bool,
14 pub code: bool,
15 pub mention: bool,
16 pub link: bool,
17 pub strike: bool,
18 pub underline: bool,
19 pub color: Option<u32>,
20 pub background: Option<u32>,
21}
22
23impl StyleFlags {
24 pub fn is_plain(&self) -> bool {
25 *self == StyleFlags::default()
26 }
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Segment {
31 pub range: Range<usize>,
32 pub style: StyleFlags,
33 pub link: Option<String>,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
37pub struct Inline {
38 pub text: String,
39 pub segments: Vec<Segment>,
40}
41
42impl Inline {
43 pub fn plain(text: &str) -> Self {
44 let mut inline = Inline::default();
45 inline.push(text, StyleFlags::default(), None);
46 inline
47 }
48
49 fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {
50 if text.is_empty() {
51 return;
52 }
53 let start = self.text.len();
54 self.text.push_str(text);
55 let end = self.text.len();
56 if let Some(last) = self.segments.last_mut()
57 && last.style == style
58 && last.link.as_deref() == link
59 && last.range.end == start
60 {
61 last.range.end = end;
62 return;
63 }
64 self.segments.push(Segment {
65 range: start..end,
66 style,
67 link: link.map(str::to_owned),
68 });
69 }
70
71 pub fn plain_text(&self) -> String {
72 self.text.replace(CODE_PADDING, "")
73 }
74
75 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
76 let mut padded = self.clone();
77 padded.push(
78 &"\u{2007}".repeat(width_in_spaces),
79 StyleFlags::default(),
80 None,
81 );
82 padded
83 }
84
85 pub fn is_blank(&self) -> bool {
86 self.text.trim().is_empty()
87 }
88
89 fn trim_end(&mut self) {
90 let trimmed = self.text.trim_end().len();
91 self.text.truncate(trimmed);
92 self.segments.retain_mut(|segment| {
93 segment.range.end = segment.range.end.min(trimmed);
94 segment.range.start < segment.range.end
95 });
96 }
97
98 fn without(&self, needle: &str) -> Inline {
99 let mut stripped = Inline::default();
100 for segment in &self.segments {
101 let text = self.text[segment.range.clone()].replace(needle, "");
102 stripped.push(&text, segment.style, segment.link.as_deref());
103 }
104 stripped.trim_end();
105 let leading = stripped.text.len() - stripped.text.trim_start().len();
106 if leading > 0 {
107 let mut trimmed = Inline::default();
108 for segment in &stripped.segments {
109 let text = stripped.text[segment.range.clone()].to_owned();
110 let skip = leading.saturating_sub(segment.range.start).min(text.len());
111 trimmed.push(&text[skip..], segment.style, segment.link.as_deref());
112 }
113 return trimmed;
114 }
115 stripped
116 }
117
118 pub fn links(&self) -> Vec<(Range<usize>, String)> {
119 self.segments
120 .iter()
121 .filter_map(|segment| Some((segment.range.clone(), segment.link.clone()?)))
122 .collect()
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum Block {
128 Paragraph(Inline),
129 Heading {
130 level: u8,
131 inline: Inline,
132 },
133 Code {
134 language: Option<String>,
135 code: String,
136 },
137 Reply(Vec<Block>),
138 Quote(Vec<Block>),
139 List {
140 ordered: bool,
141 start: u32,
142 items: Vec<Vec<Block>>,
143 },
144 Table {
145 header: bool,
146 rows: Vec<Vec<Inline>>,
147 },
148 Rule,
149 Image {
150 url: String,
151 },
152}
153
154impl Block {
155 pub fn markdown(&self) -> Option<String> {
156 let join = |blocks: &[Block]| {
157 blocks
158 .iter()
159 .filter_map(Block::markdown)
160 .collect::<Vec<_>>()
161 .join("\n")
162 };
163 match self {
164 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.plain_text()),
165 Block::Code { code, .. } => Some(format!("```\n{code}\n```")),
166 Block::List {
167 ordered,
168 start,
169 items,
170 } => Some(
171 items
172 .iter()
173 .enumerate()
174 .map(|(offset, item)| match ordered {
175 true => format!("{}. {}", *start as usize + offset, join(item)),
176 false => format!("- {}", join(item)),
177 })
178 .collect::<Vec<_>>()
179 .join("\n"),
180 ),
181 Block::Table { rows, .. } => Some(
182 rows.iter()
183 .map(|row| {
184 row.iter()
185 .map(Inline::plain_text)
186 .collect::<Vec<_>>()
187 .join(" | ")
188 })
189 .collect::<Vec<_>>()
190 .join("\n"),
191 ),
192 Block::Quote(children) => Some(join(children)),
193 Block::Reply(_) | Block::Rule | Block::Image { .. } => None,
194 }
195 }
196
197 pub fn first_line(&self) -> Option<String> {
198 match self {
199 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.plain_text()),
200 Block::Code { code, .. } => Some(code.clone()),
201 Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
202 Block::Table { rows, .. } => Some(rows.first()?.first()?.plain_text()),
203 Block::Quote(children) => children.iter().find_map(Block::first_line),
204 Block::Reply(_) | Block::Rule | Block::Image { .. } => None,
205 }
206 }
207
208 pub fn last_inline_mut(&mut self) -> Option<&mut Inline> {
209 match self {
210 Block::Paragraph(inline) => Some(inline),
211 Block::List { items, .. } => items.last_mut()?.last_mut()?.last_inline_mut(),
212 _ => None,
213 }
214 }
215}
216
217pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
218 blocks
219 .into_iter()
220 .filter_map(|block| match block {
221 Block::Paragraph(inline) => {
222 let stripped = inline.without(IMAGE_PLACEHOLDER);
223 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
224 }
225 Block::Reply(children) => {
226 let children = strip_image_placeholders(children);
227 (!children.is_empty()).then_some(Block::Reply(children))
228 }
229 Block::Quote(children) => {
230 let children = strip_image_placeholders(children);
231 (!children.is_empty()).then_some(Block::Quote(children))
232 }
233 Block::List {
234 ordered,
235 start,
236 items,
237 } => {
238 let items: Vec<Vec<Block>> = items
239 .into_iter()
240 .map(strip_image_placeholders)
241 .filter(|item| !item.is_empty())
242 .collect();
243 (!items.is_empty()).then_some(Block::List {
244 ordered,
245 start,
246 items,
247 })
248 }
249 other => Some(other),
250 })
251 .collect()
252}
253
254pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
255 layout_blocks_with(spans, true)
256}
257
258fn layout_blocks_with(spans: &[Span], split_images: bool) -> Vec<Block> {
259 let mut blocks = Vec::new();
260 let mut current = Inline::default();
261 for span in spans {
262 match span {
263 Span::CodeBlock { language, code } => {
264 flush(&mut current, &mut blocks, Block::Paragraph);
265 blocks.push(Block::Code {
266 language: language.clone(),
267 code: code.trim_end_matches('\n').to_owned(),
268 });
269 }
270 Span::Quote(children) | Span::BlockQuote(children) => {
271 flush(&mut current, &mut blocks, Block::Paragraph);
272 let inner = layout_blocks_with(children, false);
273 if !inner.is_empty() {
274 blocks.push(match span {
275 Span::Quote(_) => Block::Reply(inner),
276 _ => Block::Quote(inner),
277 });
278 }
279 }
280 Span::List {
281 ordered,
282 start,
283 items,
284 } => {
285 flush(&mut current, &mut blocks, Block::Paragraph);
286 let items: Vec<Vec<Block>> = items
287 .iter()
288 .map(|item| layout_blocks_with(item, false))
289 .filter(|item| !item.is_empty())
290 .collect();
291 if !items.is_empty() {
292 blocks.push(Block::List {
293 ordered: *ordered,
294 start: *start,
295 items,
296 });
297 }
298 }
299 Span::Table { header, rows } => {
300 flush(&mut current, &mut blocks, Block::Paragraph);
301 let rows: Vec<Vec<Inline>> = rows
302 .iter()
303 .map(|row| row.iter().map(|cell| inline_of(cell)).collect())
304 .collect();
305 if !rows.is_empty() {
306 blocks.push(Block::Table {
307 header: *header,
308 rows,
309 });
310 }
311 }
312 Span::Heading { level, children } => {
313 flush(&mut current, &mut blocks, Block::Paragraph);
314 let inline = inline_of(children);
315 if !inline.is_blank() {
316 blocks.push(Block::Heading {
317 level: *level,
318 inline,
319 });
320 }
321 }
322 Span::Rule => {
323 flush(&mut current, &mut blocks, Block::Paragraph);
324 blocks.push(Block::Rule);
325 }
326 Span::Image { hosted_content_url } if split_images => {
327 flush(&mut current, &mut blocks, Block::Paragraph);
328 blocks.push(Block::Image {
329 url: hosted_content_url.clone(),
330 });
331 }
332 other => append_inline(
333 std::slice::from_ref(other),
334 StyleFlags::default(),
335 None,
336 &mut current,
337 ),
338 }
339 }
340 flush(&mut current, &mut blocks, Block::Paragraph);
341 blocks
342}
343
344fn inline_of(spans: &[Span]) -> Inline {
345 let mut inline = Inline::default();
346 append_inline(spans, StyleFlags::default(), None, &mut inline);
347 inline.trim_end();
348 pad_code(inline)
349}
350
351fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
352 let mut inline = std::mem::take(current);
353 inline.trim_end();
354 let leading = inline.text.len() - inline.text.trim_start().len();
355 if leading > 0 {
356 inline.text.drain(..leading);
357 inline.segments.retain_mut(|segment| {
358 segment.range.start = segment.range.start.saturating_sub(leading);
359 segment.range.end = segment.range.end.saturating_sub(leading);
360 segment.range.start < segment.range.end
361 });
362 }
363 if !inline.is_blank() {
364 blocks.push(make(pad_code(inline)));
365 }
366}
367
368fn pad_code(inline: Inline) -> Inline {
369 if !inline.segments.iter().any(|segment| segment.style.code) {
370 return inline;
371 }
372 let mut padded = Inline::default();
373 for (index, segment) in inline.segments.iter().enumerate() {
374 let text = &inline.text[segment.range.clone()];
375 let touches = |neighbour: Option<&Segment>| {
376 neighbour.is_some_and(|neighbour| !neighbour.style.code && !neighbour.range.is_empty())
377 };
378 let previous = index
379 .checked_sub(1)
380 .and_then(|previous| inline.segments.get(previous));
381 if segment.style.code && touches(previous) {
382 padded.push(CODE_PADDING, StyleFlags::default(), None);
383 }
384 padded.push(text, segment.style, segment.link.as_deref());
385 if segment.style.code && touches(inline.segments.get(index + 1)) {
386 padded.push(CODE_PADDING, StyleFlags::default(), None);
387 }
388 }
389 padded
390}
391
392fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
393 for span in spans {
394 match span {
395 Span::Text(text) if link.is_none() && !style.code => {
396 push_linkified(text, style, out);
397 }
398 Span::Text(text) => out.push(text, style, link),
399 Span::Bold(children) => append_inline(
400 children,
401 StyleFlags {
402 bold: true,
403 ..style
404 },
405 link,
406 out,
407 ),
408 Span::Italic(children) => append_inline(
409 children,
410 StyleFlags {
411 italic: true,
412 ..style
413 },
414 link,
415 out,
416 ),
417 Span::Strike(children) => append_inline(
418 children,
419 StyleFlags {
420 strike: true,
421 ..style
422 },
423 link,
424 out,
425 ),
426 Span::Underline(children) => append_inline(
427 children,
428 StyleFlags {
429 underline: true,
430 ..style
431 },
432 link,
433 out,
434 ),
435 Span::Colored {
436 color,
437 background,
438 children,
439 } => append_inline(
440 children,
441 StyleFlags {
442 color: color.or(style.color),
443 background: background.or(style.background),
444 ..style
445 },
446 link,
447 out,
448 ),
449 Span::Heading { children, .. } => {
450 append_inline(
451 children,
452 StyleFlags {
453 bold: true,
454 ..style
455 },
456 link,
457 out,
458 );
459 out.push("\n", style, link);
460 }
461 Span::Code(text) => out.push(
462 text,
463 StyleFlags {
464 code: true,
465 ..style
466 },
467 link,
468 ),
469 Span::CodeBlock { code, .. } => out.push(
470 code.trim_end_matches('\n'),
471 StyleFlags {
472 code: true,
473 ..style
474 },
475 link,
476 ),
477 Span::Link { url, children } => append_inline(
478 children,
479 StyleFlags {
480 link: true,
481 ..style
482 },
483 Some(url.as_str()),
484 out,
485 ),
486 Span::Mention { name, .. } => {
487 let label = format!("@{}", name.trim_start_matches('@'));
488 out.push(
489 &label,
490 StyleFlags {
491 mention: true,
492 ..style
493 },
494 link,
495 );
496 }
497 Span::LineBreak | Span::Rule => out.push("\n", style, link),
498 Span::Quote(children) | Span::BlockQuote(children) => {
499 append_inline(children, style, link, out);
500 out.push("\n", style, link);
501 }
502 Span::List { items, .. } => {
503 for item in items {
504 append_inline(item, style, link, out);
505 out.push("\n", style, link);
506 }
507 }
508 Span::Table { rows, .. } => {
509 for row in rows {
510 for (index, cell) in row.iter().enumerate() {
511 if index > 0 {
512 out.push(" ", style, link);
513 }
514 append_inline(cell, style, link, out);
515 }
516 out.push("\n", style, link);
517 }
518 }
519 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
520 }
521 }
522}
523
524fn push_linkified(text: &str, style: StyleFlags, out: &mut Inline) {
525 let mut rest = text;
526 while let Some((start, end)) = find_url(rest) {
527 out.push(&rest[..start], style, None);
528 let visible = &rest[start..end];
529 let target = if visible.starts_with("www.") {
530 format!("https://{visible}")
531 } else {
532 visible.to_owned()
533 };
534 out.push(
535 visible,
536 StyleFlags {
537 link: true,
538 ..style
539 },
540 Some(&target),
541 );
542 rest = &rest[end..];
543 }
544 out.push(rest, style, None);
545}
546
547fn find_url(text: &str) -> Option<(usize, usize)> {
548 let mut previous_is_boundary = true;
549 for (start, character) in text.char_indices() {
550 if previous_is_boundary
551 && let Some(prefix) = URL_PREFIXES
552 .iter()
553 .find(|prefix| text[start..].starts_with(**prefix))
554 {
555 let length = text[start..]
556 .find(char::is_whitespace)
557 .unwrap_or(text.len() - start);
558 let end = start + trimmed_url_length(&text[start..start + length]);
559 if end > start + prefix.len() {
560 return Some((start, end));
561 }
562 }
563 previous_is_boundary = !character.is_alphanumeric();
564 }
565 None
566}
567
568fn trimmed_url_length(candidate: &str) -> usize {
569 let mut url = candidate;
570 while let Some(last) = url.chars().next_back() {
571 let opener = match last {
572 ')' => Some('('),
573 ']' => Some('['),
574 '}' => Some('{'),
575 _ => None,
576 };
577 let trimmable = match opener {
578 Some(opener) => url.matches(last).count() > url.matches(opener).count(),
579 None => TRAILING_PUNCTUATION.contains(last),
580 };
581 if !trimmable {
582 break;
583 }
584 url = &url[..url.len() - last.len_utf8()];
585 }
586 url.len()
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 fn text(value: &str) -> Span {
594 Span::Text(value.to_owned())
595 }
596
597 #[test]
598 fn plain_text_is_one_paragraph() {
599 let blocks = layout_blocks(&[text("hello ")]);
600 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("hello"))]);
601 }
602
603 #[test]
604 fn bold_and_italic_nest_into_flags() {
605 let blocks = layout_blocks(&[
606 text("a "),
607 Span::Bold(vec![Span::Italic(vec![text("b")])]),
608 text(" c"),
609 ]);
610 let Block::Paragraph(inline) = &blocks[0] else {
611 panic!("paragraph expected")
612 };
613 assert_eq!(inline.text, "a b c");
614 assert_eq!(inline.segments.len(), 3);
615 assert!(inline.segments[1].style.bold && inline.segments[1].style.italic);
616 assert_eq!(inline.segments[1].range, 2..3);
617 }
618
619 #[test]
620 fn link_keeps_url_and_range() {
621 let blocks = layout_blocks(&[
622 text("see "),
623 Span::Link {
624 url: "https://example.com".into(),
625 children: vec![text("here")],
626 },
627 ]);
628 let Block::Paragraph(inline) = &blocks[0] else {
629 panic!("paragraph expected")
630 };
631 assert_eq!(
632 inline.links(),
633 vec![(4..8, "https://example.com".to_owned())]
634 );
635 }
636
637 fn paragraph_inline(spans: &[Span]) -> Inline {
638 let Block::Paragraph(inline) = layout_blocks(spans).remove(0) else {
639 panic!("paragraph expected")
640 };
641 inline
642 }
643
644 #[test]
645 fn plain_url_at_end_becomes_link() {
646 let inline = paragraph_inline(&[text("see https://example.com/a")]);
647 assert_eq!(
648 inline.links(),
649 vec![(4..25, "https://example.com/a".to_owned())]
650 );
651 assert!(inline.segments[1].style.link);
652 }
653
654 #[test]
655 fn trailing_period_stays_outside_url() {
656 let inline = paragraph_inline(&[text("go to http://example.com. Then")]);
657 assert_eq!(
658 inline.links(),
659 vec![(6..24, "http://example.com".to_owned())]
660 );
661 }
662
663 #[test]
664 fn balanced_parentheses_stay_in_url() {
665 let inline = paragraph_inline(&[text("https://example.com/Rust_(language)")]);
666 assert_eq!(inline.links()[0].1, "https://example.com/Rust_(language)");
667 let wrapped = paragraph_inline(&[text("(see https://example.com)")]);
668 assert_eq!(wrapped.links()[0].1, "https://example.com");
669 }
670
671 #[test]
672 fn www_url_gets_https_target() {
673 let inline = paragraph_inline(&[text("www.example.com!")]);
674 assert_eq!(inline.text, "www.example.com!");
675 assert_eq!(
676 inline.links(),
677 vec![(0..15, "https://www.example.com".to_owned())]
678 );
679 }
680
681 #[test]
682 fn text_without_url_has_no_links() {
683 let inline = paragraph_inline(&[text("no link, just www. and https:// here")]);
684 assert!(inline.links().is_empty());
685 }
686
687 #[test]
688 fn url_inside_link_stays_one_link() {
689 let inline = paragraph_inline(&[Span::Link {
690 url: "https://target.example".into(),
691 children: vec![text("https://shown.example")],
692 }]);
693 assert_eq!(
694 inline.links(),
695 vec![(0..21, "https://target.example".to_owned())]
696 );
697 }
698
699 #[test]
700 fn mention_gets_an_at_sign_once() {
701 let blocks = layout_blocks(&[
702 Span::Mention {
703 name: "Ada".into(),
704 id: None,
705 },
706 text(" "),
707 Span::Mention {
708 name: "@Bob".into(),
709 id: None,
710 },
711 ]);
712 let Block::Paragraph(inline) = &blocks[0] else {
713 panic!("paragraph expected")
714 };
715 assert_eq!(inline.text, "@Ada @Bob");
716 assert!(inline.segments[0].style.mention);
717 }
718
719 #[test]
720 fn code_block_splits_paragraphs() {
721 let blocks = layout_blocks(&[
722 text("before"),
723 Span::CodeBlock {
724 language: None,
725 code: "let x = 1;\n".into(),
726 },
727 text("after"),
728 ]);
729 assert_eq!(
730 blocks,
731 vec![
732 Block::Paragraph(Inline::plain("before")),
733 Block::Code {
734 language: None,
735 code: "let x = 1;".into()
736 },
737 Block::Paragraph(Inline::plain("after")),
738 ]
739 );
740 }
741
742 #[test]
743 fn lists_nest_and_quotes_are_blocks() {
744 let blocks = layout_blocks(&[
745 Span::List {
746 ordered: true,
747 start: 3,
748 items: vec![
749 vec![text("one")],
750 vec![
751 text("two"),
752 Span::List {
753 ordered: false,
754 start: 1,
755 items: vec![vec![text("inner")]],
756 },
757 ],
758 ],
759 },
760 Span::Quote(vec![text("quoted")]),
761 ]);
762 assert_eq!(
763 blocks,
764 vec![
765 Block::List {
766 ordered: true,
767 start: 3,
768 items: vec![
769 vec![Block::Paragraph(Inline::plain("one"))],
770 vec![
771 Block::Paragraph(Inline::plain("two")),
772 Block::List {
773 ordered: false,
774 start: 1,
775 items: vec![vec![Block::Paragraph(Inline::plain("inner"))]],
776 },
777 ],
778 ],
779 },
780 Block::Reply(vec![Block::Paragraph(Inline::plain("quoted"))]),
781 ]
782 );
783 }
784
785 #[test]
786 fn heading_rule_and_table_are_blocks() {
787 let blocks = layout_blocks(&[
788 Span::Heading {
789 level: 2,
790 children: vec![text("Title")],
791 },
792 Span::Rule,
793 Span::Table {
794 header: true,
795 rows: vec![vec![vec![text("a")], vec![text("b")]]],
796 },
797 ]);
798 assert_eq!(
799 blocks,
800 vec![
801 Block::Heading {
802 level: 2,
803 inline: Inline::plain("Title")
804 },
805 Block::Rule,
806 Block::Table {
807 header: true,
808 rows: vec![vec![Inline::plain("a"), Inline::plain("b")]],
809 },
810 ]
811 );
812 }
813
814 #[test]
815 fn strike_underline_and_color_become_flags() {
816 let inline = paragraph_inline(&[
817 Span::Strike(vec![text("old")]),
818 Span::Underline(vec![text("u")]),
819 Span::Colored {
820 color: Some(0xff0000),
821 background: Some(0xffff00),
822 children: vec![text("c")],
823 },
824 ]);
825 assert!(inline.segments[0].style.strike);
826 assert!(inline.segments[1].style.underline);
827 assert_eq!(inline.segments[2].style.color, Some(0xff0000));
828 assert_eq!(inline.segments[2].style.background, Some(0xffff00));
829 }
830
831 #[test]
832 fn inline_code_gets_room_next_to_text() {
833 let inline = paragraph_inline(&[
834 text("run "),
835 Span::Code("x".into()),
836 text(". "),
837 Span::Code("y".into()),
838 ]);
839 assert_eq!(inline.text, "run \u{2004}x\u{2004}. \u{2004}y");
840 assert_eq!(inline.plain_text(), "run x. y");
841 }
842
843 fn image(url: &str) -> Span {
844 Span::Image {
845 hosted_content_url: url.into(),
846 }
847 }
848
849 #[test]
850 fn top_level_image_is_its_own_block() {
851 assert_eq!(
852 layout_blocks(&[image("u")]),
853 vec![Block::Image { url: "u".into() }]
854 );
855 }
856
857 #[test]
858 fn image_splits_the_paragraph_at_its_position() {
859 let blocks = layout_blocks(&[text("a "), image("u"), text(" b")]);
860 assert_eq!(
861 blocks,
862 vec![
863 Block::Paragraph(Inline::plain("a")),
864 Block::Image { url: "u".into() },
865 Block::Paragraph(Inline::plain("b")),
866 ]
867 );
868 }
869
870 #[test]
871 fn image_inside_a_list_keeps_the_placeholder() {
872 let blocks = layout_blocks(&[Span::List {
873 ordered: false,
874 start: 1,
875 items: vec![vec![text("x "), image("u")]],
876 }]);
877 assert_eq!(
878 blocks,
879 vec![Block::List {
880 ordered: false,
881 start: 1,
882 items: vec![vec![Block::Paragraph(Inline::plain("x [image]"))]],
883 }]
884 );
885 }
886
887 #[test]
888 fn image_inside_a_quote_keeps_the_placeholder() {
889 let blocks = layout_blocks(&[Span::BlockQuote(vec![image("u")])]);
890 assert_eq!(
891 blocks,
892 vec![Block::Quote(vec![Block::Paragraph(Inline::plain(
893 IMAGE_PLACEHOLDER
894 ))])]
895 );
896 }
897
898 #[test]
899 fn image_blocks_have_no_text() {
900 let block = Block::Image { url: "u".into() };
901 assert_eq!(block.markdown(), None);
902 assert_eq!(block.first_line(), None);
903 }
904
905 #[test]
906 fn stripping_placeholders_keeps_the_text_around_them() {
907 let blocks = layout_blocks(&[Span::List {
908 ordered: false,
909 start: 1,
910 items: vec![vec![
911 text("look "),
912 Span::Bold(vec![text("here")]),
913 Span::LineBreak,
914 image("u"),
915 ]],
916 }]);
917 let stripped = strip_image_placeholders(blocks);
918 let Block::List { items, .. } = &stripped[0] else {
919 panic!("list expected")
920 };
921 let Block::Paragraph(inline) = &items[0][0] else {
922 panic!("paragraph expected")
923 };
924 assert_eq!(inline.text, "look here");
925 assert!(inline.segments.last().unwrap().style.bold);
926 let only_image = vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))];
927 assert!(strip_image_placeholders(only_image).is_empty());
928 }
929
930 #[test]
931 fn stripping_placeholders_keeps_image_blocks() {
932 let blocks = vec![Block::Image { url: "u".into() }];
933 assert_eq!(strip_image_placeholders(blocks.clone()), blocks);
934 }
935
936 #[test]
937 fn line_break_stays_inside_paragraph() {
938 let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);
939 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("a\nb"))]);
940 }
941
942 #[test]
943 fn empty_input_has_no_blocks() {
944 assert!(layout_blocks(&[]).is_empty());
945 assert!(layout_blocks(&[Span::LineBreak, text(" ")]).is_empty());
946 }
947}