| 1 | use std::ops::Range; |
| 2 | |
| 3 | use teams_core::Span; |
| 4 | |
| 5 | pub const IMAGE_PLACEHOLDER: &str = "[image]"; |
| 6 | pub const CODE_PADDING: &str = "\u{200a}"; |
| 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 | pub strike: bool, |
| 18 | pub underline: bool, |
| 19 | pub color: Option<u32>, |
| 20 | pub background: Option<u32>, |
| 21 | } |
| 22 | |
| 23 | impl StyleFlags { |
| 24 | pub fn is_plain(&self) -> bool { |
| 25 | *self == StyleFlags::default() |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub struct Segment { |
| 31 | pub range: Range<usize>, |
| 32 | pub style: StyleFlags, |
| 33 | pub link: Option<String>, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 37 | pub struct Inline { |
| 38 | pub text: String, |
| 39 | pub segments: Vec<Segment>, |
| 40 | } |
| 41 | |
| 42 | impl Inline { |
| 43 | pub fn plain(text: &str) -> Self { |
| 44 | let mut inline = Inline::default(); |
| 45 | inline.push(text, StyleFlags::default(), None); |
| 46 | inline |
| 47 | } |
| 48 | |
| 49 | fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) { |
| 50 | if text.is_empty() { |
| 51 | return; |
| 52 | } |
| 53 | let start = self.text.len(); |
| 54 | self.text.push_str(text); |
| 55 | let end = self.text.len(); |
| 56 | if let Some(last) = self.segments.last_mut() |
| 57 | && last.style == style |
| 58 | && last.link.as_deref() == link |
| 59 | && last.range.end == start |
| 60 | { |
| 61 | last.range.end = end; |
| 62 | return; |
| 63 | } |
| 64 | self.segments.push(Segment { |
| 65 | range: start..end, |
| 66 | style, |
| 67 | link: link.map(str::to_owned), |
| 68 | }); |
| 69 | } |
| 70 | |
| 71 | pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline { |
| 72 | let mut padded = self.clone(); |
| 73 | padded.push( |
| 74 | &"\u{2007}".repeat(width_in_spaces), |
| 75 | StyleFlags::default(), |
| 76 | None, |
| 77 | ); |
| 78 | padded |
| 79 | } |
| 80 | |
| 81 | pub fn is_blank(&self) -> bool { |
| 82 | self.text.trim().is_empty() |
| 83 | } |
| 84 | |
| 85 | fn trim_end(&mut self) { |
| 86 | let trimmed = self.text.trim_end().len(); |
| 87 | self.text.truncate(trimmed); |
| 88 | self.segments.retain_mut(|segment| { |
| 89 | segment.range.end = segment.range.end.min(trimmed); |
| 90 | segment.range.start < segment.range.end |
| 91 | }); |
| 92 | } |
| 93 | |
| 94 | fn without(&self, needle: &str) -> Inline { |
| 95 | let mut stripped = Inline::default(); |
| 96 | for segment in &self.segments { |
| 97 | let text = self.text[segment.range.clone()].replace(needle, ""); |
| 98 | stripped.push(&text, segment.style, segment.link.as_deref()); |
| 99 | } |
| 100 | stripped.trim_end(); |
| 101 | let leading = stripped.text.len() - stripped.text.trim_start().len(); |
| 102 | if leading > 0 { |
| 103 | let mut trimmed = Inline::default(); |
| 104 | for segment in &stripped.segments { |
| 105 | let text = stripped.text[segment.range.clone()].to_owned(); |
| 106 | let skip = leading.saturating_sub(segment.range.start).min(text.len()); |
| 107 | trimmed.push(&text[skip..], segment.style, segment.link.as_deref()); |
| 108 | } |
| 109 | return trimmed; |
| 110 | } |
| 111 | stripped |
| 112 | } |
| 113 | |
| 114 | pub fn links(&self) -> Vec<(Range<usize>, String)> { |
| 115 | self.segments |
| 116 | .iter() |
| 117 | .filter_map(|segment| Some((segment.range.clone(), segment.link.clone()?))) |
| 118 | .collect() |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 123 | pub enum Block { |
| 124 | Paragraph(Inline), |
| 125 | Heading { |
| 126 | level: u8, |
| 127 | inline: Inline, |
| 128 | }, |
| 129 | Code { |
| 130 | language: Option<String>, |
| 131 | code: String, |
| 132 | }, |
| 133 | Reply(Vec<Block>), |
| 134 | Quote(Vec<Block>), |
| 135 | List { |
| 136 | ordered: bool, |
| 137 | start: u32, |
| 138 | items: Vec<Vec<Block>>, |
| 139 | }, |
| 140 | Table { |
| 141 | header: bool, |
| 142 | rows: Vec<Vec<Inline>>, |
| 143 | }, |
| 144 | Rule, |
| 145 | } |
| 146 | |
| 147 | impl Block { |
| 148 | pub fn markdown(&self) -> Option<String> { |
| 149 | let join = |blocks: &[Block]| { |
| 150 | blocks |
| 151 | .iter() |
| 152 | .filter_map(Block::markdown) |
| 153 | .collect::<Vec<_>>() |
| 154 | .join("\n") |
| 155 | }; |
| 156 | match self { |
| 157 | Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()), |
| 158 | Block::Code { code, .. } => Some(format!("```\n{code}\n```")), |
| 159 | Block::List { |
| 160 | ordered, |
| 161 | start, |
| 162 | items, |
| 163 | } => Some( |
| 164 | items |
| 165 | .iter() |
| 166 | .enumerate() |
| 167 | .map(|(offset, item)| match ordered { |
| 168 | true => format!("{}. {}", *start as usize + offset, join(item)), |
| 169 | false => format!("- {}", join(item)), |
| 170 | }) |
| 171 | .collect::<Vec<_>>() |
| 172 | .join("\n"), |
| 173 | ), |
| 174 | Block::Table { rows, .. } => Some( |
| 175 | rows.iter() |
| 176 | .map(|row| { |
| 177 | row.iter() |
| 178 | .map(|cell| cell.text.as_str()) |
| 179 | .collect::<Vec<_>>() |
| 180 | .join(" | ") |
| 181 | }) |
| 182 | .collect::<Vec<_>>() |
| 183 | .join("\n"), |
| 184 | ), |
| 185 | Block::Quote(children) => Some(join(children)), |
| 186 | Block::Reply(_) | Block::Rule => None, |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | pub fn first_line(&self) -> Option<String> { |
| 191 | match self { |
| 192 | Block::Paragraph(inline) | Block::Heading { inline, .. } => Some(inline.text.clone()), |
| 193 | Block::Code { code, .. } => Some(code.clone()), |
| 194 | Block::List { items, .. } => items.first()?.iter().find_map(Block::first_line), |
| 195 | Block::Table { rows, .. } => Some(rows.first()?.first()?.text.clone()), |
| 196 | Block::Quote(children) => children.iter().find_map(Block::first_line), |
| 197 | Block::Reply(_) | Block::Rule => None, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | pub fn last_inline_mut(&mut self) -> Option<&mut Inline> { |
| 202 | match self { |
| 203 | Block::Paragraph(inline) => Some(inline), |
| 204 | Block::List { items, .. } => items.last_mut()?.last_mut()?.last_inline_mut(), |
| 205 | _ => None, |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> { |
| 211 | blocks |
| 212 | .into_iter() |
| 213 | .filter_map(|block| match block { |
| 214 | Block::Paragraph(inline) => { |
| 215 | let stripped = inline.without(IMAGE_PLACEHOLDER); |
| 216 | (!stripped.is_blank()).then_some(Block::Paragraph(stripped)) |
| 217 | } |
| 218 | Block::Reply(children) => { |
| 219 | let children = strip_image_placeholders(children); |
| 220 | (!children.is_empty()).then_some(Block::Reply(children)) |
| 221 | } |
| 222 | Block::Quote(children) => { |
| 223 | let children = strip_image_placeholders(children); |
| 224 | (!children.is_empty()).then_some(Block::Quote(children)) |
| 225 | } |
| 226 | Block::List { |
| 227 | ordered, |
| 228 | start, |
| 229 | items, |
| 230 | } => { |
| 231 | let items: Vec<Vec<Block>> = items |
| 232 | .into_iter() |
| 233 | .map(strip_image_placeholders) |
| 234 | .filter(|item| !item.is_empty()) |
| 235 | .collect(); |
| 236 | (!items.is_empty()).then_some(Block::List { |
| 237 | ordered, |
| 238 | start, |
| 239 | items, |
| 240 | }) |
| 241 | } |
| 242 | other => Some(other), |
| 243 | }) |
| 244 | .collect() |
| 245 | } |
| 246 | |
| 247 | pub fn layout_blocks(spans: &[Span]) -> Vec<Block> { |
| 248 | let mut blocks = Vec::new(); |
| 249 | let mut current = Inline::default(); |
| 250 | for span in spans { |
| 251 | match span { |
| 252 | Span::CodeBlock { language, code } => { |
| 253 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 254 | blocks.push(Block::Code { |
| 255 | language: language.clone(), |
| 256 | code: code.trim_end_matches('\n').to_owned(), |
| 257 | }); |
| 258 | } |
| 259 | Span::Quote(children) | Span::BlockQuote(children) => { |
| 260 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 261 | let inner = layout_blocks(children); |
| 262 | if !inner.is_empty() { |
| 263 | blocks.push(match span { |
| 264 | Span::Quote(_) => Block::Reply(inner), |
| 265 | _ => Block::Quote(inner), |
| 266 | }); |
| 267 | } |
| 268 | } |
| 269 | Span::List { |
| 270 | ordered, |
| 271 | start, |
| 272 | items, |
| 273 | } => { |
| 274 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 275 | let items: Vec<Vec<Block>> = items |
| 276 | .iter() |
| 277 | .map(|item| layout_blocks(item)) |
| 278 | .filter(|item| !item.is_empty()) |
| 279 | .collect(); |
| 280 | if !items.is_empty() { |
| 281 | blocks.push(Block::List { |
| 282 | ordered: *ordered, |
| 283 | start: *start, |
| 284 | items, |
| 285 | }); |
| 286 | } |
| 287 | } |
| 288 | Span::Table { header, rows } => { |
| 289 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 290 | let rows: Vec<Vec<Inline>> = rows |
| 291 | .iter() |
| 292 | .map(|row| row.iter().map(|cell| inline_of(cell)).collect()) |
| 293 | .collect(); |
| 294 | if !rows.is_empty() { |
| 295 | blocks.push(Block::Table { |
| 296 | header: *header, |
| 297 | rows, |
| 298 | }); |
| 299 | } |
| 300 | } |
| 301 | Span::Heading { level, children } => { |
| 302 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 303 | let inline = inline_of(children); |
| 304 | if !inline.is_blank() { |
| 305 | blocks.push(Block::Heading { |
| 306 | level: *level, |
| 307 | inline, |
| 308 | }); |
| 309 | } |
| 310 | } |
| 311 | Span::Rule => { |
| 312 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 313 | blocks.push(Block::Rule); |
| 314 | } |
| 315 | other => append_inline( |
| 316 | std::slice::from_ref(other), |
| 317 | StyleFlags::default(), |
| 318 | None, |
| 319 | &mut current, |
| 320 | ), |
| 321 | } |
| 322 | } |
| 323 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 324 | blocks |
| 325 | } |
| 326 | |
| 327 | fn inline_of(spans: &[Span]) -> Inline { |
| 328 | let mut inline = Inline::default(); |
| 329 | append_inline(spans, StyleFlags::default(), None, &mut inline); |
| 330 | inline.trim_end(); |
| 331 | pad_code(inline) |
| 332 | } |
| 333 | |
| 334 | fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) { |
| 335 | let mut inline = std::mem::take(current); |
| 336 | inline.trim_end(); |
| 337 | let leading = inline.text.len() - inline.text.trim_start_matches('\n').len(); |
| 338 | if leading > 0 { |
| 339 | inline.text.drain(..leading); |
| 340 | inline.segments.retain_mut(|segment| { |
| 341 | segment.range.start = segment.range.start.saturating_sub(leading); |
| 342 | segment.range.end = segment.range.end.saturating_sub(leading); |
| 343 | segment.range.start < segment.range.end |
| 344 | }); |
| 345 | } |
| 346 | if !inline.is_blank() { |
| 347 | blocks.push(make(pad_code(inline))); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | fn pad_code(inline: Inline) -> Inline { |
| 352 | if !inline.segments.iter().any(|segment| segment.style.code) { |
| 353 | return inline; |
| 354 | } |
| 355 | let mut padded = Inline::default(); |
| 356 | for (index, segment) in inline.segments.iter().enumerate() { |
| 357 | let text = &inline.text[segment.range.clone()]; |
| 358 | let touches = |neighbour: Option<&Segment>, at_end: bool| { |
| 359 | neighbour.is_some_and(|neighbour| { |
| 360 | let neighbour_text = &inline.text[neighbour.range.clone()]; |
| 361 | let edge = if at_end { |
| 362 | neighbour_text.chars().next() |
| 363 | } else { |
| 364 | neighbour_text.chars().next_back() |
| 365 | }; |
| 366 | !neighbour.style.code && edge.is_some_and(|edge| !edge.is_whitespace()) |
| 367 | }) |
| 368 | }; |
| 369 | let previous = index |
| 370 | .checked_sub(1) |
| 371 | .and_then(|previous| inline.segments.get(previous)); |
| 372 | if segment.style.code && touches(previous, false) { |
| 373 | padded.push(CODE_PADDING, StyleFlags::default(), None); |
| 374 | } |
| 375 | padded.push(text, segment.style, segment.link.as_deref()); |
| 376 | if segment.style.code && touches(inline.segments.get(index + 1), true) { |
| 377 | padded.push(CODE_PADDING, StyleFlags::default(), None); |
| 378 | } |
| 379 | } |
| 380 | padded |
| 381 | } |
| 382 | |
| 383 | fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) { |
| 384 | for span in spans { |
| 385 | match span { |
| 386 | Span::Text(text) if link.is_none() && !style.code => { |
| 387 | push_linkified(text, style, out); |
| 388 | } |
| 389 | Span::Text(text) => out.push(text, style, link), |
| 390 | Span::Bold(children) => append_inline( |
| 391 | children, |
| 392 | StyleFlags { |
| 393 | bold: true, |
| 394 | ..style |
| 395 | }, |
| 396 | link, |
| 397 | out, |
| 398 | ), |
| 399 | Span::Italic(children) => append_inline( |
| 400 | children, |
| 401 | StyleFlags { |
| 402 | italic: true, |
| 403 | ..style |
| 404 | }, |
| 405 | link, |
| 406 | out, |
| 407 | ), |
| 408 | Span::Strike(children) => append_inline( |
| 409 | children, |
| 410 | StyleFlags { |
| 411 | strike: true, |
| 412 | ..style |
| 413 | }, |
| 414 | link, |
| 415 | out, |
| 416 | ), |
| 417 | Span::Underline(children) => append_inline( |
| 418 | children, |
| 419 | StyleFlags { |
| 420 | underline: true, |
| 421 | ..style |
| 422 | }, |
| 423 | link, |
| 424 | out, |
| 425 | ), |
| 426 | Span::Colored { |
| 427 | color, |
| 428 | background, |
| 429 | children, |
| 430 | } => append_inline( |
| 431 | children, |
| 432 | StyleFlags { |
| 433 | color: color.or(style.color), |
| 434 | background: background.or(style.background), |
| 435 | ..style |
| 436 | }, |
| 437 | link, |
| 438 | out, |
| 439 | ), |
| 440 | Span::Heading { children, .. } => { |
| 441 | append_inline( |
| 442 | children, |
| 443 | StyleFlags { |
| 444 | bold: true, |
| 445 | ..style |
| 446 | }, |
| 447 | link, |
| 448 | out, |
| 449 | ); |
| 450 | out.push("\n", style, link); |
| 451 | } |
| 452 | Span::Code(text) => out.push( |
| 453 | text, |
| 454 | StyleFlags { |
| 455 | code: true, |
| 456 | ..style |
| 457 | }, |
| 458 | link, |
| 459 | ), |
| 460 | Span::CodeBlock { code, .. } => out.push( |
| 461 | code.trim_end_matches('\n'), |
| 462 | StyleFlags { |
| 463 | code: true, |
| 464 | ..style |
| 465 | }, |
| 466 | link, |
| 467 | ), |
| 468 | Span::Link { url, children } => append_inline( |
| 469 | children, |
| 470 | StyleFlags { |
| 471 | link: true, |
| 472 | ..style |
| 473 | }, |
| 474 | Some(url.as_str()), |
| 475 | out, |
| 476 | ), |
| 477 | Span::Mention { name } => { |
| 478 | let label = format!("@{}", name.trim_start_matches('@')); |
| 479 | out.push( |
| 480 | &label, |
| 481 | StyleFlags { |
| 482 | mention: true, |
| 483 | ..style |
| 484 | }, |
| 485 | link, |
| 486 | ); |
| 487 | } |
| 488 | Span::LineBreak | Span::Rule => out.push("\n", style, link), |
| 489 | Span::Quote(children) | Span::BlockQuote(children) => { |
| 490 | append_inline(children, style, link, out); |
| 491 | out.push("\n", style, link); |
| 492 | } |
| 493 | Span::List { items, .. } => { |
| 494 | for item in items { |
| 495 | append_inline(item, style, link, out); |
| 496 | out.push("\n", style, link); |
| 497 | } |
| 498 | } |
| 499 | Span::Table { rows, .. } => { |
| 500 | for row in rows { |
| 501 | for (index, cell) in row.iter().enumerate() { |
| 502 | if index > 0 { |
| 503 | out.push(" ", style, link); |
| 504 | } |
| 505 | append_inline(cell, style, link, out); |
| 506 | } |
| 507 | out.push("\n", style, link); |
| 508 | } |
| 509 | } |
| 510 | Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link), |
| 511 | } |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | fn push_linkified(text: &str, style: StyleFlags, out: &mut Inline) { |
| 516 | let mut rest = text; |
| 517 | while let Some((start, end)) = find_url(rest) { |
| 518 | out.push(&rest[..start], style, None); |
| 519 | let visible = &rest[start..end]; |
| 520 | let target = if visible.starts_with("www.") { |
| 521 | format!("https://{visible}") |
| 522 | } else { |
| 523 | visible.to_owned() |
| 524 | }; |
| 525 | out.push( |
| 526 | visible, |
| 527 | StyleFlags { |
| 528 | link: true, |
| 529 | ..style |
| 530 | }, |
| 531 | Some(&target), |
| 532 | ); |
| 533 | rest = &rest[end..]; |
| 534 | } |
| 535 | out.push(rest, style, None); |
| 536 | } |
| 537 | |
| 538 | fn find_url(text: &str) -> Option<(usize, usize)> { |
| 539 | let mut previous_is_boundary = true; |
| 540 | for (start, character) in text.char_indices() { |
| 541 | if previous_is_boundary |
| 542 | && let Some(prefix) = URL_PREFIXES |
| 543 | .iter() |
| 544 | .find(|prefix| text[start..].starts_with(**prefix)) |
| 545 | { |
| 546 | let length = text[start..] |
| 547 | .find(char::is_whitespace) |
| 548 | .unwrap_or(text.len() - start); |
| 549 | let end = start + trimmed_url_length(&text[start..start + length]); |
| 550 | if end > start + prefix.len() { |
| 551 | return Some((start, end)); |
| 552 | } |
| 553 | } |
| 554 | previous_is_boundary = !character.is_alphanumeric(); |
| 555 | } |
| 556 | None |
| 557 | } |
| 558 | |
| 559 | fn trimmed_url_length(candidate: &str) -> usize { |
| 560 | let mut url = candidate; |
| 561 | while let Some(last) = url.chars().next_back() { |
| 562 | let opener = match last { |
| 563 | ')' => Some('('), |
| 564 | ']' => Some('['), |
| 565 | '}' => Some('{'), |
| 566 | _ => None, |
| 567 | }; |
| 568 | let trimmable = match opener { |
| 569 | Some(opener) => url.matches(last).count() > url.matches(opener).count(), |
| 570 | None => TRAILING_PUNCTUATION.contains(last), |
| 571 | }; |
| 572 | if !trimmable { |
| 573 | break; |
| 574 | } |
| 575 | url = &url[..url.len() - last.len_utf8()]; |
| 576 | } |
| 577 | url.len() |
| 578 | } |
| 579 | |
| 580 | #[cfg(test)] |
| 581 | mod tests { |
| 582 | use super::*; |
| 583 | |
| 584 | fn text(value: &str) -> Span { |
| 585 | Span::Text(value.to_owned()) |
| 586 | } |
| 587 | |
| 588 | #[test] |
| 589 | fn plain_text_is_one_paragraph() { |
| 590 | let blocks = layout_blocks(&[text("hello ")]); |
| 591 | assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("hello"))]); |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn bold_and_italic_nest_into_flags() { |
| 596 | let blocks = layout_blocks(&[ |
| 597 | text("a "), |
| 598 | Span::Bold(vec![Span::Italic(vec![text("b")])]), |
| 599 | text(" c"), |
| 600 | ]); |
| 601 | let Block::Paragraph(inline) = &blocks[0] else { |
| 602 | panic!("paragraph expected") |
| 603 | }; |
| 604 | assert_eq!(inline.text, "a b c"); |
| 605 | assert_eq!(inline.segments.len(), 3); |
| 606 | assert!(inline.segments[1].style.bold && inline.segments[1].style.italic); |
| 607 | assert_eq!(inline.segments[1].range, 2..3); |
| 608 | } |
| 609 | |
| 610 | #[test] |
| 611 | fn link_keeps_url_and_range() { |
| 612 | let blocks = layout_blocks(&[ |
| 613 | text("see "), |
| 614 | Span::Link { |
| 615 | url: "https://example.com".into(), |
| 616 | children: vec![text("here")], |
| 617 | }, |
| 618 | ]); |
| 619 | let Block::Paragraph(inline) = &blocks[0] else { |
| 620 | panic!("paragraph expected") |
| 621 | }; |
| 622 | assert_eq!( |
| 623 | inline.links(), |
| 624 | vec![(4..8, "https://example.com".to_owned())] |
| 625 | ); |
| 626 | } |
| 627 | |
| 628 | fn paragraph_inline(spans: &[Span]) -> Inline { |
| 629 | let Block::Paragraph(inline) = layout_blocks(spans).remove(0) else { |
| 630 | panic!("paragraph expected") |
| 631 | }; |
| 632 | inline |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn plain_url_at_end_becomes_link() { |
| 637 | let inline = paragraph_inline(&[text("see https://example.com/a")]); |
| 638 | assert_eq!( |
| 639 | inline.links(), |
| 640 | vec![(4..25, "https://example.com/a".to_owned())] |
| 641 | ); |
| 642 | assert!(inline.segments[1].style.link); |
| 643 | } |
| 644 | |
| 645 | #[test] |
| 646 | fn trailing_period_stays_outside_url() { |
| 647 | let inline = paragraph_inline(&[text("go to http://example.com. Then")]); |
| 648 | assert_eq!( |
| 649 | inline.links(), |
| 650 | vec![(6..24, "http://example.com".to_owned())] |
| 651 | ); |
| 652 | } |
| 653 | |
| 654 | #[test] |
| 655 | fn balanced_parentheses_stay_in_url() { |
| 656 | let inline = paragraph_inline(&[text("https://example.com/Rust_(language)")]); |
| 657 | assert_eq!(inline.links()[0].1, "https://example.com/Rust_(language)"); |
| 658 | let wrapped = paragraph_inline(&[text("(see https://example.com)")]); |
| 659 | assert_eq!(wrapped.links()[0].1, "https://example.com"); |
| 660 | } |
| 661 | |
| 662 | #[test] |
| 663 | fn www_url_gets_https_target() { |
| 664 | let inline = paragraph_inline(&[text("www.example.com!")]); |
| 665 | assert_eq!(inline.text, "www.example.com!"); |
| 666 | assert_eq!( |
| 667 | inline.links(), |
| 668 | vec![(0..15, "https://www.example.com".to_owned())] |
| 669 | ); |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn text_without_url_has_no_links() { |
| 674 | let inline = paragraph_inline(&[text("no link, just www. and https:// here")]); |
| 675 | assert!(inline.links().is_empty()); |
| 676 | } |
| 677 | |
| 678 | #[test] |
| 679 | fn url_inside_link_stays_one_link() { |
| 680 | let inline = paragraph_inline(&[Span::Link { |
| 681 | url: "https://target.example".into(), |
| 682 | children: vec![text("https://shown.example")], |
| 683 | }]); |
| 684 | assert_eq!( |
| 685 | inline.links(), |
| 686 | vec![(0..21, "https://target.example".to_owned())] |
| 687 | ); |
| 688 | } |
| 689 | |
| 690 | #[test] |
| 691 | fn mention_gets_an_at_sign_once() { |
| 692 | let blocks = layout_blocks(&[ |
| 693 | Span::Mention { name: "Ada".into() }, |
| 694 | text(" "), |
| 695 | Span::Mention { |
| 696 | name: "@Bob".into(), |
| 697 | }, |
| 698 | ]); |
| 699 | let Block::Paragraph(inline) = &blocks[0] else { |
| 700 | panic!("paragraph expected") |
| 701 | }; |
| 702 | assert_eq!(inline.text, "@Ada @Bob"); |
| 703 | assert!(inline.segments[0].style.mention); |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn code_block_splits_paragraphs() { |
| 708 | let blocks = layout_blocks(&[ |
| 709 | text("before"), |
| 710 | Span::CodeBlock { |
| 711 | language: None, |
| 712 | code: "let x = 1;\n".into(), |
| 713 | }, |
| 714 | text("after"), |
| 715 | ]); |
| 716 | assert_eq!( |
| 717 | blocks, |
| 718 | vec![ |
| 719 | Block::Paragraph(Inline::plain("before")), |
| 720 | Block::Code { |
| 721 | language: None, |
| 722 | code: "let x = 1;".into() |
| 723 | }, |
| 724 | Block::Paragraph(Inline::plain("after")), |
| 725 | ] |
| 726 | ); |
| 727 | } |
| 728 | |
| 729 | #[test] |
| 730 | fn lists_nest_and_quotes_are_blocks() { |
| 731 | let blocks = layout_blocks(&[ |
| 732 | Span::List { |
| 733 | ordered: true, |
| 734 | start: 3, |
| 735 | items: vec![ |
| 736 | vec![text("one")], |
| 737 | vec![ |
| 738 | text("two"), |
| 739 | Span::List { |
| 740 | ordered: false, |
| 741 | start: 1, |
| 742 | items: vec![vec![text("inner")]], |
| 743 | }, |
| 744 | ], |
| 745 | ], |
| 746 | }, |
| 747 | Span::Quote(vec![text("quoted")]), |
| 748 | ]); |
| 749 | assert_eq!( |
| 750 | blocks, |
| 751 | vec![ |
| 752 | Block::List { |
| 753 | ordered: true, |
| 754 | start: 3, |
| 755 | items: vec![ |
| 756 | vec![Block::Paragraph(Inline::plain("one"))], |
| 757 | vec![ |
| 758 | Block::Paragraph(Inline::plain("two")), |
| 759 | Block::List { |
| 760 | ordered: false, |
| 761 | start: 1, |
| 762 | items: vec![vec![Block::Paragraph(Inline::plain("inner"))]], |
| 763 | }, |
| 764 | ], |
| 765 | ], |
| 766 | }, |
| 767 | Block::Reply(vec![Block::Paragraph(Inline::plain("quoted"))]), |
| 768 | ] |
| 769 | ); |
| 770 | } |
| 771 | |
| 772 | #[test] |
| 773 | fn heading_rule_and_table_are_blocks() { |
| 774 | let blocks = layout_blocks(&[ |
| 775 | Span::Heading { |
| 776 | level: 2, |
| 777 | children: vec![text("Title")], |
| 778 | }, |
| 779 | Span::Rule, |
| 780 | Span::Table { |
| 781 | header: true, |
| 782 | rows: vec![vec![vec![text("a")], vec![text("b")]]], |
| 783 | }, |
| 784 | ]); |
| 785 | assert_eq!( |
| 786 | blocks, |
| 787 | vec![ |
| 788 | Block::Heading { |
| 789 | level: 2, |
| 790 | inline: Inline::plain("Title") |
| 791 | }, |
| 792 | Block::Rule, |
| 793 | Block::Table { |
| 794 | header: true, |
| 795 | rows: vec![vec![Inline::plain("a"), Inline::plain("b")]], |
| 796 | }, |
| 797 | ] |
| 798 | ); |
| 799 | } |
| 800 | |
| 801 | #[test] |
| 802 | fn strike_underline_and_color_become_flags() { |
| 803 | let inline = paragraph_inline(&[ |
| 804 | Span::Strike(vec![text("old")]), |
| 805 | Span::Underline(vec![text("u")]), |
| 806 | Span::Colored { |
| 807 | color: Some(0xff0000), |
| 808 | background: Some(0xffff00), |
| 809 | children: vec![text("c")], |
| 810 | }, |
| 811 | ]); |
| 812 | assert!(inline.segments[0].style.strike); |
| 813 | assert!(inline.segments[1].style.underline); |
| 814 | assert_eq!(inline.segments[2].style.color, Some(0xff0000)); |
| 815 | assert_eq!(inline.segments[2].style.background, Some(0xffff00)); |
| 816 | } |
| 817 | |
| 818 | #[test] |
| 819 | fn inline_code_gets_room_only_next_to_text() { |
| 820 | let inline = paragraph_inline(&[ |
| 821 | text("run "), |
| 822 | Span::Code("x".into()), |
| 823 | text(". "), |
| 824 | Span::Code("y".into()), |
| 825 | ]); |
| 826 | assert_eq!(inline.text, "run x\u{200a}. y"); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn image_becomes_placeholder() { |
| 831 | let blocks = layout_blocks(&[Span::Image { |
| 832 | hosted_content_url: "u".into(), |
| 833 | }]); |
| 834 | assert_eq!( |
| 835 | blocks, |
| 836 | vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))] |
| 837 | ); |
| 838 | } |
| 839 | |
| 840 | #[test] |
| 841 | fn stripping_placeholders_keeps_the_text_around_them() { |
| 842 | let blocks = layout_blocks(&[ |
| 843 | text("look "), |
| 844 | Span::Bold(vec![text("here")]), |
| 845 | Span::LineBreak, |
| 846 | Span::Image { |
| 847 | hosted_content_url: "u".into(), |
| 848 | }, |
| 849 | ]); |
| 850 | let stripped = strip_image_placeholders(blocks); |
| 851 | let Block::Paragraph(inline) = &stripped[0] else { |
| 852 | panic!("paragraph expected") |
| 853 | }; |
| 854 | assert_eq!(inline.text, "look here"); |
| 855 | assert!(inline.segments.last().unwrap().style.bold); |
| 856 | let only_image = layout_blocks(&[Span::Image { |
| 857 | hosted_content_url: "u".into(), |
| 858 | }]); |
| 859 | assert!(strip_image_placeholders(only_image).is_empty()); |
| 860 | } |
| 861 | |
| 862 | #[test] |
| 863 | fn line_break_stays_inside_paragraph() { |
| 864 | let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]); |
| 865 | assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("a\nb"))]); |
| 866 | } |
| 867 | |
| 868 | #[test] |
| 869 | fn empty_input_has_no_blocks() { |
| 870 | assert!(layout_blocks(&[]).is_empty()); |
| 871 | assert!(layout_blocks(&[Span::LineBreak, text(" ")]).is_empty()); |
| 872 | } |
| 873 | } |