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