BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / sidebar_model.rs

sidebar_model.rs

d39bdfed History
sidebar_model.rs 37.7 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam};
5use teams_core::ChatSection;
6use app_ui_kit::widgets::Unread;
7
8use crate::app_state::chat_title;
9use crate::data::{
10 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
11};
12use crate::format;
13use crate::typing::{TypingState, preview_label};
14
15pub const FAVORITES_FALLBACK_NAME: &str = "Favorites";
16pub const OTHERS_NAME: &str = "Other chats";
17pub const OTHERS_ID: &str = "others";
18pub const MUTED_NAME: &str = "Muted";
19pub const MUTED_ID: &str = "muted_chats";
20pub const SECTION_PAGE_SIZE: usize = 5;
21pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
22pub const DELETED_PREVIEW: &str = "Message deleted";
23const OWN_PREFIX: &str = "You";
24const GROUP_KIND: &str = "group";
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Preview {
28 Empty,
29 Deleted,
30 Typing(String),
31 Text {
32 prefix: Option<String>,
33 text: String,
34 },
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Face {
39 pub user_id: Option<String>,
40 pub name: String,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum AvatarSpec {
45 Single(Face),
46 Pair(Face, Face),
47 Meeting,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct ChatItem {
52 pub id: String,
53 pub title: String,
54 pub time_label: String,
55 pub preview: Preview,
56 pub unread: Unread,
57 pub muted: bool,
58 pub is_group: bool,
59 pub member_count: usize,
60 pub avatar: AvatarSpec,
61 pub presence_user: Option<String>,
62 pub folder_id: Option<String>,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum SectionKind {
67 Favorites,
68 Folder,
69 Others,
70 Muted,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Section {
75 pub id: String,
76 pub name: String,
77 pub kind: SectionKind,
78 pub collapsed: bool,
79 pub count: usize,
80 pub unread_chats: u32,
81 pub items: Vec<ChatItem>,
82 pub hidden_count: usize,
83 pub list_expanded: bool,
84 pub show_empty_hint: bool,
85}
86
87pub struct SectionInput<'a> {
88 pub chats: &'a [ChatRecord],
89 pub directory: &'a Directory,
90 pub collapsed: &'a HashSet<String>,
91 pub expanded_lists: &'a HashSet<String>,
92 pub typing: &'a TypingState,
93 pub now: DateTime<Utc>,
94 pub offset: FixedOffset,
95}
96
97pub 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
129pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
130 if chat.kind.eq_ignore_ascii_case("meeting") {
131 return AvatarSpec::Meeting;
132 }
133 let faces = face_members(chat, me);
134 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
135 if is_one_on_one(chat) || faces.len() < 2 {
136 return AvatarSpec::Single(match faces.into_iter().next() {
137 Some(first) => face(first),
138 None => Face {
139 user_id: None,
140 name: chat_title(chat),
141 },
142 });
143 }
144 let mut iterator = faces.into_iter();
145 let (first, second) = (iterator.next(), iterator.next());
146 match (first, second) {
147 (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)),
148 _ => AvatarSpec::Single(Face {
149 user_id: None,
150 name: chat_title(chat),
151 }),
152 }
153}
154
155pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem {
156 let me = input.directory.me.as_ref();
157 let unread = if chat.unread {
158 unread_count(input.directory, chat)
159 .filter(|count| *count > 0)
160 .map_or(Unread::Dot, Unread::Count)
161 } else {
162 Unread::None
163 };
164 let presence_user = is_one_on_one(chat)
165 .then(|| {
166 others(chat, me)
167 .into_iter()
168 .find_map(|(user_id, _)| user_id)
169 })
170 .flatten();
171 let typing_names = input.typing.names(&chat.id);
172 let preview = if typing_names.is_empty() {
173 preview_for(chat, me)
174 } else {
175 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
176 };
177 ChatItem {
178 id: chat.id.clone(),
179 title: chat_title(chat),
180 time_label: chat
181 .last_message_at
182 .map(|time| {
183 format::list_time_label(
184 time,
185 input.now.with_timezone(&input.offset).date_naive(),
186 input.offset,
187 )
188 })
189 .unwrap_or_default(),
190 preview,
191 unread,
192 muted: chat.muted,
193 is_group: chat.kind == GROUP_KIND,
194 member_count: chat.members.len(),
195 avatar: avatar_for(chat, me),
196 presence_user,
197 folder_id: folder_id.map(str::to_owned),
198 }
199}
200
201pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
202 chats
203 .iter()
204 .filter(|chat| chat.unread && !chat.muted)
205 .count() as u32
206}
207
208pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
209 sidebar
210 .teams
211 .iter()
212 .any(|team| team.channels.iter().any(|channel| channel.unread))
213}
214
215pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
216 let by_id: HashMap<&str, &ChatRecord> = input
217 .chats
218 .iter()
219 .map(|chat| (chat.id.as_str(), chat))
220 .collect();
221 let mut placed: HashSet<&str> = HashSet::new();
222 let mut built: Vec<Option<Section>> = input
223 .directory
224 .folders
225 .iter()
226 .map(|folder| {
227 let (kind, name) = match folder.kind {
228 FolderKind::Favorites => (
229 SectionKind::Favorites,
230 if folder.name.trim().is_empty() {
231 FAVORITES_FALLBACK_NAME.to_owned()
232 } else {
233 folder.name.clone()
234 },
235 ),
236 FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
237 FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,
238 };
239 let items: Vec<ChatItem> = folder
240 .conversation_ids
241 .iter()
242 .filter_map(|id| by_id.get(id.as_str()).copied())
243 .filter(|chat| placed.insert(chat.id.as_str()))
244 .map(|chat| chat_item(chat, input, Some(&folder.id)))
245 .collect();
246 Some(section(folder.id.clone(), name, kind, items, input))
247 })
248 .collect();
249 let settings = &input.directory.section_settings;
250 let mut muted = Vec::new();
251 let mut rest = Vec::new();
252 for chat in input
253 .chats
254 .iter()
255 .filter(|chat| !placed.contains(chat.id.as_str()))
256 {
257 let item = chat_item(chat, input, None);
258 if chat.muted && settings.enabled(ChatSection::Muted) {
259 muted.push(item);
260 } else {
261 rest.push(item);
262 }
263 }
264 let folder_id = |kind: FolderKind, fallback: &str| {
265 input
266 .directory
267 .folders
268 .iter()
269 .find(|folder| folder.kind == kind)
270 .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
271 };
272 let mut others = Some(section(
273 folder_id(FolderKind::Recent, OTHERS_ID),
274 OTHERS_NAME.to_owned(),
275 SectionKind::Others,
276 rest,
277 input,
278 ));
279 let mut muted = (!muted.is_empty()).then(|| {
280 section(
281 folder_id(FolderKind::Muted, MUTED_ID),
282 MUTED_NAME.to_owned(),
283 SectionKind::Muted,
284 muted,
285 input,
286 )
287 });
288 let mut sections = Vec::new();
289 for (folder, section) in input.directory.folders.iter().zip(&mut built) {
290 match folder.kind {
291 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
292 FolderKind::Recent => sections.extend(others.take()),
293 FolderKind::Meeting => {}
294 FolderKind::Muted => sections.extend(muted.take()),
295 }
296 }
297 sections.extend(others);
298 sections.extend(muted);
299 sections
300}
301
302pub fn wants_older_chats(
303 others_end: Option<f32>,
304 viewport_bottom: f32,
305 scroll_top: f32,
306 last_trigger_top: Option<f32>,
307 loading: bool,
308) -> bool {
309 !loading
310 && others_end.is_some_and(|end| end <= viewport_bottom)
311 && last_trigger_top != Some(scroll_top)
312}
313
314pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
315 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
316 (was_loading && !is_loading) || (!had_more && has_more)
317}
318
319pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
320 sections
321 .iter()
322 .filter(|section| !section.collapsed)
323 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
324 .collect()
325}
326
327pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
328 let visible = visible_chat_ids(sections);
329 let position = visible.iter().position(|id| *id == removed_id)?;
330 visible
331 .get(position + 1)
332 .or_else(|| {
333 position
334 .checked_sub(1)
335 .and_then(|previous| visible.get(previous))
336 })
337 .map(|id| (*id).to_owned())
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341pub enum Step {
342 Previous,
343 Next,
344}
345
346pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String> {
347 let position = current.and_then(|current| ids.iter().position(|id| *id == current));
348 let target = match (position, step) {
349 (Some(position), Step::Next) => position + 1,
350 (Some(position), Step::Previous) => position.checked_sub(1)?,
351 (None, Step::Next) => 0,
352 (None, Step::Previous) => ids.len().checked_sub(1)?,
353 };
354 ids.get(target).map(|id| (*id).to_owned())
355}
356
357pub struct ChannelOrderInput<'a> {
358 pub teams: &'a [SidebarTeam],
359 pub pinned_ids: &'a [String],
360 pub collapsed_teams: &'a HashSet<String>,
361 pub revealed_channel_teams: &'a HashSet<String>,
362 pub hidden_teams_open: bool,
363 pub selected_channel: Option<&'a str>,
364}
365
366pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
367 let mut ids: Vec<&str> = Vec::new();
368 let mut push = |id: &'a str| {
369 if !ids.contains(&id) {
370 ids.push(id);
371 }
372 };
373 for pinned_id in input.pinned_ids {
374 let known = input
375 .teams
376 .iter()
377 .flat_map(|entry| entry.channels.iter())
378 .find(|channel| &channel.id == pinned_id);
379 if let Some(channel) = known {
380 push(&channel.id);
381 }
382 }
383 let holds_selection = |entry: &SidebarTeam| {
384 entry
385 .channels
386 .iter()
387 .any(|channel| Some(channel.id.as_str()) == input.selected_channel)
388 };
389 let hidden_teams_shown = input.hidden_teams_open
390 || input
391 .teams
392 .iter()
393 .any(|entry| entry.hidden && holds_selection(entry));
394 let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
395 input
396 .teams
397 .iter()
398 .filter(|entry| entry.hidden && hidden_teams_shown),
399 );
400 for entry in teams {
401 if input.collapsed_teams.contains(&entry.team.id) {
402 continue;
403 }
404 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
405 let is_selected =
406 |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
407 let revealed = input.revealed_channel_teams.contains(&entry.team.id);
408 for channel in entry
409 .channels
410 .iter()
411 .filter(|channel| !is_hidden(channel) || is_selected(channel))
412 {
413 push(&channel.id);
414 }
415 if revealed {
416 for channel in entry
417 .channels
418 .iter()
419 .filter(|channel| is_hidden(channel) && !is_selected(channel))
420 {
421 push(&channel.id);
422 }
423 }
424 }
425 ids
426}
427
428fn section(
429 id: String,
430 name: String,
431 kind: SectionKind,
432 mut items: Vec<ChatItem>,
433 input: &SectionInput<'_>,
434) -> Section {
435 let collapsed = input.collapsed.contains(&id);
436 let count = items.len();
437 let unread_chats = items
438 .iter()
439 .filter(|item| item.unread.is_unread() && !item.muted)
440 .count() as u32;
441 let paged = kind == SectionKind::Muted;
442 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
443 let hidden_count = if paged && !list_expanded {
444 count.saturating_sub(SECTION_PAGE_SIZE)
445 } else {
446 0
447 };
448 items.truncate(count - hidden_count);
449 if kind == SectionKind::Muted {
450 for item in &mut items {
451 if item.unread.is_unread() {
452 item.unread = Unread::Silent;
453 }
454 }
455 }
456 Section {
457 collapsed,
458 count,
459 unread_chats,
460 hidden_count,
461 list_expanded,
462 show_empty_hint: items.is_empty()
463 && !collapsed
464 && matches!(kind, SectionKind::Favorites | SectionKind::Folder),
465 id,
466 name,
467 kind,
468 items,
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use chrono::TimeZone;
475 use store::MemberRecord;
476
477 use super::*;
478 use crate::data::FolderInfo;
479
480 fn me() -> Person {
481 Person {
482 user_id: "me".into(),
483 display_name: "Me Myself".into(),
484 }
485 }
486
487 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
488 ChatRecord {
489 id: id.into(),
490 kind: kind.into(),
491 title: id.to_uppercase(),
492 unread,
493 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
494 members: vec![
495 MemberRecord {
496 user_id: Some("me".into()),
497 display_name: "Me Myself".into(),
498 },
499 MemberRecord {
500 user_id: Some("ada".into()),
501 display_name: "Ada Example".into(),
502 },
503 MemberRecord {
504 user_id: Some("bob".into()),
505 display_name: "Bob Sample".into(),
506 },
507 ],
508 ..Default::default()
509 }
510 }
511
512 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
513 FolderInfo {
514 id: id.into(),
515 name: format!("name-{id}"),
516 kind,
517 expanded: None,
518 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
519 }
520 }
521
522 fn muted_chat(id: &str) -> ChatRecord {
523 ChatRecord {
524 muted: true,
525 ..chat(id, "group", false)
526 }
527 }
528
529 fn meeting_chat(id: &str) -> ChatRecord {
530 chat(id, "meeting", false)
531 }
532
533 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
534 let mut directory = Directory {
535 folders,
536 ..Default::default()
537 };
538 directory.section_settings.set(ChatSection::Muted, muted);
539 directory
540 }
541
542 fn section_ids(sections: &[Section]) -> Vec<&str> {
543 sections.iter().map(|section| section.id.as_str()).collect()
544 }
545
546 fn item_ids(section: &Section) -> Vec<&str> {
547 section.items.iter().map(|item| item.id.as_str()).collect()
548 }
549
550 fn input<'a>(
551 chats: &'a [ChatRecord],
552 directory: &'a Directory,
553 collapsed: &'a HashSet<String>,
554 ) -> SectionInput<'a> {
555 typing_input(chats, directory, collapsed, &NO_TYPING)
556 }
557
558 static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
559 std::sync::LazyLock::new(HashSet::new);
560
561 static NO_TYPING: std::sync::LazyLock<TypingState> =
562 std::sync::LazyLock::new(TypingState::default);
563
564 fn typing_input<'a>(
565 chats: &'a [ChatRecord],
566 directory: &'a Directory,
567 collapsed: &'a HashSet<String>,
568 typing: &'a TypingState,
569 ) -> SectionInput<'a> {
570 SectionInput {
571 chats,
572 directory,
573 collapsed,
574 expanded_lists: &NO_EXPANDED,
575 typing,
576 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
577 offset: FixedOffset::east_opt(0).unwrap(),
578 }
579 }
580
581 #[test]
582 fn next_chat_is_the_following_row_then_the_previous_one() {
583 let chats = [
584 chat("a", "group", false),
585 chat("b", "group", false),
586 chat("c", "group", false),
587 ];
588 let directory = Directory::default();
589 let collapsed = HashSet::new();
590 let sections = build_sections(&input(&chats, &directory, &collapsed));
591 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
592 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
593 assert_eq!(next_chat_id(&sections, "zzz"), None);
594 let single = [chat("a", "group", false)];
595 let sections = build_sections(&input(&single, &directory, &collapsed));
596 assert_eq!(next_chat_id(&sections, "a"), None);
597 }
598
599 #[test]
600 fn stepping_follows_the_visible_order_without_wrapping() {
601 let ids = ["a", "b", "c"];
602 assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));
603 assert_eq!(
604 step_id(&ids, Some("b"), Step::Previous),
605 Some("a".to_owned())
606 );
607 assert_eq!(step_id(&ids, Some("c"), Step::Next), None);
608 assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);
609 assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));
610 assert_eq!(
611 step_id(&ids, Some("gone"), Step::Previous),
612 Some("c".to_owned())
613 );
614 assert_eq!(step_id(&[], None, Step::Next), None);
615 }
616
617 #[test]
618 fn visible_chats_skip_collapsed_sections_and_see_more_rows() {
619 let mut chats = vec![chat("fav", "group", false), chat("hid", "group", false)];
620 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
621 chats.push(chat("other", "group", false));
622 let directory = sectioned_directory(
623 true,
624 vec![
625 folder("fav-folder", FolderKind::Favorites, &["fav"]),
626 folder("work", FolderKind::UserCreated, &["hid"]),
627 folder("recent", FolderKind::Recent, &[]),
628 folder("muted-folder", FolderKind::Muted, &[]),
629 ],
630 );
631 let mut collapsed = HashSet::new();
632 let sections = build_sections(&input(&chats, &directory, &collapsed));
633 assert_eq!(
634 visible_chat_ids(&sections),
635 vec!["fav", "hid", "other", "m0", "m1", "m2", "m3", "m4"]
636 );
637 collapsed.insert("work".to_owned());
638 collapsed.insert("muted-folder".to_owned());
639 let sections = build_sections(&input(&chats, &directory, &collapsed));
640 assert_eq!(visible_chat_ids(&sections), vec!["fav", "other"]);
641 }
642
643 fn team(
644 id: &str,
645 hidden: bool,
646 channel_ids: &[&str],
647 hidden_channel_ids: &[&str],
648 ) -> SidebarTeam {
649 SidebarTeam {
650 team: store::TeamRecord {
651 id: id.into(),
652 name: id.into(),
653 },
654 channels: channel_ids
655 .iter()
656 .map(|channel_id| ChannelRecord {
657 id: (*channel_id).into(),
658 team_id: id.into(),
659 name: (*channel_id).into(),
660 membership_type: None,
661 last_message_at: None,
662 unread: false,
663 })
664 .collect(),
665 hidden,
666 hidden_channel_ids: hidden_channel_ids
667 .iter()
668 .map(|id| (*id).to_owned())
669 .collect(),
670 notifications: HashMap::new(),
671 }
672 }
673
674 #[test]
675 fn visible_channels_list_pinned_first_then_open_teams() {
676 let teams = [
677 team("t1", false, &["a", "b", "c"], &["b"]),
678 team("t2", false, &["d", "e"], &[]),
679 team("t3", true, &["f"], &[]),
680 ];
681 let pinned = ["e".to_owned(), "missing".to_owned()];
682 let order = |selected: Option<&str>,
683 hidden_teams_open: bool,
684 collapsed: &[&str],
685 revealed: &[&str]| {
686 let to_set = |ids: &[&str]| {
687 ids.iter()
688 .map(|id| (*id).to_owned())
689 .collect::<HashSet<_>>()
690 };
691 let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
692 let input = ChannelOrderInput {
693 teams: &teams,
694 pinned_ids: &pinned,
695 collapsed_teams: &collapsed,
696 revealed_channel_teams: &revealed,
697 hidden_teams_open,
698 selected_channel: selected,
699 };
700 visible_channel_ids(&input)
701 .into_iter()
702 .map(str::to_owned)
703 .collect::<Vec<_>>()
704 };
705 assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
706 assert_eq!(
707 order(Some("b"), false, &[], &[]),
708 vec!["e", "a", "b", "c", "d"]
709 );
710 assert_eq!(
711 order(Some("f"), false, &[], &[]),
712 vec!["e", "a", "c", "d", "f"]
713 );
714 assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
715 assert_eq!(
716 order(None, true, &["t2"], &["t1"]),
717 vec!["e", "a", "c", "b", "f"]
718 );
719 }
720
721 #[test]
722 fn muted_chats_stay_out_of_unread_counts() {
723 let mut quiet = chat("a", "group", true);
724 quiet.muted = true;
725 let chats = [quiet, chat("b", "group", true)];
726 assert_eq!(unread_chat_count(&chats), 1);
727 let directory = Directory::default();
728 let collapsed = HashSet::new();
729 let sections = build_sections(&input(&chats, &directory, &collapsed));
730 assert_eq!(sections[0].unread_chats, 1);
731 assert_eq!(sections[1].kind, SectionKind::Muted);
732 assert!(sections[1].items[0].muted);
733 assert!(sections[1].items[0].unread.is_unread());
734 }
735
736 #[test]
737 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
738 let mut group = chat("g", "group", false);
739 group.last_message_preview = Some("Hello".into());
740 group.last_message_sender_id = Some("ada".into());
741 group.last_message_sender_name = Some("Ada Example".into());
742 assert_eq!(
743 preview_for(&group, Some(&me())),
744 Preview::Text {
745 prefix: Some("Ada".into()),
746 text: "Hello".into()
747 }
748 );
749 group.last_message_sender_id = Some("me".into());
750 assert_eq!(
751 preview_for(&group, Some(&me())),
752 Preview::Text {
753 prefix: Some("You".into()),
754 text: "Hello".into()
755 }
756 );
757 let mut direct = chat("d", "oneOnOne", false);
758 direct.last_message_preview = Some("Hi".into());
759 direct.last_message_sender_id = Some("ada".into());
760 direct.last_message_sender_name = Some("Ada Example".into());
761 assert_eq!(
762 preview_for(&direct, Some(&me())),
763 Preview::Text {
764 prefix: None,
765 text: "Hi".into()
766 }
767 );
768 }
769
770 #[test]
771 fn deleted_and_blank_previews() {
772 let mut deleted = chat("d", "group", false);
773 deleted.last_message_deleted = true;
774 deleted.last_message_preview = Some("secret".into());
775 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
776 assert_eq!(
777 preview_for(&chat("e", "group", false), None),
778 Preview::Empty
779 );
780 }
781
782 #[test]
783 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
784 let chats = vec![
785 chat("a", "group", false),
786 chat("b", "oneOnOne", true),
787 chat("c", "group", false),
788 chat("d", "group", false),
789 ];
790 let directory = Directory {
791 me: Some(me()),
792 folders: vec![
793 folder("fav", FolderKind::Favorites, &["c"]),
794 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
795 folder("todo", FolderKind::UserCreated, &[]),
796 ],
797 ..Default::default()
798 };
799 let collapsed = HashSet::new();
800 let sections = build_sections(&input(&chats, &directory, &collapsed));
801 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
802 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
803 let work: Vec<&str> = sections[1]
804 .items
805 .iter()
806 .map(|item| item.id.as_str())
807 .collect();
808 assert_eq!(work, vec!["b", "a"]);
809 assert_eq!(sections[1].count, 2);
810 assert_eq!(sections[2].count, 0);
811 assert!(sections[2].show_empty_hint);
812 let others: Vec<&str> = sections[3]
813 .items
814 .iter()
815 .map(|item| item.id.as_str())
816 .collect();
817 assert_eq!(others, vec!["d"]);
818 assert!(!sections[3].show_empty_hint);
819 }
820
821 #[test]
822 fn collapsed_sections_keep_the_aggregated_unread() {
823 let chats = vec![
824 chat("a", "group", true),
825 chat("b", "group", true),
826 chat("c", "group", false),
827 ];
828 let directory = Directory {
829 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
830 ..Default::default()
831 };
832 let collapsed: HashSet<String> = ["work".to_owned()].into();
833 let sections = build_sections(&input(&chats, &directory, &collapsed));
834 assert!(sections[0].collapsed);
835 assert_eq!(sections[0].unread_chats, 2);
836 assert_eq!(sections[0].count, 3);
837 assert!(!sections[0].show_empty_hint);
838 }
839
840 #[test]
841 fn collapsed_empty_folder_hides_the_hint() {
842 let directory = Directory {
843 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
844 ..Default::default()
845 };
846 let collapsed: HashSet<String> = ["todo".to_owned()].into();
847 let sections = build_sections(&input(&[], &directory, &collapsed));
848 assert!(!sections[0].show_empty_hint);
849 }
850
851 #[test]
852 fn favorites_without_a_server_name_say_angeheftet() {
853 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
854 favorites.name = String::new();
855 let directory = Directory {
856 folders: vec![favorites],
857 ..Default::default()
858 };
859 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
860 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
861 }
862
863 #[test]
864 fn unread_is_a_count_when_known_else_a_dot() {
865 let chats = vec![
866 chat("a", "group", true),
867 chat("b", "group", true),
868 chat("c", "group", false),
869 ];
870 let mut directory = Directory::default();
871 directory.unread_counts.insert("a".into(), 5);
872 let collapsed = HashSet::new();
873 let context = input(&chats, &directory, &collapsed);
874 assert_eq!(
875 chat_item(&chats[0], &context, None).unread,
876 Unread::Count(5)
877 );
878 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
879 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
880 assert_eq!(unread_chat_count(&chats), 2);
881 }
882
883 #[test]
884 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
885 let directory = Directory {
886 me: Some(me()),
887 ..Default::default()
888 };
889 let collapsed = HashSet::new();
890 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
891 let context = input(&chats, &directory, &collapsed);
892 let direct = chat_item(&chats[0], &context, None);
893 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
894 assert!(
895 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
896 );
897 let group = chat_item(&chats[1], &context, None);
898 assert_eq!(group.presence_user, None);
899 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
900 assert_eq!(avatar_for(&meeting_chat("meeting-1"), None), AvatarSpec::Meeting);
901 }
902
903 #[test]
904 fn typing_replaces_the_preview_even_in_muted_chats() {
905 let mut direct = chat("d", "oneOnOne", false);
906 direct.last_message_preview = Some("Earlier".into());
907 direct.muted = true;
908 let group = chat("g", "group", false);
909 let chats = vec![direct, group];
910 let directory = Directory::default();
911 let collapsed = HashSet::new();
912 let now = std::time::Instant::now();
913 let mut typing = TypingState::default();
914 typing.start("d", "ada", "Ada Example", now, Utc::now());
915 typing.start("g", "ada", "Ada Example", now, Utc::now());
916 let context = typing_input(&chats, &directory, &collapsed, &typing);
917 assert_eq!(
918 chat_item(&chats[0], &context, None).preview,
919 Preview::Typing("typing...".into())
920 );
921 assert_eq!(
922 chat_item(&chats[1], &context, None).preview,
923 Preview::Typing("Ada is typing...".into())
924 );
925 typing.clear("d", "ada");
926 let context = typing_input(&chats, &directory, &collapsed, &typing);
927 assert_eq!(
928 chat_item(&chats[0], &context, None).preview,
929 Preview::Text {
930 prefix: None,
931 text: "Earlier".into()
932 }
933 );
934 }
935
936 #[test]
937 fn time_label_uses_the_list_rules() {
938 let chats = vec![chat("a", "group", false)];
939 let directory = Directory::default();
940 let collapsed = HashSet::new();
941 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
942 assert_eq!(item.time_label, "09:30");
943 }
944
945 #[test]
946 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
947 let chats = vec![
948 chat("plain", "group", false),
949 muted_chat("quiet"),
950 muted_chat("pinned-quiet"),
951 meeting_chat("sync"),
952 meeting_chat("custom-sync"),
953 ChatRecord {
954 muted: true,
955 ..meeting_chat("quiet-sync")
956 },
957 ];
958 let directory = sectioned_directory(
959 true,
960 vec![
961 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
962 folder("work", FolderKind::UserCreated, &["custom-sync"]),
963 ],
964 );
965 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
966 assert_eq!(
967 section_ids(&sections),
968 vec!["fav", "work", OTHERS_ID, MUTED_ID]
969 );
970 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
971 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
972 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
973 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
974 assert_eq!(sections[3].kind, SectionKind::Muted);
975 assert_eq!(sections[3].count, 2);
976 }
977
978 #[test]
979 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
980 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
981 let directory = sectioned_directory(false, Vec::new());
982 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
983 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
984 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
985 }
986
987 #[test]
988 fn muted_is_on_until_the_user_chooses_and_meeting_chats_stay_in_others() {
989 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
990 let directory = Directory::default();
991 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
992 assert_eq!(section_ids(&sections), vec![OTHERS_ID, MUTED_ID]);
993 assert_eq!(item_ids(&sections[0]), vec!["sync"]);
994 }
995
996 #[test]
997 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
998 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
999 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
1000 assert!(!wants_older_chats(None, 1000., 0., None, false));
1001 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
1002 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
1003 }
1004
1005 #[test]
1006 fn a_running_load_never_consumes_the_trigger() {
1007 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
1008 }
1009
1010 #[test]
1011 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
1012 assert!(older_chats_trigger_resets((true, true), (true, false)));
1013 assert!(older_chats_trigger_resets((true, true), (false, false)));
1014 assert!(older_chats_trigger_resets((false, false), (true, false)));
1015 assert!(!older_chats_trigger_resets((true, false), (true, false)));
1016 assert!(!older_chats_trigger_resets((true, false), (true, true)));
1017 assert!(!older_chats_trigger_resets((false, false), (false, false)));
1018 }
1019
1020 #[test]
1021 fn empty_system_sections_are_hidden() {
1022 let chats = vec![chat("a", "group", false)];
1023 let directory = sectioned_directory(true, Vec::new());
1024 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1025 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1026 }
1027
1028 #[test]
1029 fn sections_follow_the_server_folder_order_with_system_folders() {
1030 let chats = vec![
1031 chat("a", "group", false),
1032 muted_chat("quiet"),
1033 meeting_chat("sync"),
1034 ];
1035 let directory = sectioned_directory(
1036 true,
1037 vec![
1038 folder("muted-id", FolderKind::Muted, &[]),
1039 folder("fav", FolderKind::Favorites, &[]),
1040 folder("recent-id", FolderKind::Recent, &[]),
1041 folder("meeting-id", FolderKind::Meeting, &[]),
1042 ],
1043 );
1044 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1045 let sections = build_sections(&input(&chats, &directory, &collapsed));
1046 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1047 assert!(sections[0].collapsed);
1048 assert_eq!(sections[0].name, MUTED_NAME);
1049 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1050 }
1051
1052 #[test]
1053 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
1054 let chats: Vec<ChatRecord> = (0..8)
1055 .map(|index| muted_chat(&format!("m{index}")))
1056 .collect();
1057 let directory = Directory::default();
1058 let collapsed = HashSet::new();
1059 let sections = build_sections(&input(&chats, &directory, &collapsed));
1060 let muted = &sections[1];
1061 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
1062 assert_eq!(muted.count, 8);
1063 assert_eq!(muted.hidden_count, 3);
1064 assert!(!muted.list_expanded);
1065
1066 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1067 let mut context = input(&chats, &directory, &collapsed);
1068 context.expanded_lists = &expanded;
1069 let sections = build_sections(&context);
1070 let muted = &sections[1];
1071 assert_eq!(muted.items.len(), 8);
1072 assert_eq!(muted.hidden_count, 0);
1073 assert!(muted.list_expanded);
1074 }
1075
1076 #[test]
1077 fn five_chats_need_no_see_more_even_when_marked_expanded() {
1078 let chats: Vec<ChatRecord> = (0..5)
1079 .map(|index| muted_chat(&format!("m{index}")))
1080 .collect();
1081 let directory = Directory::default();
1082 let collapsed = HashSet::new();
1083 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1084 let mut context = input(&chats, &directory, &collapsed);
1085 context.expanded_lists = &expanded;
1086 let muted = &build_sections(&context)[1];
1087 assert_eq!(muted.hidden_count, 0);
1088 assert!(!muted.list_expanded);
1089 }
1090
1091 #[test]
1092 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
1093 let mut quiet = muted_chat("quiet");
1094 quiet.unread = true;
1095 let chats = vec![
1096 quiet,
1097 ChatRecord {
1098 muted: true,
1099 ..meeting_chat("x")
1100 },
1101 ];
1102 let mut directory = Directory::default();
1103 directory.unread_counts.insert("quiet".into(), 4);
1104 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1105 let muted = &sections[1];
1106 assert_eq!(muted.items[0].unread, Unread::Silent);
1107 assert!(muted.items[0].unread.is_unread());
1108 assert_eq!(muted.unread_chats, 0);
1109 assert_eq!(unread_chat_count(&chats), 0);
1110 }
1111
1112 #[test]
1113 fn meeting_chats_keep_their_unread_count_in_others() {
1114 let mut sync = meeting_chat("sync");
1115 sync.unread = true;
1116 let chats = vec![sync];
1117 let mut directory = sectioned_directory(true, Vec::new());
1118 directory.unread_counts.insert("sync".into(), 3);
1119 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1120 assert_eq!(sections[0].id, OTHERS_ID);
1121 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1122 assert_eq!(sections[0].unread_chats, 1);
1123 }
1124}