BlueGit

ict rusty-teams

Files

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

blocks.rs

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