BlueGit

ict rusty-teams

Files

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

blocks.rs

blocks.rs 16.1 KiB Download Raw
1use std::ops::Range;
2
3use teams_core::Span;
4
5pub const IMAGE_PLACEHOLDER: &str = "[image]";
6const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
7const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
8
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub struct StyleFlags {
11 pub bold: bool,
12 pub italic: bool,
13 pub code: bool,
14 pub mention: bool,
15 pub link: bool,
16}
17
18impl StyleFlags {
19 pub fn is_plain(&self) -> bool {
20 *self == StyleFlags::default()
21 }
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Segment {
26 pub range: Range<usize>,
27 pub style: StyleFlags,
28 pub link: Option<String>,
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct Inline {
33 pub text: String,
34 pub segments: Vec<Segment>,
35}
36
37impl Inline {
38 pub fn plain(text: &str) -> Self {
39 let mut inline = Inline::default();
40 inline.push(text, StyleFlags::default(), None);
41 inline
42 }
43
44 fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) {
45 if text.is_empty() {
46 return;
47 }
48 let start = self.text.len();
49 self.text.push_str(text);
50 let end = self.text.len();
51 if let Some(last) = self.segments.last_mut()
52 && last.style == style
53 && last.link.as_deref() == link
54 && last.range.end == start
55 {
56 last.range.end = end;
57 return;
58 }
59 self.segments.push(Segment {
60 range: start..end,
61 style,
62 link: link.map(str::to_owned),
63 });
64 }
65
66 pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
67 let mut padded = self.clone();
68 padded.push(
69 &"\u{2007}".repeat(width_in_spaces),
70 StyleFlags::default(),
71 None,
72 );
73 padded
74 }
75
76 pub fn is_blank(&self) -> bool {
77 self.text.trim().is_empty()
78 }
79
80 fn trim_end(&mut self) {
81 let trimmed = self.text.trim_end().len();
82 self.text.truncate(trimmed);
83 self.segments.retain_mut(|segment| {
84 segment.range.end = segment.range.end.min(trimmed);
85 segment.range.start < segment.range.end
86 });
87 }
88
89 fn without(&self, needle: &str) -> Inline {
90 let mut stripped = Inline::default();
91 for segment in &self.segments {
92 let text = self.text[segment.range.clone()].replace(needle, "");
93 stripped.push(&text, segment.style, segment.link.as_deref());
94 }
95 stripped.trim_end();
96 let leading = stripped.text.len() - stripped.text.trim_start().len();
97 if leading > 0 {
98 let mut trimmed = Inline::default();
99 for segment in &stripped.segments {
100 let text = stripped.text[segment.range.clone()].to_owned();
101 let skip = leading.saturating_sub(segment.range.start).min(text.len());
102 trimmed.push(&text[skip..], segment.style, segment.link.as_deref());
103 }
104 return trimmed;
105 }
106 stripped
107 }
108
109 pub fn links(&self) -> Vec<(Range<usize>, String)> {
110 self.segments
111 .iter()
112 .filter_map(|segment| Some((segment.range.clone(), segment.link.clone()?)))
113 .collect()
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum Block {
119 Paragraph(Inline),
120 Code(String),
121 Quote(Vec<Block>),
122 ListItem(Inline),
123}
124
125pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> {
126 blocks
127 .into_iter()
128 .filter_map(|block| match block {
129 Block::Paragraph(inline) => {
130 let stripped = inline.without(IMAGE_PLACEHOLDER);
131 (!stripped.is_blank()).then_some(Block::Paragraph(stripped))
132 }
133 Block::Quote(children) => {
134 let children = strip_image_placeholders(children);
135 (!children.is_empty()).then_some(Block::Quote(children))
136 }
137 other => Some(other),
138 })
139 .collect()
140}
141
142pub fn layout_blocks(spans: &[Span]) -> Vec<Block> {
143 let mut blocks = Vec::new();
144 let mut current = Inline::default();
145 for span in spans {
146 match span {
147 Span::CodeBlock { code, .. } => {
148 flush(&mut current, &mut blocks, Block::Paragraph);
149 blocks.push(Block::Code(code.trim_end_matches('\n').to_owned()));
150 }
151 Span::Quote(children) => {
152 flush(&mut current, &mut blocks, Block::Paragraph);
153 let inner = layout_blocks(children);
154 if !inner.is_empty() {
155 blocks.push(Block::Quote(inner));
156 }
157 }
158 Span::ListItem(children) => {
159 flush(&mut current, &mut blocks, Block::Paragraph);
160 let mut item = Inline::default();
161 append_inline(children, StyleFlags::default(), None, &mut item);
162 item.trim_end();
163 blocks.push(Block::ListItem(item));
164 }
165 other => append_inline(
166 std::slice::from_ref(other),
167 StyleFlags::default(),
168 None,
169 &mut current,
170 ),
171 }
172 }
173 flush(&mut current, &mut blocks, Block::Paragraph);
174 blocks
175}
176
177fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) {
178 let mut inline = std::mem::take(current);
179 inline.trim_end();
180 let leading = inline.text.len() - inline.text.trim_start_matches('\n').len();
181 if leading > 0 {
182 inline.text.drain(..leading);
183 inline.segments.retain_mut(|segment| {
184 segment.range.start = segment.range.start.saturating_sub(leading);
185 segment.range.end = segment.range.end.saturating_sub(leading);
186 segment.range.start < segment.range.end
187 });
188 }
189 if !inline.is_blank() {
190 blocks.push(make(inline));
191 }
192}
193
194fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) {
195 for span in spans {
196 match span {
197 Span::Text(text) if link.is_none() && !style.code => {
198 push_linkified(text, style, out);
199 }
200 Span::Text(text) => out.push(text, style, link),
201 Span::Bold(children) => append_inline(
202 children,
203 StyleFlags {
204 bold: true,
205 ..style
206 },
207 link,
208 out,
209 ),
210 Span::Italic(children) => append_inline(
211 children,
212 StyleFlags {
213 italic: true,
214 ..style
215 },
216 link,
217 out,
218 ),
219 Span::Code(text) => out.push(
220 text,
221 StyleFlags {
222 code: true,
223 ..style
224 },
225 link,
226 ),
227 Span::CodeBlock { code, .. } => out.push(
228 code.trim_end_matches('\n'),
229 StyleFlags {
230 code: true,
231 ..style
232 },
233 link,
234 ),
235 Span::Link { url, children } => append_inline(
236 children,
237 StyleFlags {
238 link: true,
239 ..style
240 },
241 Some(url.as_str()),
242 out,
243 ),
244 Span::Mention { name } => {
245 let label = format!("@{}", name.trim_start_matches('@'));
246 out.push(
247 &label,
248 StyleFlags {
249 mention: true,
250 ..style
251 },
252 link,
253 );
254 }
255 Span::LineBreak => out.push("\n", style, link),
256 Span::ListItem(children) | Span::Quote(children) => {
257 append_inline(children, style, link, out);
258 out.push("\n", style, link);
259 }
260 Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link),
261 }
262 }
263}
264
265fn push_linkified(text: &str, style: StyleFlags, out: &mut Inline) {
266 let mut rest = text;
267 while let Some((start, end)) = find_url(rest) {
268 out.push(&rest[..start], style, None);
269 let visible = &rest[start..end];
270 let target = if visible.starts_with("www.") {
271 format!("https://{visible}")
272 } else {
273 visible.to_owned()
274 };
275 out.push(
276 visible,
277 StyleFlags {
278 link: true,
279 ..style
280 },
281 Some(&target),
282 );
283 rest = &rest[end..];
284 }
285 out.push(rest, style, None);
286}
287
288fn find_url(text: &str) -> Option<(usize, usize)> {
289 let mut previous_is_boundary = true;
290 for (start, character) in text.char_indices() {
291 if previous_is_boundary
292 && let Some(prefix) = URL_PREFIXES
293 .iter()
294 .find(|prefix| text[start..].starts_with(**prefix))
295 {
296 let length = text[start..]
297 .find(char::is_whitespace)
298 .unwrap_or(text.len() - start);
299 let end = start + trimmed_url_length(&text[start..start + length]);
300 if end > start + prefix.len() {
301 return Some((start, end));
302 }
303 }
304 previous_is_boundary = !character.is_alphanumeric();
305 }
306 None
307}
308
309fn trimmed_url_length(candidate: &str) -> usize {
310 let mut url = candidate;
311 while let Some(last) = url.chars().next_back() {
312 let opener = match last {
313 ')' => Some('('),
314 ']' => Some('['),
315 '}' => Some('{'),
316 _ => None,
317 };
318 let trimmable = match opener {
319 Some(opener) => url.matches(last).count() > url.matches(opener).count(),
320 None => TRAILING_PUNCTUATION.contains(last),
321 };
322 if !trimmable {
323 break;
324 }
325 url = &url[..url.len() - last.len_utf8()];
326 }
327 url.len()
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333
334 fn text(value: &str) -> Span {
335 Span::Text(value.to_owned())
336 }
337
338 #[test]
339 fn plain_text_is_one_paragraph() {
340 let blocks = layout_blocks(&[text("hello ")]);
341 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("hello"))]);
342 }
343
344 #[test]
345 fn bold_and_italic_nest_into_flags() {
346 let blocks = layout_blocks(&[
347 text("a "),
348 Span::Bold(vec![Span::Italic(vec![text("b")])]),
349 text(" c"),
350 ]);
351 let Block::Paragraph(inline) = &blocks[0] else {
352 panic!("paragraph expected")
353 };
354 assert_eq!(inline.text, "a b c");
355 assert_eq!(inline.segments.len(), 3);
356 assert!(inline.segments[1].style.bold && inline.segments[1].style.italic);
357 assert_eq!(inline.segments[1].range, 2..3);
358 }
359
360 #[test]
361 fn link_keeps_url_and_range() {
362 let blocks = layout_blocks(&[
363 text("see "),
364 Span::Link {
365 url: "https://example.com".into(),
366 children: vec![text("here")],
367 },
368 ]);
369 let Block::Paragraph(inline) = &blocks[0] else {
370 panic!("paragraph expected")
371 };
372 assert_eq!(
373 inline.links(),
374 vec![(4..8, "https://example.com".to_owned())]
375 );
376 }
377
378 fn paragraph_inline(spans: &[Span]) -> Inline {
379 let Block::Paragraph(inline) = layout_blocks(spans).remove(0) else {
380 panic!("paragraph expected")
381 };
382 inline
383 }
384
385 #[test]
386 fn plain_url_at_end_becomes_link() {
387 let inline = paragraph_inline(&[text("see https://example.com/a")]);
388 assert_eq!(
389 inline.links(),
390 vec![(4..25, "https://example.com/a".to_owned())]
391 );
392 assert!(inline.segments[1].style.link);
393 }
394
395 #[test]
396 fn trailing_period_stays_outside_url() {
397 let inline = paragraph_inline(&[text("go to http://example.com. Then")]);
398 assert_eq!(
399 inline.links(),
400 vec![(6..24, "http://example.com".to_owned())]
401 );
402 }
403
404 #[test]
405 fn balanced_parentheses_stay_in_url() {
406 let inline = paragraph_inline(&[text("https://example.com/Rust_(language)")]);
407 assert_eq!(inline.links()[0].1, "https://example.com/Rust_(language)");
408 let wrapped = paragraph_inline(&[text("(see https://example.com)")]);
409 assert_eq!(wrapped.links()[0].1, "https://example.com");
410 }
411
412 #[test]
413 fn www_url_gets_https_target() {
414 let inline = paragraph_inline(&[text("www.example.com!")]);
415 assert_eq!(inline.text, "www.example.com!");
416 assert_eq!(
417 inline.links(),
418 vec![(0..15, "https://www.example.com".to_owned())]
419 );
420 }
421
422 #[test]
423 fn text_without_url_has_no_links() {
424 let inline = paragraph_inline(&[text("no link, just www. and https:// here")]);
425 assert!(inline.links().is_empty());
426 }
427
428 #[test]
429 fn url_inside_link_stays_one_link() {
430 let inline = paragraph_inline(&[Span::Link {
431 url: "https://target.example".into(),
432 children: vec![text("https://shown.example")],
433 }]);
434 assert_eq!(
435 inline.links(),
436 vec![(0..21, "https://target.example".to_owned())]
437 );
438 }
439
440 #[test]
441 fn mention_gets_an_at_sign_once() {
442 let blocks = layout_blocks(&[
443 Span::Mention { name: "Ada".into() },
444 text(" "),
445 Span::Mention {
446 name: "@Bob".into(),
447 },
448 ]);
449 let Block::Paragraph(inline) = &blocks[0] else {
450 panic!("paragraph expected")
451 };
452 assert_eq!(inline.text, "@Ada @Bob");
453 assert!(inline.segments[0].style.mention);
454 }
455
456 #[test]
457 fn code_block_splits_paragraphs() {
458 let blocks = layout_blocks(&[
459 text("before"),
460 Span::CodeBlock {
461 language: None,
462 code: "let x = 1;\n".into(),
463 },
464 text("after"),
465 ]);
466 assert_eq!(
467 blocks,
468 vec![
469 Block::Paragraph(Inline::plain("before")),
470 Block::Code("let x = 1;".into()),
471 Block::Paragraph(Inline::plain("after")),
472 ]
473 );
474 }
475
476 #[test]
477 fn list_items_and_quotes_are_blocks() {
478 let blocks = layout_blocks(&[
479 Span::ListItem(vec![text("one")]),
480 Span::ListItem(vec![text("two")]),
481 Span::Quote(vec![text("quoted")]),
482 ]);
483 assert_eq!(
484 blocks,
485 vec![
486 Block::ListItem(Inline::plain("one")),
487 Block::ListItem(Inline::plain("two")),
488 Block::Quote(vec![Block::Paragraph(Inline::plain("quoted"))]),
489 ]
490 );
491 }
492
493 #[test]
494 fn image_becomes_placeholder() {
495 let blocks = layout_blocks(&[Span::Image {
496 hosted_content_url: "u".into(),
497 }]);
498 assert_eq!(
499 blocks,
500 vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))]
501 );
502 }
503
504 #[test]
505 fn stripping_placeholders_keeps_the_text_around_them() {
506 let blocks = layout_blocks(&[
507 text("look "),
508 Span::Bold(vec![text("here")]),
509 Span::LineBreak,
510 Span::Image {
511 hosted_content_url: "u".into(),
512 },
513 ]);
514 let stripped = strip_image_placeholders(blocks);
515 let Block::Paragraph(inline) = &stripped[0] else {
516 panic!("paragraph expected")
517 };
518 assert_eq!(inline.text, "look here");
519 assert!(inline.segments.last().unwrap().style.bold);
520 let only_image = layout_blocks(&[Span::Image {
521 hosted_content_url: "u".into(),
522 }]);
523 assert!(strip_image_placeholders(only_image).is_empty());
524 }
525
526 #[test]
527 fn line_break_stays_inside_paragraph() {
528 let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]);
529 assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("a\nb"))]);
530 }
531
532 #[test]
533 fn empty_input_has_no_blocks() {
534 assert!(layout_blocks(&[]).is_empty());
535 assert!(layout_blocks(&[Span::LineBreak, text(" ")]).is_empty());
536 }
537}