BlueGit

ict rusty-teams

Files

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

blocks.rs

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