BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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