BlueGit

ict rusty-teams

Files

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

blocks.rs

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