| 1 | use std::ops::Range; |
| 2 | |
| 3 | use teams_core::Span; |
| 4 | |
| 5 | pub const MENTION_PAD: char = '\u{2009}'; |
| 6 | pub const IMAGE_PLACEHOLDER: &str = "[image]"; |
| 7 | |
| 8 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 9 | pub struct StyleFlags { |
| 10 | pub bold: bool, |
| 11 | pub italic: bool, |
| 12 | pub code: bool, |
| 13 | pub mention: bool, |
| 14 | pub link: bool, |
| 15 | } |
| 16 | |
| 17 | impl StyleFlags { |
| 18 | pub fn is_plain(&self) -> bool { |
| 19 | *self == StyleFlags::default() |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 24 | pub struct Segment { |
| 25 | pub range: Range<usize>, |
| 26 | pub style: StyleFlags, |
| 27 | pub link: Option<String>, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 31 | pub struct Inline { |
| 32 | pub text: String, |
| 33 | pub segments: Vec<Segment>, |
| 34 | } |
| 35 | |
| 36 | impl Inline { |
| 37 | pub fn plain(text: &str) -> Self { |
| 38 | let mut inline = Inline::default(); |
| 39 | inline.push(text, StyleFlags::default(), None); |
| 40 | inline |
| 41 | } |
| 42 | |
| 43 | fn push(&mut self, text: &str, style: StyleFlags, link: Option<&str>) { |
| 44 | if text.is_empty() { |
| 45 | return; |
| 46 | } |
| 47 | let start = self.text.len(); |
| 48 | self.text.push_str(text); |
| 49 | let end = self.text.len(); |
| 50 | if let Some(last) = self.segments.last_mut() |
| 51 | && last.style == style |
| 52 | && last.link.as_deref() == link |
| 53 | && last.range.end == start |
| 54 | { |
| 55 | last.range.end = end; |
| 56 | return; |
| 57 | } |
| 58 | self.segments.push(Segment { |
| 59 | range: start..end, |
| 60 | style, |
| 61 | link: link.map(str::to_owned), |
| 62 | }); |
| 63 | } |
| 64 | |
| 65 | pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline { |
| 66 | let mut padded = self.clone(); |
| 67 | padded.push(&"\u{2007}".repeat(width_in_spaces), StyleFlags::default(), None); |
| 68 | padded |
| 69 | } |
| 70 | |
| 71 | pub fn is_blank(&self) -> bool { |
| 72 | self.text.trim().is_empty() |
| 73 | } |
| 74 | |
| 75 | fn trim_end(&mut self) { |
| 76 | let trimmed = self.text.trim_end().len(); |
| 77 | self.text.truncate(trimmed); |
| 78 | self.segments.retain_mut(|segment| { |
| 79 | segment.range.end = segment.range.end.min(trimmed); |
| 80 | segment.range.start < segment.range.end |
| 81 | }); |
| 82 | } |
| 83 | |
| 84 | fn without(&self, needle: &str) -> Inline { |
| 85 | let mut stripped = Inline::default(); |
| 86 | for segment in &self.segments { |
| 87 | let text = self.text[segment.range.clone()].replace(needle, ""); |
| 88 | stripped.push(&text, segment.style, segment.link.as_deref()); |
| 89 | } |
| 90 | stripped.trim_end(); |
| 91 | let leading = stripped.text.len() - stripped.text.trim_start().len(); |
| 92 | if leading > 0 { |
| 93 | let mut trimmed = Inline::default(); |
| 94 | for segment in &stripped.segments { |
| 95 | let text = stripped.text[segment.range.clone()].to_owned(); |
| 96 | let skip = leading.saturating_sub(segment.range.start).min(text.len()); |
| 97 | trimmed.push(&text[skip..], segment.style, segment.link.as_deref()); |
| 98 | } |
| 99 | return trimmed; |
| 100 | } |
| 101 | stripped |
| 102 | } |
| 103 | |
| 104 | pub fn links(&self) -> Vec<(Range<usize>, String)> { |
| 105 | self.segments |
| 106 | .iter() |
| 107 | .filter_map(|segment| Some((segment.range.clone(), segment.link.clone()?))) |
| 108 | .collect() |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 113 | pub enum Block { |
| 114 | Paragraph(Inline), |
| 115 | Code(String), |
| 116 | Quote(Vec<Block>), |
| 117 | ListItem(Inline), |
| 118 | } |
| 119 | |
| 120 | pub fn strip_image_placeholders(blocks: Vec<Block>) -> Vec<Block> { |
| 121 | blocks |
| 122 | .into_iter() |
| 123 | .filter_map(|block| match block { |
| 124 | Block::Paragraph(inline) => { |
| 125 | let stripped = inline.without(IMAGE_PLACEHOLDER); |
| 126 | (!stripped.is_blank()).then_some(Block::Paragraph(stripped)) |
| 127 | } |
| 128 | Block::Quote(children) => { |
| 129 | let children = strip_image_placeholders(children); |
| 130 | (!children.is_empty()).then_some(Block::Quote(children)) |
| 131 | } |
| 132 | other => Some(other), |
| 133 | }) |
| 134 | .collect() |
| 135 | } |
| 136 | |
| 137 | pub fn layout_blocks(spans: &[Span]) -> Vec<Block> { |
| 138 | let mut blocks = Vec::new(); |
| 139 | let mut current = Inline::default(); |
| 140 | for span in spans { |
| 141 | match span { |
| 142 | Span::CodeBlock { code, .. } => { |
| 143 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 144 | blocks.push(Block::Code(code.trim_end_matches('\n').to_owned())); |
| 145 | } |
| 146 | Span::Quote(children) => { |
| 147 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 148 | let inner = layout_blocks(children); |
| 149 | if !inner.is_empty() { |
| 150 | blocks.push(Block::Quote(inner)); |
| 151 | } |
| 152 | } |
| 153 | Span::ListItem(children) => { |
| 154 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 155 | let mut item = Inline::default(); |
| 156 | append_inline(children, StyleFlags::default(), None, &mut item); |
| 157 | item.trim_end(); |
| 158 | blocks.push(Block::ListItem(item)); |
| 159 | } |
| 160 | other => append_inline( |
| 161 | std::slice::from_ref(other), |
| 162 | StyleFlags::default(), |
| 163 | None, |
| 164 | &mut current, |
| 165 | ), |
| 166 | } |
| 167 | } |
| 168 | flush(&mut current, &mut blocks, Block::Paragraph); |
| 169 | blocks |
| 170 | } |
| 171 | |
| 172 | fn flush(current: &mut Inline, blocks: &mut Vec<Block>, make: fn(Inline) -> Block) { |
| 173 | let mut inline = std::mem::take(current); |
| 174 | inline.trim_end(); |
| 175 | let leading = inline.text.len() - inline.text.trim_start_matches('\n').len(); |
| 176 | if leading > 0 { |
| 177 | inline.text.drain(..leading); |
| 178 | inline.segments.retain_mut(|segment| { |
| 179 | segment.range.start = segment.range.start.saturating_sub(leading); |
| 180 | segment.range.end = segment.range.end.saturating_sub(leading); |
| 181 | segment.range.start < segment.range.end |
| 182 | }); |
| 183 | } |
| 184 | if !inline.is_blank() { |
| 185 | blocks.push(make(inline)); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mut Inline) { |
| 190 | for span in spans { |
| 191 | match span { |
| 192 | Span::Text(text) => out.push(text, style, link), |
| 193 | Span::Bold(children) => append_inline( |
| 194 | children, |
| 195 | StyleFlags { |
| 196 | bold: true, |
| 197 | ..style |
| 198 | }, |
| 199 | link, |
| 200 | out, |
| 201 | ), |
| 202 | Span::Italic(children) => append_inline( |
| 203 | children, |
| 204 | StyleFlags { |
| 205 | italic: true, |
| 206 | ..style |
| 207 | }, |
| 208 | link, |
| 209 | out, |
| 210 | ), |
| 211 | Span::Code(text) => out.push( |
| 212 | text, |
| 213 | StyleFlags { |
| 214 | code: true, |
| 215 | ..style |
| 216 | }, |
| 217 | link, |
| 218 | ), |
| 219 | Span::CodeBlock { code, .. } => out.push( |
| 220 | code.trim_end_matches('\n'), |
| 221 | StyleFlags { |
| 222 | code: true, |
| 223 | ..style |
| 224 | }, |
| 225 | link, |
| 226 | ), |
| 227 | Span::Link { url, children } => append_inline( |
| 228 | children, |
| 229 | StyleFlags { |
| 230 | link: true, |
| 231 | ..style |
| 232 | }, |
| 233 | Some(url.as_str()), |
| 234 | out, |
| 235 | ), |
| 236 | Span::Mention { name } => { |
| 237 | let label = format!( |
| 238 | "{MENTION_PAD}@{}{MENTION_PAD}", |
| 239 | name.trim_start_matches('@') |
| 240 | ); |
| 241 | out.push( |
| 242 | &label, |
| 243 | StyleFlags { |
| 244 | mention: true, |
| 245 | ..style |
| 246 | }, |
| 247 | link, |
| 248 | ); |
| 249 | } |
| 250 | Span::LineBreak => out.push("\n", style, link), |
| 251 | Span::ListItem(children) | Span::Quote(children) => { |
| 252 | append_inline(children, style, link, out); |
| 253 | out.push("\n", style, link); |
| 254 | } |
| 255 | Span::Image { .. } => out.push(IMAGE_PLACEHOLDER, style, link), |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | #[cfg(test)] |
| 261 | mod tests { |
| 262 | use super::*; |
| 263 | |
| 264 | fn text(value: &str) -> Span { |
| 265 | Span::Text(value.to_owned()) |
| 266 | } |
| 267 | |
| 268 | #[test] |
| 269 | fn plain_text_is_one_paragraph() { |
| 270 | let blocks = layout_blocks(&[text("hello ")]); |
| 271 | assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("hello"))]); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn bold_and_italic_nest_into_flags() { |
| 276 | let blocks = layout_blocks(&[ |
| 277 | text("a "), |
| 278 | Span::Bold(vec![Span::Italic(vec![text("b")])]), |
| 279 | text(" c"), |
| 280 | ]); |
| 281 | let Block::Paragraph(inline) = &blocks[0] else { |
| 282 | panic!("paragraph expected") |
| 283 | }; |
| 284 | assert_eq!(inline.text, "a b c"); |
| 285 | assert_eq!(inline.segments.len(), 3); |
| 286 | assert!(inline.segments[1].style.bold && inline.segments[1].style.italic); |
| 287 | assert_eq!(inline.segments[1].range, 2..3); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn link_keeps_url_and_range() { |
| 292 | let blocks = layout_blocks(&[ |
| 293 | text("see "), |
| 294 | Span::Link { |
| 295 | url: "https://example.com".into(), |
| 296 | children: vec![text("here")], |
| 297 | }, |
| 298 | ]); |
| 299 | let Block::Paragraph(inline) = &blocks[0] else { |
| 300 | panic!("paragraph expected") |
| 301 | }; |
| 302 | assert_eq!( |
| 303 | inline.links(), |
| 304 | vec![(4..8, "https://example.com".to_owned())] |
| 305 | ); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn mention_gets_an_at_sign_once() { |
| 310 | let blocks = layout_blocks(&[ |
| 311 | Span::Mention { name: "Ada".into() }, |
| 312 | text(" "), |
| 313 | Span::Mention { |
| 314 | name: "@Bob".into(), |
| 315 | }, |
| 316 | ]); |
| 317 | let Block::Paragraph(inline) = &blocks[0] else { |
| 318 | panic!("paragraph expected") |
| 319 | }; |
| 320 | assert_eq!(inline.text, "\u{2009}@Ada\u{2009} \u{2009}@Bob"); |
| 321 | assert!(inline.segments[0].style.mention); |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn code_block_splits_paragraphs() { |
| 326 | let blocks = layout_blocks(&[ |
| 327 | text("before"), |
| 328 | Span::CodeBlock { |
| 329 | language: None, |
| 330 | code: "let x = 1;\n".into(), |
| 331 | }, |
| 332 | text("after"), |
| 333 | ]); |
| 334 | assert_eq!( |
| 335 | blocks, |
| 336 | vec![ |
| 337 | Block::Paragraph(Inline::plain("before")), |
| 338 | Block::Code("let x = 1;".into()), |
| 339 | Block::Paragraph(Inline::plain("after")), |
| 340 | ] |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn list_items_and_quotes_are_blocks() { |
| 346 | let blocks = layout_blocks(&[ |
| 347 | Span::ListItem(vec![text("one")]), |
| 348 | Span::ListItem(vec![text("two")]), |
| 349 | Span::Quote(vec![text("quoted")]), |
| 350 | ]); |
| 351 | assert_eq!( |
| 352 | blocks, |
| 353 | vec![ |
| 354 | Block::ListItem(Inline::plain("one")), |
| 355 | Block::ListItem(Inline::plain("two")), |
| 356 | Block::Quote(vec![Block::Paragraph(Inline::plain("quoted"))]), |
| 357 | ] |
| 358 | ); |
| 359 | } |
| 360 | |
| 361 | #[test] |
| 362 | fn image_becomes_placeholder() { |
| 363 | let blocks = layout_blocks(&[Span::Image { |
| 364 | hosted_content_url: "u".into(), |
| 365 | }]); |
| 366 | assert_eq!( |
| 367 | blocks, |
| 368 | vec![Block::Paragraph(Inline::plain(IMAGE_PLACEHOLDER))] |
| 369 | ); |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn stripping_placeholders_keeps_the_text_around_them() { |
| 374 | let blocks = layout_blocks(&[ |
| 375 | text("look "), |
| 376 | Span::Bold(vec![text("here")]), |
| 377 | Span::LineBreak, |
| 378 | Span::Image { |
| 379 | hosted_content_url: "u".into(), |
| 380 | }, |
| 381 | ]); |
| 382 | let stripped = strip_image_placeholders(blocks); |
| 383 | let Block::Paragraph(inline) = &stripped[0] else { |
| 384 | panic!("paragraph expected") |
| 385 | }; |
| 386 | assert_eq!(inline.text, "look here"); |
| 387 | assert!(inline.segments.last().unwrap().style.bold); |
| 388 | let only_image = layout_blocks(&[Span::Image { |
| 389 | hosted_content_url: "u".into(), |
| 390 | }]); |
| 391 | assert!(strip_image_placeholders(only_image).is_empty()); |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn line_break_stays_inside_paragraph() { |
| 396 | let blocks = layout_blocks(&[text("a"), Span::LineBreak, text("b")]); |
| 397 | assert_eq!(blocks, vec![Block::Paragraph(Inline::plain("a\nb"))]); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn empty_input_has_no_blocks() { |
| 402 | assert!(layout_blocks(&[]).is_empty()); |
| 403 | assert!(layout_blocks(&[Span::LineBreak, text(" ")]).is_empty()); |
| 404 | } |
| 405 | } |