BlueGit

ict rusty-teams

Files

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

blocks.rs

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