| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use chrono::{DateTime, FixedOffset, Utc}; |
| 4 | use store::{ChatRecord, Sidebar}; |
| 5 | |
| 6 | use crate::app_state::chat_title; |
| 7 | use crate::data::{ |
| 8 | Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count, |
| 9 | }; |
| 10 | use crate::format; |
| 11 | |
| 12 | pub const FAVORITES_FALLBACK_NAME: &str = "Pinned"; |
| 13 | pub const OTHERS_NAME: &str = "Other chats"; |
| 14 | pub const OTHERS_ID: &str = "others"; |
| 15 | pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here."; |
| 16 | pub const DELETED_PREVIEW: &str = "Message deleted"; |
| 17 | const OWN_PREFIX: &str = "You"; |
| 18 | const GROUP_KIND: &str = "group"; |
| 19 | |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub enum Preview { |
| 22 | Empty, |
| 23 | Deleted, |
| 24 | Text { |
| 25 | prefix: Option<String>, |
| 26 | text: String, |
| 27 | }, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 31 | pub enum Unread { |
| 32 | None, |
| 33 | Dot, |
| 34 | Count(u32), |
| 35 | } |
| 36 | |
| 37 | impl Unread { |
| 38 | pub fn is_unread(self) -> bool { |
| 39 | self != Unread::None |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 44 | pub struct Face { |
| 45 | pub user_id: Option<String>, |
| 46 | pub name: String, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 50 | pub enum AvatarSpec { |
| 51 | Single(Face), |
| 52 | Pair(Face, Face), |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 56 | pub struct ChatItem { |
| 57 | pub id: String, |
| 58 | pub title: String, |
| 59 | pub time_label: String, |
| 60 | pub preview: Preview, |
| 61 | pub unread: Unread, |
| 62 | pub muted: bool, |
| 63 | pub is_group: bool, |
| 64 | pub member_count: usize, |
| 65 | pub avatar: AvatarSpec, |
| 66 | pub presence_user: Option<String>, |
| 67 | pub folder_id: Option<String>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 71 | pub enum SectionKind { |
| 72 | Favorites, |
| 73 | Folder, |
| 74 | Others, |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 78 | pub struct Section { |
| 79 | pub id: String, |
| 80 | pub name: String, |
| 81 | pub kind: SectionKind, |
| 82 | pub collapsed: bool, |
| 83 | pub count: usize, |
| 84 | pub unread_chats: u32, |
| 85 | pub items: Vec<ChatItem>, |
| 86 | pub show_empty_hint: bool, |
| 87 | } |
| 88 | |
| 89 | pub struct SectionInput<'a> { |
| 90 | pub chats: &'a [ChatRecord], |
| 91 | pub directory: &'a Directory, |
| 92 | pub collapsed: &'a HashSet<String>, |
| 93 | pub now: DateTime<Utc>, |
| 94 | pub offset: FixedOffset, |
| 95 | } |
| 96 | |
| 97 | pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview { |
| 98 | if chat.last_message_deleted { |
| 99 | return Preview::Deleted; |
| 100 | } |
| 101 | let Some(text) = chat |
| 102 | .last_message_preview |
| 103 | .as_deref() |
| 104 | .map(str::trim) |
| 105 | .filter(|text| !text.is_empty()) |
| 106 | else { |
| 107 | return Preview::Empty; |
| 108 | }; |
| 109 | let from_me = match (chat.last_message_sender_id.as_deref(), me) { |
| 110 | (Some(sender), Some(me)) => sender == me.user_id, |
| 111 | _ => false, |
| 112 | }; |
| 113 | let prefix = if from_me { |
| 114 | Some(OWN_PREFIX.to_owned()) |
| 115 | } else if is_one_on_one(chat) { |
| 116 | None |
| 117 | } else { |
| 118 | chat.last_message_sender_name |
| 119 | .as_deref() |
| 120 | .map(|name| format::first_name(name).to_owned()) |
| 121 | .filter(|name| !name.is_empty()) |
| 122 | }; |
| 123 | Preview::Text { |
| 124 | prefix, |
| 125 | text: text.to_owned(), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec { |
| 130 | let faces = face_members(chat, me); |
| 131 | let face = |(user_id, name): (Option<String>, String)| Face { user_id, name }; |
| 132 | if is_one_on_one(chat) || faces.len() < 2 { |
| 133 | return AvatarSpec::Single(match faces.into_iter().next() { |
| 134 | Some(first) => face(first), |
| 135 | None => Face { |
| 136 | user_id: None, |
| 137 | name: chat_title(chat), |
| 138 | }, |
| 139 | }); |
| 140 | } |
| 141 | let mut iterator = faces.into_iter(); |
| 142 | let (first, second) = (iterator.next(), iterator.next()); |
| 143 | match (first, second) { |
| 144 | (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)), |
| 145 | _ => AvatarSpec::Single(Face { |
| 146 | user_id: None, |
| 147 | name: chat_title(chat), |
| 148 | }), |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem { |
| 153 | let me = input.directory.me.as_ref(); |
| 154 | let unread = if chat.unread { |
| 155 | unread_count(input.directory, chat) |
| 156 | .filter(|count| *count > 0) |
| 157 | .map_or(Unread::Dot, Unread::Count) |
| 158 | } else { |
| 159 | Unread::None |
| 160 | }; |
| 161 | let presence_user = is_one_on_one(chat) |
| 162 | .then(|| { |
| 163 | others(chat, me) |
| 164 | .into_iter() |
| 165 | .find_map(|(user_id, _)| user_id) |
| 166 | }) |
| 167 | .flatten(); |
| 168 | ChatItem { |
| 169 | id: chat.id.clone(), |
| 170 | title: chat_title(chat), |
| 171 | time_label: chat |
| 172 | .last_message_at |
| 173 | .map(|time| { |
| 174 | format::list_time_label( |
| 175 | time, |
| 176 | input.now.with_timezone(&input.offset).date_naive(), |
| 177 | input.offset, |
| 178 | ) |
| 179 | }) |
| 180 | .unwrap_or_default(), |
| 181 | preview: preview_for(chat, me), |
| 182 | unread, |
| 183 | muted: chat.muted, |
| 184 | is_group: chat.kind == GROUP_KIND, |
| 185 | member_count: chat.members.len(), |
| 186 | avatar: avatar_for(chat, me), |
| 187 | presence_user, |
| 188 | folder_id: folder_id.map(str::to_owned), |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 { |
| 193 | chats |
| 194 | .iter() |
| 195 | .filter(|chat| chat.unread && !chat.muted) |
| 196 | .count() as u32 |
| 197 | } |
| 198 | |
| 199 | pub fn any_unread_channel(sidebar: &Sidebar) -> bool { |
| 200 | sidebar |
| 201 | .teams |
| 202 | .iter() |
| 203 | .any(|team| team.channels.iter().any(|channel| channel.unread)) |
| 204 | } |
| 205 | |
| 206 | pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> { |
| 207 | let by_id: HashMap<&str, &ChatRecord> = input |
| 208 | .chats |
| 209 | .iter() |
| 210 | .map(|chat| (chat.id.as_str(), chat)) |
| 211 | .collect(); |
| 212 | let mut placed: HashSet<&str> = HashSet::new(); |
| 213 | let mut sections = Vec::new(); |
| 214 | for folder in &input.directory.folders { |
| 215 | let items: Vec<ChatItem> = folder |
| 216 | .conversation_ids |
| 217 | .iter() |
| 218 | .filter_map(|id| by_id.get(id.as_str()).copied()) |
| 219 | .filter(|chat| placed.insert(chat.id.as_str())) |
| 220 | .map(|chat| chat_item(chat, input, Some(&folder.id))) |
| 221 | .collect(); |
| 222 | let (kind, name) = match folder.kind { |
| 223 | FolderKind::Favorites => ( |
| 224 | SectionKind::Favorites, |
| 225 | if folder.name.trim().is_empty() { |
| 226 | FAVORITES_FALLBACK_NAME.to_owned() |
| 227 | } else { |
| 228 | folder.name.clone() |
| 229 | }, |
| 230 | ), |
| 231 | FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()), |
| 232 | }; |
| 233 | sections.push(section(folder.id.clone(), name, kind, items, input)); |
| 234 | } |
| 235 | let rest: Vec<ChatItem> = input |
| 236 | .chats |
| 237 | .iter() |
| 238 | .filter(|chat| !placed.contains(chat.id.as_str())) |
| 239 | .map(|chat| chat_item(chat, input, None)) |
| 240 | .collect(); |
| 241 | sections.push(section( |
| 242 | OTHERS_ID.to_owned(), |
| 243 | OTHERS_NAME.to_owned(), |
| 244 | SectionKind::Others, |
| 245 | rest, |
| 246 | input, |
| 247 | )); |
| 248 | sections |
| 249 | } |
| 250 | |
| 251 | pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> { |
| 252 | let visible: Vec<&str> = sections |
| 253 | .iter() |
| 254 | .filter(|section| !section.collapsed) |
| 255 | .flat_map(|section| section.items.iter().map(|item| item.id.as_str())) |
| 256 | .collect(); |
| 257 | let position = visible.iter().position(|id| *id == removed_id)?; |
| 258 | visible |
| 259 | .get(position + 1) |
| 260 | .or_else(|| { |
| 261 | position |
| 262 | .checked_sub(1) |
| 263 | .and_then(|previous| visible.get(previous)) |
| 264 | }) |
| 265 | .map(|id| (*id).to_owned()) |
| 266 | } |
| 267 | |
| 268 | fn section( |
| 269 | id: String, |
| 270 | name: String, |
| 271 | kind: SectionKind, |
| 272 | items: Vec<ChatItem>, |
| 273 | input: &SectionInput<'_>, |
| 274 | ) -> Section { |
| 275 | let collapsed = input.collapsed.contains(&id); |
| 276 | let unread_chats = items |
| 277 | .iter() |
| 278 | .filter(|item| item.unread.is_unread() && !item.muted) |
| 279 | .count() as u32; |
| 280 | Section { |
| 281 | collapsed, |
| 282 | count: items.len(), |
| 283 | unread_chats, |
| 284 | show_empty_hint: items.is_empty() && !collapsed && kind != SectionKind::Others, |
| 285 | id, |
| 286 | name, |
| 287 | kind, |
| 288 | items, |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | #[cfg(test)] |
| 293 | mod tests { |
| 294 | use chrono::TimeZone; |
| 295 | use store::MemberRecord; |
| 296 | |
| 297 | use super::*; |
| 298 | use crate::data::FolderInfo; |
| 299 | |
| 300 | fn me() -> Person { |
| 301 | Person { |
| 302 | user_id: "me".into(), |
| 303 | display_name: "Me Myself".into(), |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord { |
| 308 | ChatRecord { |
| 309 | id: id.into(), |
| 310 | kind: kind.into(), |
| 311 | title: id.to_uppercase(), |
| 312 | unread, |
| 313 | last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()), |
| 314 | members: vec![ |
| 315 | MemberRecord { |
| 316 | user_id: Some("me".into()), |
| 317 | display_name: "Me Myself".into(), |
| 318 | }, |
| 319 | MemberRecord { |
| 320 | user_id: Some("ada".into()), |
| 321 | display_name: "Ada Example".into(), |
| 322 | }, |
| 323 | MemberRecord { |
| 324 | user_id: Some("bob".into()), |
| 325 | display_name: "Bob Sample".into(), |
| 326 | }, |
| 327 | ], |
| 328 | ..Default::default() |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo { |
| 333 | FolderInfo { |
| 334 | id: id.into(), |
| 335 | name: format!("name-{id}"), |
| 336 | kind, |
| 337 | conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn input<'a>( |
| 342 | chats: &'a [ChatRecord], |
| 343 | directory: &'a Directory, |
| 344 | collapsed: &'a HashSet<String>, |
| 345 | ) -> SectionInput<'a> { |
| 346 | SectionInput { |
| 347 | chats, |
| 348 | directory, |
| 349 | collapsed, |
| 350 | now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(), |
| 351 | offset: FixedOffset::east_opt(0).unwrap(), |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | #[test] |
| 356 | fn next_chat_is_the_following_row_then_the_previous_one() { |
| 357 | let chats = [ |
| 358 | chat("a", "group", false), |
| 359 | chat("b", "group", false), |
| 360 | chat("c", "group", false), |
| 361 | ]; |
| 362 | let directory = Directory::default(); |
| 363 | let collapsed = HashSet::new(); |
| 364 | let sections = build_sections(&input(&chats, &directory, &collapsed)); |
| 365 | assert_eq!(next_chat_id(§ions, "a"), Some("b".to_owned())); |
| 366 | assert_eq!(next_chat_id(§ions, "c"), Some("b".to_owned())); |
| 367 | assert_eq!(next_chat_id(§ions, "zzz"), None); |
| 368 | let single = [chat("a", "group", false)]; |
| 369 | let sections = build_sections(&input(&single, &directory, &collapsed)); |
| 370 | assert_eq!(next_chat_id(§ions, "a"), None); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn muted_chats_stay_out_of_unread_counts() { |
| 375 | let mut quiet = chat("a", "group", true); |
| 376 | quiet.muted = true; |
| 377 | let chats = [quiet, chat("b", "group", true)]; |
| 378 | assert_eq!(unread_chat_count(&chats), 1); |
| 379 | let directory = Directory::default(); |
| 380 | let collapsed = HashSet::new(); |
| 381 | let sections = build_sections(&input(&chats, &directory, &collapsed)); |
| 382 | assert_eq!(sections[0].unread_chats, 1); |
| 383 | assert!(sections[0].items[0].muted); |
| 384 | assert!(sections[0].items[0].unread.is_unread()); |
| 385 | } |
| 386 | |
| 387 | #[test] |
| 388 | fn preview_prefix_is_you_for_own_and_first_name_for_groups() { |
| 389 | let mut group = chat("g", "group", false); |
| 390 | group.last_message_preview = Some("Hello".into()); |
| 391 | group.last_message_sender_id = Some("ada".into()); |
| 392 | group.last_message_sender_name = Some("Ada Example".into()); |
| 393 | assert_eq!( |
| 394 | preview_for(&group, Some(&me())), |
| 395 | Preview::Text { |
| 396 | prefix: Some("Ada".into()), |
| 397 | text: "Hello".into() |
| 398 | } |
| 399 | ); |
| 400 | group.last_message_sender_id = Some("me".into()); |
| 401 | assert_eq!( |
| 402 | preview_for(&group, Some(&me())), |
| 403 | Preview::Text { |
| 404 | prefix: Some("You".into()), |
| 405 | text: "Hello".into() |
| 406 | } |
| 407 | ); |
| 408 | let mut direct = chat("d", "oneOnOne", false); |
| 409 | direct.last_message_preview = Some("Hi".into()); |
| 410 | direct.last_message_sender_id = Some("ada".into()); |
| 411 | direct.last_message_sender_name = Some("Ada Example".into()); |
| 412 | assert_eq!( |
| 413 | preview_for(&direct, Some(&me())), |
| 414 | Preview::Text { |
| 415 | prefix: None, |
| 416 | text: "Hi".into() |
| 417 | } |
| 418 | ); |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn deleted_and_blank_previews() { |
| 423 | let mut deleted = chat("d", "group", false); |
| 424 | deleted.last_message_deleted = true; |
| 425 | deleted.last_message_preview = Some("secret".into()); |
| 426 | assert_eq!(preview_for(&deleted, None), Preview::Deleted); |
| 427 | assert_eq!( |
| 428 | preview_for(&chat("e", "group", false), None), |
| 429 | Preview::Empty |
| 430 | ); |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn sections_follow_folder_order_and_leave_the_rest_for_others() { |
| 435 | let chats = vec![ |
| 436 | chat("a", "group", false), |
| 437 | chat("b", "oneOnOne", true), |
| 438 | chat("c", "group", false), |
| 439 | chat("d", "group", false), |
| 440 | ]; |
| 441 | let directory = Directory { |
| 442 | me: Some(me()), |
| 443 | folders: vec![ |
| 444 | folder("fav", FolderKind::Favorites, &["c"]), |
| 445 | folder("work", FolderKind::UserCreated, &["b", "gone", "a"]), |
| 446 | folder("todo", FolderKind::UserCreated, &[]), |
| 447 | ], |
| 448 | ..Default::default() |
| 449 | }; |
| 450 | let collapsed = HashSet::new(); |
| 451 | let sections = build_sections(&input(&chats, &directory, &collapsed)); |
| 452 | let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect(); |
| 453 | assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]); |
| 454 | let work: Vec<&str> = sections[1] |
| 455 | .items |
| 456 | .iter() |
| 457 | .map(|item| item.id.as_str()) |
| 458 | .collect(); |
| 459 | assert_eq!(work, vec!["b", "a"]); |
| 460 | assert_eq!(sections[1].count, 2); |
| 461 | assert_eq!(sections[2].count, 0); |
| 462 | assert!(sections[2].show_empty_hint); |
| 463 | let others: Vec<&str> = sections[3] |
| 464 | .items |
| 465 | .iter() |
| 466 | .map(|item| item.id.as_str()) |
| 467 | .collect(); |
| 468 | assert_eq!(others, vec!["d"]); |
| 469 | assert!(!sections[3].show_empty_hint); |
| 470 | } |
| 471 | |
| 472 | #[test] |
| 473 | fn collapsed_sections_keep_the_aggregated_unread() { |
| 474 | let chats = vec![ |
| 475 | chat("a", "group", true), |
| 476 | chat("b", "group", true), |
| 477 | chat("c", "group", false), |
| 478 | ]; |
| 479 | let directory = Directory { |
| 480 | folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])], |
| 481 | ..Default::default() |
| 482 | }; |
| 483 | let collapsed: HashSet<String> = ["work".to_owned()].into(); |
| 484 | let sections = build_sections(&input(&chats, &directory, &collapsed)); |
| 485 | assert!(sections[0].collapsed); |
| 486 | assert_eq!(sections[0].unread_chats, 2); |
| 487 | assert_eq!(sections[0].count, 3); |
| 488 | assert!(!sections[0].show_empty_hint); |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn collapsed_empty_folder_hides_the_hint() { |
| 493 | let directory = Directory { |
| 494 | folders: vec![folder("todo", FolderKind::UserCreated, &[])], |
| 495 | ..Default::default() |
| 496 | }; |
| 497 | let collapsed: HashSet<String> = ["todo".to_owned()].into(); |
| 498 | let sections = build_sections(&input(&[], &directory, &collapsed)); |
| 499 | assert!(!sections[0].show_empty_hint); |
| 500 | } |
| 501 | |
| 502 | #[test] |
| 503 | fn favorites_without_a_server_name_say_angeheftet() { |
| 504 | let mut favorites = folder("fav", FolderKind::Favorites, &[]); |
| 505 | favorites.name = String::new(); |
| 506 | let directory = Directory { |
| 507 | folders: vec![favorites], |
| 508 | ..Default::default() |
| 509 | }; |
| 510 | let sections = build_sections(&input(&[], &directory, &HashSet::new())); |
| 511 | assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME); |
| 512 | } |
| 513 | |
| 514 | #[test] |
| 515 | fn unread_is_a_count_when_known_else_a_dot() { |
| 516 | let chats = vec![ |
| 517 | chat("a", "group", true), |
| 518 | chat("b", "group", true), |
| 519 | chat("c", "group", false), |
| 520 | ]; |
| 521 | let mut directory = Directory::default(); |
| 522 | directory.unread_counts.insert("a".into(), 5); |
| 523 | let collapsed = HashSet::new(); |
| 524 | let context = input(&chats, &directory, &collapsed); |
| 525 | assert_eq!( |
| 526 | chat_item(&chats[0], &context, None).unread, |
| 527 | Unread::Count(5) |
| 528 | ); |
| 529 | assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot); |
| 530 | assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None); |
| 531 | assert_eq!(unread_chat_count(&chats), 2); |
| 532 | } |
| 533 | |
| 534 | #[test] |
| 535 | fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() { |
| 536 | let directory = Directory { |
| 537 | me: Some(me()), |
| 538 | ..Default::default() |
| 539 | }; |
| 540 | let collapsed = HashSet::new(); |
| 541 | let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)]; |
| 542 | let context = input(&chats, &directory, &collapsed); |
| 543 | let direct = chat_item(&chats[0], &context, None); |
| 544 | assert_eq!(direct.presence_user.as_deref(), Some("ada")); |
| 545 | assert!( |
| 546 | matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example") |
| 547 | ); |
| 548 | let group = chat_item(&chats[1], &context, None); |
| 549 | assert_eq!(group.presence_user, None); |
| 550 | assert!(matches!(group.avatar, AvatarSpec::Pair(..))); |
| 551 | } |
| 552 | |
| 553 | #[test] |
| 554 | fn time_label_uses_the_list_rules() { |
| 555 | let chats = vec![chat("a", "group", false)]; |
| 556 | let directory = Directory::default(); |
| 557 | let collapsed = HashSet::new(); |
| 558 | let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None); |
| 559 | assert_eq!(item.time_label, "09:30"); |
| 560 | } |
| 561 | } |