BlueGit

ict rusty-teams

Files

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

blocks.rs

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