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