| 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 | AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards, |
| 10 | card_texts, files, images, link_preview, linked_message_spans, meeting_link_in_html, |
| 11 | message_spans, reactions, translated_spans, |
| 12 | }; |
| 13 | |
| 14 | use crate::card_state::CardOverride; |
| 15 | use crate::format; |
| 16 | use crate::reaction_model::{Reactor, UNKNOWN_REACTOR}; |
| 17 | use crate::render::blocks::{Inline, strip_image_placeholders}; |
| 18 | use crate::render::{Block, layout_blocks}; |
| 19 | use crate::translation::{TranslationContext, TranslationLine}; |
| 20 | |
| 21 | const POST_VISIBLE_REPLIES: usize = 3; |
| 22 | |
| 23 | pub const LOAD_OLDER_KEY: &str = "load-older"; |
| 24 | pub const LOAD_NEWER_KEY: &str = "load-newer"; |
| 25 | const UNKNOWN_AUTHOR: &str = "Unknown"; |
| 26 | const DELETED_TEXT: &str = "Message deleted"; |
| 27 | const SERIES_GAP_MINUTES: i64 = 5; |
| 28 | const CORNER_RADIUS: f32 = 14.; |
| 29 | const CORNER_SERIES: f32 = 4.; |
| 30 | |
| 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 32 | pub struct ReactionChip { |
| 33 | pub reaction_type: String, |
| 34 | pub label: String, |
| 35 | pub count: usize, |
| 36 | pub mine: bool, |
| 37 | pub reactors: Vec<Reactor>, |
| 38 | } |
| 39 | |
| 40 | impl ReactionChip { |
| 41 | pub fn glyph(&self) -> String { |
| 42 | reaction_glyph(&self.reaction_type) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 47 | pub struct Series { |
| 48 | pub has_prev: bool, |
| 49 | pub has_next: bool, |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 53 | pub struct Corners { |
| 54 | pub top_left: f32, |
| 55 | pub top_right: f32, |
| 56 | pub bottom_right: f32, |
| 57 | pub bottom_left: f32, |
| 58 | } |
| 59 | |
| 60 | pub fn bubble_corners(own: bool, series: Series) -> Corners { |
| 61 | let joined = |joined: bool| if joined { CORNER_SERIES } else { CORNER_RADIUS }; |
| 62 | if own { |
| 63 | Corners { |
| 64 | top_left: CORNER_RADIUS, |
| 65 | top_right: joined(series.has_prev), |
| 66 | bottom_right: joined(series.has_next), |
| 67 | bottom_left: CORNER_RADIUS, |
| 68 | } |
| 69 | } else { |
| 70 | Corners { |
| 71 | top_left: joined(series.has_prev), |
| 72 | top_right: CORNER_RADIUS, |
| 73 | bottom_right: CORNER_RADIUS, |
| 74 | bottom_left: joined(series.has_next), |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 80 | pub enum Receipt { |
| 81 | #[default] |
| 82 | Hidden, |
| 83 | Pending, |
| 84 | Sent, |
| 85 | Read, |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 89 | pub enum ScheduledState { |
| 90 | Waiting, |
| 91 | DeliveryFailed, |
| 92 | ChangeFailed, |
| 93 | } |
| 94 | |
| 95 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 96 | pub enum Delivery { |
| 97 | Delivered, |
| 98 | Sending, |
| 99 | Failed(String), |
| 100 | Scheduled(ScheduledState), |
| 101 | } |
| 102 | |
| 103 | /// An image of a message that is still being sent, shown from its local bytes. |
| 104 | #[derive(Debug, Clone, PartialEq)] |
| 105 | pub struct LocalImage { |
| 106 | pub image: Arc<Image>, |
| 107 | pub size: Option<(u32, u32)>, |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, PartialEq)] |
| 111 | pub struct MessageRow { |
| 112 | pub key: String, |
| 113 | pub conversation_id: String, |
| 114 | pub author: String, |
| 115 | pub sender_id: Option<String>, |
| 116 | pub application_id: Option<String>, |
| 117 | pub created_at: DateTime<Utc>, |
| 118 | pub series: Series, |
| 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 link_preview: Option<LinkPreview>, |
| 129 | pub meeting_link: Option<String>, |
| 130 | pub adaptive_cards: Vec<AdaptiveCard>, |
| 131 | pub subject: Option<String>, |
| 132 | pub new_marker: bool, |
| 133 | pub reply_root: Option<String>, |
| 134 | pub delivery: Delivery, |
| 135 | pub own: bool, |
| 136 | pub receipt: Receipt, |
| 137 | pub forwarded: bool, |
| 138 | pub translation: Option<TranslationLine>, |
| 139 | } |
| 140 | |
| 141 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 142 | pub struct StartInfo { |
| 143 | pub title: String, |
| 144 | pub user_id: Option<String>, |
| 145 | } |
| 146 | |
| 147 | pub const START_KEY: &str = "conversation-start"; |
| 148 | |
| 149 | #[derive(Debug, Clone, PartialEq)] |
| 150 | pub enum Row { |
| 151 | LoadOlder, |
| 152 | LoadNewer, |
| 153 | Start(StartInfo), |
| 154 | Skeleton(Skeleton), |
| 155 | Message(Box<MessageRow>), |
| 156 | Post(Box<PostRow>), |
| 157 | } |
| 158 | |
| 159 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 160 | pub struct Skeleton { |
| 161 | pub key: &'static str, |
| 162 | pub own: bool, |
| 163 | pub width_ratio: f32, |
| 164 | pub lines: u8, |
| 165 | } |
| 166 | |
| 167 | const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [ |
| 168 | Skeleton { |
| 169 | key: "skeleton-0", |
| 170 | own: false, |
| 171 | width_ratio: 0.42, |
| 172 | lines: 1, |
| 173 | }, |
| 174 | Skeleton { |
| 175 | key: "skeleton-1", |
| 176 | own: true, |
| 177 | width_ratio: 0.3, |
| 178 | lines: 1, |
| 179 | }, |
| 180 | Skeleton { |
| 181 | key: "skeleton-2", |
| 182 | own: true, |
| 183 | width_ratio: 0.48, |
| 184 | lines: 2, |
| 185 | }, |
| 186 | Skeleton { |
| 187 | key: "skeleton-3", |
| 188 | own: false, |
| 189 | width_ratio: 0.26, |
| 190 | lines: 1, |
| 191 | }, |
| 192 | ]; |
| 193 | |
| 194 | pub fn placeholder_rows() -> Vec<Row> { |
| 195 | SKELETON_PLACEHOLDERS |
| 196 | .into_iter() |
| 197 | .map(Row::Skeleton) |
| 198 | .collect() |
| 199 | } |
| 200 | |
| 201 | fn sender_key(row: &MessageRow) -> &str { |
| 202 | row.sender_id.as_deref().unwrap_or(&row.author) |
| 203 | } |
| 204 | |
| 205 | fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool { |
| 206 | next.day_header.is_none() |
| 207 | && !next.new_marker |
| 208 | && sender_key(previous) == sender_key(next) |
| 209 | && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES) |
| 210 | && next.created_at >= previous.created_at |
| 211 | } |
| 212 | |
| 213 | pub fn assign_series(rows: &mut [Row]) { |
| 214 | let mut previous: Option<usize> = None; |
| 215 | for index in 0..rows.len() { |
| 216 | let Row::Message(_) = &rows[index] else { |
| 217 | previous = None; |
| 218 | continue; |
| 219 | }; |
| 220 | if let Some(before) = previous { |
| 221 | let joined = match (&rows[before], &rows[index]) { |
| 222 | (Row::Message(a), Row::Message(b)) => continues_series(a, b), |
| 223 | _ => false, |
| 224 | }; |
| 225 | if joined { |
| 226 | if let Row::Message(a) = &mut rows[before] { |
| 227 | a.series.has_next = true; |
| 228 | } |
| 229 | if let Row::Message(b) = &mut rows[index] { |
| 230 | b.series.has_prev = true; |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | previous = Some(index); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | impl Row { |
| 239 | pub fn key(&self) -> &str { |
| 240 | match self { |
| 241 | Row::LoadOlder => LOAD_OLDER_KEY, |
| 242 | Row::LoadNewer => LOAD_NEWER_KEY, |
| 243 | Row::Start(_) => START_KEY, |
| 244 | Row::Skeleton(skeleton) => skeleton.key, |
| 245 | Row::Message(message) => &message.key, |
| 246 | Row::Post(post) => &post.root.key, |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> { |
| 251 | match self { |
| 252 | Row::Message(message) => Box::new(std::iter::once(message.as_ref())), |
| 253 | Row::Post(post) => Box::new(post.messages()), |
| 254 | Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => { |
| 255 | Box::new(std::iter::empty()) |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | #[derive(Debug, Clone, PartialEq)] |
| 262 | pub struct PostRow { |
| 263 | pub root: MessageRow, |
| 264 | pub replies: Vec<MessageRow>, |
| 265 | pub hidden_reply_count: usize, |
| 266 | pub hidden_repliers: Vec<String>, |
| 267 | } |
| 268 | |
| 269 | impl PostRow { |
| 270 | pub fn local(root: MessageRow) -> Self { |
| 271 | PostRow { |
| 272 | root, |
| 273 | replies: Vec::new(), |
| 274 | hidden_reply_count: 0, |
| 275 | hidden_repliers: Vec::new(), |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | pub fn messages(&self) -> impl Iterator<Item = &MessageRow> { |
| 280 | std::iter::once(&self.root).chain(&self.replies) |
| 281 | } |
| 282 | |
| 283 | pub fn hidden_replies_label(&self) -> Option<String> { |
| 284 | (self.hidden_reply_count > 0) |
| 285 | .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers)) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | fn first_name(name: &str) -> &str { |
| 290 | name.split_whitespace().next().unwrap_or(name) |
| 291 | } |
| 292 | |
| 293 | pub fn replies_label(count: usize, repliers: &[String]) -> String { |
| 294 | let noun = if count == 1 { "reply" } else { "replies" }; |
| 295 | let mut names: Vec<&str> = Vec::new(); |
| 296 | for name in repliers.iter().map(|name| first_name(name)) { |
| 297 | if !names.contains(&name) { |
| 298 | names.push(name); |
| 299 | } |
| 300 | } |
| 301 | let people = match names.as_slice() { |
| 302 | [] => return format!("{count} {noun}"), |
| 303 | [only] => (*only).to_owned(), |
| 304 | [first, second] => format!("{first} and {second}"), |
| 305 | [first, second, third] => format!("{first}, {second} and {third}"), |
| 306 | [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()), |
| 307 | }; |
| 308 | format!("{count} {noun} from {people}") |
| 309 | } |
| 310 | |
| 311 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 312 | pub struct Thread { |
| 313 | pub root_id: String, |
| 314 | pub reply_ids: Vec<String>, |
| 315 | } |
| 316 | |
| 317 | pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String { |
| 318 | time.with_timezone(&offset).format("%H:%M").to_string() |
| 319 | } |
| 320 | |
| 321 | pub fn reaction_label(reaction_type: &str) -> String { |
| 322 | match reaction_type { |
| 323 | "like" => "\u{1F44D}".to_owned(), |
| 324 | "heart" => "\u{2764}".to_owned(), |
| 325 | "laugh" => "\u{1F606}".to_owned(), |
| 326 | "surprised" => "\u{1F62E}".to_owned(), |
| 327 | "sad" => "\u{1F641}".to_owned(), |
| 328 | "angry" => "\u{1F620}".to_owned(), |
| 329 | other => other.to_owned(), |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | pub fn reaction_glyph(reaction_type: &str) -> String { |
| 334 | reaction_label(reaction_type) |
| 335 | .trim_end_matches('\u{FE0F}') |
| 336 | .to_owned() |
| 337 | } |
| 338 | |
| 339 | /// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported"). |
| 340 | pub fn api_reaction(glyph: &str) -> String { |
| 341 | match glyph { |
| 342 | "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(), |
| 343 | other => other.to_owned(), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// The reaction type Teams uses for a glyph: the legacy name for the six classic ones. |
| 348 | pub fn reaction_type_for(glyph: &str) -> String { |
| 349 | let bare = glyph.trim_end_matches('\u{FE0F}'); |
| 350 | ["like", "heart", "laugh", "surprised", "sad", "angry"] |
| 351 | .into_iter() |
| 352 | .find(|name| reaction_label(name) == bare) |
| 353 | .map_or_else(|| bare.to_owned(), str::to_owned) |
| 354 | } |
| 355 | |
| 356 | pub type PendingReactions = HashMap<String, Vec<(String, bool)>>; |
| 357 | |
| 358 | fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool { |
| 359 | my_user_id.is_some() |
| 360 | && reaction.user_id.as_deref() == my_user_id |
| 361 | && reaction_glyph(&reaction.reaction_type) == wanted |
| 362 | } |
| 363 | |
| 364 | pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool { |
| 365 | let wanted = reaction_glyph(glyph); |
| 366 | reactions |
| 367 | .iter() |
| 368 | .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id)) |
| 369 | } |
| 370 | |
| 371 | pub fn set_own_reaction( |
| 372 | reactions: &mut Vec<ReactionInfo>, |
| 373 | glyph: &str, |
| 374 | my_user_id: Option<&str>, |
| 375 | present: bool, |
| 376 | now: DateTime<Utc>, |
| 377 | ) { |
| 378 | let wanted = reaction_glyph(glyph); |
| 379 | if !present { |
| 380 | reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id)); |
| 381 | } else if !has_own_reaction(reactions, glyph, my_user_id) { |
| 382 | reactions.push(ReactionInfo { |
| 383 | reaction_type: reaction_type_for(glyph), |
| 384 | user_id: my_user_id.map(str::to_owned), |
| 385 | user_name: Some("You".to_owned()), |
| 386 | created_at: Some(now), |
| 387 | }); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | pub fn apply_pending_reactions( |
| 392 | reactions: &mut Vec<ReactionInfo>, |
| 393 | pending: Option<&Vec<(String, bool)>>, |
| 394 | my_user_id: Option<&str>, |
| 395 | now: DateTime<Utc>, |
| 396 | ) { |
| 397 | for (glyph, present) in pending.into_iter().flatten() { |
| 398 | set_own_reaction(reactions, glyph, my_user_id, *present, now); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> { |
| 403 | let my_user_id = context.my_user_id.as_deref(); |
| 404 | let mut chips: Vec<ReactionChip> = Vec::new(); |
| 405 | for reaction in reactions { |
| 406 | let glyph = reaction_glyph(&reaction.reaction_type); |
| 407 | let position = match chips.iter().position(|chip| chip.glyph() == glyph) { |
| 408 | Some(position) => position, |
| 409 | None => { |
| 410 | chips.push(ReactionChip { |
| 411 | reaction_type: reaction.reaction_type.clone(), |
| 412 | label: reaction_label(&reaction.reaction_type), |
| 413 | count: 0, |
| 414 | mine: false, |
| 415 | reactors: Vec::new(), |
| 416 | }); |
| 417 | chips.len() - 1 |
| 418 | } |
| 419 | }; |
| 420 | let chip = &mut chips[position]; |
| 421 | chip.count += 1; |
| 422 | chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id; |
| 423 | chip.reactors.push(Reactor { |
| 424 | user_id: reaction.user_id.clone(), |
| 425 | name: reactor_name(reaction, context), |
| 426 | created_at: reaction.created_at, |
| 427 | }); |
| 428 | } |
| 429 | chips |
| 430 | } |
| 431 | |
| 432 | fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String { |
| 433 | reaction |
| 434 | .user_name |
| 435 | .clone() |
| 436 | .or_else(|| { |
| 437 | reaction |
| 438 | .user_id |
| 439 | .as_ref() |
| 440 | .and_then(|user_id| context.names.get(user_id).cloned()) |
| 441 | }) |
| 442 | .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned()) |
| 443 | } |
| 444 | |
| 445 | const REPLY_EXCERPT_CHARS: usize = 90; |
| 446 | const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward"; |
| 447 | |
| 448 | pub fn message_text(record: &MessageRecord) -> String { |
| 449 | let own_spans: Vec<Span> = message_spans(record) |
| 450 | .into_iter() |
| 451 | .filter(|span| !matches!(span, Span::Quote(_))) |
| 452 | .collect(); |
| 453 | strip_image_placeholders(layout_blocks(&own_spans)) |
| 454 | .into_iter() |
| 455 | .filter_map(|block| block.markdown()) |
| 456 | .collect::<Vec<_>>() |
| 457 | .join("\n") |
| 458 | } |
| 459 | |
| 460 | /// The message as the composer edits it, formatting kept. |
| 461 | pub fn message_draft(record: &MessageRecord) -> Draft { |
| 462 | let own_spans: Vec<Span> = message_spans(record) |
| 463 | .into_iter() |
| 464 | .filter(|span| !matches!(span, Span::Quote(_))) |
| 465 | .collect(); |
| 466 | Draft::from_spans(&own_spans).trimmed() |
| 467 | } |
| 468 | |
| 469 | pub fn reply_excerpt(record: &MessageRecord) -> String { |
| 470 | let own_spans: Vec<Span> = message_spans(record) |
| 471 | .into_iter() |
| 472 | .filter(|span| !matches!(span, Span::Quote(_))) |
| 473 | .collect(); |
| 474 | let text = strip_image_placeholders(layout_blocks(&own_spans)) |
| 475 | .into_iter() |
| 476 | .find_map(|block| block.first_line()) |
| 477 | .unwrap_or_default(); |
| 478 | let first_line = text.lines().map(str::trim).find(|line| !line.is_empty()); |
| 479 | let excerpt = match first_line { |
| 480 | Some(line) => line.to_owned(), |
| 481 | None if !images(record).is_empty() => "Image".to_owned(), |
| 482 | None if let Some(line) = card_texts(record) |
| 483 | .iter() |
| 484 | .flat_map(|text| text.lines()) |
| 485 | .next() => |
| 486 | { |
| 487 | line.to_owned() |
| 488 | } |
| 489 | None => files(record) |
| 490 | .into_iter() |
| 491 | .next() |
| 492 | .map_or_else(|| "Message".to_owned(), |card| card.name), |
| 493 | }; |
| 494 | if excerpt.chars().count() > REPLY_EXCERPT_CHARS { |
| 495 | let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect(); |
| 496 | format!("{}...", cut.trim_end()) |
| 497 | } else { |
| 498 | excerpt |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | pub struct RowContext { |
| 503 | pub offset: FixedOffset, |
| 504 | pub today: NaiveDate, |
| 505 | pub my_user_id: Option<String>, |
| 506 | pub names: HashMap<String, String>, |
| 507 | pub pending_reactions: PendingReactions, |
| 508 | pub card_overrides: HashMap<String, CardOverride>, |
| 509 | pub translation: TranslationContext, |
| 510 | } |
| 511 | |
| 512 | fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> { |
| 513 | let mut visible = reactions(record); |
| 514 | apply_pending_reactions( |
| 515 | &mut visible, |
| 516 | context.pending_reactions.get(&record.message_id), |
| 517 | context.my_user_id.as_deref(), |
| 518 | Utc::now(), |
| 519 | ); |
| 520 | visible |
| 521 | } |
| 522 | |
| 523 | pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow { |
| 524 | let local = record.created_at.with_timezone(&context.offset); |
| 525 | let images = images(record); |
| 526 | let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id; |
| 527 | let translation = context.translation.resolve(record, own); |
| 528 | let blocks = if record.deleted { |
| 529 | vec![Block::Paragraph(Inline::plain(DELETED_TEXT))] |
| 530 | } else if let Some(html) = &translation.translated_html { |
| 531 | layout_blocks(&translated_spans(record, html)) |
| 532 | } else { |
| 533 | layout_blocks(&linked_message_spans(record)) |
| 534 | }; |
| 535 | let blocks = if images.is_empty() { |
| 536 | blocks |
| 537 | } else { |
| 538 | strip_image_placeholders(blocks) |
| 539 | }; |
| 540 | MessageRow { |
| 541 | key: record.message_id.clone(), |
| 542 | conversation_id: record.conversation_id.clone(), |
| 543 | sender_id: record.sender_id.clone(), |
| 544 | application_id: record.sender_application_id.clone(), |
| 545 | created_at: record.created_at, |
| 546 | series: Series::default(), |
| 547 | author: record |
| 548 | .sender_name |
| 549 | .clone() |
| 550 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()), |
| 551 | time: clock_label(record.created_at, context.offset), |
| 552 | day_header: Some(format::day_label(local.date_naive(), context.today)), |
| 553 | blocks, |
| 554 | edited: record.edited_at.is_some() && !record.deleted, |
| 555 | deleted: record.deleted, |
| 556 | reactions: reaction_chips(&visible_reactions(record, context), context), |
| 557 | images, |
| 558 | local_images: Vec::new(), |
| 559 | files: files(record), |
| 560 | link_preview: link_preview(record), |
| 561 | meeting_link: (!record.deleted) |
| 562 | .then(|| meeting_link_in_html(&record.body_html)) |
| 563 | .flatten(), |
| 564 | adaptive_cards: match context.card_overrides.get(&record.message_id) { |
| 565 | Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(), |
| 566 | _ => adaptive_cards(record), |
| 567 | }, |
| 568 | subject: record.subject.clone(), |
| 569 | new_marker: false, |
| 570 | reply_root: record.reply_to_id.clone(), |
| 571 | delivery: Delivery::Delivered, |
| 572 | receipt: Receipt::Hidden, |
| 573 | own, |
| 574 | forwarded: !record.deleted && is_forwarded(&record.body_html), |
| 575 | translation: translation.line, |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | pub fn is_forwarded(body_html: &str) -> bool { |
| 580 | body_html.contains(FORWARD_ITEMTYPE) |
| 581 | } |
| 582 | |
| 583 | pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> { |
| 584 | let mut rows = Vec::with_capacity(records.len() + 1); |
| 585 | if has_older { |
| 586 | rows.push(Row::LoadOlder); |
| 587 | } |
| 588 | let mut previous_day: Option<NaiveDate> = None; |
| 589 | for record in records { |
| 590 | let mut row = message_row(record, context); |
| 591 | let day = record |
| 592 | .created_at |
| 593 | .with_timezone(&context.offset) |
| 594 | .date_naive(); |
| 595 | if previous_day == Some(day) { |
| 596 | row.day_header = None; |
| 597 | } |
| 598 | previous_day = Some(day); |
| 599 | rows.push(Row::Message(Box::new(row))); |
| 600 | } |
| 601 | assign_series(&mut rows); |
| 602 | rows |
| 603 | } |
| 604 | |
| 605 | pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> { |
| 606 | let mut threads: Vec<Thread> = Vec::new(); |
| 607 | let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new(); |
| 608 | for record in records.iter().filter(|record| record.reply_to_id.is_none()) { |
| 609 | index_by_root.insert(record.message_id.as_str(), threads.len()); |
| 610 | threads.push(Thread { |
| 611 | root_id: record.message_id.clone(), |
| 612 | reply_ids: Vec::new(), |
| 613 | }); |
| 614 | } |
| 615 | for record in records { |
| 616 | let Some(root_id) = record.reply_to_id.as_deref() else { |
| 617 | continue; |
| 618 | }; |
| 619 | if let Some(&index) = index_by_root.get(root_id) { |
| 620 | threads[index].reply_ids.push(record.message_id.clone()); |
| 621 | } |
| 622 | } |
| 623 | threads |
| 624 | } |
| 625 | |
| 626 | fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> { |
| 627 | thread |
| 628 | .reply_ids |
| 629 | .iter() |
| 630 | .chain(std::iter::once(&thread.root_id)) |
| 631 | .filter_map(|id| by_id.get(id.as_str())) |
| 632 | .map(|record| record.created_at) |
| 633 | .max() |
| 634 | .unwrap_or_default() |
| 635 | } |
| 636 | |
| 637 | fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow { |
| 638 | let mut row = message_row(record, context); |
| 639 | row.day_header = None; |
| 640 | row.time = format::post_time_label(record.created_at, context.today, context.offset); |
| 641 | row |
| 642 | } |
| 643 | |
| 644 | fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> { |
| 645 | let mut names: Vec<String> = Vec::new(); |
| 646 | for record in records { |
| 647 | let name = record |
| 648 | .sender_name |
| 649 | .clone() |
| 650 | .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()); |
| 651 | if !names.contains(&name) { |
| 652 | names.push(name); |
| 653 | } |
| 654 | } |
| 655 | names |
| 656 | } |
| 657 | |
| 658 | fn post_row( |
| 659 | root: &MessageRecord, |
| 660 | mut replies: Vec<&MessageRecord>, |
| 661 | context: &RowContext, |
| 662 | ) -> PostRow { |
| 663 | replies.sort_by_key(|reply| reply.created_at); |
| 664 | let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES); |
| 665 | PostRow { |
| 666 | root: post_message_row(root, context), |
| 667 | hidden_reply_count: hidden, |
| 668 | hidden_repliers: distinct_names(replies[..hidden].iter().copied()), |
| 669 | replies: replies[hidden..] |
| 670 | .iter() |
| 671 | .map(|reply| post_message_row(reply, context)) |
| 672 | .collect(), |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | pub fn thread_list_rows( |
| 677 | records: &[MessageRecord], |
| 678 | context: &RowContext, |
| 679 | has_older: bool, |
| 680 | ) -> Vec<Row> { |
| 681 | let by_id: BTreeMap<&str, &MessageRecord> = records |
| 682 | .iter() |
| 683 | .map(|record| (record.message_id.as_str(), record)) |
| 684 | .collect(); |
| 685 | let mut threads = group_threads(records); |
| 686 | threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id))); |
| 687 | let mut rows: Vec<Row> = threads |
| 688 | .iter() |
| 689 | .filter_map(|thread| { |
| 690 | let root = by_id.get(thread.root_id.as_str())?; |
| 691 | let replies = thread |
| 692 | .reply_ids |
| 693 | .iter() |
| 694 | .filter_map(|id| by_id.get(id.as_str()).copied()) |
| 695 | .collect(); |
| 696 | Some(Row::Post(Box::new(post_row(root, replies, context)))) |
| 697 | }) |
| 698 | .collect(); |
| 699 | if has_older { |
| 700 | rows.push(Row::LoadOlder); |
| 701 | } |
| 702 | rows |
| 703 | } |
| 704 | |
| 705 | pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) { |
| 706 | for message in local { |
| 707 | let Some(root_id) = message.reply_root.clone() else { |
| 708 | rows.insert(0, Row::Post(Box::new(PostRow::local(message)))); |
| 709 | continue; |
| 710 | }; |
| 711 | let position = rows |
| 712 | .iter() |
| 713 | .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id)); |
| 714 | if let Some(position) = position { |
| 715 | let mut row = rows.remove(position); |
| 716 | if let Row::Post(post) = &mut row { |
| 717 | post.replies.push(message); |
| 718 | } |
| 719 | rows.insert(0, row); |
| 720 | } |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> { |
| 725 | let members: Vec<MessageRecord> = records |
| 726 | .iter() |
| 727 | .filter(|record| { |
| 728 | record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id) |
| 729 | }) |
| 730 | .cloned() |
| 731 | .collect(); |
| 732 | flat_rows(&members, context, false) |
| 733 | } |
| 734 | |
| 735 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 736 | pub struct Splice { |
| 737 | pub range: Range<usize>, |
| 738 | pub count: usize, |
| 739 | } |
| 740 | |
| 741 | pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> { |
| 742 | if old == new { |
| 743 | return None; |
| 744 | } |
| 745 | let prefix = old |
| 746 | .iter() |
| 747 | .zip(new) |
| 748 | .take_while(|(left, right)| left == right) |
| 749 | .count(); |
| 750 | let suffix = old[prefix..] |
| 751 | .iter() |
| 752 | .rev() |
| 753 | .zip(new[prefix..].iter().rev()) |
| 754 | .take_while(|(left, right)| left == right) |
| 755 | .count(); |
| 756 | Some(Splice { |
| 757 | range: prefix..old.len() - suffix, |
| 758 | count: new.len() - prefix - suffix, |
| 759 | }) |
| 760 | } |
| 761 | |
| 762 | pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> { |
| 763 | let prefix = old |
| 764 | .iter() |
| 765 | .zip(new) |
| 766 | .take_while(|(left, right)| left.key() == right.key()) |
| 767 | .count(); |
| 768 | let suffix = old[prefix..] |
| 769 | .iter() |
| 770 | .rev() |
| 771 | .zip(new[prefix..].iter().rev()) |
| 772 | .take_while(|(left, right)| left.key() == right.key()) |
| 773 | .count(); |
| 774 | let mut changed: Vec<usize> = (0..prefix) |
| 775 | .filter(|&index| old[index] != new[index]) |
| 776 | .collect(); |
| 777 | changed.extend((0..suffix).filter_map(|offset| { |
| 778 | let old_index = old.len() - 1 - offset; |
| 779 | let new_index = new.len() - 1 - offset; |
| 780 | (old[old_index] != new[new_index]).then_some(new_index) |
| 781 | })); |
| 782 | changed |
| 783 | } |
| 784 | |
| 785 | #[cfg(test)] |
| 786 | mod tests { |
| 787 | use chrono::TimeZone; |
| 788 | |
| 789 | use super::*; |
| 790 | |
| 791 | fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord { |
| 792 | MessageRecord { |
| 793 | conversation_id: "c".into(), |
| 794 | message_id: id.into(), |
| 795 | reply_to_id: reply_to.map(str::to_owned), |
| 796 | sender_id: Some("u".into()), |
| 797 | sender_name: Some("Author".into()), |
| 798 | sender_application_id: None, |
| 799 | links_json: "[]".to_owned(), |
| 800 | created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(), |
| 801 | edited_at: None, |
| 802 | deleted: false, |
| 803 | body_html: format!("<p>text {id}</p>"), |
| 804 | attachments_json: "[]".into(), |
| 805 | reactions_json: "[]".into(), |
| 806 | mentions_json: "[]".into(), |
| 807 | subject: None, |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | fn own_reaction(reaction_type: &str) -> ReactionInfo { |
| 812 | ReactionInfo { |
| 813 | reaction_type: reaction_type.into(), |
| 814 | user_id: Some("me".into()), |
| 815 | user_name: None, |
| 816 | created_at: None, |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn setting_a_reaction_is_idempotent_and_only_touches_mine() { |
| 822 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 823 | let other = ReactionInfo { |
| 824 | user_id: Some("them".into()), |
| 825 | ..own_reaction("like") |
| 826 | }; |
| 827 | let mut reactions = vec![other.clone()]; |
| 828 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now); |
| 829 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now); |
| 830 | assert_eq!(reactions.len(), 2); |
| 831 | assert_eq!(reactions[1].reaction_type, "like"); |
| 832 | assert_eq!(reactions[1].user_id.as_deref(), Some("me")); |
| 833 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now); |
| 834 | set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now); |
| 835 | assert_eq!(reactions, vec![other]); |
| 836 | } |
| 837 | |
| 838 | #[test] |
| 839 | fn setting_matches_legacy_names_and_variation_selectors() { |
| 840 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 841 | let mut reactions = vec![own_reaction("heart")]; |
| 842 | assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me"))); |
| 843 | set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now); |
| 844 | assert!(reactions.is_empty()); |
| 845 | set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now); |
| 846 | assert_eq!(reactions[0].reaction_type, "\u{1F389}"); |
| 847 | } |
| 848 | |
| 849 | #[test] |
| 850 | fn setting_without_a_known_user_never_matches() { |
| 851 | let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap(); |
| 852 | let mut reactions = Vec::new(); |
| 853 | set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now); |
| 854 | set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now); |
| 855 | assert_eq!(reactions.len(), 2); |
| 856 | } |
| 857 | |
| 858 | #[test] |
| 859 | fn pending_reactions_overlay_the_stored_ones() { |
| 860 | let mut stored = record("a", None, 8, 6); |
| 861 | stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap(); |
| 862 | let mut context = context(); |
| 863 | context.my_user_id = Some("me".into()); |
| 864 | context.pending_reactions.insert( |
| 865 | "a".into(), |
| 866 | vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)], |
| 867 | ); |
| 868 | let chips = message_row(&stored, &context).reactions; |
| 869 | assert_eq!(chips.len(), 1); |
| 870 | assert_eq!(chips[0].reaction_type, "\u{1F389}"); |
| 871 | assert!(chips[0].mine); |
| 872 | } |
| 873 | |
| 874 | #[test] |
| 875 | fn reaction_type_maps_classic_glyphs_to_names() { |
| 876 | assert_eq!(reaction_type_for("\u{1F44D}"), "like"); |
| 877 | assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart"); |
| 878 | assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}"); |
| 879 | assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}")); |
| 880 | assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}")); |
| 881 | assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}"); |
| 882 | assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}"); |
| 883 | } |
| 884 | |
| 885 | #[test] |
| 886 | fn forwarded_messages_are_detected_by_the_forward_blockquote() { |
| 887 | assert!(is_forwarded( |
| 888 | r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"# |
| 889 | )); |
| 890 | assert!(!is_forwarded( |
| 891 | r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"# |
| 892 | )); |
| 893 | assert!(!is_forwarded("<p>plain</p>")); |
| 894 | let mut forwarded = record("f", None, 8, 6); |
| 895 | forwarded.body_html = |
| 896 | r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into(); |
| 897 | assert!(message_row(&forwarded, &context()).forwarded); |
| 898 | forwarded.deleted = true; |
| 899 | assert!(!message_row(&forwarded, &context()).forwarded); |
| 900 | } |
| 901 | |
| 902 | #[test] |
| 903 | fn editing_loads_the_message_formatted_without_its_reply_quote() { |
| 904 | let mut edited = record("a", None, 8, 6); |
| 905 | edited.body_html = |
| 906 | "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\ |
| 907 | <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\ |
| 908 | <ol><li>one</li><li>two</li></ol>" |
| 909 | .into(); |
| 910 | let draft = message_draft(&edited); |
| 911 | assert_eq!(draft.text(), "Plan for today\n1. one\n2. two"); |
| 912 | assert_eq!( |
| 913 | draft.to_html(), |
| 914 | "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>" |
| 915 | ); |
| 916 | } |
| 917 | |
| 918 | #[test] |
| 919 | fn reply_excerpt_uses_the_first_line_or_the_attachment() { |
| 920 | let mut text = record("a", None, 8, 6); |
| 921 | text.body_html = "<p>first line</p><p>second</p>".into(); |
| 922 | assert_eq!(reply_excerpt(&text), "first line"); |
| 923 | let mut quoted = record("q", None, 8, 6); |
| 924 | quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into(); |
| 925 | assert_eq!(reply_excerpt("ed), "my answer"); |
| 926 | let mut image = record("b", None, 8, 6); |
| 927 | image.body_html = "<img src=\"u\">".into(); |
| 928 | assert_eq!(reply_excerpt(&image), "Image"); |
| 929 | let mut long = record("c", None, 8, 6); |
| 930 | long.body_html = format!("<p>{}</p>", "x".repeat(200)); |
| 931 | assert!(reply_excerpt(&long).ends_with("...")); |
| 932 | assert_eq!( |
| 933 | reply_excerpt(&long).chars().count(), |
| 934 | REPLY_EXCERPT_CHARS + 3 |
| 935 | ); |
| 936 | } |
| 937 | |
| 938 | fn context() -> RowContext { |
| 939 | RowContext { |
| 940 | offset: FixedOffset::east_opt(0).unwrap(), |
| 941 | today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(), |
| 942 | my_user_id: None, |
| 943 | names: HashMap::new(), |
| 944 | pending_reactions: HashMap::new(), |
| 945 | card_overrides: HashMap::new(), |
| 946 | translation: TranslationContext::default(), |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | fn keys(rows: &[Row]) -> Vec<String> { |
| 951 | rows.iter().map(|row| row.key().to_owned()).collect() |
| 952 | } |
| 953 | |
| 954 | fn translation_context(shown: bool) -> RowContext { |
| 955 | use crate::translation::CachedTranslation; |
| 956 | let mut context = context(); |
| 957 | context.translation.enabled = true; |
| 958 | context.translation.target = "en".into(); |
| 959 | context.translation.stamps.insert( |
| 960 | "a".into(), |
| 961 | "languages=fr:100;length:80;&detector=Bling".into(), |
| 962 | ); |
| 963 | context.my_user_id = Some("me".into()); |
| 964 | if shown { |
| 965 | context.translation.cached.insert( |
| 966 | ("a".into(), 0), |
| 967 | CachedTranslation { |
| 968 | html: "<p><strong>translated</strong> body</p>".into(), |
| 969 | source: Some("fr".into()), |
| 970 | }, |
| 971 | ); |
| 972 | context.translation.shown.insert("a".into()); |
| 973 | } |
| 974 | context |
| 975 | } |
| 976 | |
| 977 | #[test] |
| 978 | fn a_foreign_message_carries_the_offer_and_keeps_its_text() { |
| 979 | let row = message_row(&record("a", None, 8, 6), &translation_context(false)); |
| 980 | assert!(matches!( |
| 981 | row.translation, |
| 982 | Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr" |
| 983 | )); |
| 984 | assert_eq!( |
| 985 | row.blocks, |
| 986 | layout_blocks(&linked_message_spans(&record("a", None, 8, 6))) |
| 987 | ); |
| 988 | } |
| 989 | |
| 990 | #[test] |
| 991 | fn a_shown_translation_replaces_the_body_and_the_original_comes_back() { |
| 992 | let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks; |
| 993 | let translated = message_row(&record("a", None, 8, 6), &translation_context(true)); |
| 994 | assert_ne!(translated.blocks, original); |
| 995 | assert_eq!( |
| 996 | translated.translation, |
| 997 | Some(TranslationLine::Translated { |
| 998 | language: Some("French".into()), |
| 999 | showing_original: false |
| 1000 | }) |
| 1001 | ); |
| 1002 | let mut hidden = translation_context(true); |
| 1003 | hidden.translation.shown.clear(); |
| 1004 | let back = message_row(&record("a", None, 8, 6), &hidden); |
| 1005 | assert_eq!(back.blocks, original); |
| 1006 | assert_eq!( |
| 1007 | back.translation, |
| 1008 | Some(TranslationLine::Translated { |
| 1009 | language: Some("French".into()), |
| 1010 | showing_original: true |
| 1011 | }) |
| 1012 | ); |
| 1013 | } |
| 1014 | |
| 1015 | #[test] |
| 1016 | fn own_messages_get_no_offer() { |
| 1017 | let mut own = record("a", None, 8, 6); |
| 1018 | own.sender_id = Some("me".into()); |
| 1019 | assert_eq!( |
| 1020 | message_row(&own, &translation_context(false)).translation, |
| 1021 | None |
| 1022 | ); |
| 1023 | } |
| 1024 | |
| 1025 | #[test] |
| 1026 | fn day_header_only_on_first_message_of_a_day() { |
| 1027 | let records = vec![ |
| 1028 | record("a", None, 8, 6), |
| 1029 | record("b", None, 9, 6), |
| 1030 | record("c", None, 9, 7), |
| 1031 | ]; |
| 1032 | let rows = flat_rows(&records, &context(), false); |
| 1033 | let headers: Vec<Option<String>> = rows |
| 1034 | .iter() |
| 1035 | .map(|row| match row { |
| 1036 | Row::Message(message) => message.day_header.clone(), |
| 1037 | Row::LoadOlder |
| 1038 | | Row::LoadNewer |
| 1039 | | Row::Start(_) |
| 1040 | | Row::Skeleton(_) |
| 1041 | | Row::Post(_) => None, |
| 1042 | }) |
| 1043 | .collect(); |
| 1044 | assert_eq!( |
| 1045 | headers, |
| 1046 | vec![Some("Yesterday".into()), None, Some("Today".into())] |
| 1047 | ); |
| 1048 | } |
| 1049 | |
| 1050 | #[test] |
| 1051 | fn load_older_row_only_when_more_exists() { |
| 1052 | let records = vec![record("a", None, 8, 6)]; |
| 1053 | assert_eq!( |
| 1054 | keys(&flat_rows(&records, &context(), true))[0], |
| 1055 | LOAD_OLDER_KEY |
| 1056 | ); |
| 1057 | assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]); |
| 1058 | } |
| 1059 | |
| 1060 | #[test] |
| 1061 | fn threads_group_replies_by_root() { |
| 1062 | let records = vec![ |
| 1063 | record("r1", None, 8, 6), |
| 1064 | record("r2", None, 9, 6), |
| 1065 | record("x1", Some("r1"), 10, 6), |
| 1066 | record("x2", Some("r1"), 11, 6), |
| 1067 | record("orphan", Some("missing"), 12, 6), |
| 1068 | ]; |
| 1069 | let threads = group_threads(&records); |
| 1070 | assert_eq!(threads.len(), 2); |
| 1071 | assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]); |
| 1072 | assert!(threads[1].reply_ids.is_empty()); |
| 1073 | } |
| 1074 | |
| 1075 | fn post_of(row: &Row) -> &PostRow { |
| 1076 | let Row::Post(post) = row else { |
| 1077 | panic!("post expected") |
| 1078 | }; |
| 1079 | post |
| 1080 | } |
| 1081 | |
| 1082 | fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord { |
| 1083 | let mut reply = record(id, Some(root), hour, 6); |
| 1084 | reply.sender_name = Some(sender.into()); |
| 1085 | reply |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn feed_orders_posts_by_last_activity_newest_first() { |
| 1090 | let records = vec![ |
| 1091 | record("r1", None, 8, 6), |
| 1092 | record("r2", None, 9, 6), |
| 1093 | record("r3", None, 10, 6), |
| 1094 | record("x1", Some("r1"), 11, 6), |
| 1095 | ]; |
| 1096 | let rows = thread_list_rows(&records, &context(), false); |
| 1097 | assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]); |
| 1098 | } |
| 1099 | |
| 1100 | #[test] |
| 1101 | fn feed_puts_load_older_at_the_bottom() { |
| 1102 | let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)]; |
| 1103 | let rows = thread_list_rows(&records, &context(), true); |
| 1104 | assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn post_shows_the_last_three_replies_oldest_first() { |
| 1109 | let mut records = vec![record("r1", None, 1, 6)]; |
| 1110 | for hour in 2..=6 { |
| 1111 | records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour)); |
| 1112 | } |
| 1113 | records.reverse(); |
| 1114 | let rows = thread_list_rows(&records, &context(), false); |
| 1115 | let post = post_of(&rows[0]); |
| 1116 | let shown: Vec<&str> = post |
| 1117 | .replies |
| 1118 | .iter() |
| 1119 | .map(|reply| reply.key.as_str()) |
| 1120 | .collect(); |
| 1121 | assert_eq!(shown, vec!["x4", "x5", "x6"]); |
| 1122 | assert_eq!(post.hidden_reply_count, 2); |
| 1123 | assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]); |
| 1124 | } |
| 1125 | |
| 1126 | #[test] |
| 1127 | fn post_without_hidden_replies_has_no_link() { |
| 1128 | let records = vec![ |
| 1129 | record("r1", None, 1, 6), |
| 1130 | reply_by("x1", "r1", "Ada", 2), |
| 1131 | reply_by("x2", "r1", "Ben", 3), |
| 1132 | reply_by("x3", "r1", "Cy", 4), |
| 1133 | ]; |
| 1134 | let rows = thread_list_rows(&records, &context(), false); |
| 1135 | assert_eq!(post_of(&rows[0]).hidden_replies_label(), None); |
| 1136 | assert_eq!(post_of(&rows[0]).replies.len(), 3); |
| 1137 | } |
| 1138 | |
| 1139 | fn label_for(repliers: &[&str]) -> String { |
| 1140 | let mut records = vec![record("r1", None, 1, 6)]; |
| 1141 | for (index, name) in repliers.iter().enumerate() { |
| 1142 | records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32)); |
| 1143 | } |
| 1144 | for index in 0..POST_VISIBLE_REPLIES { |
| 1145 | records.push(reply_by( |
| 1146 | &format!("v{index}"), |
| 1147 | "r1", |
| 1148 | "Shown", |
| 1149 | 20 + index as u32, |
| 1150 | )); |
| 1151 | } |
| 1152 | let rows = thread_list_rows(&records, &context(), false); |
| 1153 | post_of(&rows[0]).hidden_replies_label().unwrap() |
| 1154 | } |
| 1155 | |
| 1156 | #[test] |
| 1157 | fn replies_label_names_one_to_three_people() { |
| 1158 | assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna"); |
| 1159 | assert_eq!( |
| 1160 | label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]), |
| 1161 | "3 replies from Anna and Ben" |
| 1162 | ); |
| 1163 | assert_eq!( |
| 1164 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]), |
| 1165 | "4 replies from Anna, Ben and Clara" |
| 1166 | ); |
| 1167 | } |
| 1168 | |
| 1169 | #[test] |
| 1170 | fn replies_label_counts_the_others_beyond_three_people() { |
| 1171 | assert_eq!( |
| 1172 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]), |
| 1173 | "5 replies from Anna, Ben and 3 others" |
| 1174 | ); |
| 1175 | assert_eq!( |
| 1176 | label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]), |
| 1177 | "4 replies from Anna, Ben and 2 others" |
| 1178 | ); |
| 1179 | } |
| 1180 | |
| 1181 | #[test] |
| 1182 | fn local_reply_lands_in_its_post_and_local_post_on_top() { |
| 1183 | let records = vec![ |
| 1184 | record("r1", None, 8, 6), |
| 1185 | record("r2", None, 9, 6), |
| 1186 | reply_by("x1", "r1", "Ada", 10), |
| 1187 | ]; |
| 1188 | let mut rows = thread_list_rows(&records, &context(), true); |
| 1189 | let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context()); |
| 1190 | pending_reply.reply_root = Some("r2".into()); |
| 1191 | let pending_post = message_row(&record("pending-2", None, 12, 6), &context()); |
| 1192 | place_local_rows(&mut rows, vec![pending_reply, pending_post]); |
| 1193 | assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]); |
| 1194 | let replies: Vec<&str> = post_of(&rows[1]) |
| 1195 | .replies |
| 1196 | .iter() |
| 1197 | .map(|reply| reply.key.as_str()) |
| 1198 | .collect(); |
| 1199 | assert_eq!(replies, vec!["pending-1"]); |
| 1200 | } |
| 1201 | |
| 1202 | #[test] |
| 1203 | fn local_reply_to_an_unloaded_post_is_not_shown() { |
| 1204 | let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false); |
| 1205 | let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context()); |
| 1206 | orphan.reply_root = Some("gone".into()); |
| 1207 | place_local_rows(&mut rows, vec![orphan]); |
| 1208 | assert_eq!(keys(&rows), vec!["r1"]); |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn subject_reaches_the_post_root() { |
| 1213 | let mut with_subject = record("r1", None, 8, 6); |
| 1214 | with_subject.subject = Some("Release plan".into()); |
| 1215 | let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false); |
| 1216 | assert_eq!( |
| 1217 | post_of(&rows[0]).root.subject.as_deref(), |
| 1218 | Some("Release plan") |
| 1219 | ); |
| 1220 | assert_eq!(post_of(&rows[1]).root.subject, None); |
| 1221 | } |
| 1222 | |
| 1223 | #[test] |
| 1224 | fn thread_view_has_root_then_replies() { |
| 1225 | let records = vec![ |
| 1226 | record("r1", None, 8, 6), |
| 1227 | record("r2", None, 9, 6), |
| 1228 | record("x1", Some("r1"), 10, 6), |
| 1229 | ]; |
| 1230 | assert_eq!( |
| 1231 | keys(&thread_rows(&records, "r1", &context())), |
| 1232 | vec!["r1", "x1"] |
| 1233 | ); |
| 1234 | } |
| 1235 | |
| 1236 | #[test] |
| 1237 | fn reactions_are_counted_in_first_seen_order() { |
| 1238 | let reaction = |kind: &str| ReactionInfo { |
| 1239 | reaction_type: kind.into(), |
| 1240 | user_id: None, |
| 1241 | user_name: None, |
| 1242 | created_at: None, |
| 1243 | }; |
| 1244 | let chips = reaction_chips( |
| 1245 | &[reaction("heart"), reaction("like"), reaction("heart")], |
| 1246 | &context(), |
| 1247 | ); |
| 1248 | assert_eq!(chips.len(), 2); |
| 1249 | assert_eq!(chips[0].count, 2); |
| 1250 | assert_eq!(chips[1].label, reaction_label("like")); |
| 1251 | } |
| 1252 | |
| 1253 | #[test] |
| 1254 | fn legacy_laugh_and_sad_use_the_teams_glyphs() { |
| 1255 | assert_eq!(reaction_label("laugh"), "\u{1F606}"); |
| 1256 | assert_eq!(reaction_label("sad"), "\u{1F641}"); |
| 1257 | assert_eq!(reaction_type_for("\u{1F606}"), "laugh"); |
| 1258 | assert_eq!(reaction_type_for("\u{1F641}"), "sad"); |
| 1259 | } |
| 1260 | |
| 1261 | #[test] |
| 1262 | fn legacy_and_emoji_reactions_share_a_chip() { |
| 1263 | let reaction = |kind: &str| ReactionInfo { |
| 1264 | reaction_type: kind.into(), |
| 1265 | user_id: None, |
| 1266 | user_name: Some("Lea".into()), |
| 1267 | created_at: None, |
| 1268 | }; |
| 1269 | let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context()); |
| 1270 | assert_eq!(chips.len(), 1); |
| 1271 | assert_eq!(chips[0].count, 2); |
| 1272 | } |
| 1273 | |
| 1274 | #[test] |
| 1275 | fn reactor_name_falls_back_to_directory_then_unknown() { |
| 1276 | let reaction = |user: &str| ReactionInfo { |
| 1277 | reaction_type: "like".into(), |
| 1278 | user_id: Some(user.into()), |
| 1279 | user_name: None, |
| 1280 | created_at: None, |
| 1281 | }; |
| 1282 | let mut context = context(); |
| 1283 | context.names.insert("known".into(), "Priya Nair".into()); |
| 1284 | let chips = reaction_chips(&[reaction("known"), reaction("other")], &context); |
| 1285 | assert_eq!(chips[0].reactors[0].name, "Priya Nair"); |
| 1286 | assert_eq!(chips[0].reactors[1].name, "Unknown"); |
| 1287 | } |
| 1288 | |
| 1289 | fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord { |
| 1290 | let mut record = record(id, None, hour, day); |
| 1291 | record.sender_id = Some(sender.into()); |
| 1292 | record.created_at = Utc |
| 1293 | .with_ymd_and_hms(2026, 10, day, hour, minute, 0) |
| 1294 | .unwrap(); |
| 1295 | record |
| 1296 | } |
| 1297 | |
| 1298 | fn series_of(rows: &[Row]) -> Vec<(bool, bool)> { |
| 1299 | rows.iter() |
| 1300 | .filter_map(|row| match row { |
| 1301 | Row::Message(message) => Some((message.series.has_prev, message.series.has_next)), |
| 1302 | Row::LoadOlder |
| 1303 | | Row::LoadNewer |
| 1304 | | Row::Start(_) |
| 1305 | | Row::Skeleton(_) |
| 1306 | | Row::Post(_) => None, |
| 1307 | }) |
| 1308 | .collect() |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn series_joins_same_sender_within_five_minutes() { |
| 1313 | let records = vec![ |
| 1314 | record_by("a", "ada", 9, 0, 7), |
| 1315 | record_by("b", "ada", 9, 4, 7), |
| 1316 | record_by("c", "ada", 9, 20, 7), |
| 1317 | record_by("d", "bob", 9, 21, 7), |
| 1318 | record_by("e", "ada", 9, 22, 7), |
| 1319 | ]; |
| 1320 | let rows = flat_rows(&records, &context(), false); |
| 1321 | assert_eq!( |
| 1322 | series_of(&rows), |
| 1323 | vec![ |
| 1324 | (false, true), |
| 1325 | (true, false), |
| 1326 | (false, false), |
| 1327 | (false, false), |
| 1328 | (false, false) |
| 1329 | ] |
| 1330 | ); |
| 1331 | } |
| 1332 | |
| 1333 | #[test] |
| 1334 | fn series_window_ends_exactly_at_the_gap_constant() { |
| 1335 | let gap = SERIES_GAP_MINUTES as u32; |
| 1336 | let records = vec![ |
| 1337 | record_by("a", "ada", 9, 0, 7), |
| 1338 | record_by("b", "ada", 9, gap - 1, 7), |
| 1339 | record_by("c", "ada", 9, 2 * gap - 1 + gap, 7), |
| 1340 | ]; |
| 1341 | let rows = flat_rows(&records, &context(), false); |
| 1342 | assert_eq!( |
| 1343 | series_of(&rows), |
| 1344 | vec![(false, true), (true, false), (false, false)] |
| 1345 | ); |
| 1346 | } |
| 1347 | |
| 1348 | #[test] |
| 1349 | fn series_breaks_at_a_new_day() { |
| 1350 | let records = vec![ |
| 1351 | record_by("a", "ada", 23, 58, 6), |
| 1352 | record_by("b", "ada", 0, 1, 7), |
| 1353 | ]; |
| 1354 | let rows = flat_rows(&records, &context(), false); |
| 1355 | assert_eq!(series_of(&rows), vec![(false, false), (false, false)]); |
| 1356 | } |
| 1357 | |
| 1358 | fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] { |
| 1359 | let corners = bubble_corners(own, Series { has_prev, has_next }); |
| 1360 | [ |
| 1361 | corners.top_left, |
| 1362 | corners.top_right, |
| 1363 | corners.bottom_right, |
| 1364 | corners.bottom_left, |
| 1365 | ] |
| 1366 | } |
| 1367 | |
| 1368 | #[test] |
| 1369 | fn corners_match_the_mockup_for_other_senders() { |
| 1370 | assert_eq!(corners(false, false, false), [14., 14., 14., 14.]); |
| 1371 | assert_eq!(corners(false, false, true), [14., 14., 14., 4.]); |
| 1372 | assert_eq!(corners(false, true, true), [4., 14., 14., 4.]); |
| 1373 | assert_eq!(corners(false, true, false), [4., 14., 14., 14.]); |
| 1374 | } |
| 1375 | |
| 1376 | #[test] |
| 1377 | fn corners_match_the_mockup_for_own_messages() { |
| 1378 | assert_eq!(corners(true, false, false), [14., 14., 14., 14.]); |
| 1379 | assert_eq!(corners(true, false, true), [14., 14., 4., 14.]); |
| 1380 | assert_eq!(corners(true, true, true), [14., 4., 4., 14.]); |
| 1381 | assert_eq!(corners(true, true, false), [14., 4., 14., 14.]); |
| 1382 | } |
| 1383 | |
| 1384 | #[test] |
| 1385 | fn own_reaction_is_marked() { |
| 1386 | let reaction = |user: &str| ReactionInfo { |
| 1387 | reaction_type: "like".into(), |
| 1388 | user_id: Some(user.into()), |
| 1389 | user_name: None, |
| 1390 | created_at: None, |
| 1391 | }; |
| 1392 | let mut context = context(); |
| 1393 | context.my_user_id = Some("me".into()); |
| 1394 | let chips = reaction_chips(&[reaction("x"), reaction("me")], &context); |
| 1395 | assert!(chips[0].mine); |
| 1396 | assert!(!reaction_chips(&[reaction("x")], &context)[0].mine); |
| 1397 | } |
| 1398 | |
| 1399 | fn strings(values: &[&str]) -> Vec<String> { |
| 1400 | values.iter().map(|value| (*value).to_owned()).collect() |
| 1401 | } |
| 1402 | |
| 1403 | #[test] |
| 1404 | fn diff_detects_append_prepend_and_replace() { |
| 1405 | let base = strings(&["a", "b"]); |
| 1406 | assert_eq!(diff_keys(&base, &base), None); |
| 1407 | assert_eq!( |
| 1408 | diff_keys(&base, &strings(&["a", "b", "c"])), |
| 1409 | Some(Splice { |
| 1410 | range: 2..2, |
| 1411 | count: 1 |
| 1412 | }) |
| 1413 | ); |
| 1414 | assert_eq!( |
| 1415 | diff_keys(&base, &strings(&["x", "a", "b"])), |
| 1416 | Some(Splice { |
| 1417 | range: 0..0, |
| 1418 | count: 1 |
| 1419 | }) |
| 1420 | ); |
| 1421 | assert_eq!( |
| 1422 | diff_keys( |
| 1423 | &strings(&["load-older", "a"]), |
| 1424 | &strings(&["load-older", "x", "y", "a"]) |
| 1425 | ), |
| 1426 | Some(Splice { |
| 1427 | range: 1..1, |
| 1428 | count: 2 |
| 1429 | }) |
| 1430 | ); |
| 1431 | assert_eq!( |
| 1432 | diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])), |
| 1433 | Some(Splice { |
| 1434 | range: 0..1, |
| 1435 | count: 0 |
| 1436 | }) |
| 1437 | ); |
| 1438 | assert_eq!( |
| 1439 | diff_keys(&base, &strings(&["x"])), |
| 1440 | Some(Splice { |
| 1441 | range: 0..2, |
| 1442 | count: 1 |
| 1443 | }) |
| 1444 | ); |
| 1445 | } |
| 1446 | |
| 1447 | #[test] |
| 1448 | fn changed_indices_find_edited_rows() { |
| 1449 | let old = flat_rows( |
| 1450 | &[record("a", None, 8, 6), record("b", None, 9, 6)], |
| 1451 | &context(), |
| 1452 | false, |
| 1453 | ); |
| 1454 | let mut edited = record("b", None, 9, 6); |
| 1455 | edited.body_html = "<p>changed</p>".into(); |
| 1456 | let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false); |
| 1457 | assert_eq!(changed_indices(&old, &new), vec![1]); |
| 1458 | } |
| 1459 | } |