BlueGit

ict rusty-teams

Files

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

blocks.rs

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