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