BlueGit

ict rusty-teams

Files

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

blocks.rs

blocks.rs 43.1 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}";
7pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
8const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
9const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
10const BASE_FONT_PIXELS: f32 = 14.;
11// CSS absolute sizes Teams sends: xx-small = 9px, x-large = 24px, against a 14px body.
12const SMALL_SCALE: f32 = 9. / 14.;
13const LARGE_SCALE: f32 = 24. / 14.;
14const SCRIPT_SCALE: f32 = 0.75;
15const SUPERSCRIPT_RAISE: f32 = 0.35;
16const SUBSCRIPT_DROP: f32 = 0.2;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Script {
20 Super,
21 Sub,
22}
23
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct StyleFlags {
26 pub bold: bool,
27 pub italic: bool,
28 pub code: bool,
29 pub mention: bool,
30 pub link: bool,
31 pub strike: bool,
32 pub underline: bool,
33 pub script: Option<Script>,
34 pub size: Option<FontSize>,
35 pub color: Option<u32>,
36 pub background: Option<u32>,
37}
38
39impl StyleFlags {
40 pub fn is_plain(&self) -> bool {
41 *self == StyleFlags::default()
42 }
43
44 pub fn is_flowed(&self) -> bool {
45 self.script.is_some() || self.size.is_some()
46 }
47
48 pub fn baseline_raise(&self) -> f32 {
49 match self.script {
50 Some(Script::Super) => SUPERSCRIPT_RAISE,
51 Some(Script::Sub) => -SUBSCRIPT_DROP,
52 None => 0.,
53 }
54 }
55
56 pub fn font_scale(&self) -> f32 {
57 let size = match self.size {
58 Some(FontSize::Small) => SMALL_SCALE,
59 Some(FontSize::Large) => LARGE_SCALE,
60 Some(FontSize::Pixels(pixels)) => f32::from(pixels) / BASE_FONT_PIXELS,
61 Some(FontSize::Hidden) | None => 1.,
62 };
63 match self.script {
64 Some(_) => size * SCRIPT_SCALE,
65 None => size,
66 }
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Segment {
72 pub range: Range<usize>,
73 pub style: StyleFlags,
74 pub link: Option<String>,
75 pub emoji: Option<String>,
76}
77
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct Inline {
80 pub text: String,
81 pub segments: Vec<Segment>,
82}
83
84impl Inline {
85 pub fn plain(text: &str) -> Self {
86 let mut inline = Inline::default();
87 inline.push(text, StyleFlags::default(), None);
88 inline
89 }
90
91 fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {
92 self.push_part(text, style, link, None);
93 }
94
95 fn push_part(&mut self, text: &str, style: StyleFlags, link: Option<&str>, emoji: Option<&str>) {
96 if text.is_empty() {
97 return;
98 }
99 let start = self.text.len();
100 self.text.push_str(text);
101 let end = self.text.len();
102 if let Some(last) = self.segments.last_mut()
103 && emoji.is_none()
104 && last.emoji.is_none()
105 && last.style == style
106 && last.link.as_deref() == link
107 && last.range.end == start
108 {
109 last.range.end = end;
110 return;
111 }
112 self.segments.push(Segment {
113 range: start..end,
114 style,
115 link: link.map(str::to_owned),
116 emoji: emoji.map(str::to_owned),
117 });
118 }
119
120 pub fn emoji(&self) -> Vec<(Range<usize>, String)> {
121 self.segments
122 .iter()
123 .filter_map(|segment| Some((segment.range.clone(), segment.emoji.clone()?)))
124 .collect()
125 }
126
127 pub fn plain_text(&self) -> String {
128 self.segments
129 .iter()
130 .filter(|segment| segment.emoji.is_none())
131 .map(|segment| self.text[segment.range.clone()].replace(CODE_PADDING, ""))
132 .collect()
133 }
134
135 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
136 let mut padded = self.clone();
137 padded.push(
138 &"\u{2007}".repeat(width_in_spaces),
139 StyleFlags::default(),
140 None,
141 );
142 padded
143 }
144
145 fn slice(&self, range: Range<usize>) -> Inline {
146 let mut part = Inline::default();
147 for segment in &self.segments {
148 let start = segment.range.start.max(range.start);
149 let end = segment.range.end.min(range.end);
150 if start < end {
151 part.push_part(
152 &self.text[start..end],
153 segment.style,
154 segment.link.as_deref(),
155 segment.emoji.as_deref(),
156 );
157 }
158 }
159 part
160 }
161
162 pub fn is_blank(&self) -> bool {
163 self.text.trim().is_empty()
164 }
165
166 fn trim_end(&mut self) {
167 let trimmed = self.text.trim_end().len();
168 self.text.truncate(trimmed);
169 self.segments.retain_mut(|segment| {
170 segment.range.end = segment.range.end.min(trimmed);
171 segment.range.start < segment.range.end
172 });
173 }
174
175 fn without(&self, needle: &str) -> Inline {
176 let mut stripped = Inline::default();
177 for segment in &self.segments {
178 let text = self.text[segment.range.clone()].replace(needle, "");
179 stripped.push_part(&text, segment.style, segment.link.as_deref(), segment.emoji.as_deref());
180 }
181 stripped.trim_end();
182 let leading = stripped.text.len() - stripped.text.trim_start().len();
183 if leading > 0 {
184 let mut trimmed = Inline::default();
185 for segment in &stripped.segments {
186 let text = stripped.text[segment.range.clone()].to_owned();
187 let skip = leading.saturating_sub(segment.range.start).min(text.len());
188 trimmed.push_part(
189 &text[skip..],
190 segment.style,
191 segment.link.as_deref(),
192 segment.emoji.as_deref(),
193 );
194 }
195 return trimmed;
196 }
197 stripped
198 }
199
200 pub fn links(&self) -> Vec<(Range<usize>, String)> {
201 self.segments
202 .iter()
203 .filter_map(|segment| Some((segment.range.clone(), segment.link.clone()?)))
204 .collect()
205 }
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub enum Block {
210 Paragraph(Inline),
211 Heading {
212 level: u8,
213 inline: Inline,
214 },
215 Code {
216 language: Option<String>,
217 code: String,
218 },
219 CodeLine {
220 code: String,
221 },
222 Reply {
223 message_id: Option<String>,
224 children: Vec<Block>,
225 },
226 Quote(Vec<Block>),
227 Indent {
228 level: u8,
229 children: Vec<Block>,
230 },
231 List {
232 ordered: bool,
233 start: u32,
234 items: Vec<Vec<Block>>,
235 },
236 Table {
237 header: bool,
238 rows: Vec<Vec<TableCell>>,
239 },
240 Rule,
241 Image {
242 url: String,
243 },
244}
245
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct TableCell {
248 pub inline: Inline,
249 /// Images inside the cell, drawn in the cell by a renderer that knows them.
250 pub images: Vec<String>,
251}
252
253impl TableCell {
254 fn of(spans: &[Span]) -> TableCell {
255 let mut images = Vec::new();
256 collect_images(spans, &mut images);
257 let inline = inline_of(spans);
258 let inline = if images.is_empty() {
259 inline
260 } else {
261 inline.without(IMAGE_PLACEHOLDER)
262 };
263 TableCell { inline, images }
264 }
265}
266
267fn collect_images(spans: &[Span], images: &mut Vec<String>) {
268 for span in spans {
269 match span {
270 Span::Image { hosted_content_url } => images.push(hosted_content_url.clone()),
271 Span::Bold(children)
272 | Span::Italic(children)
273 | Span::Strike(children)
274 | Span::Superscript(children)
275 | Span::Subscript(children)
276 | Span::Sized(_, children)
277 | Span::Underline(children)
278 | Span::BlockQuote(children)
279 | Span::Link { children, .. }
280 | Span::Colored { children, .. }
281 | Span::Heading { children, .. }
282 | Span::Indent { children, .. } => collect_images(children, images),
283 _ => {}
284 }
285 }
286}
287
288/// Image urls that a table draws inside its cells.
289pub fn table_images(block: &Block) -> Vec<&str> {
290 match block {
291 Block::Table { rows, .. } => rows
292 .iter()
293 .flatten()
294 .flat_map(|cell| cell.images.iter().map(String::as_str))
295 .collect(),
296 _ => Vec::new(),
297 }
298}
299
300impl Block {
301 pub fn markdown(&self) -> Option<String> {
302 let join = |blocks: &[Block]| {
303 blocks
304 .iter()
305 .filter_map(Block::markdown)
306 .collect::<Vec<_>>()
307 .join("\n")
308 };
309 match self {
310 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.plain_text()),
311 Block::Code { code, .. } => Some(format!("```\n{code}\n```")),
312 Block::CodeLine { code } => Some(format!("`{code}`")),
313 Block::List {
314 ordered,
315 start,
316 items,
317 } => Some(
318 items
319 .iter()
320 .enumerate()
321 .map(|(offset, item)| match ordered {
322 true => format!("{}. {}", *start as usize + offset, join(item)),
323 false => format!("- {}", join(item)),
324 })
325 .collect::<Vec<_>>()
326 .join("\n"),
327 ),
328 Block::Table { rows, .. } => Some(
329 rows.iter()
330 .map(|row| {
331 row.iter()
332 .map(|cell| cell.inline.plain_text())
333 .collect::<Vec<_>>()
334 .join(" | ")
335 })
336 .collect::<Vec<_>>()
337 .join("\n"),
338 ),
339 Block::Quote(children) | Block::Indent { children, .. } => Some(join(children)),
340 Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,
341 }
342 }
343
344 pub fn first_line(&self) -> Option<String> {
345 match self {
346 Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.plain_text()),
347 Block::Code { code, .. } | Block::CodeLine { code } => Some(code.clone()),
348 Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line),
349 Block::Table { rows, .. } => Some(rows.first()?.first()?.inline.plain_text()),
350 Block::Quote(children) | Block::Indent { children, .. } => {
351 children.iter().find_map(Block::first_line)
352 }
353 Block::Reply { .. } | Block::Rule | Block::Image { .. } => None,
354 }
355 }
356
357 pub fn last_inline_mut(&mut self) -> Option<&mut Inline> {
358 match self {
359 Block::Paragraph(inline) => Some(inline),
360 Block::List { items, .. } => items.last_mut()?.last_mut()?.last_inline_mut(),
361 _ => None,
362 }
363 }
364}
365
366fn unlink(blocks: &mut [Block]) {
367 for block in blocks {
368 match block {
369 Block::Paragraph(inline) | Block::Heading { inline, .. } => {
370 for segment in &mut inline.segments {
371 segment.link = None;
372 segment.style.link = false;
373 }
374 }
375 Block::Reply { children, .. }
376 | Block::Quote(children)
377 | Block::Indent { children, .. } => unlink(children),
378 Block::List { items, .. } => items.iter_mut().for_each(|item| unlink(item)),
379 _ => {}
380 }
381 }
382}
383
384pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
385 blocks
386 .into_iter()
387 .filter_map(|block| match block {
388 Block::Paragraph(inline) => {
389 let stripped = inline.without(IMAGE_PLACEHOLDER);
390 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
391 }
392 Block::Reply {
393 message_id,
394 children,
395 } => {
396 let children = strip_image_placeholders(children);
397 (!children.is_empty()).then_some(Block::Reply {
398 message_id,
399 children,
400 })
401 }
402 Block::Quote(children) => {
403 let children = strip_image_placeholders(children);
404 (!children.is_empty()).then_some(Block::Quote(children))
405 }
406 Block::Indent { level, children } => {
407 let children = strip_image_placeholders(children);
408 (!children.is_empty()).then_some(Block::Indent { level, children })
409 }
410 Block::List {
411 ordered,
412 start,
413 items,
414 } => {
415 let items: Vec<Vec<Block>> = items
416 .into_iter()
417 .map(strip_image_placeholders)
418 .filter(|item| !item.is_empty())
419 .collect();
420 (!items.is_empty()).then_some(Block::List {
421 ordered,
422 start,
423 items,
424 })
425 }
426 other => Some(other),
427 })
428 .collect()
429}
430
431pub fn emoji_urls(blocks: &[Block]) -> Vec<String> {
432 let mut urls: Vec<String> = Vec::new();
433 let mut add = |inline: &Inline| {
434 for (_, url) in inline.emoji() {
435 if !urls.contains(&url) {
436 urls.push(url);
437 }
438 }
439 };
440 let mut pending: Vec<&Block> = blocks.iter().collect();
441 while let Some(block) = pending.pop() {
442 match block {
443 Block::Paragraph(inline) | Block::Heading { inline, .. } => add(inline),
444 Block::Table { rows, .. } => rows.iter().flatten().for_each(|cell| add(&cell.inline)),
445 Block::Reply { children, .. } | Block::Quote(children) | Block::Indent { children, .. } => {
446 pending.extend(children)
447 }
448 Block::List { items, .. } => pending.extend(items.iter().flatten()),
449 Block::Code { .. } | Block::CodeLine { .. } | Block::Rule | Block::Image { .. } => {}
450 }
451 }
452 urls
453}
454
455pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
456 layout_blocks_with(spans, true, true)
457}
458
459pub fn layout_card_blocks(spans: &[Span]) -> Vec<Block> {
460 layout_blocks_with(spans, true, false)
461}
462
463fn layout_blocks_with(spans: &[Span], split_images: bool, frame_code: bool) -> Vec<Block> {
464 let mut blocks = Vec::new();
465 let mut current = Inline::default();
466 for span in spans {
467 match span {
468 Span::CodeBlock { language, code } => {
469 flush(&mut current, &mut blocks, frame_code);
470 blocks.push(Block::Code {
471 language: language.clone(),
472 code: code.trim_end_matches('\n').to_owned(),
473 });
474 }
475 Span::Quote {
476 message_id,
477 children,
478 } => {
479 flush(&mut current, &mut blocks, frame_code);
480 let mut inner = layout_blocks_with(children, false, frame_code);
481 unlink(&mut inner);
482 if !inner.is_empty() {
483 blocks.push(Block::Reply {
484 message_id: message_id.clone(),
485 children: inner,
486 });
487 }
488 }
489 Span::BlockQuote(children) => {
490 flush(&mut current, &mut blocks, frame_code);
491 let inner = layout_blocks_with(children, false, frame_code);
492 if !inner.is_empty() {
493 blocks.push(Block::Quote(inner));
494 }
495 }
496 Span::Indent { level, children } => {
497 flush(&mut current, &mut blocks, frame_code);
498 let inner = layout_blocks_with(children, split_images, frame_code);
499 if !inner.is_empty() {
500 blocks.push(Block::Indent {
501 level: *level,
502 children: inner,
503 });
504 }
505 }
506 Span::List {
507 ordered,
508 start,
509 items,
510 } => {
511 flush(&mut current, &mut blocks, frame_code);
512 let items: Vec<Vec<Block>> = items
513 .iter()
514 // The bullet shares the item's line, so code alone in an item is
515 // not "alone on its line": it stays an inline chip instead of
516 // becoming a framed code line.
517 .map(|item| layout_blocks_with(item, false, false))
518 .filter(|item| !item.is_empty())
519 .collect();
520 if !items.is_empty() {
521 blocks.push(Block::List {
522 ordered: *ordered,
523 start: *start,
524 items,
525 });
526 }
527 }
528 Span::Table { header, rows } => {
529 flush(&mut current, &mut blocks, frame_code);
530 let rows: Vec<Vec<TableCell>> = rows
531 .iter()
532 .map(|row| row.iter().map(|cell| TableCell::of(cell)).collect())
533 .collect();
534 if !rows.is_empty() {
535 blocks.push(Block::Table {
536 header: *header,
537 rows,
538 });
539 }
540 }
541 Span::Heading { level, children } => {
542 flush(&mut current, &mut blocks, frame_code);
543 let inline = inline_of(children);
544 if !inline.is_blank() {
545 blocks.push(Block::Heading {
546 level: *level,
547 inline,
548 });
549 }
550 }
551 Span::Rule => {
552 flush(&mut current, &mut blocks, frame_code);
553 blocks.push(Block::Rule);
554 }
555 Span::Image { hosted_content_url } if split_images => {
556 flush(&mut current, &mut blocks, frame_code);
557 blocks.push(Block::Image {
558 url: hosted_content_url.clone(),
559 });
560 }
561 other => append_inline(
562 std::slice::from_ref(other),
563 StyleFlags::default(),
564 None,
565 &mut current,
566 ),
567 }
568 }
569 flush(&mut current, &mut blocks, frame_code);
570 blocks
571}
572
573fn inline_of(spans: &[Span]) -> Inline {
574 let mut inline = Inline::default();
575 append_inline(spans, StyleFlags::default(), None, &mut inline);
576 inline.trim_end();
577 pad_code(inline)
578}
579
580fn trimmed(mut inline: Inline) -> Inline {
581 inline.trim_end();
582 let leading = inline.text.len() - inline.text.trim_start().len();
583 if leading > 0 {
584 inline.text.drain(..leading);
585 inline.segments.retain_mut(|segment| {
586 segment.range.start = segment.range.start.saturating_sub(leading);
587 segment.range.end = segment.range.end.saturating_sub(leading);
588 segment.range.start < segment.range.end
589 });
590 }
591 inline
592}
593
594fn flush(current: &mut Inline, blocks: &mut Vec<Block>, frame_code: bool) {
595 let inline = trimmed(std::mem::take(current));
596 if inline.is_blank() {
597 return;
598 }
599 if !frame_code {
600 blocks.push(Block::Paragraph(pad_code(inline)));
601 return;
602 }
603 for piece in split_code_lines(inline) {
604 match piece {
605 LinePiece::Text(text) => {
606 let text = trimmed(text);
607 if !text.is_blank() {
608 blocks.push(Block::Paragraph(pad_code(text)));
609 }
610 }
611 LinePiece::Code(code) => blocks.push(Block::CodeLine { code }),
612 }
613 }
614}
615
616fn is_own_line(text: &str, range: &Range<usize>) -> bool {
617 let before = &text[..range.start];
618 let after = &text[range.end..];
619 let line_start = before.rfind('\n').map_or(0, |position| position + 1);
620 let line_end = after.find('\n').unwrap_or(after.len());
621 before[line_start..].trim().is_empty() && after[..line_end].trim().is_empty()
622}
623
624enum LinePiece {
625 Text(Inline),
626 Code(String),
627}
628
629fn split_code_lines(inline: Inline) -> Vec<LinePiece> {
630 let mut pieces = Vec::new();
631 let mut cursor = 0;
632 for segment in &inline.segments {
633 let code = &inline.text[segment.range.clone()];
634 if !segment.style.code
635 || segment.link.is_some()
636 || code.trim().is_empty()
637 || !is_own_line(&inline.text, &segment.range)
638 {
639 continue;
640 }
641 pieces.push(LinePiece::Text(inline.slice(cursor..segment.range.start)));
642 pieces.push(LinePiece::Code(code.trim().to_owned()));
643 cursor = segment.range.end;
644 }
645 pieces.push(LinePiece::Text(inline.slice(cursor..inline.text.len())));
646 pieces
647}
648
649fn pad_code(inline: Inline) -> Inline {
650 if !inline.segments.iter().any(|segment| segment.style.code) {
651 return inline;
652 }
653 let mut padded = Inline::default();
654 for (index, segment) in inline.segments.iter().enumerate() {
655 let text = &inline.text[segment.range.clone()];
656 let touches = |neighbour: Option<&Segment>| {
657 neighbour.is_some_and(|neighbour| !neighbour.style.code && !neighbour.range.is_empty())
658 };
659 let previous = index
660 .checked_sub(1)
661 .and_then(|previous| inline.segments.get(previous));
662 if segment.style.code && touches(previous) {
663 padded.push(CODE_PADDING, StyleFlags::default(), None);
664 }
665 padded.push(text, segment.style, segment.link.as_deref());
666 if segment.style.code && touches(inline.segments.get(index + 1)) {
667 padded.push(CODE_PADDING, StyleFlags::default(), None);
668 }
669 }
670 padded
671}
672
673fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
674 for span in spans {
675 match span {
676 Span::Text(text) if link.is_none() && !style.code => {
677 push_linkified(text, style, out);
678 }
679 Span::Text(text) => out.push(text, style, link),
680 Span::Bold(children) => append_inline(
681 children,
682 StyleFlags {
683 bold: true,
684 ..style
685 },
686 link,
687 out,
688 ),
689 Span::Italic(children) => append_inline(
690 children,
691 StyleFlags {
692 italic: true,
693 ..style
694 },
695 link,
696 out,
697 ),
698 Span::Strike(children) => append_inline(
699 children,
700 StyleFlags {
701 strike: true,
702 ..style
703 },
704 link,
705 out,
706 ),
707 Span::Underline(children) => append_inline(
708 children,
709 StyleFlags {
710 underline: true,
711 ..style
712 },
713 link,
714 out,
715 ),
716 Span::Superscript(children) => append_inline(
717 children,
718 StyleFlags {
719 script: Some(Script::Super),
720 ..style
721 },
722 link,
723 out,
724 ),
725 Span::Subscript(children) => append_inline(
726 children,
727 StyleFlags {
728 script: Some(Script::Sub),
729 ..style
730 },
731 link,
732 out,
733 ),
734 Span::Sized(FontSize::Hidden, _) => {}
735 Span::Sized(size, children) => append_inline(
736 children,
737 StyleFlags {
738 size: Some(*size),
739 ..style
740 },
741 link,
742 out,
743 ),
744 Span::Colored {
745 color,
746 background,
747 children,
748 } => append_inline(
749 children,
750 StyleFlags {
751 color: color.or(style.color),
752 background: background.or(style.background),
753 ..style
754 },
755 link,
756 out,
757 ),
758 Span::Heading { children, .. } => {
759 append_inline(
760 children,
761 StyleFlags {
762 bold: true,
763 ..style
764 },
765 link,
766 out,
767 );
768 out.push("\n", style, link);
769 }
770 Span::Code(text) => out.push(
771 text,
772 StyleFlags {
773 code: true,
774 ..style
775 },
776 link,
777 ),
778 Span::CodeBlock { code, .. } => out.push(
779 code.trim_end_matches('\n'),
780 StyleFlags {
781 code: true,
782 ..style
783 },
784 link,
785 ),
786 Span::Link { url, children } => append_inline(
787 children,
788 StyleFlags {
789 link: true,
790 ..style
791 },
792 Some(url.as_str()),
793 out,
794 ),
795 Span::Mention { name, id } => {
796 let label = format!("@{}", name.trim_start_matches('@'));
797 let profile_link = id
798 .as_deref()
799 .filter(|id| id.starts_with(PROFILE_LINK_PREFIX));
800 out.push(
801 &label,
802 StyleFlags {
803 mention: true,
804 ..style
805 },
806 profile_link.or(link),
807 );
808 }
809 Span::LineBreak | Span::Rule => out.push("\n", style, link),
810 Span::Quote { children, .. }
811 | Span::BlockQuote(children)
812 | Span::Indent { children, .. } => {
813 append_inline(children, style, link, out);
814 out.push("\n", style, link);
815 }
816 Span::List { items, .. } => {
817 for item in items {
818 append_inline(item, style, link, out);
819 out.push("\n", style, link);
820 }
821 }
822 Span::Table { rows, .. } => {
823 for row in rows {
824 for (index, cell) in row.iter().enumerate() {
825 if index > 0 {
826 out.push(" ", style, link);
827 }
828 append_inline(cell, style, link, out);
829 }
830 out.push("\n", style, link);
831 }
832 }
833 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
834 Span::CustomEmoji { url, .. } => out.push_part(EMOJI_PLACEHOLDER, style, link, Some(url)),
835 }
836 }
837}
838
839fn push_linkified(text: &str, style: StyleFlags, out: &mut Inline) {
840 let mut rest = text;
841 while let Some((start, end)) = find_url(rest) {
842 out.push(&rest[..start], style, None);
843 let visible = &rest[start..end];
844 let target = if visible.starts_with("www.") {
845 format!("https://{visible}")
846 } else {
847 visible.to_owned()
848 };
849 out.push(
850 visible,
851 StyleFlags {
852 link: true,
853 ..style
854 },
855 Some(&target),
856 );
857 rest = &rest[end..];
858 }
859 out.push(rest, style, None);
860}
861
862fn find_url(text: &str) -> Option<(usize, usize)> {
863 let mut previous_is_boundary = true;
864 for (start, character) in text.char_indices() {
865 if previous_is_boundary
866 && let Some(prefix) = URL_PREFIXES
867 .iter()
868 .find(|prefix| text[start..].starts_with(**prefix))
869 {
870 let length = text[start..]
871 .find(char::is_whitespace)
872 .unwrap_or(text.len() - start);
873 let end = start + trimmed_url_length(&text[start..start + length]);
874 if end > start + prefix.len() {
875 return Some((start, end));
876 }
877 }
878 previous_is_boundary = !character.is_alphanumeric();
879 }
880 None
881}
882
883fn trimmed_url_length(candidate: &str) -> usize {
884 let mut url = candidate;
885 while let Some(last) = url.chars().next_back() {
886 let opener = match last {
887 ')' => Some('('),
888 ']' => Some('['),
889 '}' => Some('{'),
890 _ => None,
891 };
892 let trimmable = match opener {
893 Some(opener) => url.matches(last).count() > url.matches(opener).count(),
894 None => TRAILING_PUNCTUATION.contains(last),
895 };
896 if !trimmable {
897 break;
898 }
899 url = &url[..url.len() - last.len_utf8()];
900 }
901 url.len()
902}
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907
908 fn text(value: &str) -> Span {
909 Span::Text(value.to_owned())
910 }
911
912 #[test]
913 fn org_emoji_sit_in_the_text_and_stay_out_of_copied_text() {
914 let emoji = |url: &str| Span::CustomEmoji {
915 name: "cat".into(),
916 url: url.into(),
917 };
918 let blocks = layout_blocks(&[text("hi "), emoji("a"), emoji("a"), text(" ok")]);
919 let Block::Paragraph(inline) = &blocks[0] else {
920 panic!("paragraph expected");
921 };
922 assert_eq!(inline.emoji().len(), 2);
923 assert_eq!(inline.plain_text(), "hi ok");
924 assert_eq!(emoji_urls(&blocks), vec!["a".to_owned()]);
925 let trailing = layout_blocks(&[text("bye "), emoji("b")]);
926 let Block::Paragraph(inline) = &trailing[0] else {
927 panic!("paragraph expected");
928 };
929 assert_eq!(inline.emoji().len(), 1);
930 }
931
932 #[test]
933 fn plain_text_is_one_paragraph() {
934 let blocks = layout_blocks(&[text("hello ")]);
935 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("hello"))]);
936 }
937
938 #[test]
939 fn bold_and_italic_nest_into_flags() {
940 let blocks = layout_blocks(&[
941 text("a "),
942 Span::Bold(vec![Span::Italic(vec![text("b")])]),
943 text(" c"),
944 ]);
945 let Block::Paragraph(inline) = &blocks[0] else {
946 panic!("paragraph expected")
947 };
948 assert_eq!(inline.text, "a b c");
949 assert_eq!(inline.segments.len(), 3);
950 assert!(inline.segments[1].style.bold && inline.segments[1].style.italic);
951 assert_eq!(inline.segments[1].range, 2..3);
952 }
953
954 #[test]
955 fn link_keeps_url_and_range() {
956 let blocks = layout_blocks(&[
957 text("see "),
958 Span::Link {
959 url: "https://example.com".into(),
960 children: vec![text("here")],
961 },
962 ]);
963 let Block::Paragraph(inline) = &blocks[0] else {
964 panic!("paragraph expected")
965 };
966 assert_eq!(
967 inline.links(),
968 vec![(4..8, "https://example.com".to_owned())]
969 );
970 }
971
972 fn paragraph_inline(spans: &[Span]) -> Inline {
973 let Block::Paragraph(inline) = layout_blocks(spans).remove(0) else {
974 panic!("paragraph expected")
975 };
976 inline
977 }
978
979 #[test]
980 fn plain_url_at_end_becomes_link() {
981 let inline = paragraph_inline(&[text("see https://example.com/a")]);
982 assert_eq!(
983 inline.links(),
984 vec![(4..25, "https://example.com/a".to_owned())]
985 );
986 assert!(inline.segments[1].style.link);
987 }
988
989 #[test]
990 fn trailing_period_stays_outside_url() {
991 let inline = paragraph_inline(&[text("go to http://example.com. Then")]);
992 assert_eq!(
993 inline.links(),
994 vec![(6..24, "http://example.com".to_owned())]
995 );
996 }
997
998 #[test]
999 fn balanced_parentheses_stay_in_url() {
1000 let inline = paragraph_inline(&[text("https://example.com/Rust_(language)")]);
1001 assert_eq!(inline.links()[0].1, "https://example.com/Rust_(language)");
1002 let wrapped = paragraph_inline(&[text("(see https://example.com)")]);
1003 assert_eq!(wrapped.links()[0].1, "https://example.com");
1004 }
1005
1006 #[test]
1007 fn www_url_gets_https_target() {
1008 let inline = paragraph_inline(&[text("www.example.com!")]);
1009 assert_eq!(inline.text, "www.example.com!");
1010 assert_eq!(
1011 inline.links(),
1012 vec![(0..15, "https://www.example.com".to_owned())]
1013 );
1014 }
1015
1016 #[test]
1017 fn text_without_url_has_no_links() {
1018 let inline = paragraph_inline(&[text("no link, just www. and https:// here")]);
1019 assert!(inline.links().is_empty());
1020 }
1021
1022 #[test]
1023 fn url_inside_link_stays_one_link() {
1024 let inline = paragraph_inline(&[Span::Link {
1025 url: "https://target.example".into(),
1026 children: vec![text("https://shown.example")],
1027 }]);
1028 assert_eq!(
1029 inline.links(),
1030 vec![(0..21, "https://target.example".to_owned())]
1031 );
1032 }
1033
1034 #[test]
1035 fn mention_gets_an_at_sign_once() {
1036 let blocks = layout_blocks(&[
1037 Span::Mention {
1038 name: "Ada".into(),
1039 id: None,
1040 },
1041 text(" "),
1042 Span::Mention {
1043 name: "@Bob".into(),
1044 id: None,
1045 },
1046 ]);
1047 let Block::Paragraph(inline) = &blocks[0] else {
1048 panic!("paragraph expected")
1049 };
1050 assert_eq!(inline.text, "@Ada @Bob");
1051 assert!(inline.segments[0].style.mention);
1052 }
1053
1054 #[test]
1055 fn code_block_splits_paragraphs() {
1056 let blocks = layout_blocks(&[
1057 text("before"),
1058 Span::CodeBlock {
1059 language: None,
1060 code: "let x = 1;\n".into(),
1061 },
1062 text("after"),
1063 ]);
1064 assert_eq!(
1065 blocks,
1066 vec![
1067 Block::Paragraph(Inline::plain("before")),
1068 Block::Code {
1069 language: None,
1070 code: "let x = 1;".into()
1071 },
1072 Block::Paragraph(Inline::plain("after")),
1073 ]
1074 );
1075 }
1076
1077 #[test]
1078 fn lists_nest_and_quotes_are_blocks() {
1079 let blocks = layout_blocks(&[
1080 Span::List {
1081 ordered: true,
1082 start: 3,
1083 items: vec![
1084 vec![text("one")],
1085 vec![
1086 text("two"),
1087 Span::List {
1088 ordered: false,
1089 start: 1,
1090 items: vec![vec![text("inner")]],
1091 },
1092 ],
1093 ],
1094 },
1095 Span::Quote { message_id: Some("m1".into()), children: vec![text("quoted")] },
1096 ]);
1097 assert_eq!(
1098 blocks,
1099 vec![
1100 Block::List {
1101 ordered: true,
1102 start: 3,
1103 items: vec![
1104 vec![Block::Paragraph(Inline::plain("one"))],
1105 vec![
1106 Block::Paragraph(Inline::plain("two")),
1107 Block::List {
1108 ordered: false,
1109 start: 1,
1110 items: vec![vec![Block::Paragraph(Inline::plain("inner"))]],
1111 },
1112 ],
1113 ],
1114 },
1115 Block::Reply {
1116 message_id: Some("m1".into()),
1117 children: vec![Block::Paragraph(Inline::plain("quoted"))]
1118 },
1119 ]
1120 );
1121 }
1122
1123 fn cell(text: &str) -> TableCell {
1124 TableCell {
1125 inline: Inline::plain(text),
1126 images: Vec::new(),
1127 }
1128 }
1129
1130 #[test]
1131 fn an_image_in_a_cell_stays_in_the_cell() {
1132 let image = Span::Image {
1133 hosted_content_url: "https://img/1".into(),
1134 };
1135 let blocks = layout_blocks(&[Span::Table {
1136 header: false,
1137 rows: vec![vec![vec![image], vec![text("words")]]],
1138 }]);
1139 let [Block::Table { rows, .. }] = blocks.as_slice() else {
1140 panic!("one table: {blocks:?}");
1141 };
1142 assert_eq!(rows[0][0].images, ["https://img/1"]);
1143 assert!(rows[0][0].inline.is_blank());
1144 assert_eq!(rows[0][1], cell("words"));
1145 assert_eq!(table_images(&blocks[0]), ["https://img/1"]);
1146 }
1147
1148 #[test]
1149 fn heading_rule_and_table_are_blocks() {
1150 let blocks = layout_blocks(&[
1151 Span::Heading {
1152 level: 2,
1153 children: vec![text("Title")],
1154 },
1155 Span::Rule,
1156 Span::Table {
1157 header: true,
1158 rows: vec![vec![vec![text("a")], vec![text("b")]]],
1159 },
1160 ]);
1161 assert_eq!(
1162 blocks,
1163 vec![
1164 Block::Heading {
1165 level: 2,
1166 inline: Inline::plain("Title")
1167 },
1168 Block::Rule,
1169 Block::Table {
1170 header: true,
1171 rows: vec![vec![cell("a"), cell("b")]],
1172 },
1173 ]
1174 );
1175 }
1176
1177 #[test]
1178 fn script_and_size_become_flags_with_a_font_scale() {
1179 let inline = paragraph_inline(&[
1180 Span::Superscript(vec![text("2")]),
1181 Span::Sized(FontSize::Large, vec![text("big")]),
1182 Span::Sized(FontSize::Small, vec![Span::Subscript(vec![text("s")])]),
1183 Span::Sized(FontSize::Pixels(21), vec![text("p")]),
1184 Span::Sized(FontSize::Hidden, vec![text("secret")]),
1185 ]);
1186 let styles: Vec<StyleFlags> = inline
1187 .segments
1188 .iter()
1189 .map(|segment| segment.style)
1190 .collect();
1191 assert_eq!(inline.text, "2bigsp");
1192 assert_eq!(styles[0].script, Some(Script::Super));
1193 assert_eq!(styles[0].font_scale(), 0.75);
1194 assert_eq!(styles[1].font_scale(), 24. / 14.);
1195 assert_eq!(styles[2].script, Some(Script::Sub));
1196 assert_eq!(styles[2].font_scale(), 9. / 14. * 0.75);
1197 assert_eq!(styles[3].font_scale(), 1.5);
1198 }
1199
1200 #[test]
1201 fn strike_underline_and_color_become_flags() {
1202 let inline = paragraph_inline(&[
1203 Span::Strike(vec![text("old")]),
1204 Span::Underline(vec![text("u")]),
1205 Span::Colored {
1206 color: Some(0xff0000),
1207 background: Some(0xffff00),
1208 children: vec![text("c")],
1209 },
1210 ]);
1211 assert!(inline.segments[0].style.strike);
1212 assert!(inline.segments[1].style.underline);
1213 assert_eq!(inline.segments[2].style.color, Some(0xff0000));
1214 assert_eq!(inline.segments[2].style.background, Some(0xffff00));
1215 }
1216
1217 #[test]
1218 fn code_alone_on_its_line_is_one_framed_block() {
1219 let blocks = layout_blocks(&[
1220 text("error:"),
1221 Span::LineBreak,
1222 Span::Code("a long line".into()),
1223 ]);
1224 assert_eq!(
1225 blocks,
1226 vec![
1227 Block::Paragraph(Inline::plain("error:")),
1228 Block::CodeLine {
1229 code: "a long line".into()
1230 },
1231 ]
1232 );
1233 assert!(matches!(
1234 layout_card_blocks(&[Span::Code("mono".into())]).as_slice(),
1235 [Block::Paragraph(_)]
1236 ));
1237 }
1238
1239 #[test]
1240 fn code_alone_in_a_list_item_stays_inline() {
1241 let blocks = layout_blocks(&[Span::List {
1242 ordered: false,
1243 start: 1,
1244 items: vec![vec![Span::Code("mono".into())]],
1245 }]);
1246 let [Block::List { items, .. }] = blocks.as_slice() else {
1247 panic!("{blocks:?}");
1248 };
1249 assert!(matches!(items[0].as_slice(), [Block::Paragraph(_)]));
1250 }
1251
1252 #[test]
1253 fn inline_code_gets_room_next_to_text() {
1254 let inline = paragraph_inline(&[
1255 text("run "),
1256 Span::Code("x".into()),
1257 text(". "),
1258 Span::Code("y".into()),
1259 ]);
1260 assert_eq!(inline.text, "run \u{2004}x\u{2004}. \u{2004}y");
1261 assert_eq!(inline.plain_text(), "run x. y");
1262 }
1263
1264 fn image(url: &str) -> Span {
1265 Span::Image {
1266 hosted_content_url: url.into(),
1267 }
1268 }
1269
1270 #[test]
1271 fn top_level_image_is_its_own_block() {
1272 assert_eq!(
1273 layout_blocks(&[image("u")]),
1274 vec![Block::Image { url: "u".into() }]
1275 );
1276 }
1277
1278 #[test]
1279 fn image_splits_the_paragraph_at_its_position() {
1280 let blocks = layout_blocks(&[text("a "), image("u"), text(" b")]);
1281 assert_eq!(
1282 blocks,
1283 vec![
1284 Block::Paragraph(Inline::plain("a")),
1285 Block::Image { url: "u".into() },
1286 Block::Paragraph(Inline::plain("b")),
1287 ]
1288 );
1289 }
1290
1291 #[test]
1292 fn image_inside_a_list_keeps_the_placeholder() {
1293 let blocks = layout_blocks(&[Span::List {
1294 ordered: false,
1295 start: 1,
1296 items: vec![vec![text("x "), image("u")]],
1297 }]);
1298 assert_eq!(
1299 blocks,
1300 vec![Block::List {
1301 ordered: false,
1302 start: 1,
1303 items: vec![vec![Block::Paragraph(Inline::plain("x [image]"))]],
1304 }]
1305 );
1306 }
1307
1308 #[test]
1309 fn image_inside_a_quote_keeps_the_placeholder() {
1310 let blocks = layout_blocks(&[Span::BlockQuote(vec![image("u")])]);
1311 assert_eq!(
1312 blocks,
1313 vec![Block::Quote(vec![Block::Paragraph(Inline::plain(
1314 IMAGE_PLACEHOLDER
1315 ))])]
1316 );
1317 }
1318
1319 #[test]
1320 fn image_blocks_have_no_text() {
1321 let block = Block::Image { url: "u".into() };
1322 assert_eq!(block.markdown(), None);
1323 assert_eq!(block.first_line(), None);
1324 }
1325
1326 #[test]
1327 fn stripping_placeholders_keeps_the_text_around_them() {
1328 let blocks = layout_blocks(&[Span::List {
1329 ordered: false,
1330 start: 1,
1331 items: vec![vec![
1332 text("look "),
1333 Span::Bold(vec![text("here")]),
1334 Span::LineBreak,
1335 image("u"),
1336 ]],
1337 }]);
1338 let stripped = strip_image_placeholders(blocks);
1339 let Block::List { items, .. } = &stripped[0] else {
1340 panic!("list expected")
1341 };
1342 let Block::Paragraph(inline) = &items[0][0] else {
1343 panic!("paragraph expected")
1344 };
1345 assert_eq!(inline.text, "look here");
1346 assert!(inline.segments.last().unwrap().style.bold);
1347 let only_image = vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))];
1348 assert!(strip_image_placeholders(only_image).is_empty());
1349 }
1350
1351 #[test]
1352 fn stripping_placeholders_keeps_image_blocks() {
1353 let blocks = vec![Block::Image { url: "u".into() }];
1354 assert_eq!(strip_image_placeholders(blocks.clone()), blocks);
1355 }
1356
1357 #[test]
1358 fn line_break_stays_inside_paragraph() {
1359 let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);
1360 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("a\nb"))]);
1361 }
1362
1363 #[test]
1364 fn empty_input_has_no_blocks() {
1365 assert!(layout_blocks(&[]).is_empty());
1366 assert!(layout_blocks(&[Span::LineBreak, text(" ")]).is_empty());
1367 }
1368}