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