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