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