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