| 1 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 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 | JumboEmoji, jumbo_emoji, |
| 10 | AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ForwardHeader, ForwardInfo, |
| 11 | ImageRef, LinkPreview, forwards, |
| 12 | ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration, |
| 13 | forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes, |
| 14 | reactions, readable_text, translated_spans, |
| 15 | }; |
| 16 | |
| 17 | use crate::card_state::CardOverride; |
| 18 | use crate::format; |
| 19 | use crate::reaction_model::{Reactor, UNKNOWN_REACTOR}; |
| 20 | use crate::render::blocks::{Inline, strip_image_placeholders}; |
| 21 | use crate::render::{Block, layout_blocks}; |
| 22 | use crate::translation::{TranslationContext, TranslationLine}; |
| 23 | |
| 24 | const POST_VISIBLE_REPLIES: usize = 3; |
| 25 | |
| 26 | pub const LOAD_OLDER_KEY: &str = "load-older"; |
| 27 | pub const LOAD_NEWER_KEY: &str = "load-newer"; |
| 28 | const UNKNOWN_AUTHOR: &str = "Unknown"; |
| 29 | const DELETED_TEXT: &str = "Message deleted"; |
| 30 | const SERIES_GAP_MINUTES: i64 = 5; |
| 31 | const CORNER_RADIUS: f32 = 14.; |
| 32 | const CORNER_SERIES: f32 = 4.; |
| 33 | |
| 34 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 35 | pub struct ReactionChip { |
| 36 | pub reaction_type: String, |
| 37 | pub label: String, |
| 38 | pub click_glyph: String, |
| 39 | pub count: usize, |
| 40 | pub mine: bool, |
| 41 | pub reactors: Vec<Reactor>, |
| 42 | } |
| 43 | |
| 44 | impl ReactionChip { |
| 45 | pub fn glyph(&self) -> String { |
| 46 | reaction_glyph(&self.reaction_type) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 51 | pub struct Series { |
| 52 | pub has_prev: bool, |
| 53 | pub has_next: bool, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 57 | pub struct Corners { |
| 58 | pub top_left: f32, |
| 59 | pub top_right: f32, |
| 60 | pub bottom_right: f32, |
| 61 | pub bottom_left: f32, |
| 62 | } |
| 63 | |
| 64 | pub fn bubble_corners(own: bool, series: Series) -> Corners { |
| 65 | let joined = |joined: bool| if joined { CORNER_SERIES } else { CORNER_RADIUS }; |
| 66 | if own { |
| 67 | Corners { |
| 68 | top_left: CORNER_RADIUS, |
| 69 | top_right: joined(series.has_prev), |
| 70 | bottom_right: joined(series.has_next), |
| 71 | bottom_left: CORNER_RADIUS, |
| 72 | } |
| 73 | } else { |
| 74 | Corners { |
| 75 | top_left: joined(series.has_prev), |
| 76 | top_right: CORNER_RADIUS, |
| 77 | bottom_right: CORNER_RADIUS, |
| 78 | bottom_left: joined(series.has_next), |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 84 | pub enum Receipt { |
| 85 | #[default] |
| 86 | Hidden, |
| 87 | Pending, |
| 88 | Sent, |
| 89 | Read, |
| 90 | } |
| 91 | |
| 92 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 93 | pub enum ScheduledState { |
| 94 | Waiting, |
| 95 | DeliveryFailed, |
| 96 | ChangeFailed, |
| 97 | } |
| 98 | |
| 99 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 100 | pub enum Delivery { |
| 101 | Delivered, |
| 102 | Sending, |
| 103 | Failed(String), |
| 104 | Scheduled(ScheduledState), |
| 105 | } |
| 106 | |
| 107 | /// An image of a message that is still being sent, shown from its local bytes. |
| 108 | #[derive(Debug, Clone, PartialEq)] |
| 109 | pub struct LocalImage { |
| 110 | pub image: Arc<Image>, |
| 111 | pub size: Option<(u32, u32)>, |
| 112 | } |
| 113 | |
| 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 115 | pub enum CallIcon { |
| 116 | Call, |
| 117 | Missed, |
| 118 | Video, |
| 119 | } |
| 120 | |
| 121 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 122 | pub struct CallCard { |
| 123 | pub title: &'static str, |
| 124 | pub detail: String, |
| 125 | pub icon: CallIcon, |
| 126 | pub missed: bool, |
| 127 | pub started: bool, |
| 128 | } |
| 129 | |
| 130 | #[derive(Debug, Clone, PartialEq)] |
| 131 | pub struct MessageRow { |
| 132 | pub key: String, |
| 133 | pub conversation_id: String, |
| 134 | pub author: String, |
| 135 | pub sender_id: Option<String>, |
| 136 | pub application_id: Option<String>, |
| 137 | pub created_at: DateTime<Utc>, |
| 138 | pub series: Series, |
| 139 | pub time: String, |
| 140 | pub day_header: Option<String>, |
| 141 | pub blocks: Vec<Block>, |
| 142 | pub jumbo: Option<Vec<JumboEmoji>>, |
| 143 | pub edited: bool, |
| 144 | pub deleted: bool, |
| 145 | pub reactions: Vec<ReactionChip>, |
| 146 | pub images: Vec<ImageRef>, |
| 147 | pub local_images: Vec<LocalImage>, |
| 148 | pub files: Vec<FileCard>, |
| 149 | pub link_preview: Option<LinkPreview>, |
| 150 | pub meeting_link: Option<String>, |
| 151 | pub adaptive_cards: Vec<AdaptiveCard>, |
| 152 | pub subject: Option<String>, |
| 153 | pub new_marker: bool, |
| 154 | pub reply_root: Option<String>, |
| 155 | pub delivery: Delivery, |
| 156 | pub own: bool, |
| 157 | pub receipt: Receipt, |
| 158 | pub forwarded: bool, |
| 159 | pub translation: Option<TranslationLine>, |
| 160 | pub call: Option<CallCard>, |
| 161 | } |
| 162 | |
| 163 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 164 | pub struct StartInfo { |
| 165 | pub title: String, |
| 166 | pub user_id: Option<String>, |
| 167 | } |
| 168 | |
| 169 | pub const START_KEY: &str = "conversation-start"; |
| 170 | |
| 171 | #[derive(Debug, Clone, PartialEq)] |
| 172 | pub enum Row { |
| 173 | LoadOlder, |
| 174 | LoadNewer, |
| 175 | Start(StartInfo), |
| 176 | Skeleton(Skeleton), |
| 177 | Message(Box<MessageRow>), |
| 178 | Post(Box<PostRow>), |
| 179 | } |
| 180 | |
| 181 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 182 | pub struct Skeleton { |
| 183 | pub key: &'static str, |
| 184 | pub own: bool, |
| 185 | pub width_ratio: f32, |
| 186 | pub lines: u8, |
| 187 | } |
| 188 | |
| 189 | const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [ |
| 190 | Skeleton { |
| 191 | key: "skeleton-0", |
| 192 | own: false, |
| 193 | width_ratio: 0.42, |
| 194 | lines: 1, |
| 195 | }, |
| 196 | Skeleton { |
| 197 | key: "skeleton-1", |
| 198 | own: true, |
| 199 | width_ratio: 0.3, |
| 200 | lines: 1, |
| 201 | }, |
| 202 | Skeleton { |
| 203 | key: "skeleton-2", |
| 204 | own: true, |
| 205 | width_ratio: 0.48, |
| 206 | lines: 2, |
| 207 | }, |
| 208 | Skeleton { |
| 209 | key: "skeleton-3", |
| 210 | own: false, |
| 211 | width_ratio: 0.26, |
| 212 | lines: 1, |
| 213 | }, |
| 214 | ]; |
| 215 | |
| 216 | pub fn placeholder_rows() -> Vec<Row> { |
| 217 | SKELETON_PLACEHOLDERS |
| 218 | .into_iter() |
| 219 | .map(Row::Skeleton) |
| 220 | .collect() |
| 221 | } |
| 222 | |
| 223 | fn sender_key(row: &MessageRow) -> &str { |
| 224 | row.sender_id.as_deref().unwrap_or(&row.author) |
| 225 | } |
| 226 | |
| 227 | fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool { |
| 228 | previous.call.is_none() |
| 229 | && next.call.is_none() |
| 230 | && next.day_header.is_none() |
| 231 | && !next.new_marker |
| 232 | && sender_key(previous) == sender_key(next) |
| 233 | && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES) |
| 234 | && next.created_at >= previous.created_at |
| 235 | } |
| 236 | |
| 237 | pub fn assign_series(rows: &mut [Row]) { |
| 238 | let mut previous: Option<usize> = None; |
| 239 | for index in 0..rows.len() { |
| 240 | let Row::Message(_) = &rows[index] else { |
| 241 | previous = None; |
| 242 | continue; |
| 243 | }; |
| 244 | if let Some(before) = previous { |
| 245 | let joined = match (&rows[before], &rows[index]) { |
| 246 | (Row::Message(a), Row::Message(b)) => continues_series(a, b), |
| 247 | _ => false, |
| 248 | }; |
| 249 | if joined { |
| 250 | if let Row::Message(a) = &mut rows[before] { |
| 251 | a.series.has_next = true; |
| 252 | } |
| 253 | if let Row::Message(b) = &mut rows[index] { |
| 254 | b.series.has_prev = true; |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | previous = Some(index); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | impl Row { |
| 263 | pub fn key(&self) -> &str { |
| 264 | match self { |
| 265 | Row::LoadOlder => LOAD_OLDER_KEY, |
| 266 | Row::LoadNewer => LOAD_NEWER_KEY, |
| 267 | Row::Start(_) => START_KEY, |
| 268 | Row::Skeleton(skeleton) => skeleton.key, |
| 269 | Row::Message(message) => &message.key, |
| 270 | Row::Post(post) => &post.root.key, |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> { |
| 275 | match self { |
| 276 | Row::Message(message) => Box::new(std::iter::once(message.as_ref())), |
| 277 | Row::Post(post) => Box::new(post.messages()), |
| 278 | Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => { |
| 279 | Box::new(std::iter::empty()) |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | #[derive(Debug, Clone, PartialEq)] |
| 286 | pub struct PostRow { |
| 287 | pub root: MessageRow, |
| 288 | pub replies: Vec<MessageRow>, |
| 289 | pub hidden_reply_count: usize, |
| 290 | pub hidden_repliers: Vec<String>, |
| 291 | } |
| 292 | |
| 293 | impl PostRow { |
| 294 | pub fn local(root: MessageRow) -> Self { |
| 295 | PostRow { |
| 296 | root, |
| 297 | replies: Vec::new(), |
| 298 | hidden_reply_count: 0, |
| 299 | hidden_repliers: Vec::new(), |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | pub fn messages(&self) -> impl Iterator<Item = &MessageRow> { |
| 304 | std::iter::once(&self.root).chain(&self.replies) |
| 305 | } |
| 306 | |
| 307 | pub fn hidden_replies_label(&self) -> Option<String> { |
| 308 | (self.hidden_reply_count > 0) |
| 309 | .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers)) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | fn first_name(name: &str) -> &str { |
| 314 | name.split_whitespace().next().unwrap_or(name) |
| 315 | } |
| 316 | |
| 317 | pub fn replies_label(count: usize, repliers: &[String]) -> String { |
| 318 | let noun = if count == 1 { "reply" } else { "replies" }; |
| 319 | let mut names: Vec<&str> = Vec::new(); |
| 320 | for name in repliers.iter().map(|name| first_name(name)) { |
| 321 | if !names.contains(&name) { |
| 322 | names.push(name); |
| 323 | } |
| 324 | } |
| 325 | let people = match names.as_slice() { |
| 326 | [] => return format!("{count} {noun}"), |
| 327 | [only] => (*only).to_owned(), |
| 328 | [first, second] => format!("{first} and {second}"), |
| 329 | [first, second, third] => format!("{first}, {second} and {third}"), |
| 330 | [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()), |
| 331 | }; |
| 332 | format!("{count} {noun} from {people}") |
| 333 | } |
| 334 | |
| 335 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 336 | pub struct Thread { |
| 337 | pub root_id: String, |
| 338 | pub reply_ids: Vec<String>, |
| 339 | } |
| 340 | |
| 341 | pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String { |
| 342 | time.with_timezone(&offset).format("%H:%M").to_string() |
| 343 | } |
| 344 | |
| 345 | pub fn reaction_label(reaction_type: &str) -> String { |
| 346 | match reaction_type { |
| 347 | "like" => "\u{1F44D}".to_owned(), |
| 348 | "heart" => "\u{2764}".to_owned(), |
| 349 | "laugh" => "\u{1F606}".to_owned(), |
| 350 | "surprised" => "\u{1F62E}".to_owned(), |
| 351 | "sad" => "\u{1F641}".to_owned(), |
| 352 | "angry" => "\u{1F620}".to_owned(), |
| 353 | other => other.to_owned(), |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | pub fn reaction_glyph(reaction_type: &str) -> String { |
| 358 | let label = reaction_label(reaction_type); |
| 359 | let glyph = if label == reaction_type { |
| 360 | chatsvc::reaction_glyph_for_key(reaction_type).unwrap_or(label) |
| 361 | } else { |
| 362 | label |
| 363 | }; |
| 364 | glyph.trim_end_matches('\u{FE0F}').to_owned() |
| 365 | } |
| 366 | |
| 367 | fn same_reaction(left: &str, right: &str) -> bool { |
| 368 | crate::emoticons::without_tone(left) == crate::emoticons::without_tone(right) |
| 369 | } |
| 370 | |
| 371 | /// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported"). |
| 372 | pub fn api_reaction(glyph: &str) -> String { |
| 373 | match glyph { |
| 374 | "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(), |
| 375 | other => other.to_owned(), |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | /// The reaction type Teams uses for a glyph: the legacy name for the six classic ones. |
| 380 | pub fn reaction_type_for(glyph: &str) -> String { |
| 381 | let bare = glyph.trim_end_matches('\u{FE0F}'); |
| 382 | ["like", "heart", "laugh", "surprised", "sad", "angry"] |
| 383 | .into_iter() |
| 384 | .find(|name| reaction_label(name) == bare) |
| 385 | .map_or_else(|| bare.to_owned(), str::to_owned) |
| 386 | } |
| 387 | |
| 388 | const MAX_TONE_VARIANTS: usize = 3; |
| 389 | |
| 390 | pub type PendingReactions = HashMap<String, Vec<(String, bool)>>; |
| 391 | |
| 392 | fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool { |
| 393 | my_user_id.is_some() |
| 394 | && reaction.user_id.as_deref() == my_user_id |
| 395 | && same_reaction(&reaction_glyph(&reaction.reaction_type), wanted) |
| 396 | } |
| 397 | |
| 398 | /// The glyph of the own reaction that matches `glyph` regardless of skin tone. |
| 399 | pub fn own_reaction_glyph( |
| 400 | reactions: &[ReactionInfo], |
| 401 | glyph: &str, |
| 402 | my_user_id: Option<&str>, |
| 403 | ) -> Option<String> { |
| 404 | let wanted = reaction_glyph(glyph); |
| 405 | reactions |
| 406 | .iter() |
| 407 | .find(|reaction| is_own_reaction(reaction, &wanted, my_user_id)) |
| 408 | .map(|reaction| reaction_glyph(&reaction.reaction_type)) |
| 409 | } |
| 410 | |
| 411 | pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool { |
| 412 | let wanted = reaction_glyph(glyph); |
| 413 | reactions |
| 414 | .iter() |
| 415 | .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id)) |
| 416 | } |
| 417 | |
| 418 | pub fn set_own_reaction( |
| 419 | reactions: &mut Vec<ReactionInfo>, |
| 420 | glyph: &str, |
| 421 | my_user_id: Option<&str>, |
| 422 | present: bool, |
| 423 | now: DateTime<Utc>, |
| 424 | ) { |
| 425 | let wanted = reaction_glyph(glyph); |
| 426 | if !present { |
| 427 | reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id)); |
| 428 | } else if !has_own_reaction(reactions, glyph, my_user_id) { |
| 429 | reactions.push(ReactionInfo { |
| 430 | reaction_type: reaction_type_for(glyph), |
| 431 | user_id: my_user_id.map(str::to_owned), |
| 432 | user_name: Some("You".to_owned()), |
| 433 | created_at: Some(now), |
| 434 | }); |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | pub fn apply_pending_reactions( |
| 439 | reactions: &mut Vec<ReactionInfo>, |
| 440 | pending: Option<&Vec<(String, bool)>>, |
| 441 | my_user_id: Option<&str>, |
| 442 | now: DateTime<Utc>, |
| 443 | ) { |
| 444 | for (glyph, present) in pending.into_iter().flatten() { |
| 445 | set_own_reaction(reactions, glyph, my_user_id, *present, now); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> { |
| 450 | let my_user_id = context.my_user_id.as_deref(); |
| 451 | let mut chips: Vec<ReactionChip> = Vec::new(); |
| 452 | let mut variants: Vec<Vec<String>> = Vec::new(); |
| 453 | for reaction in reactions { |
| 454 | let glyph = reaction_glyph(&reaction.reaction_type); |
| 455 | let position = match chips |
| 456 | .iter() |
| 457 | .position(|chip| same_reaction(&chip.glyph(), &glyph)) |
| 458 | { |
| 459 | Some(position) => position, |
| 460 | None => { |
| 461 | chips.push(ReactionChip { |
| 462 | reaction_type: reaction.reaction_type.clone(), |
| 463 | label: String::new(), |
| 464 | click_glyph: crate::emoticons::with_tone(&glyph, context.skin_tone), |
| 465 | count: 0, |
| 466 | mine: false, |
| 467 | reactors: Vec::new(), |
| 468 | }); |
| 469 | variants.push(Vec::new()); |
| 470 | chips.len() - 1 |
| 471 | } |
| 472 | }; |
| 473 | let label = glyph; |
| 474 | let shown = &mut variants[position]; |
| 475 | if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) { |
| 476 | shown.push(label); |
| 477 | } |
| 478 | let chip = &mut chips[position]; |
| 479 | chip.count += 1; |
| 480 | chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id; |
| 481 | chip.reactors.push(Reactor { |
| 482 | user_id: reaction.user_id.clone(), |
| 483 | name: reactor_name(reaction, context), |
| 484 | created_at: reaction.created_at, |
| 485 | }); |
| 486 | } |
| 487 | for (chip, shown) in chips.iter_mut().zip(variants) { |
| 488 | chip.label = shown.concat(); |
| 489 | } |
| 490 | chips |
| 491 | } |
| 492 | |
| 493 | fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String { |
| 494 | reaction |
| 495 | .user_name |
| 496 | .clone() |
| 497 | .or_else(|| { |
| 498 | reaction |
| 499 | .user_id |
| 500 | .as_ref() |
| 501 | .and_then(|user_id| context.names.get(user_id).cloned()) |
| 502 | }) |
| 503 | .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned()) |
| 504 | } |
| 505 | |
| 506 | const REPLY_EXCERPT_CHARS: usize = 90; |
| 507 | |
| 508 | pub fn message_text(record: &MessageRecord) -> String { |
| 509 | let own_spans: Vec<Span> = message_spans(record) |
| 510 | .into_iter() |
| 511 | .filter(|span| !matches!(span, Span::Quote { .. })) |
| 512 | .collect(); |
| 513 | strip_image_placeholders(layout_blocks(&own_spans)) |
| 514 | .into_iter() |
| 515 | .filter_map(|block| block.markdown()) |
| 516 | .chain(forwarded_texts(record)) |
| 517 | .collect::<Vec<_>>() |
| 518 | .join("\n") |
| 519 | } |
| 520 | |
| 521 | /// The message as the composer edits it, formatting kept. |
| 522 | pub fn message_draft(record: &MessageRecord) -> Draft { |
| 523 | let own_spans: Vec<Span> = message_spans(record) |
| 524 | .into_iter() |
| 525 | .filter(|span| !matches!(span, Span::Quote { .. })) |
| 526 | .collect(); |
| 527 | Draft::from_spans(&own_spans).trimmed() |
| 528 | } |
| 529 | |
| 530 | pub fn reply_excerpt(record: &MessageRecord) -> String { |
| 531 | let own_spans: Vec<Span> = message_spans(record) |
| 532 | .into_iter() |
| 533 | .filter(|span| !matches!(span, Span::Quote { .. })) |
| 534 | .collect(); |
| 535 | let text = strip_image_placeholders(layout_blocks(&own_spans)) |
| 536 | .into_iter() |
| 537 | .find_map(|block| block.first_line()) |
| 538 | .unwrap_or_default(); |
| 539 | let first_line = text.lines().map(str::trim).find(|line| !line.is_empty()); |
| 540 | let excerpt = match first_line { |
| 541 | Some(line) => line.to_owned(), |
| 542 | None if let Some(line) = forwarded_texts(record) |
| 543 | .iter() |
| 544 | .flat_map(|text| text.lines()) |
| 545 | .map(str::trim) |
| 546 | .find(|line| !line.is_empty()) => |
| 547 | { |
| 548 | line.to_owned() |
| 549 | } |
| 550 | None if !images(record).is_empty() => "Image".to_owned(), |
| 551 | None if let Some(line) = card_texts(record) |
| 552 | .iter() |
| 553 | .flat_map(|text| text.lines()) |
| 554 | .next() => |
| 555 | { |
| 556 | line.to_owned() |
| 557 | } |
| 558 | None => files(record) |
| 559 | .into_iter() |
| 560 | .next() |
| 561 | .map_or_else(|| "Message".to_owned(), |card| card.name), |
| 562 | }; |
| 563 | if excerpt.chars().count() > REPLY_EXCERPT_CHARS { |
| 564 | let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect(); |
| 565 | format!("{}...", cut.trim_end()) |
| 566 | } else { |
| 567 | excerpt |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | pub struct RowContext { |
| 572 | pub offset: FixedOffset, |
| 573 | pub today: NaiveDate, |
| 574 | pub my_user_id: Option<String>, |
| 575 | pub names: HashMap<String, String>, |
| 576 | pub pending_reactions: PendingReactions, |
| 577 | pub card_overrides: HashMap<String, CardOverride>, |
| 578 | pub translation: TranslationContext, |
| 579 | pub skin_tone: u8, |
| 580 | } |
| 581 | |
| 582 | fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> { |
| 583 | let mut visible = reactions(record); |
| 584 | apply_pending_reactions( |
| 585 | &mut visible, |
| 586 | context.pending_reactions.get(&record.message_id), |
| 587 | context.my_user_id.as_deref(), |
| 588 | Utc::now(), |
| 589 | ); |
| 590 | visible |
| 591 | } |
| 592 | |
| 593 | pub fn call_card(event: &CallEvent, time: &str, my_user_id: Option<&str>) -> CallCard { |
| 594 | let missed = event.missed(my_user_id); |
| 595 | let detail = match (event.phase, event.duration_seconds) { |
| 596 | (CallPhase::Ended, Some(seconds)) if !missed => { |
| 597 | format!("{} \u{b7} {time}", format_duration(seconds)) |
| 598 | } |
| 599 | _ => time.to_owned(), |
| 600 | }; |
| 601 | CallCard { |
| 602 | title: event.title(missed), |
| 603 | detail, |
| 604 | icon: match (missed, event.call_type) { |
| 605 | (true, _) => CallIcon::Missed, |
| 606 | (false, CallType::Meeting) => CallIcon::Video, |
| 607 | (false, CallType::Call) => CallIcon::Call, |
| 608 | }, |
| 609 | missed, |
| 610 | started: event.phase == CallPhase::Started, |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | fn call_row(record: &MessageRecord, event: &CallEvent, context: &RowContext) -> MessageRow { |
| 615 | let my_user_id = context.my_user_id.as_deref(); |
| 616 | let time = clock_label(record.created_at, context.offset); |
| 617 | let author = event |
| 618 | .initiator_name |
| 619 | .clone() |
| 620 | .or_else(|| { |
| 621 | event |
| 622 | .initiator_id |
| 623 | .as_ref() |
| 624 | .and_then(|user_id| context.names.get(user_id).cloned()) |
| 625 | }) |
| 626 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()); |
| 627 | MessageRow { |
| 628 | key: record.message_id.clone(), |
| 629 | conversation_id: record.conversation_id.clone(), |
| 630 | sender_id: event.initiator_id.clone(), |
| 631 | application_id: None, |
| 632 | created_at: record.created_at, |
| 633 | series: Series::default(), |
| 634 | author, |
| 635 | day_header: Some(format::day_label( |
| 636 | record |
| 637 | .created_at |
| 638 | .with_timezone(&context.offset) |
| 639 | .date_naive(), |
| 640 | context.today, |
| 641 | )), |
| 642 | blocks: Vec::new(), |
| 643 | jumbo: None, |
| 644 | edited: false, |
| 645 | deleted: false, |
| 646 | reactions: Vec::new(), |
| 647 | images: Vec::new(), |
| 648 | local_images: Vec::new(), |
| 649 | files: Vec::new(), |
| 650 | link_preview: None, |
| 651 | meeting_link: None, |
| 652 | adaptive_cards: Vec::new(), |
| 653 | subject: None, |
| 654 | new_marker: false, |
| 655 | reply_root: None, |
| 656 | delivery: Delivery::Delivered, |
| 657 | receipt: Receipt::Hidden, |
| 658 | own: event.initiated_by(my_user_id), |
| 659 | forwarded: false, |
| 660 | translation: None, |
| 661 | call: Some(call_card(event, &time, my_user_id)), |
| 662 | time, |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | const QUOTE_LINES: usize = 5; |
| 667 | |
| 668 | pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> { |
| 669 | let wanted: std::collections::HashSet<String> = records |
| 670 | .iter() |
| 671 | .flat_map(quotes) |
| 672 | .map(|quote| quote.message_id) |
| 673 | .collect(); |
| 674 | records |
| 675 | .iter() |
| 676 | .filter(|record| !record.deleted && wanted.contains(&record.message_id)) |
| 677 | .map(|record| { |
| 678 | let mut text = readable_text(record); |
| 679 | if text.is_empty() { |
| 680 | text = forwarded_texts(record).join("\n"); |
| 681 | } |
| 682 | let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect(); |
| 683 | let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n"); |
| 684 | if lines.len() > QUOTE_LINES { |
| 685 | shown.push_str(" …"); |
| 686 | } |
| 687 | (record.message_id.clone(), shown) |
| 688 | }) |
| 689 | .collect() |
| 690 | } |
| 691 | |
| 692 | fn forward_header(forward: &ForwardInfo, context: &RowContext) -> ForwardHeader { |
| 693 | ForwardHeader { |
| 694 | sender: forward |
| 695 | .sender_id |
| 696 | .as_ref() |
| 697 | .and_then(|user_id| context.names.get(user_id).cloned()), |
| 698 | time: forward |
| 699 | .sent_at |
| 700 | .map(|time| format::post_time_label(time, context.today, context.offset)), |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | /// User ids a row needs a name for beyond its author: original senders of forwards. |
| 705 | pub fn forward_sender_ids(records: &[MessageRecord]) -> Vec<String> { |
| 706 | let mut user_ids: Vec<String> = Vec::new(); |
| 707 | for user_id in records |
| 708 | .iter() |
| 709 | .flat_map(forwards) |
| 710 | .filter_map(|forward| forward.sender_id) |
| 711 | { |
| 712 | if !user_ids.contains(&user_id) { |
| 713 | user_ids.push(user_id); |
| 714 | } |
| 715 | } |
| 716 | user_ids |
| 717 | } |
| 718 | |
| 719 | pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow { |
| 720 | message_row_with(record, context, &HashMap::new()) |
| 721 | } |
| 722 | |
| 723 | fn message_row_with( |
| 724 | record: &MessageRecord, |
| 725 | context: &RowContext, |
| 726 | quoted: &HashMap<String, String>, |
| 727 | ) -> MessageRow { |
| 728 | if let Some(event) = call_event(record) { |
| 729 | return call_row(record, &event, context); |
| 730 | } |
| 731 | let local = record.created_at.with_timezone(&context.offset); |
| 732 | let images = images(record); |
| 733 | let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id; |
| 734 | let translation = context.translation.resolve(record, own); |
| 735 | let forward_header = |forward: &ForwardInfo| forward_header(forward, context); |
| 736 | let blocks = if record.deleted { |
| 737 | vec![Block::Paragraph(Inline::plain(DELETED_TEXT))] |
| 738 | } else if let Some(html) = &translation.translated_html { |
| 739 | layout_blocks(&translated_spans(record, html, &forward_header)) |
| 740 | } else { |
| 741 | layout_blocks(&linked_message_spans_with( |
| 742 | record, |
| 743 | &|id| quoted.get(id).cloned(), |
| 744 | &forward_header, |
| 745 | )) |
| 746 | }; |
| 747 | let blocks = if images.is_empty() { |
| 748 | blocks |
| 749 | } else { |
| 750 | strip_image_placeholders(blocks) |
| 751 | }; |
| 752 | MessageRow { |
| 753 | key: record.message_id.clone(), |
| 754 | conversation_id: record.conversation_id.clone(), |
| 755 | sender_id: record.sender_id.clone(), |
| 756 | application_id: record.sender_application_id.clone(), |
| 757 | created_at: record.created_at, |
| 758 | series: Series::default(), |
| 759 | author: record |
| 760 | .sender_name |
| 761 | .clone() |
| 762 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()), |
| 763 | time: clock_label(record.created_at, context.offset), |
| 764 | day_header: Some(format::day_label(local.date_naive(), context.today)), |
| 765 | blocks, |
| 766 | jumbo: (!record.deleted && !is_forwarded(record)) |
| 767 | .then(|| jumbo_emoji(&record.body_html)) |
| 768 | .flatten(), |
| 769 | edited: record.edited_at.is_some() && !record.deleted, |
| 770 | deleted: record.deleted, |
| 771 | reactions: reaction_chips(&visible_reactions(record, context), context), |
| 772 | images, |
| 773 | local_images: Vec::new(), |
| 774 | files: files(record), |
| 775 | link_preview: link_preview(record), |
| 776 | meeting_link: (!record.deleted) |
| 777 | .then(|| meeting_link_in_html(&record.body_html)) |
| 778 | .flatten(), |
| 779 | adaptive_cards: match context.card_overrides.get(&record.message_id) { |
| 780 | Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(), |
| 781 | _ => adaptive_cards(record), |
| 782 | }, |
| 783 | subject: record.subject.clone(), |
| 784 | new_marker: false, |
| 785 | reply_root: record.reply_to_id.clone(), |
| 786 | delivery: Delivery::Delivered, |
| 787 | receipt: Receipt::Hidden, |
| 788 | own, |
| 789 | forwarded: is_forwarded(record), |
| 790 | translation: translation.line, |
| 791 | call: None, |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | fn finished_call_ids(events: &[Option<CallEvent>]) -> HashSet<&str> { |
| 796 | events |
| 797 | .iter() |
| 798 | .flatten() |
| 799 | .filter(|event| event.phase == CallPhase::Ended) |
| 800 | .map(|event| event.call_id.as_str()) |
| 801 | .collect() |
| 802 | } |
| 803 | |
| 804 | fn is_open_start(event: &CallEvent, finished: &HashSet<&str>) -> bool { |
| 805 | event.phase == CallPhase::Started && !finished.contains(event.call_id.as_str()) |
| 806 | } |
| 807 | |
| 808 | pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> { |
| 809 | let mut rows = Vec::with_capacity(records.len() + 1); |
| 810 | if has_older { |
| 811 | rows.push(Row::LoadOlder); |
| 812 | } |
| 813 | let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect(); |
| 814 | let finished = finished_call_ids(&events); |
| 815 | let newest_open_start = events.iter().rposition(|event| { |
| 816 | event |
| 817 | .as_ref() |
| 818 | .is_some_and(|event| is_open_start(event, &finished)) |
| 819 | }); |
| 820 | let mut previous_day: Option<NaiveDate> = None; |
| 821 | let quoted = quoted_texts(records); |
| 822 | for (index, (record, event)) in records.iter().zip(&events).enumerate() { |
| 823 | let mut row = match event { |
| 824 | Some(event) |
| 825 | if event.phase == CallPhase::Started && !is_open_start(event, &finished) => |
| 826 | { |
| 827 | continue; |
| 828 | } |
| 829 | Some(event) => call_row(record, event, context), |
| 830 | None => message_row_with(record, context, "ed), |
| 831 | }; |
| 832 | if let Some(call) = row.call.as_mut() { |
| 833 | call.started &= newest_open_start == Some(index); |
| 834 | } |
| 835 | let day = record |
| 836 | .created_at |
| 837 | .with_timezone(&context.offset) |
| 838 | .date_naive(); |
| 839 | if previous_day == Some(day) { |
| 840 | row.day_header = None; |
| 841 | } |
| 842 | previous_day = Some(day); |
| 843 | rows.push(Row::Message(Box::new(row))); |
| 844 | } |
| 845 | assign_series(&mut rows); |
| 846 | rows |
| 847 | } |
| 848 | |
| 849 | pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> { |
| 850 | let mut threads: Vec<Thread> = Vec::new(); |
| 851 | let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new(); |
| 852 | for record in records.iter().filter(|record| record.reply_to_id.is_none()) { |
| 853 | index_by_root.insert(record.message_id.as_str(), threads.len()); |
| 854 | threads.push(Thread { |
| 855 | root_id: record.message_id.clone(), |
| 856 | reply_ids: Vec::new(), |
| 857 | }); |
| 858 | } |
| 859 | for record in records { |
| 860 | let Some(root_id) = record.reply_to_id.as_deref() else { |
| 861 | continue; |
| 862 | }; |
| 863 | if let Some(&index) = index_by_root.get(root_id) { |
| 864 | threads[index].reply_ids.push(record.message_id.clone()); |
| 865 | } |
| 866 | } |
| 867 | threads |
| 868 | } |
| 869 | |
| 870 | fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> { |
| 871 | thread |
| 872 | .reply_ids |
| 873 | .iter() |
| 874 | .chain(std::iter::once(&thread.root_id)) |
| 875 | .filter_map(|id| by_id.get(id.as_str())) |
| 876 | .map(|record| record.created_at) |
| 877 | .max() |
| 878 | .unwrap_or_default() |
| 879 | } |
| 880 | |
| 881 | fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow { |
| 882 | let mut row = message_row(record, context); |
| 883 | row.day_header = None; |
| 884 | row.time = format::post_time_label(record.created_at, context.today, context.offset); |
| 885 | row |
| 886 | } |
| 887 | |
| 888 | fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> { |
| 889 | let mut names: Vec<String> = Vec::new(); |
| 890 | for record in records { |
| 891 | let name = record |
| 892 | .sender_name |
| 893 | .clone() |
| 894 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()); |
| 895 | if !names.contains(&name) { |
| 896 | names.push(name); |
| 897 | } |
| 898 | } |
| 899 | names |
| 900 | } |
| 901 | |
| 902 | fn post_row( |
| 903 | root: &MessageRecord, |
| 904 | mut replies: Vec<&MessageRecord>, |
| 905 | context: &RowContext, |
| 906 | ) -> PostRow { |
| 907 | replies.sort_by_key(|reply| reply.created_at); |
| 908 | let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES); |
| 909 | PostRow { |
| 910 | root: post_message_row(root, context), |
| 911 | hidden_reply_count: hidden, |
| 912 | hidden_repliers: distinct_names(replies[..hidden].iter().copied()), |
| 913 | replies: replies[hidden..] |
| 914 | .iter() |
| 915 | .map(|reply| post_message_row(reply, context)) |
| 916 | .collect(), |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | pub fn thread_list_rows( |
| 921 | records: &[MessageRecord], |
| 922 | context: &RowContext, |
| 923 | has_older: bool, |
| 924 | ) -> Vec<Row> { |
| 925 | let by_id: BTreeMap<&str, &MessageRecord> = records |
| 926 | .iter() |
| 927 | .filter(|record| record.call_event_json.is_none()) |
| 928 | .map(|record| (record.message_id.as_str(), record)) |
| 929 | .collect(); |
| 930 | let mut threads = group_threads(records); |
| 931 | threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id))); |
| 932 | let mut rows: Vec<Row> = threads |
| 933 | .iter() |
| 934 | .filter_map(|thread| { |
| 935 | let root = by_id.get(thread.root_id.as_str())?; |
| 936 | let replies = thread |
| 937 | .reply_ids |
| 938 | .iter() |
| 939 | .filter_map(|id| by_id.get(id.as_str()).copied()) |
| 940 | .collect(); |
| 941 | Some(Row::Post(Box::new(post_row(root, replies, context)))) |
| 942 | }) |
| 943 | .collect(); |
| 944 | if has_older { |
| 945 | rows.push(Row::LoadOlder); |
| 946 | } |
| 947 | rows |
| 948 | } |
| 949 | |
| 950 | pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) { |
| 951 | for message in local { |
| 952 | let Some(root_id) = message.reply_root.clone() else { |
| 953 | rows.insert(0, Row::Post(Box::new(PostRow::local(message)))); |
| 954 | continue; |
| 955 | }; |
| 956 | let position = rows |
| 957 | .iter() |
| 958 | .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id)); |
| 959 | if let Some(position) = position { |
| 960 | let mut row = rows.remove(position); |
| 961 | if let Row::Post(post) = &mut row { |
| 962 | post.replies.push(message); |
| 963 | } |
| 964 | rows.insert(0, row); |
| 965 | } |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> { |
| 970 | let members: Vec<MessageRecord> = records |
| 971 | .iter() |
| 972 | .filter(|record| { |
| 973 | record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id) |
| 974 | }) |
| 975 | .cloned() |
| 976 | .collect(); |
| 977 | flat_rows(&members, context, false) |
| 978 | } |
| 979 | |
| 980 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 981 | pub struct Splice { |
| 982 | pub range: Range<usize>, |
| 983 | pub count: usize, |
| 984 | } |
| 985 | |
| 986 | pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> { |
| 987 | if old == new { |
| 988 | return None; |
| 989 | } |
| 990 | let prefix = old |
| 991 | .iter() |
| 992 | .zip(new) |
| 993 | .take_while(|(left, right)| left == right) |
| 994 | .count(); |
| 995 | let suffix = old[prefix..] |
| 996 | .iter() |
| 997 | .rev() |
| 998 | .zip(new[prefix..].iter().rev()) |
| 999 | .take_while(|(left, right)| left == right) |
| 1000 | .count(); |
| 1001 | Some(Splice { |
| 1002 | range: prefix..old.len() - suffix, |
| 1003 | count: new.len() - prefix - suffix, |
| 1004 | }) |
| 1005 | } |
| 1006 | |
| 1007 | pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> { |
| 1008 | let prefix = old |
| 1009 | .iter() |
| 1010 | .zip(new) |
| 1011 | .take_while(|(left, right)| left.key() == right.key()) |
| 1012 | .count(); |
| 1013 | let suffix = old[prefix..] |
| 1014 | .iter() |
| 1015 | .rev() |
| 1016 | .zip(new[prefix..].iter().rev()) |
| 1017 | .take_while(|(left, right)| left.key() == right.key()) |
| 1018 | .count(); |
| 1019 | let mut changed: Vec<usize> = (0..prefix) |
| 1020 | .filter(|&index| old[index] != new[index]) |
| 1021 | .collect(); |
| 1022 | changed.extend((0..suffix).filter_map(|offset| { |
| 1023 | let old_index = old.len() - 1 - offset; |
| 1024 | let new_index = new.len() - 1 - offset; |
| 1025 | (old[old_index] != new[new_index]).then_some(new_index) |
| 1026 | })); |
| 1027 | changed |
| 1028 | } |
| 1029 | |
| 1030 | #[cfg(test)] |
| 1031 | mod tests { |
| 1032 | use chrono::TimeZone; |
| 1033 | |
| 1034 | use super::*; |
| 1035 | |
| 1036 | fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord { |
| 1037 | MessageRecord { |
| 1038 | conversation_id: "c".into(), |
| 1039 | message_id: id.into(), |
| 1040 | reply_to_id: reply_to.map(str::to_owned), |
| 1041 | sender_id: Some("u".into()), |
| 1042 | sender_name: Some("Author".into()), |
| 1043 | sender_application_id: None, |
| 1044 | links_json: "[]".to_owned(), |
| 1045 | created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(), |
| 1046 | edited_at: None, |
| 1047 | deleted: false, |
| 1048 | body_html: format!("<p>text {id}</p>"), |
| 1049 | attachments_json: "[]".into(), |
| 1050 | reactions_json: "[]".into(), |
| 1051 | mentions_json: "[]".into(), |
| 1052 | subject: None, |
| 1053 | call_event_json: None, |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | #[test] |
| 1058 | fn a_quote_shows_the_lines_of_the_quoted_message_when_it_is_loaded() { |
| 1059 | let mut quoted = record("q1", None, 8, 6); |
| 1060 | quoted.body_html = "<p>first link</p><p>second link</p>".into(); |
| 1061 | let mut answer = record("a1", None, 9, 6); |
| 1062 | answer.body_html = "<attachment id=\"q1\"></attachment><p>please again</p>".into(); |
| 1063 | answer.attachments_json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"q1","quote":{"message_id":"q1","preview":"first link second link","sender_name":"Robin"}}]"#.into(); |
| 1064 | let rows = flat_rows(&[quoted, answer], &context(), false); |
| 1065 | let reply = rows |
| 1066 | .iter() |
| 1067 | .find_map(|row| match row { |
| 1068 | Row::Message(row) if row.key == "a1" => Some(row.blocks.clone()), |
| 1069 | _ => None, |
| 1070 | }) |
| 1071 | .unwrap(); |
| 1072 | let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") }; |
| 1073 | let text = format!("{children:?}"); |
| 1074 | assert!(text.contains(r"first link\nsecond link"), "{text}"); |
| 1075 | } |
| 1076 | |
| 1077 | fn own_reaction(reaction_type: &str) -> ReactionInfo { |
| 1078 | ReactionInfo { |
| 1079 | reaction_type: reaction_type.into(), |
| 1080 | user_id: Some("me".into()), |
| 1081 | user_name: None, |
| 1082 | created_at: None, |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | #[test] |
| 1087 | fn setting_a_reaction_is_idempotent_and_only_touches_mine() { |
| 1088 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 1089 | let other = ReactionInfo { |
| 1090 | user_id: Some("them".into()), |
| 1091 | ..own_reaction("like") |
| 1092 | }; |
| 1093 | let mut reactions = vec![other.clone()]; |
| 1094 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now); |
| 1095 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now); |
| 1096 | assert_eq!(reactions.len(), 2); |
| 1097 | assert_eq!(reactions[1].reaction_type, "like"); |
| 1098 | assert_eq!(reactions[1].user_id.as_deref(), Some("me")); |
| 1099 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now); |
| 1100 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now); |
| 1101 | assert_eq!(reactions, vec![other]); |
| 1102 | } |
| 1103 | |
| 1104 | #[test] |
| 1105 | fn setting_matches_legacy_names_and_variation_selectors() { |
| 1106 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 1107 | let mut reactions = vec![own_reaction("heart")]; |
| 1108 | assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me"))); |
| 1109 | set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now); |
| 1110 | assert!(reactions.is_empty()); |
| 1111 | set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now); |
| 1112 | assert_eq!(reactions[0].reaction_type, "\u{1F389}"); |
| 1113 | } |
| 1114 | |
| 1115 | #[test] |
| 1116 | fn setting_without_a_known_user_never_matches() { |
| 1117 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 1118 | let mut reactions = Vec::new(); |
| 1119 | set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now); |
| 1120 | set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now); |
| 1121 | assert_eq!(reactions.len(), 2); |
| 1122 | } |
| 1123 | |
| 1124 | #[test] |
| 1125 | fn pending_reactions_overlay_the_stored_ones() { |
| 1126 | let mut stored = record("a", None, 8, 6); |
| 1127 | stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap(); |
| 1128 | let mut context = context(); |
| 1129 | context.my_user_id = Some("me".into()); |
| 1130 | context.pending_reactions.insert( |
| 1131 | "a".into(), |
| 1132 | vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)], |
| 1133 | ); |
| 1134 | let chips = message_row(&stored, &context).reactions; |
| 1135 | assert_eq!(chips.len(), 1); |
| 1136 | assert_eq!(chips[0].reaction_type, "\u{1F389}"); |
| 1137 | assert!(chips[0].mine); |
| 1138 | } |
| 1139 | |
| 1140 | #[test] |
| 1141 | fn reaction_type_maps_classic_glyphs_to_names() { |
| 1142 | assert_eq!(reaction_type_for("\u{1F44D}"), "like"); |
| 1143 | assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart"); |
| 1144 | assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}"); |
| 1145 | assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}")); |
| 1146 | assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}")); |
| 1147 | assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}"); |
| 1148 | assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}"); |
| 1149 | } |
| 1150 | |
| 1151 | #[test] |
| 1152 | fn forwarded_messages_are_detected_by_the_forward_blockquote() { |
| 1153 | let mut forwarded = record("f", None, 8, 6); |
| 1154 | forwarded.body_html = |
| 1155 | r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#.into(); |
| 1156 | assert!(message_row(&forwarded, &context()).forwarded); |
| 1157 | forwarded.body_html = |
| 1158 | r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#.into(); |
| 1159 | assert!(!message_row(&forwarded, &context()).forwarded); |
| 1160 | forwarded.body_html = |
| 1161 | r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into(); |
| 1162 | forwarded.deleted = true; |
| 1163 | assert!(!message_row(&forwarded, &context()).forwarded); |
| 1164 | } |
| 1165 | |
| 1166 | #[test] |
| 1167 | fn a_graph_forward_shows_the_original_sender_and_text_in_a_quote() { |
| 1168 | let mut forwarded = record("f", None, 8, 6); |
| 1169 | forwarded.body_html = r#"<attachment id="9"></attachment>"#.into(); |
| 1170 | forwarded.attachments_json = serde_json::json!([{ |
| 1171 | "content_type": "forwardedMessageReference", |
| 1172 | "name": null, "url": null, "text": null, "id": "9", |
| 1173 | "content": serde_json::json!({ |
| 1174 | "originalMessageId": "9", |
| 1175 | "originalMessageContent": "<p>original words</p>", |
| 1176 | "originalSentDateTime": "2026-10-06T07:00:00.000+00:00", |
| 1177 | "originalMessageSender": {"user": {"id": "orig", "displayName": null}} |
| 1178 | }).to_string() |
| 1179 | }]) |
| 1180 | .to_string(); |
| 1181 | let mut context = context(); |
| 1182 | context.names.insert("orig".into(), "Priya Nair".into()); |
| 1183 | let row = message_row(&forwarded, &context); |
| 1184 | assert!(row.forwarded); |
| 1185 | assert!(row.jumbo.is_none()); |
| 1186 | let [Block::Quote(children)] = row.blocks.as_slice() else { |
| 1187 | panic!("expected one forward quote, got {:?}", row.blocks); |
| 1188 | }; |
| 1189 | let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect(); |
| 1190 | assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}"); |
| 1191 | assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}"); |
| 1192 | assert_eq!(reply_excerpt(&forwarded), "original words"); |
| 1193 | assert_eq!(message_text(&forwarded), "original words"); |
| 1194 | } |
| 1195 | |
| 1196 | #[test] |
| 1197 | fn editing_loads_the_message_formatted_without_its_reply_quote() { |
| 1198 | let mut edited = record("a", None, 8, 6); |
| 1199 | edited.body_html = |
| 1200 | "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\ |
| 1201 | <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\ |
| 1202 | <ol><li>one</li><li>two</li></ol>" |
| 1203 | .into(); |
| 1204 | let draft = message_draft(&edited); |
| 1205 | assert_eq!(draft.text(), "Plan for today\n1. one\n2. two"); |
| 1206 | assert_eq!( |
| 1207 | draft.to_html(), |
| 1208 | "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>" |
| 1209 | ); |
| 1210 | } |
| 1211 | |
| 1212 | #[test] |
| 1213 | fn reply_excerpt_uses_the_first_line_or_the_attachment() { |
| 1214 | let mut text = record("a", None, 8, 6); |
| 1215 | text.body_html = "<p>first line</p><p>second</p>".into(); |
| 1216 | assert_eq!(reply_excerpt(&text), "first line"); |
| 1217 | let mut quoted = record("q", None, 8, 6); |
| 1218 | quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into(); |
| 1219 | assert_eq!(reply_excerpt("ed), "my answer"); |
| 1220 | let mut image = record("b", None, 8, 6); |
| 1221 | image.body_html = "<img src=\"u\">".into(); |
| 1222 | assert_eq!(reply_excerpt(&image), "Image"); |
| 1223 | let mut long = record("c", None, 8, 6); |
| 1224 | long.body_html = format!("<p>{}</p>", "x".repeat(200)); |
| 1225 | assert!(reply_excerpt(&long).ends_with("...")); |
| 1226 | assert_eq!( |
| 1227 | reply_excerpt(&long).chars().count(), |
| 1228 | REPLY_EXCERPT_CHARS + 3 |
| 1229 | ); |
| 1230 | } |
| 1231 | |
| 1232 | fn context() -> RowContext { |
| 1233 | RowContext { |
| 1234 | offset: FixedOffset::east_opt(0).unwrap(), |
| 1235 | today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(), |
| 1236 | my_user_id: None, |
| 1237 | names: HashMap::new(), |
| 1238 | pending_reactions: HashMap::new(), |
| 1239 | card_overrides: HashMap::new(), |
| 1240 | translation: TranslationContext::default(), |
| 1241 | skin_tone: 0, |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | fn keys(rows: &[Row]) -> Vec<String> { |
| 1246 | rows.iter().map(|row| row.key().to_owned()).collect() |
| 1247 | } |
| 1248 | |
| 1249 | fn translation_context(shown: bool) -> RowContext { |
| 1250 | use crate::translation::CachedTranslation; |
| 1251 | let mut context = context(); |
| 1252 | context.translation.enabled = true; |
| 1253 | context.translation.target = "en".into(); |
| 1254 | context.translation.stamps.insert( |
| 1255 | "a".into(), |
| 1256 | "languages=fr:100;length:80;&detector=Bling".into(), |
| 1257 | ); |
| 1258 | context.my_user_id = Some("me".into()); |
| 1259 | if shown { |
| 1260 | context.translation.cached.insert( |
| 1261 | ("a".into(), 0), |
| 1262 | CachedTranslation { |
| 1263 | html: "<p><strong>translated</strong> body</p>".into(), |
| 1264 | source: Some("fr".into()), |
| 1265 | }, |
| 1266 | ); |
| 1267 | context.translation.shown.insert("a".into()); |
| 1268 | } |
| 1269 | context |
| 1270 | } |
| 1271 | |
| 1272 | #[test] |
| 1273 | fn a_foreign_message_carries_the_offer_and_keeps_its_text() { |
| 1274 | let row = message_row(&record("a", None, 8, 6), &translation_context(false)); |
| 1275 | assert!(matches!( |
| 1276 | row.translation, |
| 1277 | Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr" |
| 1278 | )); |
| 1279 | assert_eq!( |
| 1280 | row.blocks, |
| 1281 | layout_blocks(&teams_core::linked_message_spans(&record("a", None, 8, 6))) |
| 1282 | ); |
| 1283 | } |
| 1284 | |
| 1285 | #[test] |
| 1286 | fn a_shown_translation_replaces_the_body_and_the_original_comes_back() { |
| 1287 | let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks; |
| 1288 | let translated = message_row(&record("a", None, 8, 6), &translation_context(true)); |
| 1289 | assert_ne!(translated.blocks, original); |
| 1290 | assert_eq!( |
| 1291 | translated.translation, |
| 1292 | Some(TranslationLine::Translated { |
| 1293 | language: Some("French".into()), |
| 1294 | showing_original: false |
| 1295 | }) |
| 1296 | ); |
| 1297 | let mut hidden = translation_context(true); |
| 1298 | hidden.translation.shown.clear(); |
| 1299 | let back = message_row(&record("a", None, 8, 6), &hidden); |
| 1300 | assert_eq!(back.blocks, original); |
| 1301 | assert_eq!( |
| 1302 | back.translation, |
| 1303 | Some(TranslationLine::Translated { |
| 1304 | language: Some("French".into()), |
| 1305 | showing_original: true |
| 1306 | }) |
| 1307 | ); |
| 1308 | } |
| 1309 | |
| 1310 | #[test] |
| 1311 | fn own_messages_get_no_offer() { |
| 1312 | let mut own = record("a", None, 8, 6); |
| 1313 | own.sender_id = Some("me".into()); |
| 1314 | assert_eq!( |
| 1315 | message_row(&own, &translation_context(false)).translation, |
| 1316 | None |
| 1317 | ); |
| 1318 | } |
| 1319 | |
| 1320 | #[test] |
| 1321 | fn day_header_only_on_first_message_of_a_day() { |
| 1322 | let records = vec![ |
| 1323 | record("a", None, 8, 6), |
| 1324 | record("b", None, 9, 6), |
| 1325 | record("c", None, 9, 7), |
| 1326 | ]; |
| 1327 | let rows = flat_rows(&records, &context(), false); |
| 1328 | let headers: Vec<Option<String>> = rows |
| 1329 | .iter() |
| 1330 | .map(|row| match row { |
| 1331 | Row::Message(message) => message.day_header.clone(), |
| 1332 | Row::LoadOlder |
| 1333 | | Row::LoadNewer |
| 1334 | | Row::Start(_) |
| 1335 | | Row::Skeleton(_) |
| 1336 | | Row::Post(_) => None, |
| 1337 | }) |
| 1338 | .collect(); |
| 1339 | assert_eq!( |
| 1340 | headers, |
| 1341 | vec![Some("Yesterday".into()), None, Some("Today".into())] |
| 1342 | ); |
| 1343 | } |
| 1344 | |
| 1345 | #[test] |
| 1346 | fn load_older_row_only_when_more_exists() { |
| 1347 | let records = vec![record("a", None, 8, 6)]; |
| 1348 | assert_eq!( |
| 1349 | keys(&flat_rows(&records, &context(), true))[0], |
| 1350 | LOAD_OLDER_KEY |
| 1351 | ); |
| 1352 | assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]); |
| 1353 | } |
| 1354 | |
| 1355 | #[test] |
| 1356 | fn threads_group_replies_by_root() { |
| 1357 | let records = vec![ |
| 1358 | record("r1", None, 8, 6), |
| 1359 | record("r2", None, 9, 6), |
| 1360 | record("x1", Some("r1"), 10, 6), |
| 1361 | record("x2", Some("r1"), 11, 6), |
| 1362 | record("orphan", Some("missing"), 12, 6), |
| 1363 | ]; |
| 1364 | let threads = group_threads(&records); |
| 1365 | assert_eq!(threads.len(), 2); |
| 1366 | assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]); |
| 1367 | assert!(threads[1].reply_ids.is_empty()); |
| 1368 | } |
| 1369 | |
| 1370 | fn post_of(row: &Row) -> &PostRow { |
| 1371 | let Row::Post(post) = row else { |
| 1372 | panic!("post expected") |
| 1373 | }; |
| 1374 | post |
| 1375 | } |
| 1376 | |
| 1377 | fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord { |
| 1378 | let mut reply = record(id, Some(root), hour, 6); |
| 1379 | reply.sender_name = Some(sender.into()); |
| 1380 | reply |
| 1381 | } |
| 1382 | |
| 1383 | #[test] |
| 1384 | fn feed_orders_posts_by_last_activity_newest_first() { |
| 1385 | let records = vec![ |
| 1386 | record("r1", None, 8, 6), |
| 1387 | record("r2", None, 9, 6), |
| 1388 | record("r3", None, 10, 6), |
| 1389 | record("x1", Some("r1"), 11, 6), |
| 1390 | ]; |
| 1391 | let rows = thread_list_rows(&records, &context(), false); |
| 1392 | assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]); |
| 1393 | } |
| 1394 | |
| 1395 | #[test] |
| 1396 | fn feed_puts_load_older_at_the_bottom() { |
| 1397 | let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)]; |
| 1398 | let rows = thread_list_rows(&records, &context(), true); |
| 1399 | assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]); |
| 1400 | } |
| 1401 | |
| 1402 | #[test] |
| 1403 | fn post_shows_the_last_three_replies_oldest_first() { |
| 1404 | let mut records = vec![record("r1", None, 1, 6)]; |
| 1405 | for hour in 2..=6 { |
| 1406 | records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour)); |
| 1407 | } |
| 1408 | records.reverse(); |
| 1409 | let rows = thread_list_rows(&records, &context(), false); |
| 1410 | let post = post_of(&rows[0]); |
| 1411 | let shown: Vec<&str> = post |
| 1412 | .replies |
| 1413 | .iter() |
| 1414 | .map(|reply| reply.key.as_str()) |
| 1415 | .collect(); |
| 1416 | assert_eq!(shown, vec!["x4", "x5", "x6"]); |
| 1417 | assert_eq!(post.hidden_reply_count, 2); |
| 1418 | assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]); |
| 1419 | } |
| 1420 | |
| 1421 | #[test] |
| 1422 | fn post_without_hidden_replies_has_no_link() { |
| 1423 | let records = vec![ |
| 1424 | record("r1", None, 1, 6), |
| 1425 | reply_by("x1", "r1", "Ada", 2), |
| 1426 | reply_by("x2", "r1", "Ben", 3), |
| 1427 | reply_by("x3", "r1", "Cy", 4), |
| 1428 | ]; |
| 1429 | let rows = thread_list_rows(&records, &context(), false); |
| 1430 | assert_eq!(post_of(&rows[0]).hidden_replies_label(), None); |
| 1431 | assert_eq!(post_of(&rows[0]).replies.len(), 3); |
| 1432 | } |
| 1433 | |
| 1434 | fn label_for(repliers: &[&str]) -> String { |
| 1435 | let mut records = vec![record("r1", None, 1, 6)]; |
| 1436 | for (index, name) in repliers.iter().enumerate() { |
| 1437 | records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32)); |
| 1438 | } |
| 1439 | for index in 0..POST_VISIBLE_REPLIES { |
| 1440 | records.push(reply_by( |
| 1441 | &format!("v{index}"), |
| 1442 | "r1", |
| 1443 | "Shown", |
| 1444 | 20 + index as u32, |
| 1445 | )); |
| 1446 | } |
| 1447 | let rows = thread_list_rows(&records, &context(), false); |
| 1448 | post_of(&rows[0]).hidden_replies_label().unwrap() |
| 1449 | } |
| 1450 | |
| 1451 | #[test] |
| 1452 | fn replies_label_names_one_to_three_people() { |
| 1453 | assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna"); |
| 1454 | assert_eq!( |
| 1455 | label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]), |
| 1456 | "3 replies from Anna and Ben" |
| 1457 | ); |
| 1458 | assert_eq!( |
| 1459 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]), |
| 1460 | "4 replies from Anna, Ben and Clara" |
| 1461 | ); |
| 1462 | } |
| 1463 | |
| 1464 | #[test] |
| 1465 | fn replies_label_counts_the_others_beyond_three_people() { |
| 1466 | assert_eq!( |
| 1467 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]), |
| 1468 | "5 replies from Anna, Ben and 3 others" |
| 1469 | ); |
| 1470 | assert_eq!( |
| 1471 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]), |
| 1472 | "4 replies from Anna, Ben and 2 others" |
| 1473 | ); |
| 1474 | } |
| 1475 | |
| 1476 | #[test] |
| 1477 | fn local_reply_lands_in_its_post_and_local_post_on_top() { |
| 1478 | let records = vec![ |
| 1479 | record("r1", None, 8, 6), |
| 1480 | record("r2", None, 9, 6), |
| 1481 | reply_by("x1", "r1", "Ada", 10), |
| 1482 | ]; |
| 1483 | let mut rows = thread_list_rows(&records, &context(), true); |
| 1484 | let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context()); |
| 1485 | pending_reply.reply_root = Some("r2".into()); |
| 1486 | let pending_post = message_row(&record("pending-2", None, 12, 6), &context()); |
| 1487 | place_local_rows(&mut rows, vec![pending_reply, pending_post]); |
| 1488 | assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]); |
| 1489 | let replies: Vec<&str> = post_of(&rows[1]) |
| 1490 | .replies |
| 1491 | .iter() |
| 1492 | .map(|reply| reply.key.as_str()) |
| 1493 | .collect(); |
| 1494 | assert_eq!(replies, vec!["pending-1"]); |
| 1495 | } |
| 1496 | |
| 1497 | #[test] |
| 1498 | fn local_reply_to_an_unloaded_post_is_not_shown() { |
| 1499 | let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false); |
| 1500 | let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context()); |
| 1501 | orphan.reply_root = Some("gone".into()); |
| 1502 | place_local_rows(&mut rows, vec![orphan]); |
| 1503 | assert_eq!(keys(&rows), vec!["r1"]); |
| 1504 | } |
| 1505 | |
| 1506 | #[test] |
| 1507 | fn subject_reaches_the_post_root() { |
| 1508 | let mut with_subject = record("r1", None, 8, 6); |
| 1509 | with_subject.subject = Some("Release plan".into()); |
| 1510 | let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false); |
| 1511 | assert_eq!( |
| 1512 | post_of(&rows[0]).root.subject.as_deref(), |
| 1513 | Some("Release plan") |
| 1514 | ); |
| 1515 | assert_eq!(post_of(&rows[1]).root.subject, None); |
| 1516 | } |
| 1517 | |
| 1518 | #[test] |
| 1519 | fn thread_view_has_root_then_replies() { |
| 1520 | let records = vec![ |
| 1521 | record("r1", None, 8, 6), |
| 1522 | record("r2", None, 9, 6), |
| 1523 | record("x1", Some("r1"), 10, 6), |
| 1524 | ]; |
| 1525 | assert_eq!( |
| 1526 | keys(&thread_rows(&records, "r1", &context())), |
| 1527 | vec!["r1", "x1"] |
| 1528 | ); |
| 1529 | } |
| 1530 | |
| 1531 | #[test] |
| 1532 | fn reactions_are_counted_in_first_seen_order() { |
| 1533 | let reaction = |kind: &str| ReactionInfo { |
| 1534 | reaction_type: kind.into(), |
| 1535 | user_id: None, |
| 1536 | user_name: None, |
| 1537 | created_at: None, |
| 1538 | }; |
| 1539 | let chips = reaction_chips( |
| 1540 | &[reaction("heart"), reaction("like"), reaction("heart")], |
| 1541 | &context(), |
| 1542 | ); |
| 1543 | assert_eq!(chips.len(), 2); |
| 1544 | assert_eq!(chips[0].count, 2); |
| 1545 | assert_eq!(chips[1].label, reaction_label("like")); |
| 1546 | } |
| 1547 | |
| 1548 | #[test] |
| 1549 | fn legacy_laugh_and_sad_use_the_teams_glyphs() { |
| 1550 | assert_eq!(reaction_label("laugh"), "\u{1F606}"); |
| 1551 | assert_eq!(reaction_label("sad"), "\u{1F641}"); |
| 1552 | assert_eq!(reaction_type_for("\u{1F606}"), "laugh"); |
| 1553 | assert_eq!(reaction_type_for("\u{1F641}"), "sad"); |
| 1554 | } |
| 1555 | |
| 1556 | #[test] |
| 1557 | fn legacy_and_emoji_reactions_share_a_chip() { |
| 1558 | let reaction = |kind: &str| ReactionInfo { |
| 1559 | reaction_type: kind.into(), |
| 1560 | user_id: None, |
| 1561 | user_name: Some("Lea".into()), |
| 1562 | created_at: None, |
| 1563 | }; |
| 1564 | let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context()); |
| 1565 | assert_eq!(chips.len(), 1); |
| 1566 | assert_eq!(chips[0].count, 2); |
| 1567 | } |
| 1568 | |
| 1569 | #[test] |
| 1570 | fn skin_tones_share_a_chip_showing_up_to_three_variants() { |
| 1571 | let reaction = |kind: &str| ReactionInfo { |
| 1572 | reaction_type: kind.into(), |
| 1573 | user_id: Some(kind.into()), |
| 1574 | user_name: Some("Lea".into()), |
| 1575 | created_at: None, |
| 1576 | }; |
| 1577 | let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"]; |
| 1578 | let mut context = context(); |
| 1579 | context.skin_tone = 3; |
| 1580 | let chips = reaction_chips(&kinds.map(reaction), &context); |
| 1581 | assert_eq!(chips.len(), 1); |
| 1582 | assert_eq!(chips[0].count, 5); |
| 1583 | assert_eq!(chips[0].label, "👍🏼👍🏿👍"); |
| 1584 | assert_eq!(chips[0].click_glyph, "👍🏽"); |
| 1585 | } |
| 1586 | |
| 1587 | #[test] |
| 1588 | fn own_toned_reaction_matches_the_plain_glyph() { |
| 1589 | let mine = ReactionInfo { |
| 1590 | reaction_type: "👍🏼".into(), |
| 1591 | user_id: Some("me".into()), |
| 1592 | user_name: None, |
| 1593 | created_at: None, |
| 1594 | }; |
| 1595 | let reactions = vec![mine]; |
| 1596 | assert!(has_own_reaction(&reactions, "\u{1F44D}", Some("me"))); |
| 1597 | assert_eq!( |
| 1598 | own_reaction_glyph(&reactions, "like", Some("me")).as_deref(), |
| 1599 | Some("👍🏼") |
| 1600 | ); |
| 1601 | assert_eq!(reaction_glyph("yes-tone5"), "👍🏿"); |
| 1602 | } |
| 1603 | |
| 1604 | #[test] |
| 1605 | fn reactor_name_falls_back_to_directory_then_unknown() { |
| 1606 | let reaction = |user: &str| ReactionInfo { |
| 1607 | reaction_type: "like".into(), |
| 1608 | user_id: Some(user.into()), |
| 1609 | user_name: None, |
| 1610 | created_at: None, |
| 1611 | }; |
| 1612 | let mut context = context(); |
| 1613 | context.names.insert("known".into(), "Priya Nair".into()); |
| 1614 | let chips = reaction_chips(&[reaction("known"), reaction("other")], &context); |
| 1615 | assert_eq!(chips[0].reactors[0].name, "Priya Nair"); |
| 1616 | assert_eq!(chips[0].reactors[1].name, "Unknown"); |
| 1617 | } |
| 1618 | |
| 1619 | fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord { |
| 1620 | let mut record = record(id, None, hour, day); |
| 1621 | record.sender_id = Some(sender.into()); |
| 1622 | record.created_at = Utc |
| 1623 | .with_ymd_and_hms(2026, 10, day, hour, minute, 0) |
| 1624 | .unwrap(); |
| 1625 | record |
| 1626 | } |
| 1627 | |
| 1628 | fn series_of(rows: &[Row]) -> Vec<(bool, bool)> { |
| 1629 | rows.iter() |
| 1630 | .filter_map(|row| match row { |
| 1631 | Row::Message(message) => Some((message.series.has_prev, message.series.has_next)), |
| 1632 | Row::LoadOlder |
| 1633 | | Row::LoadNewer |
| 1634 | | Row::Start(_) |
| 1635 | | Row::Skeleton(_) |
| 1636 | | Row::Post(_) => None, |
| 1637 | }) |
| 1638 | .collect() |
| 1639 | } |
| 1640 | |
| 1641 | #[test] |
| 1642 | fn series_joins_same_sender_within_five_minutes() { |
| 1643 | let records = vec![ |
| 1644 | record_by("a", "ada", 9, 0, 7), |
| 1645 | record_by("b", "ada", 9, 4, 7), |
| 1646 | record_by("c", "ada", 9, 20, 7), |
| 1647 | record_by("d", "bob", 9, 21, 7), |
| 1648 | record_by("e", "ada", 9, 22, 7), |
| 1649 | ]; |
| 1650 | let rows = flat_rows(&records, &context(), false); |
| 1651 | assert_eq!( |
| 1652 | series_of(&rows), |
| 1653 | vec![ |
| 1654 | (false, true), |
| 1655 | (true, false), |
| 1656 | (false, false), |
| 1657 | (false, false), |
| 1658 | (false, false) |
| 1659 | ] |
| 1660 | ); |
| 1661 | } |
| 1662 | |
| 1663 | #[test] |
| 1664 | fn series_window_ends_exactly_at_the_gap_constant() { |
| 1665 | let gap = SERIES_GAP_MINUTES as u32; |
| 1666 | let records = vec![ |
| 1667 | record_by("a", "ada", 9, 0, 7), |
| 1668 | record_by("b", "ada", 9, gap - 1, 7), |
| 1669 | record_by("c", "ada", 9, 2 * gap - 1 + gap, 7), |
| 1670 | ]; |
| 1671 | let rows = flat_rows(&records, &context(), false); |
| 1672 | assert_eq!( |
| 1673 | series_of(&rows), |
| 1674 | vec![(false, true), (true, false), (false, false)] |
| 1675 | ); |
| 1676 | } |
| 1677 | |
| 1678 | #[test] |
| 1679 | fn series_breaks_at_a_new_day() { |
| 1680 | let records = vec![ |
| 1681 | record_by("a", "ada", 23, 58, 6), |
| 1682 | record_by("b", "ada", 0, 1, 7), |
| 1683 | ]; |
| 1684 | let rows = flat_rows(&records, &context(), false); |
| 1685 | assert_eq!(series_of(&rows), vec![(false, false), (false, false)]); |
| 1686 | } |
| 1687 | |
| 1688 | fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] { |
| 1689 | let corners = bubble_corners(own, Series { has_prev, has_next }); |
| 1690 | [ |
| 1691 | corners.top_left, |
| 1692 | corners.top_right, |
| 1693 | corners.bottom_right, |
| 1694 | corners.bottom_left, |
| 1695 | ] |
| 1696 | } |
| 1697 | |
| 1698 | #[test] |
| 1699 | fn corners_match_the_mockup_for_other_senders() { |
| 1700 | assert_eq!(corners(false, false, false), [14., 14., 14., 14.]); |
| 1701 | assert_eq!(corners(false, false, true), [14., 14., 14., 4.]); |
| 1702 | assert_eq!(corners(false, true, true), [4., 14., 14., 4.]); |
| 1703 | assert_eq!(corners(false, true, false), [4., 14., 14., 14.]); |
| 1704 | } |
| 1705 | |
| 1706 | #[test] |
| 1707 | fn corners_match_the_mockup_for_own_messages() { |
| 1708 | assert_eq!(corners(true, false, false), [14., 14., 14., 14.]); |
| 1709 | assert_eq!(corners(true, false, true), [14., 14., 4., 14.]); |
| 1710 | assert_eq!(corners(true, true, true), [14., 4., 4., 14.]); |
| 1711 | assert_eq!(corners(true, true, false), [14., 4., 14., 14.]); |
| 1712 | } |
| 1713 | |
| 1714 | #[test] |
| 1715 | fn own_reaction_is_marked() { |
| 1716 | let reaction = |user: &str| ReactionInfo { |
| 1717 | reaction_type: "like".into(), |
| 1718 | user_id: Some(user.into()), |
| 1719 | user_name: None, |
| 1720 | created_at: None, |
| 1721 | }; |
| 1722 | let mut context = context(); |
| 1723 | context.my_user_id = Some("me".into()); |
| 1724 | let chips = reaction_chips(&[reaction("x"), reaction("me")], &context); |
| 1725 | assert!(chips[0].mine); |
| 1726 | assert!(!reaction_chips(&[reaction("x")], &context)[0].mine); |
| 1727 | } |
| 1728 | |
| 1729 | fn strings(values: &[&str]) -> Vec<String> { |
| 1730 | values.iter().map(|value| (*value).to_owned()).collect() |
| 1731 | } |
| 1732 | |
| 1733 | #[test] |
| 1734 | fn diff_detects_append_prepend_and_replace() { |
| 1735 | let base = strings(&["a", "b"]); |
| 1736 | assert_eq!(diff_keys(&base, &base), None); |
| 1737 | assert_eq!( |
| 1738 | diff_keys(&base, &strings(&["a", "b", "c"])), |
| 1739 | Some(Splice { |
| 1740 | range: 2..2, |
| 1741 | count: 1 |
| 1742 | }) |
| 1743 | ); |
| 1744 | assert_eq!( |
| 1745 | diff_keys(&base, &strings(&["x", "a", "b"])), |
| 1746 | Some(Splice { |
| 1747 | range: 0..0, |
| 1748 | count: 1 |
| 1749 | }) |
| 1750 | ); |
| 1751 | assert_eq!( |
| 1752 | diff_keys( |
| 1753 | &strings(&["load-older", "a"]), |
| 1754 | &strings(&["load-older", "x", "y", "a"]) |
| 1755 | ), |
| 1756 | Some(Splice { |
| 1757 | range: 1..1, |
| 1758 | count: 2 |
| 1759 | }) |
| 1760 | ); |
| 1761 | assert_eq!( |
| 1762 | diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])), |
| 1763 | Some(Splice { |
| 1764 | range: 0..1, |
| 1765 | count: 0 |
| 1766 | }) |
| 1767 | ); |
| 1768 | assert_eq!( |
| 1769 | diff_keys(&base, &strings(&["x"])), |
| 1770 | Some(Splice { |
| 1771 | range: 0..2, |
| 1772 | count: 1 |
| 1773 | }) |
| 1774 | ); |
| 1775 | } |
| 1776 | |
| 1777 | #[test] |
| 1778 | fn changed_indices_find_edited_rows() { |
| 1779 | let old = flat_rows( |
| 1780 | &[record("a", None, 8, 6), record("b", None, 9, 6)], |
| 1781 | &context(), |
| 1782 | false, |
| 1783 | ); |
| 1784 | let mut edited = record("b", None, 9, 6); |
| 1785 | edited.body_html = "<p>changed</p>".into(); |
| 1786 | let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false); |
| 1787 | assert_eq!(changed_indices(&old, &new), vec![1]); |
| 1788 | } |
| 1789 | |
| 1790 | fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord { |
| 1791 | MessageRecord { |
| 1792 | sender_id: None, |
| 1793 | sender_name: None, |
| 1794 | body_html: String::new(), |
| 1795 | call_event_json: Some(event.to_json()), |
| 1796 | ..record(id, None, hour, 7) |
| 1797 | } |
| 1798 | } |
| 1799 | |
| 1800 | fn call_event_of( |
| 1801 | phase: CallPhase, |
| 1802 | call_id: &str, |
| 1803 | initiator: &str, |
| 1804 | seconds: Option<u64>, |
| 1805 | participants: &[&str], |
| 1806 | ) -> CallEvent { |
| 1807 | CallEvent { |
| 1808 | phase, |
| 1809 | call_type: CallType::Call, |
| 1810 | call_id: call_id.into(), |
| 1811 | duration_seconds: seconds, |
| 1812 | initiator_id: Some(initiator.into()), |
| 1813 | initiator_name: Some(format!("Name {initiator}")), |
| 1814 | participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(), |
| 1815 | } |
| 1816 | } |
| 1817 | |
| 1818 | fn call_context() -> RowContext { |
| 1819 | let mut context = context(); |
| 1820 | context.my_user_id = Some("me".into()); |
| 1821 | context |
| 1822 | } |
| 1823 | |
| 1824 | fn call_of(row: &Row) -> &CallCard { |
| 1825 | let Row::Message(message) = row else { |
| 1826 | panic!("not a message row") |
| 1827 | }; |
| 1828 | message.call.as_ref().expect("call row") |
| 1829 | } |
| 1830 | |
| 1831 | #[test] |
| 1832 | fn started_call_is_hidden_when_the_same_call_ended() { |
| 1833 | let records = [ |
| 1834 | call_record( |
| 1835 | "s1", |
| 1836 | 9, |
| 1837 | call_event_of(CallPhase::Started, "one", "u", None, &[]), |
| 1838 | ), |
| 1839 | call_record( |
| 1840 | "e1", |
| 1841 | 10, |
| 1842 | call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]), |
| 1843 | ), |
| 1844 | call_record( |
| 1845 | "s2", |
| 1846 | 11, |
| 1847 | call_event_of(CallPhase::Started, "two", "u", None, &[]), |
| 1848 | ), |
| 1849 | ]; |
| 1850 | let rows = flat_rows(&records, &call_context(), false); |
| 1851 | assert_eq!(keys(&rows), ["e1", "s2"]); |
| 1852 | assert_eq!(call_of(&rows[0]).title, "Call ended"); |
| 1853 | assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00"); |
| 1854 | assert_eq!(call_of(&rows[1]).title, "Call started"); |
| 1855 | assert_eq!(call_of(&rows[1]).detail, "11:00"); |
| 1856 | assert!(call_of(&rows[1]).started); |
| 1857 | } |
| 1858 | |
| 1859 | #[test] |
| 1860 | fn only_the_newest_open_start_can_be_joined() { |
| 1861 | let records = [ |
| 1862 | call_record( |
| 1863 | "old", |
| 1864 | 9, |
| 1865 | call_event_of(CallPhase::Started, "lost", "u", None, &[]), |
| 1866 | ), |
| 1867 | call_record( |
| 1868 | "new", |
| 1869 | 11, |
| 1870 | call_event_of(CallPhase::Started, "live", "u", None, &[]), |
| 1871 | ), |
| 1872 | ]; |
| 1873 | let rows = flat_rows(&records, &call_context(), false); |
| 1874 | assert_eq!(keys(&rows), ["old", "new"]); |
| 1875 | assert!(!call_of(&rows[0]).started); |
| 1876 | assert!(call_of(&rows[1]).started); |
| 1877 | } |
| 1878 | |
| 1879 | #[test] |
| 1880 | fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() { |
| 1881 | let rows = flat_rows( |
| 1882 | &[ |
| 1883 | call_record( |
| 1884 | "incoming", |
| 1885 | 9, |
| 1886 | call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]), |
| 1887 | ), |
| 1888 | call_record( |
| 1889 | "outgoing", |
| 1890 | 10, |
| 1891 | call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]), |
| 1892 | ), |
| 1893 | call_record( |
| 1894 | "answered", |
| 1895 | 11, |
| 1896 | call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]), |
| 1897 | ), |
| 1898 | ], |
| 1899 | &call_context(), |
| 1900 | false, |
| 1901 | ); |
| 1902 | let missed = call_of(&rows[0]); |
| 1903 | assert!(missed.missed); |
| 1904 | assert_eq!(missed.title, "Missed call"); |
| 1905 | assert_eq!(missed.detail, "09:00"); |
| 1906 | assert_eq!(missed.icon, CallIcon::Missed); |
| 1907 | let outgoing = call_of(&rows[1]); |
| 1908 | assert!(!outgoing.missed); |
| 1909 | assert_eq!(outgoing.title, "Call ended"); |
| 1910 | assert_eq!(outgoing.detail, "1m \u{b7} 10:00"); |
| 1911 | assert!(!call_of(&rows[2]).missed); |
| 1912 | } |
| 1913 | |
| 1914 | #[test] |
| 1915 | fn call_side_follows_the_initiator() { |
| 1916 | let rows = flat_rows( |
| 1917 | &[ |
| 1918 | call_record( |
| 1919 | "mine", |
| 1920 | 9, |
| 1921 | call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]), |
| 1922 | ), |
| 1923 | call_record( |
| 1924 | "theirs", |
| 1925 | 10, |
| 1926 | call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]), |
| 1927 | ), |
| 1928 | ], |
| 1929 | &call_context(), |
| 1930 | false, |
| 1931 | ); |
| 1932 | let sides: Vec<(bool, Option<&str>)> = rows |
| 1933 | .iter() |
| 1934 | .map(|row| match row { |
| 1935 | Row::Message(message) => (message.own, message.sender_id.as_deref()), |
| 1936 | _ => unreachable!(), |
| 1937 | }) |
| 1938 | .collect(); |
| 1939 | assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]); |
| 1940 | } |
| 1941 | |
| 1942 | #[test] |
| 1943 | fn meeting_events_use_the_video_icon_and_meeting_titles() { |
| 1944 | let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]); |
| 1945 | event.call_type = CallType::Meeting; |
| 1946 | let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false); |
| 1947 | let card = call_of(&rows[0]); |
| 1948 | assert_eq!(card.title, "Meeting ended"); |
| 1949 | assert_eq!(card.icon, CallIcon::Video); |
| 1950 | assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00"); |
| 1951 | } |
| 1952 | |
| 1953 | #[test] |
| 1954 | fn call_rows_never_join_a_series() { |
| 1955 | let mut records = vec![ |
| 1956 | record_by("a", "u", 9, 0, 7), |
| 1957 | call_record( |
| 1958 | "c", |
| 1959 | 9, |
| 1960 | call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]), |
| 1961 | ), |
| 1962 | ]; |
| 1963 | records.push(record_by("b", "u", 9, 1, 7)); |
| 1964 | let rows = flat_rows(&records, &call_context(), false); |
| 1965 | let series: Vec<Series> = rows |
| 1966 | .iter() |
| 1967 | .map(|row| match row { |
| 1968 | Row::Message(message) => message.series, |
| 1969 | _ => unreachable!(), |
| 1970 | }) |
| 1971 | .collect(); |
| 1972 | assert!(series.iter().all(|series| *series == Series::default())); |
| 1973 | } |
| 1974 | |
| 1975 | #[test] |
| 1976 | fn thread_lists_leave_call_events_out() { |
| 1977 | let records = [call_record( |
| 1978 | "c", |
| 1979 | 9, |
| 1980 | call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]), |
| 1981 | )]; |
| 1982 | assert!(thread_list_rows(&records, &call_context(), false).is_empty()); |
| 1983 | } |
| 1984 | } |