| 1 | use std::collections::BTreeMap; |
| 2 | use std::ops::Range; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc}; |
| 6 | use gpui_kit::Image; |
| 7 | use store::MessageRecord; |
| 8 | use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions}; |
| 9 | |
| 10 | use crate::format; |
| 11 | use crate::render::blocks::{Inline, strip_image_placeholders}; |
| 12 | use crate::render::{Block, layout_blocks}; |
| 13 | use crate::sidebar_model::Face; |
| 14 | |
| 15 | const REPLY_FACE_LIMIT: usize = 3; |
| 16 | |
| 17 | pub const LOAD_OLDER_KEY: &str = "load-older"; |
| 18 | const UNKNOWN_AUTHOR: &str = "Unknown"; |
| 19 | const DELETED_TEXT: &str = "Message deleted"; |
| 20 | const SERIES_GAP_MINUTES: i64 = 5; |
| 21 | const CORNER_RADIUS: f32 = 14.; |
| 22 | const CORNER_SERIES: f32 = 4.; |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 25 | pub struct ReactionChip { |
| 26 | pub reaction_type: String, |
| 27 | pub label: String, |
| 28 | pub count: usize, |
| 29 | pub mine: bool, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 33 | pub struct Series { |
| 34 | pub has_prev: bool, |
| 35 | pub has_next: bool, |
| 36 | } |
| 37 | |
| 38 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 39 | pub struct Corners { |
| 40 | pub top_left: f32, |
| 41 | pub top_right: f32, |
| 42 | pub bottom_right: f32, |
| 43 | pub bottom_left: f32, |
| 44 | } |
| 45 | |
| 46 | pub fn bubble_corners(own: bool, series: Series) -> Corners { |
| 47 | if own { |
| 48 | let top_right = if series.has_prev || !series.has_next { |
| 49 | CORNER_SERIES |
| 50 | } else { |
| 51 | CORNER_RADIUS |
| 52 | }; |
| 53 | let bottom_right = if series.has_next || !series.has_prev { |
| 54 | CORNER_SERIES |
| 55 | } else { |
| 56 | CORNER_RADIUS |
| 57 | }; |
| 58 | Corners { |
| 59 | top_left: CORNER_RADIUS, |
| 60 | top_right, |
| 61 | bottom_right, |
| 62 | bottom_left: CORNER_RADIUS, |
| 63 | } |
| 64 | } else { |
| 65 | Corners { |
| 66 | top_left: CORNER_SERIES, |
| 67 | top_right: CORNER_RADIUS, |
| 68 | bottom_right: CORNER_RADIUS, |
| 69 | bottom_left: if series.has_next { |
| 70 | CORNER_SERIES |
| 71 | } else { |
| 72 | CORNER_RADIUS |
| 73 | }, |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 79 | pub enum Receipt { |
| 80 | #[default] |
| 81 | Hidden, |
| 82 | Pending, |
| 83 | Sent, |
| 84 | Read, |
| 85 | } |
| 86 | |
| 87 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 88 | pub enum Delivery { |
| 89 | Delivered, |
| 90 | Sending, |
| 91 | Failed(String), |
| 92 | } |
| 93 | |
| 94 | /// An image of a message that is still being sent, shown from its local bytes. |
| 95 | #[derive(Debug, Clone, PartialEq)] |
| 96 | pub struct LocalImage { |
| 97 | pub image: Arc<Image>, |
| 98 | pub size: Option<(u32, u32)>, |
| 99 | } |
| 100 | |
| 101 | #[derive(Debug, Clone, PartialEq)] |
| 102 | pub struct MessageRow { |
| 103 | pub key: String, |
| 104 | pub author: String, |
| 105 | pub sender_id: Option<String>, |
| 106 | pub created_at: DateTime<Utc>, |
| 107 | pub series: Series, |
| 108 | pub card: bool, |
| 109 | pub time: String, |
| 110 | pub day_header: Option<String>, |
| 111 | pub blocks: Vec<Block>, |
| 112 | pub edited: bool, |
| 113 | pub deleted: bool, |
| 114 | pub reactions: Vec<ReactionChip>, |
| 115 | pub images: Vec<ImageRef>, |
| 116 | pub local_images: Vec<LocalImage>, |
| 117 | pub files: Vec<FileCard>, |
| 118 | pub reply_count: Option<usize>, |
| 119 | pub new_marker: bool, |
| 120 | pub reply_faces: Vec<Face>, |
| 121 | pub last_reply_time: Option<String>, |
| 122 | pub open_thread: Option<String>, |
| 123 | pub is_reply: bool, |
| 124 | pub delivery: Delivery, |
| 125 | pub own: bool, |
| 126 | pub receipt: Receipt, |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 130 | pub struct StartInfo { |
| 131 | pub title: String, |
| 132 | pub user_id: Option<String>, |
| 133 | } |
| 134 | |
| 135 | pub const START_KEY: &str = "conversation-start"; |
| 136 | |
| 137 | #[derive(Debug, Clone, PartialEq)] |
| 138 | pub enum Row { |
| 139 | LoadOlder, |
| 140 | Start(StartInfo), |
| 141 | Skeleton(Skeleton), |
| 142 | Message(Box<MessageRow>), |
| 143 | } |
| 144 | |
| 145 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 146 | pub struct Skeleton { |
| 147 | pub key: &'static str, |
| 148 | pub own: bool, |
| 149 | pub width_ratio: f32, |
| 150 | pub lines: u8, |
| 151 | } |
| 152 | |
| 153 | const SKELETON_TRAILING: Skeleton = Skeleton { |
| 154 | key: "skeleton-trailing", |
| 155 | own: false, |
| 156 | width_ratio: 0.32, |
| 157 | lines: 1, |
| 158 | }; |
| 159 | |
| 160 | const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [ |
| 161 | Skeleton { |
| 162 | key: "skeleton-0", |
| 163 | own: false, |
| 164 | width_ratio: 0.42, |
| 165 | lines: 1, |
| 166 | }, |
| 167 | Skeleton { |
| 168 | key: "skeleton-1", |
| 169 | own: true, |
| 170 | width_ratio: 0.3, |
| 171 | lines: 1, |
| 172 | }, |
| 173 | Skeleton { |
| 174 | key: "skeleton-2", |
| 175 | own: true, |
| 176 | width_ratio: 0.48, |
| 177 | lines: 2, |
| 178 | }, |
| 179 | Skeleton { |
| 180 | key: "skeleton-3", |
| 181 | own: false, |
| 182 | width_ratio: 0.26, |
| 183 | lines: 1, |
| 184 | }, |
| 185 | ]; |
| 186 | |
| 187 | pub fn placeholder_rows() -> Vec<Row> { |
| 188 | SKELETON_PLACEHOLDERS |
| 189 | .into_iter() |
| 190 | .map(Row::Skeleton) |
| 191 | .collect() |
| 192 | } |
| 193 | |
| 194 | pub fn trailing_skeleton() -> Row { |
| 195 | Row::Skeleton(SKELETON_TRAILING) |
| 196 | } |
| 197 | |
| 198 | fn sender_key(row: &MessageRow) -> &str { |
| 199 | row.sender_id.as_deref().unwrap_or(&row.author) |
| 200 | } |
| 201 | |
| 202 | fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool { |
| 203 | !previous.card |
| 204 | && !next.card |
| 205 | && next.day_header.is_none() |
| 206 | && !next.new_marker |
| 207 | && sender_key(previous) == sender_key(next) |
| 208 | && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES) |
| 209 | && next.created_at >= previous.created_at |
| 210 | } |
| 211 | |
| 212 | pub fn assign_series(rows: &mut [Row]) { |
| 213 | let mut previous: Option<usize> = None; |
| 214 | for index in 0..rows.len() { |
| 215 | let Row::Message(_) = &rows[index] else { |
| 216 | previous = None; |
| 217 | continue; |
| 218 | }; |
| 219 | if let Some(before) = previous { |
| 220 | let joined = match (&rows[before], &rows[index]) { |
| 221 | (Row::Message(a), Row::Message(b)) => continues_series(a, b), |
| 222 | _ => false, |
| 223 | }; |
| 224 | if joined { |
| 225 | if let Row::Message(a) = &mut rows[before] { |
| 226 | a.series.has_next = true; |
| 227 | } |
| 228 | if let Row::Message(b) = &mut rows[index] { |
| 229 | b.series.has_prev = true; |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | previous = Some(index); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | impl Row { |
| 238 | pub fn key(&self) -> &str { |
| 239 | match self { |
| 240 | Row::LoadOlder => LOAD_OLDER_KEY, |
| 241 | Row::Start(_) => START_KEY, |
| 242 | Row::Skeleton(skeleton) => skeleton.key, |
| 243 | Row::Message(message) => &message.key, |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 249 | pub struct Thread { |
| 250 | pub root_id: String, |
| 251 | pub reply_ids: Vec<String>, |
| 252 | } |
| 253 | |
| 254 | pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String { |
| 255 | time.with_timezone(&offset).format("%H:%M").to_string() |
| 256 | } |
| 257 | |
| 258 | pub fn reaction_label(reaction_type: &str) -> String { |
| 259 | match reaction_type { |
| 260 | "like" => "\u{1F44D}".to_owned(), |
| 261 | "heart" => "\u{2764}".to_owned(), |
| 262 | "laugh" => "\u{1F602}".to_owned(), |
| 263 | "surprised" => "\u{1F62E}".to_owned(), |
| 264 | "sad" => "\u{1F622}".to_owned(), |
| 265 | "angry" => "\u{1F620}".to_owned(), |
| 266 | other => other.to_owned(), |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// The reaction type Teams uses for a glyph: the legacy name for the six classic ones. |
| 271 | pub fn reaction_type_for(glyph: &str) -> String { |
| 272 | let bare = glyph.trim_end_matches('\u{FE0F}'); |
| 273 | ["like", "heart", "laugh", "surprised", "sad", "angry"] |
| 274 | .into_iter() |
| 275 | .find(|name| reaction_label(name) == bare) |
| 276 | .map_or_else(|| bare.to_owned(), str::to_owned) |
| 277 | } |
| 278 | |
| 279 | pub fn reaction_chips(reactions: &[ReactionInfo], my_user_id: Option<&str>) -> Vec<ReactionChip> { |
| 280 | let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); |
| 281 | let mut mine: BTreeMap<&str, bool> = BTreeMap::new(); |
| 282 | let mut order: Vec<&str> = Vec::new(); |
| 283 | for reaction in reactions { |
| 284 | let entry = counts.entry(reaction.reaction_type.as_str()).or_insert(0); |
| 285 | if *entry == 0 { |
| 286 | order.push(reaction.reaction_type.as_str()); |
| 287 | } |
| 288 | *entry += 1; |
| 289 | if my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id { |
| 290 | mine.insert(reaction.reaction_type.as_str(), true); |
| 291 | } |
| 292 | } |
| 293 | order |
| 294 | .into_iter() |
| 295 | .map(|reaction_type| ReactionChip { |
| 296 | reaction_type: reaction_type.to_owned(), |
| 297 | label: reaction_label(reaction_type), |
| 298 | count: counts[reaction_type], |
| 299 | mine: mine.contains_key(reaction_type), |
| 300 | }) |
| 301 | .collect() |
| 302 | } |
| 303 | |
| 304 | const REPLY_EXCERPT_CHARS: usize = 90; |
| 305 | |
| 306 | pub fn message_text(record: &MessageRecord) -> String { |
| 307 | let own_spans: Vec<Span> = message_spans(record) |
| 308 | .into_iter() |
| 309 | .filter(|span| !matches!(span, Span::Quote(_))) |
| 310 | .collect(); |
| 311 | strip_image_placeholders(layout_blocks(&own_spans)) |
| 312 | .into_iter() |
| 313 | .filter_map(|block| block.markdown()) |
| 314 | .collect::<Vec<_>>() |
| 315 | .join("\n") |
| 316 | } |
| 317 | |
| 318 | pub fn reply_excerpt(record: &MessageRecord) -> String { |
| 319 | let own_spans: Vec<Span> = message_spans(record) |
| 320 | .into_iter() |
| 321 | .filter(|span| !matches!(span, Span::Quote(_))) |
| 322 | .collect(); |
| 323 | let text = strip_image_placeholders(layout_blocks(&own_spans)) |
| 324 | .into_iter() |
| 325 | .find_map(|block| block.first_line()) |
| 326 | .unwrap_or_default(); |
| 327 | let first_line = text.lines().map(str::trim).find(|line| !line.is_empty()); |
| 328 | let excerpt = match first_line { |
| 329 | Some(line) => line.to_owned(), |
| 330 | None if !images(record).is_empty() => "Image".to_owned(), |
| 331 | None => files(record) |
| 332 | .into_iter() |
| 333 | .next() |
| 334 | .map_or_else(|| "Message".to_owned(), |card| card.name), |
| 335 | }; |
| 336 | if excerpt.chars().count() > REPLY_EXCERPT_CHARS { |
| 337 | let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect(); |
| 338 | format!("{}...", cut.trim_end()) |
| 339 | } else { |
| 340 | excerpt |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | pub struct RowContext { |
| 345 | pub offset: FixedOffset, |
| 346 | pub today: NaiveDate, |
| 347 | pub my_user_id: Option<String>, |
| 348 | } |
| 349 | |
| 350 | pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow { |
| 351 | let local = record.created_at.with_timezone(&context.offset); |
| 352 | let images = images(record); |
| 353 | let blocks = if record.deleted { |
| 354 | vec![Block::Paragraph(Inline::plain(DELETED_TEXT))] |
| 355 | } else { |
| 356 | layout_blocks(&message_spans(record)) |
| 357 | }; |
| 358 | let blocks = if images.is_empty() { |
| 359 | blocks |
| 360 | } else { |
| 361 | strip_image_placeholders(blocks) |
| 362 | }; |
| 363 | MessageRow { |
| 364 | key: record.message_id.clone(), |
| 365 | sender_id: record.sender_id.clone(), |
| 366 | created_at: record.created_at, |
| 367 | series: Series::default(), |
| 368 | card: false, |
| 369 | author: record |
| 370 | .sender_name |
| 371 | .clone() |
| 372 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()), |
| 373 | time: clock_label(record.created_at, context.offset), |
| 374 | day_header: Some(format::day_label(local.date_naive(), context.today)), |
| 375 | blocks, |
| 376 | edited: record.edited_at.is_some() && !record.deleted, |
| 377 | deleted: record.deleted, |
| 378 | reactions: reaction_chips(&reactions(record), context.my_user_id.as_deref()), |
| 379 | images, |
| 380 | local_images: Vec::new(), |
| 381 | files: files(record), |
| 382 | reply_count: None, |
| 383 | new_marker: false, |
| 384 | reply_faces: Vec::new(), |
| 385 | last_reply_time: None, |
| 386 | open_thread: None, |
| 387 | is_reply: record.reply_to_id.is_some(), |
| 388 | delivery: Delivery::Delivered, |
| 389 | receipt: Receipt::Hidden, |
| 390 | own: context.my_user_id.is_some() && record.sender_id == context.my_user_id, |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> { |
| 395 | let mut rows = Vec::with_capacity(records.len() + 1); |
| 396 | if has_older { |
| 397 | rows.push(Row::LoadOlder); |
| 398 | } |
| 399 | let mut previous_day: Option<NaiveDate> = None; |
| 400 | for record in records { |
| 401 | let mut row = message_row(record, context); |
| 402 | let day = record |
| 403 | .created_at |
| 404 | .with_timezone(&context.offset) |
| 405 | .date_naive(); |
| 406 | if previous_day == Some(day) { |
| 407 | row.day_header = None; |
| 408 | } |
| 409 | previous_day = Some(day); |
| 410 | rows.push(Row::Message(Box::new(row))); |
| 411 | } |
| 412 | assign_series(&mut rows); |
| 413 | rows |
| 414 | } |
| 415 | |
| 416 | pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> { |
| 417 | let mut threads: Vec<Thread> = Vec::new(); |
| 418 | let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new(); |
| 419 | for record in records.iter().filter(|record| record.reply_to_id.is_none()) { |
| 420 | index_by_root.insert(record.message_id.as_str(), threads.len()); |
| 421 | threads.push(Thread { |
| 422 | root_id: record.message_id.clone(), |
| 423 | reply_ids: Vec::new(), |
| 424 | }); |
| 425 | } |
| 426 | for record in records { |
| 427 | let Some(root_id) = record.reply_to_id.as_deref() else { |
| 428 | continue; |
| 429 | }; |
| 430 | if let Some(&index) = index_by_root.get(root_id) { |
| 431 | threads[index].reply_ids.push(record.message_id.clone()); |
| 432 | } |
| 433 | } |
| 434 | threads |
| 435 | } |
| 436 | |
| 437 | fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> { |
| 438 | thread |
| 439 | .reply_ids |
| 440 | .iter() |
| 441 | .chain(std::iter::once(&thread.root_id)) |
| 442 | .filter_map(|id| by_id.get(id.as_str())) |
| 443 | .map(|record| record.created_at) |
| 444 | .max() |
| 445 | .unwrap_or_default() |
| 446 | } |
| 447 | |
| 448 | pub fn thread_list_rows( |
| 449 | records: &[MessageRecord], |
| 450 | context: &RowContext, |
| 451 | has_older: bool, |
| 452 | ) -> Vec<Row> { |
| 453 | let by_id: BTreeMap<&str, &MessageRecord> = records |
| 454 | .iter() |
| 455 | .map(|record| (record.message_id.as_str(), record)) |
| 456 | .collect(); |
| 457 | let mut threads = group_threads(records); |
| 458 | threads.sort_by_key(|thread| last_activity(thread, &by_id)); |
| 459 | let mut rows = Vec::with_capacity(threads.len() + 1); |
| 460 | if has_older { |
| 461 | rows.push(Row::LoadOlder); |
| 462 | } |
| 463 | let mut previous_day: Option<NaiveDate> = None; |
| 464 | for thread in threads { |
| 465 | let Some(root) = by_id.get(thread.root_id.as_str()) else { |
| 466 | continue; |
| 467 | }; |
| 468 | let mut row = message_row(root, context); |
| 469 | let day = last_activity(&thread, &by_id) |
| 470 | .with_timezone(&context.offset) |
| 471 | .date_naive(); |
| 472 | row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today)); |
| 473 | previous_day = Some(day); |
| 474 | row.card = true; |
| 475 | row.time = format::post_time_label(root.created_at, context.today, context.offset); |
| 476 | row.reply_count = Some(thread.reply_ids.len()); |
| 477 | let replies: Vec<&&MessageRecord> = thread |
| 478 | .reply_ids |
| 479 | .iter() |
| 480 | .filter_map(|id| by_id.get(id.as_str())) |
| 481 | .collect(); |
| 482 | for reply in &replies { |
| 483 | let face = Face { |
| 484 | user_id: reply.sender_id.clone(), |
| 485 | name: reply |
| 486 | .sender_name |
| 487 | .clone() |
| 488 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()), |
| 489 | }; |
| 490 | if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) { |
| 491 | row.reply_faces.push(face); |
| 492 | } |
| 493 | } |
| 494 | row.last_reply_time = replies |
| 495 | .iter() |
| 496 | .map(|reply| reply.created_at) |
| 497 | .max() |
| 498 | .map(|time| { |
| 499 | let local = time.with_timezone(&context.offset); |
| 500 | format!( |
| 501 | "{} {}", |
| 502 | format::day_label(local.date_naive(), context.today), |
| 503 | clock_label(time, context.offset) |
| 504 | ) |
| 505 | }); |
| 506 | row.open_thread = Some(thread.root_id.clone()); |
| 507 | rows.push(Row::Message(Box::new(row))); |
| 508 | } |
| 509 | rows |
| 510 | } |
| 511 | |
| 512 | pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> { |
| 513 | let members: Vec<MessageRecord> = records |
| 514 | .iter() |
| 515 | .filter(|record| { |
| 516 | record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id) |
| 517 | }) |
| 518 | .cloned() |
| 519 | .collect(); |
| 520 | flat_rows(&members, context, false) |
| 521 | } |
| 522 | |
| 523 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 524 | pub struct Splice { |
| 525 | pub range: Range<usize>, |
| 526 | pub count: usize, |
| 527 | } |
| 528 | |
| 529 | pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> { |
| 530 | if old == new { |
| 531 | return None; |
| 532 | } |
| 533 | let prefix = old |
| 534 | .iter() |
| 535 | .zip(new) |
| 536 | .take_while(|(left, right)| left == right) |
| 537 | .count(); |
| 538 | let suffix = old[prefix..] |
| 539 | .iter() |
| 540 | .rev() |
| 541 | .zip(new[prefix..].iter().rev()) |
| 542 | .take_while(|(left, right)| left == right) |
| 543 | .count(); |
| 544 | Some(Splice { |
| 545 | range: prefix..old.len() - suffix, |
| 546 | count: new.len() - prefix - suffix, |
| 547 | }) |
| 548 | } |
| 549 | |
| 550 | pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> { |
| 551 | let prefix = old |
| 552 | .iter() |
| 553 | .zip(new) |
| 554 | .take_while(|(left, right)| left.key() == right.key()) |
| 555 | .count(); |
| 556 | let suffix = old[prefix..] |
| 557 | .iter() |
| 558 | .rev() |
| 559 | .zip(new[prefix..].iter().rev()) |
| 560 | .take_while(|(left, right)| left.key() == right.key()) |
| 561 | .count(); |
| 562 | let mut changed: Vec<usize> = (0..prefix) |
| 563 | .filter(|&index| old[index] != new[index]) |
| 564 | .collect(); |
| 565 | changed.extend((0..suffix).filter_map(|offset| { |
| 566 | let old_index = old.len() - 1 - offset; |
| 567 | let new_index = new.len() - 1 - offset; |
| 568 | (old[old_index] != new[new_index]).then_some(new_index) |
| 569 | })); |
| 570 | changed |
| 571 | } |
| 572 | |
| 573 | #[cfg(test)] |
| 574 | mod tests { |
| 575 | use chrono::TimeZone; |
| 576 | |
| 577 | use super::*; |
| 578 | |
| 579 | fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord { |
| 580 | MessageRecord { |
| 581 | conversation_id: "c".into(), |
| 582 | message_id: id.into(), |
| 583 | reply_to_id: reply_to.map(str::to_owned), |
| 584 | sender_id: Some("u".into()), |
| 585 | sender_name: Some("Author".into()), |
| 586 | created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(), |
| 587 | edited_at: None, |
| 588 | deleted: false, |
| 589 | body_html: format!("<p>text {id}</p>"), |
| 590 | attachments_json: "[]".into(), |
| 591 | reactions_json: "[]".into(), |
| 592 | mentions_json: "[]".into(), |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | #[test] |
| 597 | fn reaction_type_maps_classic_glyphs_to_names() { |
| 598 | assert_eq!(reaction_type_for("\u{1F44D}"), "like"); |
| 599 | assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart"); |
| 600 | assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}"); |
| 601 | } |
| 602 | |
| 603 | #[test] |
| 604 | fn reply_excerpt_uses_the_first_line_or_the_attachment() { |
| 605 | let mut text = record("a", None, 8, 6); |
| 606 | text.body_html = "<p>first line</p><p>second</p>".into(); |
| 607 | assert_eq!(reply_excerpt(&text), "first line"); |
| 608 | let mut quoted = record("q", None, 8, 6); |
| 609 | quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into(); |
| 610 | assert_eq!(reply_excerpt("ed), "my answer"); |
| 611 | let mut image = record("b", None, 8, 6); |
| 612 | image.body_html = "<img src=\"u\">".into(); |
| 613 | assert_eq!(reply_excerpt(&image), "Image"); |
| 614 | let mut long = record("c", None, 8, 6); |
| 615 | long.body_html = format!("<p>{}</p>", "x".repeat(200)); |
| 616 | assert!(reply_excerpt(&long).ends_with("...")); |
| 617 | assert_eq!( |
| 618 | reply_excerpt(&long).chars().count(), |
| 619 | REPLY_EXCERPT_CHARS + 3 |
| 620 | ); |
| 621 | } |
| 622 | |
| 623 | fn context() -> RowContext { |
| 624 | RowContext { |
| 625 | offset: FixedOffset::east_opt(0).unwrap(), |
| 626 | today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(), |
| 627 | my_user_id: None, |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | fn keys(rows: &[Row]) -> Vec<String> { |
| 632 | rows.iter().map(|row| row.key().to_owned()).collect() |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn day_header_only_on_first_message_of_a_day() { |
| 637 | let records = vec![ |
| 638 | record("a", None, 8, 6), |
| 639 | record("b", None, 9, 6), |
| 640 | record("c", None, 9, 7), |
| 641 | ]; |
| 642 | let rows = flat_rows(&records, &context(), false); |
| 643 | let headers: Vec<Option<String>> = rows |
| 644 | .iter() |
| 645 | .map(|row| match row { |
| 646 | Row::Message(message) => message.day_header.clone(), |
| 647 | Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None, |
| 648 | }) |
| 649 | .collect(); |
| 650 | assert_eq!( |
| 651 | headers, |
| 652 | vec![Some("Yesterday".into()), None, Some("Today".into())] |
| 653 | ); |
| 654 | } |
| 655 | |
| 656 | #[test] |
| 657 | fn load_older_row_only_when_more_exists() { |
| 658 | let records = vec![record("a", None, 8, 6)]; |
| 659 | assert_eq!( |
| 660 | keys(&flat_rows(&records, &context(), true))[0], |
| 661 | LOAD_OLDER_KEY |
| 662 | ); |
| 663 | assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]); |
| 664 | } |
| 665 | |
| 666 | #[test] |
| 667 | fn threads_group_replies_by_root() { |
| 668 | let records = vec![ |
| 669 | record("r1", None, 8, 6), |
| 670 | record("r2", None, 9, 6), |
| 671 | record("x1", Some("r1"), 10, 6), |
| 672 | record("x2", Some("r1"), 11, 6), |
| 673 | record("orphan", Some("missing"), 12, 6), |
| 674 | ]; |
| 675 | let threads = group_threads(&records); |
| 676 | assert_eq!(threads.len(), 2); |
| 677 | assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]); |
| 678 | assert!(threads[1].reply_ids.is_empty()); |
| 679 | } |
| 680 | |
| 681 | #[test] |
| 682 | fn thread_list_orders_by_last_activity_with_reply_count() { |
| 683 | let records = vec![ |
| 684 | record("r1", None, 8, 6), |
| 685 | record("r2", None, 9, 6), |
| 686 | record("x1", Some("r1"), 10, 6), |
| 687 | ]; |
| 688 | let rows = thread_list_rows(&records, &context(), false); |
| 689 | assert_eq!(keys(&rows), vec!["r2", "r1"]); |
| 690 | let Row::Message(last) = &rows[1] else { |
| 691 | panic!("message expected") |
| 692 | }; |
| 693 | assert_eq!(last.reply_count, Some(1)); |
| 694 | assert_eq!(last.open_thread.as_deref(), Some("r1")); |
| 695 | } |
| 696 | |
| 697 | #[test] |
| 698 | fn thread_view_has_root_then_replies() { |
| 699 | let records = vec![ |
| 700 | record("r1", None, 8, 6), |
| 701 | record("r2", None, 9, 6), |
| 702 | record("x1", Some("r1"), 10, 6), |
| 703 | ]; |
| 704 | assert_eq!( |
| 705 | keys(&thread_rows(&records, "r1", &context())), |
| 706 | vec!["r1", "x1"] |
| 707 | ); |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn reactions_are_counted_in_first_seen_order() { |
| 712 | let reaction = |kind: &str| ReactionInfo { |
| 713 | reaction_type: kind.into(), |
| 714 | user_id: None, |
| 715 | user_name: None, |
| 716 | }; |
| 717 | let chips = reaction_chips( |
| 718 | &[reaction("heart"), reaction("like"), reaction("heart")], |
| 719 | None, |
| 720 | ); |
| 721 | assert_eq!(chips.len(), 2); |
| 722 | assert_eq!(chips[0].count, 2); |
| 723 | assert_eq!(chips[1].label, reaction_label("like")); |
| 724 | } |
| 725 | |
| 726 | fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord { |
| 727 | let mut record = record(id, None, hour, day); |
| 728 | record.sender_id = Some(sender.into()); |
| 729 | record.created_at = Utc |
| 730 | .with_ymd_and_hms(2026, 10, day, hour, minute, 0) |
| 731 | .unwrap(); |
| 732 | record |
| 733 | } |
| 734 | |
| 735 | fn series_of(rows: &[Row]) -> Vec<(bool, bool)> { |
| 736 | rows.iter() |
| 737 | .filter_map(|row| match row { |
| 738 | Row::Message(message) => Some((message.series.has_prev, message.series.has_next)), |
| 739 | Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None, |
| 740 | }) |
| 741 | .collect() |
| 742 | } |
| 743 | |
| 744 | #[test] |
| 745 | fn series_joins_same_sender_within_five_minutes() { |
| 746 | let records = vec![ |
| 747 | record_by("a", "ada", 9, 0, 7), |
| 748 | record_by("b", "ada", 9, 4, 7), |
| 749 | record_by("c", "ada", 9, 20, 7), |
| 750 | record_by("d", "bob", 9, 21, 7), |
| 751 | record_by("e", "ada", 9, 22, 7), |
| 752 | ]; |
| 753 | let rows = flat_rows(&records, &context(), false); |
| 754 | assert_eq!( |
| 755 | series_of(&rows), |
| 756 | vec![ |
| 757 | (false, true), |
| 758 | (true, false), |
| 759 | (false, false), |
| 760 | (false, false), |
| 761 | (false, false) |
| 762 | ] |
| 763 | ); |
| 764 | } |
| 765 | |
| 766 | #[test] |
| 767 | fn series_window_ends_exactly_at_the_gap_constant() { |
| 768 | let gap = SERIES_GAP_MINUTES as u32; |
| 769 | let records = vec![ |
| 770 | record_by("a", "ada", 9, 0, 7), |
| 771 | record_by("b", "ada", 9, gap - 1, 7), |
| 772 | record_by("c", "ada", 9, 2 * gap - 1 + gap, 7), |
| 773 | ]; |
| 774 | let rows = flat_rows(&records, &context(), false); |
| 775 | assert_eq!( |
| 776 | series_of(&rows), |
| 777 | vec![(false, true), (true, false), (false, false)] |
| 778 | ); |
| 779 | } |
| 780 | |
| 781 | #[test] |
| 782 | fn series_breaks_at_a_new_day() { |
| 783 | let records = vec![ |
| 784 | record_by("a", "ada", 23, 58, 6), |
| 785 | record_by("b", "ada", 0, 1, 7), |
| 786 | ]; |
| 787 | let rows = flat_rows(&records, &context(), false); |
| 788 | assert_eq!(series_of(&rows), vec![(false, false), (false, false)]); |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn thread_list_rows_never_join() { |
| 793 | let records = vec![ |
| 794 | record_by("a", "ada", 9, 0, 7), |
| 795 | record_by("b", "ada", 9, 1, 7), |
| 796 | ]; |
| 797 | let rows = thread_list_rows(&records, &context(), false); |
| 798 | assert_eq!(series_of(&rows), vec![(false, false), (false, false)]); |
| 799 | } |
| 800 | |
| 801 | fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] { |
| 802 | let corners = bubble_corners(own, Series { has_prev, has_next }); |
| 803 | [ |
| 804 | corners.top_left, |
| 805 | corners.top_right, |
| 806 | corners.bottom_right, |
| 807 | corners.bottom_left, |
| 808 | ] |
| 809 | } |
| 810 | |
| 811 | #[test] |
| 812 | fn corners_match_the_mockup_for_other_senders() { |
| 813 | assert_eq!(corners(false, false, false), [4., 14., 14., 14.]); |
| 814 | assert_eq!(corners(false, false, true), [4., 14., 14., 4.]); |
| 815 | assert_eq!(corners(false, true, true), [4., 14., 14., 4.]); |
| 816 | assert_eq!(corners(false, true, false), [4., 14., 14., 14.]); |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn corners_match_the_mockup_for_own_messages() { |
| 821 | assert_eq!(corners(true, false, false), [14., 4., 4., 14.]); |
| 822 | assert_eq!(corners(true, false, true), [14., 14., 4., 14.]); |
| 823 | assert_eq!(corners(true, true, true), [14., 4., 4., 14.]); |
| 824 | assert_eq!(corners(true, true, false), [14., 4., 14., 14.]); |
| 825 | } |
| 826 | |
| 827 | #[test] |
| 828 | fn own_reaction_is_marked() { |
| 829 | let reaction = |user: &str| ReactionInfo { |
| 830 | reaction_type: "like".into(), |
| 831 | user_id: Some(user.into()), |
| 832 | user_name: None, |
| 833 | }; |
| 834 | let chips = reaction_chips(&[reaction("x"), reaction("me")], Some("me")); |
| 835 | assert!(chips[0].mine); |
| 836 | assert!(!reaction_chips(&[reaction("x")], Some("me"))[0].mine); |
| 837 | } |
| 838 | |
| 839 | fn strings(values: &[&str]) -> Vec<String> { |
| 840 | values.iter().map(|value| (*value).to_owned()).collect() |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn diff_detects_append_prepend_and_replace() { |
| 845 | let base = strings(&["a", "b"]); |
| 846 | assert_eq!(diff_keys(&base, &base), None); |
| 847 | assert_eq!( |
| 848 | diff_keys(&base, &strings(&["a", "b", "c"])), |
| 849 | Some(Splice { |
| 850 | range: 2..2, |
| 851 | count: 1 |
| 852 | }) |
| 853 | ); |
| 854 | assert_eq!( |
| 855 | diff_keys(&base, &strings(&["x", "a", "b"])), |
| 856 | Some(Splice { |
| 857 | range: 0..0, |
| 858 | count: 1 |
| 859 | }) |
| 860 | ); |
| 861 | assert_eq!( |
| 862 | diff_keys( |
| 863 | &strings(&["load-older", "a"]), |
| 864 | &strings(&["load-older", "x", "y", "a"]) |
| 865 | ), |
| 866 | Some(Splice { |
| 867 | range: 1..1, |
| 868 | count: 2 |
| 869 | }) |
| 870 | ); |
| 871 | assert_eq!( |
| 872 | diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])), |
| 873 | Some(Splice { |
| 874 | range: 0..1, |
| 875 | count: 0 |
| 876 | }) |
| 877 | ); |
| 878 | assert_eq!( |
| 879 | diff_keys(&base, &strings(&["x"])), |
| 880 | Some(Splice { |
| 881 | range: 0..2, |
| 882 | count: 1 |
| 883 | }) |
| 884 | ); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn changed_indices_find_edited_rows() { |
| 889 | let old = flat_rows( |
| 890 | &[record("a", None, 8, 6), record("b", None, 9, 6)], |
| 891 | &context(), |
| 892 | false, |
| 893 | ); |
| 894 | let mut edited = record("b", None, 9, 6); |
| 895 | edited.body_html = "<p>changed</p>".into(); |
| 896 | let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false); |
| 897 | assert_eq!(changed_indices(&old, &new), vec![1]); |
| 898 | } |
| 899 | } |