BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

fc95684c History
sidebar_model.rs 56.3 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use app_ui_kit::widgets::Unread;
4use chrono::{DateTime, FixedOffset, Utc};
5use store::{
6 ChannelNotificationLevel, ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam,
7 is_bot_id,
8};
9use teams_core::{ChatSection, is_event_preview};
10
11use crate::app_state::chat_title;
12use crate::data::{
13 Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
14 unread_count, unread_importance_of,
15};
16use crate::format;
17use crate::typing::{TypingState, preview_label};
18
19pub const FAVORITES_FALLBACK_NAME: &str = "Favorites";
20pub const OTHERS_NAME: &str = "Other chats";
21pub const OTHERS_ID: &str = "others";
22pub const MUTED_NAME: &str = "Muted";
23pub const MUTED_ID: &str = "muted_chats";
24pub const SECTION_PAGE_SIZE: usize = 5;
25pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
26pub const DELETED_PREVIEW: &str = "Message deleted";
27pub const DELETED_CHAT_PREVIEW: &str = "This message was deleted";
28const OWN_PREFIX: &str = "You";
29const GROUP_KIND: &str = "group";
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Preview {
33 Empty,
34 Deleted,
35 Event(String),
36 Typing(String),
37 Text {
38 prefix: Option<String>,
39 text: String,
40 },
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Face {
45 pub user_id: Option<String>,
46 pub name: String,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum AvatarSpec {
51 Single(Face),
52 Pair(Face, Face),
53 Bot(Face),
54 Meeting,
55 Muted,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ChatItem {
60 pub id: String,
61 pub title: String,
62 pub time_label: String,
63 pub preview: Preview,
64 pub unread: Unread,
65 pub importance: MessageImportance,
66 pub muted: bool,
67 pub is_group: bool,
68 pub member_count: usize,
69 pub avatar: AvatarSpec,
70 pub presence_user: Option<String>,
71 pub folder_id: Option<String>,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum SectionKind {
76 Favorites,
77 Folder,
78 Others,
79 Muted,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Section {
84 pub id: String,
85 pub name: String,
86 pub kind: SectionKind,
87 pub collapsed: bool,
88 pub count: usize,
89 pub unread_chats: u32,
90 pub items: Vec<ChatItem>,
91 pub hidden_count: usize,
92 pub list_expanded: bool,
93 pub show_empty_hint: bool,
94}
95
96pub struct SectionInput<'a> {
97 pub chats: &'a [ChatRecord],
98 pub directory: &'a Directory,
99 pub collapsed: &'a HashSet<String>,
100 pub expanded_lists: &'a HashSet<String>,
101 pub typing: &'a TypingState,
102 pub now: DateTime<Utc>,
103 pub offset: FixedOffset,
104}
105
106pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
107 if chat.last_message_deleted {
108 return Preview::Deleted;
109 }
110 let Some(text) = chat
111 .last_message_preview
112 .as_deref()
113 .map(str::trim)
114 .filter(|text| !text.is_empty())
115 else {
116 return Preview::Empty;
117 };
118 let sender_id = chat
119 .last_message_sender_id
120 .as_deref()
121 .filter(|sender_id| !sender_id.is_empty());
122 if sender_id.is_none() && is_event_preview(text) {
123 return Preview::Event(text.to_owned());
124 }
125 let from_me = match (sender_id, me) {
126 (Some(sender), Some(me)) => sender == me.user_id,
127 _ => false,
128 };
129 let prefix = if from_me {
130 Some(OWN_PREFIX.to_owned())
131 } else if is_one_on_one(chat) {
132 None
133 } else {
134 chat.last_message_sender_name
135 .as_deref()
136 .map(|name| format::first_name(name).to_owned())
137 .filter(|name| !name.is_empty())
138 };
139 Preview::Text {
140 prefix,
141 text: text.to_owned(),
142 }
143}
144
145pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
146 if chat.kind.eq_ignore_ascii_case("meeting") {
147 return AvatarSpec::Meeting;
148 }
149 let faces = face_members(chat, me);
150 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
151 if let Some(bot) = one_on_one_bot(chat, me) {
152 return AvatarSpec::Bot(face(bot));
153 }
154 if is_one_on_one(chat) || faces.len() < 2 {
155 return AvatarSpec::Single(match faces.into_iter().next() {
156 Some(first) => face(first),
157 None => Face {
158 user_id: None,
159 name: chat_title(chat),
160 },
161 });
162 }
163 let mut iterator = faces.into_iter();
164 let (first, second) = (iterator.next(), iterator.next());
165 match (first, second) {
166 (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)),
167 _ => AvatarSpec::Single(Face {
168 user_id: None,
169 name: chat_title(chat),
170 }),
171 }
172}
173
174pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem {
175 let me = input.directory.me.as_ref();
176 let unread = if chat.unread {
177 unread_count(input.directory, chat)
178 .filter(|count| *count > 0)
179 .map_or(Unread::Dot, Unread::Count)
180 } else {
181 Unread::None
182 };
183 let presence_user = (is_one_on_one(chat) && !chat.muted)
184 .then(|| {
185 others(chat, me)
186 .into_iter()
187 .find_map(|(user_id, _)| user_id)
188 })
189 .flatten()
190 .filter(|user_id| !is_bot_id(user_id));
191 let typing_names = input.typing.names(&chat.id);
192 let preview = if typing_names.is_empty() {
193 preview_for(chat, me)
194 } else {
195 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
196 };
197 ChatItem {
198 id: chat.id.clone(),
199 title: chat_title(chat),
200 time_label: chat
201 .last_message_at
202 .map(|time| {
203 format::list_time_label(
204 time,
205 input.now.with_timezone(&input.offset).date_naive(),
206 input.offset,
207 )
208 })
209 .unwrap_or_default(),
210 preview,
211 unread,
212 importance: if chat.unread {
213 unread_importance_of(input.directory, chat)
214 } else {
215 MessageImportance::Normal
216 },
217 muted: chat.muted,
218 is_group: chat.kind == GROUP_KIND,
219 member_count: chat.members.len(),
220 avatar: if chat.muted {
221 AvatarSpec::Muted
222 } else {
223 avatar_for(chat, me)
224 },
225 presence_user,
226 folder_id: folder_id.map(str::to_owned),
227 }
228}
229
230pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
231 chats
232 .iter()
233 .filter(|chat| chat.unread && !chat.muted)
234 .count() as u32
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum NameWeight {
239 Regular,
240 Semibold,
241 Bold,
242}
243
244/// Teams channel list: `highlighted` is colorNeutralForeground1, otherwise colorNeutralForeground3.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub struct NameStyle {
247 pub weight: NameWeight,
248 pub highlighted: bool,
249}
250
251impl NameStyle {
252 const PLAIN: NameStyle = NameStyle {
253 weight: NameWeight::Regular,
254 highlighted: false,
255 };
256}
257
258pub fn channel_name_style(unread: bool, shown: bool, selected: bool) -> NameStyle {
259 if !unread || !shown {
260 return NameStyle::PLAIN;
261 }
262 NameStyle {
263 weight: if selected {
264 NameWeight::Regular
265 } else {
266 NameWeight::Bold
267 },
268 highlighted: true,
269 }
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum MentionBadge {
274 Count(u32),
275 Channel,
276 Team,
277}
278
279/// Teams pulls a hidden channel into the list while it holds personal @mentions.
280pub fn channel_shown(team: &SidebarTeam, channel_id: &str) -> bool {
281 !team.hidden_channel_ids.iter().any(|id| id == channel_id)
282 || team.channel_mentions(channel_id).personal > 0
283}
284
285pub fn channel_hoisted(team: &SidebarTeam, channel_id: &str) -> bool {
286 team.hidden_channel_ids.iter().any(|id| id == channel_id)
287 && team.channel_mentions(channel_id).personal > 0
288}
289
290pub fn team_hoisted(team: &SidebarTeam) -> bool {
291 team.hidden
292 && team
293 .channels
294 .iter()
295 .any(|channel| channel_hoisted(team, &channel.id))
296}
297
298pub fn channel_badge(team: &SidebarTeam, channel_id: &str) -> Option<MentionBadge> {
299 let mentions = team.channel_mentions(channel_id);
300 if mentions.personal > 0 {
301 Some(MentionBadge::Count(mentions.personal))
302 } else if mentions.channel > 0 {
303 Some(MentionBadge::Channel)
304 } else if mentions.team > 0 {
305 Some(MentionBadge::Team)
306 } else {
307 None
308 }
309}
310
311/// The collapsed team row sums personal mentions of every channel, the icons only of shown channels.
312pub fn team_badge(team: &SidebarTeam, expanded: bool) -> Option<MentionBadge> {
313 if expanded || !team_has_unread(team) {
314 return None;
315 }
316 let personal: u32 = team
317 .mentions
318 .iter()
319 .filter(|(channel_id, _)| {
320 team.channels
321 .iter()
322 .any(|channel| &channel.id == *channel_id)
323 })
324 .map(|(_, mentions)| mentions.personal)
325 .sum();
326 if personal > 0 {
327 return Some(MentionBadge::Count(personal));
328 }
329 let shown = || {
330 team.channels
331 .iter()
332 .filter(|channel| channel_shown(team, &channel.id))
333 .map(|channel| team.channel_mentions(&channel.id))
334 };
335 if shown().any(|mentions| mentions.channel > 0) {
336 Some(MentionBadge::Channel)
337 } else if shown().any(|mentions| mentions.team > 0) {
338 Some(MentionBadge::Team)
339 } else {
340 None
341 }
342}
343
344pub fn channel_shows_unread(team: &SidebarTeam, channel: &ChannelRecord) -> bool {
345 channel.unread
346 && (team.channel_notifications(&channel.id).level != ChannelNotificationLevel::Off
347 || team.channel_mentions(&channel.id).personal > 0)
348}
349
350pub fn team_has_unread(team: &SidebarTeam) -> bool {
351 team.channels
352 .iter()
353 .any(|channel| channel_shows_unread(team, channel) && channel_shown(team, &channel.id))
354}
355
356pub fn team_name_style(team: &SidebarTeam, expanded: bool) -> NameStyle {
357 if expanded || !team_has_unread(team) {
358 return NameStyle::PLAIN;
359 }
360 NameStyle {
361 weight: NameWeight::Semibold,
362 highlighted: true,
363 }
364}
365
366pub fn channel_unread(sidebar: &Sidebar, channel_id: &str) -> bool {
367 sidebar
368 .teams
369 .iter()
370 .flat_map(|team| team.channels.iter())
371 .any(|channel| channel.id == channel_id && channel.unread)
372}
373
374pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
375 sidebar
376 .teams
377 .iter()
378 .filter(|team| !team.hidden)
379 .any(team_has_unread)
380}
381
382pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
383 let by_id: HashMap<&str, &ChatRecord> = input
384 .chats
385 .iter()
386 .map(|chat| (chat.id.as_str(), chat))
387 .collect();
388 let mut placed: HashSet<&str> = HashSet::new();
389 let mut built: Vec<Option<Section>> = input
390 .directory
391 .folders
392 .iter()
393 .map(|folder| {
394 let (kind, name) = match folder.kind {
395 FolderKind::Favorites => (
396 SectionKind::Favorites,
397 if folder.name.trim().is_empty() {
398 FAVORITES_FALLBACK_NAME.to_owned()
399 } else {
400 folder.name.clone()
401 },
402 ),
403 FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
404 FolderKind::Recent | FolderKind::Meeting | FolderKind::Muted => return None,
405 };
406 let items: Vec<ChatItem> = folder
407 .conversation_ids
408 .iter()
409 .filter_map(|id| by_id.get(id.as_str()).copied())
410 .filter(|chat| placed.insert(chat.id.as_str()))
411 .map(|chat| chat_item(chat, input, Some(&folder.id)))
412 .collect();
413 Some(section(folder.id.clone(), name, kind, items, input))
414 })
415 .collect();
416 let settings = &input.directory.section_settings;
417 let mut muted = Vec::new();
418 let mut rest = Vec::new();
419 for chat in input
420 .chats
421 .iter()
422 .filter(|chat| !placed.contains(chat.id.as_str()))
423 {
424 let item = chat_item(chat, input, None);
425 if chat.muted && settings.enabled(ChatSection::Muted) {
426 muted.push(item);
427 } else {
428 rest.push(item);
429 }
430 }
431 let folder_id = |kind: FolderKind, fallback: &str| {
432 input
433 .directory
434 .folders
435 .iter()
436 .find(|folder| folder.kind == kind)
437 .map_or_else(|| fallback.to_owned(), |folder| folder.id.clone())
438 };
439 let mut others = Some(section(
440 folder_id(FolderKind::Recent, OTHERS_ID),
441 OTHERS_NAME.to_owned(),
442 SectionKind::Others,
443 rest,
444 input,
445 ));
446 let mut muted = (!muted.is_empty()).then(|| {
447 section(
448 folder_id(FolderKind::Muted, MUTED_ID),
449 MUTED_NAME.to_owned(),
450 SectionKind::Muted,
451 muted,
452 input,
453 )
454 });
455 let mut sections = Vec::new();
456 for (folder, section) in input.directory.folders.iter().zip(&mut built) {
457 match folder.kind {
458 FolderKind::Favorites | FolderKind::UserCreated => sections.extend(section.take()),
459 FolderKind::Recent => sections.extend(others.take()),
460 FolderKind::Meeting => {}
461 FolderKind::Muted => sections.extend(muted.take()),
462 }
463 }
464 sections.extend(others);
465 sections.extend(muted);
466 sections
467}
468
469pub fn wants_older_chats(
470 others_end: Option<f32>,
471 viewport_bottom: f32,
472 scroll_top: f32,
473 last_trigger_top: Option<f32>,
474 loading: bool,
475) -> bool {
476 !loading
477 && others_end.is_some_and(|end| end <= viewport_bottom)
478 && last_trigger_top != Some(scroll_top)
479}
480
481pub fn older_chats_trigger_resets(previous: (bool, bool), current: (bool, bool)) -> bool {
482 let ((had_more, was_loading), (has_more, is_loading)) = (previous, current);
483 (was_loading && !is_loading) || (!had_more && has_more)
484}
485
486pub fn visible_chat_ids(sections: &[Section]) -> Vec<&str> {
487 sections
488 .iter()
489 .filter(|section| !section.collapsed)
490 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
491 .collect()
492}
493
494pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
495 let visible = visible_chat_ids(sections);
496 let position = visible.iter().position(|id| *id == removed_id)?;
497 visible
498 .get(position + 1)
499 .or_else(|| {
500 position
501 .checked_sub(1)
502 .and_then(|previous| visible.get(previous))
503 })
504 .map(|id| (*id).to_owned())
505}
506
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub enum Step {
509 Previous,
510 Next,
511}
512
513pub fn step_id(ids: &[&str], current: Option<&str>, step: Step) -> Option<String> {
514 let position = current.and_then(|current| ids.iter().position(|id| *id == current));
515 let target = match (position, step) {
516 (Some(position), Step::Next) => position + 1,
517 (Some(position), Step::Previous) => position.checked_sub(1)?,
518 (None, Step::Next) => 0,
519 (None, Step::Previous) => ids.len().checked_sub(1)?,
520 };
521 ids.get(target).map(|id| (*id).to_owned())
522}
523
524pub fn step_unread_id(
525 sections: &[Section],
526 current: Option<&str>,
527 step: Step,
528) -> Option<String> {
529 let items: Vec<&ChatItem> = sections
530 .iter()
531 .filter(|section| !section.collapsed)
532 .flat_map(|section| section.items.iter())
533 .collect();
534 let position = current.and_then(|current| items.iter().position(|item| item.id == current));
535 let unread = |item: &&&ChatItem| item.unread.is_unread();
536 let found = match (position, step) {
537 (Some(position), Step::Next) => items[position + 1..].iter().find(unread),
538 (Some(position), Step::Previous) => items[..position].iter().rev().find(unread),
539 (None, Step::Next) => items.iter().find(unread),
540 (None, Step::Previous) => items.iter().rev().find(unread),
541 };
542 found.map(|item| item.id.clone())
543}
544
545pub struct ChannelOrderInput<'a> {
546 pub teams: &'a [SidebarTeam],
547 pub pinned_ids: &'a [String],
548 pub collapsed_teams: &'a HashSet<String>,
549 pub revealed_channel_teams: &'a HashSet<String>,
550 pub hidden_teams_open: bool,
551 pub selected_channel: Option<&'a str>,
552}
553
554pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
555 let mut ids: Vec<&str> = Vec::new();
556 let mut push = |id: &'a str| {
557 if !ids.contains(&id) {
558 ids.push(id);
559 }
560 };
561 for pinned_id in input.pinned_ids {
562 let known = input
563 .teams
564 .iter()
565 .flat_map(|entry| entry.channels.iter())
566 .find(|channel| &channel.id == pinned_id);
567 if let Some(channel) = known {
568 push(&channel.id);
569 }
570 }
571 let holds_selection = |entry: &SidebarTeam| {
572 entry
573 .channels
574 .iter()
575 .any(|channel| Some(channel.id.as_str()) == input.selected_channel)
576 };
577 let hidden_teams_shown = input.hidden_teams_open
578 || input
579 .teams
580 .iter()
581 .any(|entry| entry.hidden && holds_selection(entry));
582 let main_teams = input
583 .teams
584 .iter()
585 .filter(|entry| !entry.hidden || team_hoisted(entry))
586 .map(|entry| (entry, entry.hidden));
587 let hidden_teams = input
588 .teams
589 .iter()
590 .filter(|entry| entry.hidden && hidden_teams_shown)
591 .map(|entry| (entry, false));
592 for (entry, hoisted_only) in main_teams.chain(hidden_teams) {
593 if input.collapsed_teams.contains(&entry.team.id) {
594 continue;
595 }
596 for channel_id in team_channel_ids(entry, hoisted_only, input) {
597 push(channel_id);
598 }
599 }
600 ids
601}
602
603fn team_channel_ids<'a>(
604 entry: &'a SidebarTeam,
605 hoisted_only: bool,
606 input: &ChannelOrderInput<'_>,
607) -> Vec<&'a str> {
608 let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
609 let rows = team_channel_rows(
610 entry,
611 hoisted_only,
612 input.revealed_channel_teams.contains(&entry.team.id),
613 is_selected,
614 );
615 rows.shown
616 .into_iter()
617 .chain(rows.revealed)
618 .map(|channel| channel.id.as_str())
619 .collect()
620}
621
622pub struct TeamChannelRows<'a> {
623 pub shown: Vec<&'a ChannelRecord>,
624 pub hidden_count: usize,
625 pub revealed: Vec<&'a ChannelRecord>,
626}
627
628/// `hoisted_only` is a hidden team pulled into the main list: it shows only its hoisted channels.
629pub fn team_channel_rows<'a>(
630 entry: &'a SidebarTeam,
631 hoisted_only: bool,
632 revealed: bool,
633 is_selected: impl Fn(&ChannelRecord) -> bool,
634) -> TeamChannelRows<'a> {
635 let shown: Vec<&ChannelRecord> = entry
636 .channels
637 .iter()
638 .filter(|channel| {
639 if hoisted_only {
640 channel_hoisted(entry, &channel.id)
641 } else {
642 is_selected(channel) || channel_shown(entry, &channel.id)
643 }
644 })
645 .collect();
646 if hoisted_only {
647 return TeamChannelRows {
648 shown,
649 hidden_count: 0,
650 revealed: Vec::new(),
651 };
652 }
653 let hidden: Vec<&ChannelRecord> = entry
654 .channels
655 .iter()
656 .filter(|channel| !shown.iter().any(|row| row.id == channel.id))
657 .collect();
658 TeamChannelRows {
659 shown,
660 hidden_count: hidden.len(),
661 revealed: if revealed { hidden } else { Vec::new() },
662 }
663}
664
665fn section(
666 id: String,
667 name: String,
668 kind: SectionKind,
669 mut items: Vec<ChatItem>,
670 input: &SectionInput<'_>,
671) -> Section {
672 let collapsed = input.collapsed.contains(&id);
673 let count = items.len();
674 let unread_chats = items
675 .iter()
676 .filter(|item| item.unread.is_unread() && !item.muted)
677 .count() as u32;
678 let paged = kind == SectionKind::Muted;
679 let list_expanded = paged && count > SECTION_PAGE_SIZE && input.expanded_lists.contains(&id);
680 let hidden_count = if paged && !list_expanded {
681 count.saturating_sub(SECTION_PAGE_SIZE)
682 } else {
683 0
684 };
685 items.truncate(count - hidden_count);
686 for item in items.iter_mut().filter(|item| item.muted) {
687 if item.unread.is_unread() {
688 item.unread = Unread::Silent;
689 }
690 }
691 Section {
692 collapsed,
693 count,
694 unread_chats,
695 hidden_count,
696 list_expanded,
697 show_empty_hint: items.is_empty()
698 && !collapsed
699 && matches!(kind, SectionKind::Favorites | SectionKind::Folder),
700 id,
701 name,
702 kind,
703 items,
704 }
705}
706
707#[cfg(test)]
708mod tests {
709 use chrono::TimeZone;
710 use store::MemberRecord;
711
712 use super::*;
713 use crate::data::FolderInfo;
714
715 fn me() -> Person {
716 Person {
717 user_id: "me".into(),
718 display_name: "Me Myself".into(),
719 }
720 }
721
722 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
723 ChatRecord {
724 id: id.into(),
725 kind: kind.into(),
726 title: id.to_uppercase(),
727 unread,
728 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
729 members: vec![
730 MemberRecord {
731 user_id: Some("me".into()),
732 display_name: "Me Myself".into(),
733 },
734 MemberRecord {
735 user_id: Some("ada".into()),
736 display_name: "Ada Example".into(),
737 },
738 MemberRecord {
739 user_id: Some("bob".into()),
740 display_name: "Bob Sample".into(),
741 },
742 ],
743 ..Default::default()
744 }
745 }
746
747 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
748 FolderInfo {
749 id: id.into(),
750 name: format!("name-{id}"),
751 kind,
752 expanded: None,
753 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
754 }
755 }
756
757 fn muted_chat(id: &str) -> ChatRecord {
758 ChatRecord {
759 muted: true,
760 ..chat(id, "group", false)
761 }
762 }
763
764 fn meeting_chat(id: &str) -> ChatRecord {
765 chat(id, "meeting", false)
766 }
767
768 fn sectioned_directory(muted: bool, folders: Vec<FolderInfo>) -> Directory {
769 let mut directory = Directory {
770 folders,
771 ..Default::default()
772 };
773 directory.section_settings.set(ChatSection::Muted, muted);
774 directory
775 }
776
777 fn section_ids(sections: &[Section]) -> Vec<&str> {
778 sections.iter().map(|section| section.id.as_str()).collect()
779 }
780
781 fn item_ids(section: &Section) -> Vec<&str> {
782 section.items.iter().map(|item| item.id.as_str()).collect()
783 }
784
785 fn input<'a>(
786 chats: &'a [ChatRecord],
787 directory: &'a Directory,
788 collapsed: &'a HashSet<String>,
789 ) -> SectionInput<'a> {
790 typing_input(chats, directory, collapsed, &NO_TYPING)
791 }
792
793 static NO_EXPANDED: std::sync::LazyLock<HashSet<String>> =
794 std::sync::LazyLock::new(HashSet::new);
795
796 static NO_TYPING: std::sync::LazyLock<TypingState> =
797 std::sync::LazyLock::new(TypingState::default);
798
799 fn typing_input<'a>(
800 chats: &'a [ChatRecord],
801 directory: &'a Directory,
802 collapsed: &'a HashSet<String>,
803 typing: &'a TypingState,
804 ) -> SectionInput<'a> {
805 SectionInput {
806 chats,
807 directory,
808 collapsed,
809 expanded_lists: &NO_EXPANDED,
810 typing,
811 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
812 offset: FixedOffset::east_opt(0).unwrap(),
813 }
814 }
815
816 #[test]
817 fn next_chat_is_the_following_row_then_the_previous_one() {
818 let chats = [
819 chat("a", "group", false),
820 chat("b", "group", false),
821 chat("c", "group", false),
822 ];
823 let directory = Directory::default();
824 let collapsed = HashSet::new();
825 let sections = build_sections(&input(&chats, &directory, &collapsed));
826 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
827 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
828 assert_eq!(next_chat_id(&sections, "zzz"), None);
829 let single = [chat("a", "group", false)];
830 let sections = build_sections(&input(&single, &directory, &collapsed));
831 assert_eq!(next_chat_id(&sections, "a"), None);
832 }
833
834 #[test]
835 fn stepping_follows_the_visible_order_without_wrapping() {
836 let ids = ["a", "b", "c"];
837 assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));
838 assert_eq!(
839 step_id(&ids, Some("b"), Step::Previous),
840 Some("a".to_owned())
841 );
842 assert_eq!(step_id(&ids, Some("c"), Step::Next), None);
843 assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);
844 assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));
845 assert_eq!(
846 step_id(&ids, Some("gone"), Step::Previous),
847 Some("c".to_owned())
848 );
849 assert_eq!(step_id(&[], None, Step::Next), None);
850 }
851
852 #[test]
853 fn unread_stepping_skips_read_chats_in_both_directions() {
854 let directory = Directory::default();
855 let collapsed = HashSet::new();
856 let chats = [
857 chat("a", "group", true),
858 chat("b", "group", false),
859 chat("c", "group", true),
860 chat("d", "group", false),
861 ];
862 let sections = build_sections(&input(&chats, &directory, &collapsed));
863 let unread: Vec<&str> = visible_chat_ids(&sections)
864 .into_iter()
865 .filter(|id| *id == "a" || *id == "c")
866 .collect();
867 let (first_unread, last_unread) = (unread[0], unread[1]);
868 assert_eq!(
869 step_unread_id(&sections, None, Step::Next).as_deref(),
870 Some(first_unread)
871 );
872 assert_eq!(step_unread_id(&sections, Some(last_unread), Step::Next), None);
873 assert_eq!(
874 step_unread_id(&sections, Some(last_unread), Step::Previous).as_deref(),
875 Some(first_unread)
876 );
877 assert_eq!(
878 step_unread_id(&sections, None, Step::Previous).as_deref(),
879 Some(last_unread)
880 );
881 }
882
883 #[test]
884 fn visible_chats_skip_collapsed_sections_and_see_more_rows() {
885 let mut chats = vec![chat("fav", "group", false), chat("hid", "group", false)];
886 chats.extend((0..7).map(|index| muted_chat(&format!("m{index}"))));
887 chats.push(chat("other", "group", false));
888 let directory = sectioned_directory(
889 true,
890 vec![
891 folder("fav-folder", FolderKind::Favorites, &["fav"]),
892 folder("work", FolderKind::UserCreated, &["hid"]),
893 folder("recent", FolderKind::Recent, &[]),
894 folder("muted-folder", FolderKind::Muted, &[]),
895 ],
896 );
897 let mut collapsed = HashSet::new();
898 let sections = build_sections(&input(&chats, &directory, &collapsed));
899 assert_eq!(
900 visible_chat_ids(&sections),
901 vec!["fav", "hid", "other", "m0", "m1", "m2", "m3", "m4"]
902 );
903 collapsed.insert("work".to_owned());
904 collapsed.insert("muted-folder".to_owned());
905 let sections = build_sections(&input(&chats, &directory, &collapsed));
906 assert_eq!(visible_chat_ids(&sections), vec!["fav", "other"]);
907 }
908
909 fn team(
910 id: &str,
911 hidden: bool,
912 channel_ids: &[&str],
913 hidden_channel_ids: &[&str],
914 ) -> SidebarTeam {
915 SidebarTeam {
916 rights: Default::default(),
917 team: store::TeamRecord {
918 id: id.into(),
919 name: id.into(),
920 },
921 channels: channel_ids
922 .iter()
923 .map(|channel_id| ChannelRecord {
924 id: (*channel_id).into(),
925 team_id: id.into(),
926 name: (*channel_id).into(),
927 membership_type: None,
928 last_message_at: None,
929 unread: false,
930 })
931 .collect(),
932 hidden,
933 hidden_channel_ids: hidden_channel_ids
934 .iter()
935 .map(|id| (*id).to_owned())
936 .collect(),
937 notifications: HashMap::new(),
938 mentions: Default::default(),
939 }
940 }
941
942 fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam {
943 for channel in &mut entry.channels {
944 channel.unread = unread_ids.contains(&channel.id.as_str());
945 }
946 entry
947 }
948
949 #[test]
950 fn unread_shown_channel_is_bold_and_highlighted() {
951 let bold = NameStyle {
952 weight: NameWeight::Bold,
953 highlighted: true,
954 };
955 let plain = NameStyle {
956 weight: NameWeight::Regular,
957 highlighted: false,
958 };
959 assert_eq!(channel_name_style(true, true, false), bold);
960 assert_eq!(channel_name_style(false, true, false), plain);
961 assert_eq!(channel_name_style(true, false, false), plain);
962 assert_eq!(
963 channel_name_style(true, true, true),
964 NameStyle {
965 weight: NameWeight::Regular,
966 highlighted: true,
967 }
968 );
969 }
970
971 #[test]
972 fn collapsed_team_with_an_unread_shown_channel_is_semibold() {
973 let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]);
974 let semibold = NameStyle {
975 weight: NameWeight::Semibold,
976 highlighted: true,
977 };
978 assert_eq!(team_name_style(&entry, false), semibold);
979 assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN);
980 let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
981 assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN);
982 }
983
984 #[test]
985 fn muted_channel_shows_no_unread_unless_personally_mentioned() {
986 let mut entry = with_unread(team("t1", false, &["a"], &[]), &["a"]);
987 entry.notifications.insert(
988 "a".into(),
989 store::ChannelNotifications {
990 level: ChannelNotificationLevel::Off,
991 include_replies: false,
992 },
993 );
994 assert!(!channel_shows_unread(&entry, &entry.channels[0]));
995 assert_eq!(team_name_style(&entry, false), NameStyle::PLAIN);
996 entry.mentions.insert(
997 "a".into(),
998 store::ChannelMentions {
999 personal: 1,
1000 ..Default::default()
1001 },
1002 );
1003 assert!(channel_shows_unread(&entry, &entry.channels[0]));
1004 }
1005
1006 #[test]
1007 fn rail_dot_counts_shown_channels_of_shown_teams_only() {
1008 let sidebar = |teams: Vec<SidebarTeam>| Sidebar {
1009 teams,
1010 ..Sidebar::default()
1011 };
1012 let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
1013 let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]);
1014 assert!(!any_unread_channel(&sidebar(vec![
1015 hidden_channel,
1016 hidden_team
1017 ])));
1018 let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]);
1019 let both = sidebar(vec![shown]);
1020 assert!(any_unread_channel(&both));
1021 assert!(channel_unread(&both, "a"));
1022 assert!(!channel_unread(&both, "missing"));
1023 }
1024
1025 #[test]
1026 fn visible_channels_list_pinned_first_then_open_teams() {
1027 let teams = [
1028 team("t1", false, &["a", "b", "c"], &["b"]),
1029 team("t2", false, &["d", "e"], &[]),
1030 team("t3", true, &["f"], &[]),
1031 ];
1032 let pinned = ["e".to_owned(), "missing".to_owned()];
1033 let order = |selected: Option<&str>,
1034 hidden_teams_open: bool,
1035 collapsed: &[&str],
1036 revealed: &[&str]| {
1037 let to_set = |ids: &[&str]| {
1038 ids.iter()
1039 .map(|id| (*id).to_owned())
1040 .collect::<HashSet<_>>()
1041 };
1042 let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
1043 let input = ChannelOrderInput {
1044 teams: &teams,
1045 pinned_ids: &pinned,
1046 collapsed_teams: &collapsed,
1047 revealed_channel_teams: &revealed,
1048 hidden_teams_open,
1049 selected_channel: selected,
1050 };
1051 visible_channel_ids(&input)
1052 .into_iter()
1053 .map(str::to_owned)
1054 .collect::<Vec<_>>()
1055 };
1056 assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
1057 assert_eq!(
1058 order(Some("b"), false, &[], &[]),
1059 vec!["e", "a", "b", "c", "d"]
1060 );
1061 assert_eq!(
1062 order(Some("f"), false, &[], &[]),
1063 vec!["e", "a", "c", "d", "f"]
1064 );
1065 assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
1066 assert_eq!(
1067 order(None, true, &["t2"], &["t1"]),
1068 vec!["e", "a", "c", "b", "f"]
1069 );
1070 }
1071
1072 fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
1073 for (channel_id, personal, channel, team) in mentions {
1074 entry.mentions.insert(
1075 (*channel_id).to_owned(),
1076 store::ChannelMentions {
1077 personal: *personal,
1078 channel: *channel,
1079 team: *team,
1080 },
1081 );
1082 }
1083 entry
1084 }
1085
1086 #[test]
1087 fn channel_badges_prefer_the_count_then_channel_then_team() {
1088 let entry = with_mentions(
1089 team("t", false, &["a", "b", "c", "d"], &[]),
1090 &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1091 );
1092 assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1093 assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1094 assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1095 assert_eq!(channel_badge(&entry, "d"), None);
1096 }
1097
1098 #[test]
1099 fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1100 let entry = with_unread(
1101 with_mentions(
1102 team("t", false, &["a", "b", "c"], &["b", "c"]),
1103 &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1104 ),
1105 &["a", "b", "c"],
1106 );
1107 assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1108 assert_eq!(team_badge(&entry, true), None);
1109 let icons_only = with_unread(
1110 with_mentions(
1111 team("t", false, &["a", "c"], &["c"]),
1112 &[("a", 0, 0, 1), ("c", 0, 1, 0)],
1113 ),
1114 &["a", "c"],
1115 );
1116 assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1117 let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1118 assert_eq!(team_badge(&read, false), None);
1119 }
1120
1121 #[test]
1122 fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1123 let entry = with_unread(
1124 with_mentions(
1125 team("t", false, &["a", "b", "c"], &["b", "c"]),
1126 &[("b", 1, 0, 0), ("c", 0, 1, 0)],
1127 ),
1128 &["b", "c"],
1129 );
1130 assert!(channel_shown(&entry, "b"));
1131 assert!(!channel_shown(&entry, "c"));
1132 assert!(team_has_unread(&entry));
1133 let rows = team_channel_rows(&entry, false, false, |_| false);
1134 let shown: Vec<&str> = rows
1135 .shown
1136 .iter()
1137 .map(|channel| channel.id.as_str())
1138 .collect();
1139 assert_eq!(shown, ["a", "b"]);
1140 assert_eq!(rows.hidden_count, 1);
1141 assert!(rows.revealed.is_empty());
1142 }
1143
1144 #[test]
1145 fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1146 let teams = [
1147 team("t1", false, &["a"], &[]),
1148 with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1149 ];
1150 assert!(team_hoisted(&teams[1]));
1151 assert!(!team_hoisted(&teams[0]));
1152 let rows = team_channel_rows(&teams[1], true, true, |_| true);
1153 let shown: Vec<&str> = rows
1154 .shown
1155 .iter()
1156 .map(|channel| channel.id.as_str())
1157 .collect();
1158 assert_eq!(shown, ["c"]);
1159 assert_eq!(rows.hidden_count, 0);
1160 let empty = HashSet::new();
1161 let input = ChannelOrderInput {
1162 teams: &teams,
1163 pinned_ids: &[],
1164 collapsed_teams: &empty,
1165 revealed_channel_teams: &empty,
1166 hidden_teams_open: false,
1167 selected_channel: None,
1168 };
1169 assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1170 let open = ChannelOrderInput {
1171 hidden_teams_open: true,
1172 ..input
1173 };
1174 assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1175 }
1176
1177 #[test]
1178 fn muted_chats_stay_out_of_unread_counts() {
1179 let mut quiet = chat("a", "group", true);
1180 quiet.muted = true;
1181 let chats = [quiet, chat("b", "group", true)];
1182 assert_eq!(unread_chat_count(&chats), 1);
1183 let directory = sectioned_directory(true, Vec::new());
1184 let collapsed = HashSet::new();
1185 let sections = build_sections(&input(&chats, &directory, &collapsed));
1186 assert_eq!(sections[0].unread_chats, 1);
1187 assert_eq!(sections[1].kind, SectionKind::Muted);
1188 assert!(sections[1].items[0].muted);
1189 assert!(sections[1].items[0].unread.is_unread());
1190 }
1191
1192 #[test]
1193 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
1194 let mut group = chat("g", "group", false);
1195 group.last_message_preview = Some("Hello".into());
1196 group.last_message_sender_id = Some("ada".into());
1197 group.last_message_sender_name = Some("Ada Example".into());
1198 assert_eq!(
1199 preview_for(&group, Some(&me())),
1200 Preview::Text {
1201 prefix: Some("Ada".into()),
1202 text: "Hello".into()
1203 }
1204 );
1205 group.last_message_sender_id = Some("me".into());
1206 assert_eq!(
1207 preview_for(&group, Some(&me())),
1208 Preview::Text {
1209 prefix: Some("You".into()),
1210 text: "Hello".into()
1211 }
1212 );
1213 let mut direct = chat("d", "oneOnOne", false);
1214 direct.last_message_preview = Some("Hi".into());
1215 direct.last_message_sender_id = Some("ada".into());
1216 direct.last_message_sender_name = Some("Ada Example".into());
1217 assert_eq!(
1218 preview_for(&direct, Some(&me())),
1219 Preview::Text {
1220 prefix: None,
1221 text: "Hi".into()
1222 }
1223 );
1224 }
1225
1226 #[test]
1227 fn deleted_and_blank_previews() {
1228 let mut deleted = chat("d", "group", false);
1229 deleted.last_message_deleted = true;
1230 deleted.last_message_preview = Some("secret".into());
1231 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
1232 assert_eq!(
1233 preview_for(&chat("e", "group", false), None),
1234 Preview::Empty
1235 );
1236 }
1237
1238 #[test]
1239 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
1240 let chats = vec![
1241 chat("a", "group", false),
1242 chat("b", "oneOnOne", true),
1243 chat("c", "group", false),
1244 chat("d", "group", false),
1245 ];
1246 let directory = Directory {
1247 me: Some(me()),
1248 folders: vec![
1249 folder("fav", FolderKind::Favorites, &["c"]),
1250 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
1251 folder("todo", FolderKind::UserCreated, &[]),
1252 ],
1253 ..Default::default()
1254 };
1255 let collapsed = HashSet::new();
1256 let sections = build_sections(&input(&chats, &directory, &collapsed));
1257 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
1258 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
1259 let work: Vec<&str> = sections[1]
1260 .items
1261 .iter()
1262 .map(|item| item.id.as_str())
1263 .collect();
1264 assert_eq!(work, vec!["b", "a"]);
1265 assert_eq!(sections[1].count, 2);
1266 assert_eq!(sections[2].count, 0);
1267 assert!(sections[2].show_empty_hint);
1268 let others: Vec<&str> = sections[3]
1269 .items
1270 .iter()
1271 .map(|item| item.id.as_str())
1272 .collect();
1273 assert_eq!(others, vec!["d"]);
1274 assert!(!sections[3].show_empty_hint);
1275 }
1276
1277 #[test]
1278 fn collapsed_sections_keep_the_aggregated_unread() {
1279 let chats = vec![
1280 chat("a", "group", true),
1281 chat("b", "group", true),
1282 chat("c", "group", false),
1283 ];
1284 let directory = Directory {
1285 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
1286 ..Default::default()
1287 };
1288 let collapsed: HashSet<String> = ["work".to_owned()].into();
1289 let sections = build_sections(&input(&chats, &directory, &collapsed));
1290 assert!(sections[0].collapsed);
1291 assert_eq!(sections[0].unread_chats, 2);
1292 assert_eq!(sections[0].count, 3);
1293 assert!(!sections[0].show_empty_hint);
1294 }
1295
1296 #[test]
1297 fn collapsed_empty_folder_hides_the_hint() {
1298 let directory = Directory {
1299 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
1300 ..Default::default()
1301 };
1302 let collapsed: HashSet<String> = ["todo".to_owned()].into();
1303 let sections = build_sections(&input(&[], &directory, &collapsed));
1304 assert!(!sections[0].show_empty_hint);
1305 }
1306
1307 #[test]
1308 fn favorites_without_a_server_name_say_angeheftet() {
1309 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
1310 favorites.name = String::new();
1311 let directory = Directory {
1312 folders: vec![favorites],
1313 ..Default::default()
1314 };
1315 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
1316 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1317 }
1318
1319 #[test]
1320 fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1321 let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1322 let mut directory = Directory::default();
1323 directory
1324 .unread_importance
1325 .insert("a".into(), MessageImportance::Urgent);
1326 directory
1327 .unread_importance
1328 .insert("b".into(), MessageImportance::High);
1329 let collapsed = HashSet::new();
1330 let context = input(&chats, &directory, &collapsed);
1331 assert_eq!(
1332 chat_item(&chats[0], &context, None).importance,
1333 MessageImportance::Urgent
1334 );
1335 assert_eq!(
1336 chat_item(&chats[1], &context, None).importance,
1337 MessageImportance::Normal
1338 );
1339 }
1340
1341 #[test]
1342 fn unread_is_a_count_when_known_else_a_dot() {
1343 let chats = vec![
1344 chat("a", "group", true),
1345 chat("b", "group", true),
1346 chat("c", "group", false),
1347 ];
1348 let mut directory = Directory::default();
1349 directory.unread_counts.insert("a".into(), 5);
1350 let collapsed = HashSet::new();
1351 let context = input(&chats, &directory, &collapsed);
1352 assert_eq!(
1353 chat_item(&chats[0], &context, None).unread,
1354 Unread::Count(5)
1355 );
1356 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
1357 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
1358 assert_eq!(unread_chat_count(&chats), 2);
1359 }
1360
1361 #[test]
1362 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
1363 let directory = Directory {
1364 me: Some(me()),
1365 ..Default::default()
1366 };
1367 let collapsed = HashSet::new();
1368 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
1369 let context = input(&chats, &directory, &collapsed);
1370 let direct = chat_item(&chats[0], &context, None);
1371 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
1372 assert!(
1373 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
1374 );
1375 let group = chat_item(&chats[1], &context, None);
1376 assert_eq!(group.presence_user, None);
1377 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1378 assert_eq!(
1379 avatar_for(&meeting_chat("meeting-1"), None),
1380 AvatarSpec::Meeting
1381 );
1382 }
1383
1384 #[test]
1385 fn the_notes_chat_shows_my_face_and_my_presence() {
1386 let directory = Directory {
1387 me: Some(me()),
1388 ..Default::default()
1389 };
1390 let collapsed = HashSet::new();
1391 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1392 notes.title = "Me Myself (You)".into();
1393 notes
1394 .members
1395 .retain(|member| member.user_id.as_deref() == Some("me"));
1396 let chats = vec![notes];
1397 let context = input(&chats, &directory, &collapsed);
1398 let item = chat_item(&chats[0], &context, None);
1399 assert_eq!(item.title, "Me Myself (You)");
1400 assert_eq!(item.presence_user.as_deref(), Some("me"));
1401 assert!(
1402 matches!(item.avatar, AvatarSpec::Single(ref face) if face.user_id.as_deref() == Some("me"))
1403 );
1404 }
1405
1406 #[test]
1407 fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() {
1408 let directory = Directory {
1409 me: Some(me()),
1410 ..Default::default()
1411 };
1412 let collapsed = HashSet::new();
1413 let mut echo = chat("echo", "oneOnOne", false);
1414 echo.title = "Echo".into();
1415 echo.members.truncate(1);
1416 echo.members.push(MemberRecord {
1417 user_id: Some("28:bot-echo".into()),
1418 display_name: "Echo".into(),
1419 });
1420 echo.last_message_preview = Some("Recording is ready".into());
1421 let chats = vec![echo];
1422 let context = input(&chats, &directory, &collapsed);
1423 let item = chat_item(&chats[0], &context, None);
1424 assert_eq!(item.title, "Echo");
1425 assert_eq!(item.presence_user, None);
1426 assert!(
1427 matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo"))
1428 );
1429 assert_eq!(item.preview, Preview::Event("Recording is ready".into()));
1430 }
1431
1432 #[test]
1433 fn an_event_label_from_a_person_stays_plain_text() {
1434 let mut direct = chat("d", "oneOnOne", false);
1435 direct.last_message_preview = Some("Recording is ready".into());
1436 direct.last_message_sender_id = Some("ada".into());
1437 assert_eq!(
1438 preview_for(&direct, Some(&me())),
1439 Preview::Text {
1440 prefix: None,
1441 text: "Recording is ready".into()
1442 }
1443 );
1444 }
1445
1446 #[test]
1447 fn typing_replaces_the_preview_even_in_muted_chats() {
1448 let mut direct = chat("d", "oneOnOne", false);
1449 direct.last_message_preview = Some("Earlier".into());
1450 direct.muted = true;
1451 let group = chat("g", "group", false);
1452 let chats = vec![direct, group];
1453 let directory = Directory::default();
1454 let collapsed = HashSet::new();
1455 let now = std::time::Instant::now();
1456 let mut typing = TypingState::default();
1457 typing.start("d", "ada", "Ada Example", now, Utc::now());
1458 typing.start("g", "ada", "Ada Example", now, Utc::now());
1459 let context = typing_input(&chats, &directory, &collapsed, &typing);
1460 assert_eq!(
1461 chat_item(&chats[0], &context, None).preview,
1462 Preview::Typing("typing...".into())
1463 );
1464 assert_eq!(
1465 chat_item(&chats[1], &context, None).preview,
1466 Preview::Typing("Ada is typing...".into())
1467 );
1468 typing.clear("d", "ada");
1469 let context = typing_input(&chats, &directory, &collapsed, &typing);
1470 assert_eq!(
1471 chat_item(&chats[0], &context, None).preview,
1472 Preview::Text {
1473 prefix: None,
1474 text: "Earlier".into()
1475 }
1476 );
1477 }
1478
1479 #[test]
1480 fn time_label_uses_the_list_rules() {
1481 let chats = vec![chat("a", "group", false)];
1482 let directory = Directory::default();
1483 let collapsed = HashSet::new();
1484 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
1485 assert_eq!(item.time_label, "09:30");
1486 }
1487
1488 #[test]
1489 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
1490 let chats = vec![
1491 chat("plain", "group", false),
1492 muted_chat("quiet"),
1493 muted_chat("pinned-quiet"),
1494 meeting_chat("sync"),
1495 meeting_chat("custom-sync"),
1496 ChatRecord {
1497 muted: true,
1498 ..meeting_chat("quiet-sync")
1499 },
1500 ];
1501 let directory = sectioned_directory(
1502 true,
1503 vec![
1504 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
1505 folder("work", FolderKind::UserCreated, &["custom-sync"]),
1506 ],
1507 );
1508 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1509 assert_eq!(
1510 section_ids(&sections),
1511 vec!["fav", "work", OTHERS_ID, MUTED_ID]
1512 );
1513 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
1514 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
1515 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
1516 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
1517 assert_eq!(sections[3].kind, SectionKind::Muted);
1518 assert_eq!(sections[3].count, 2);
1519 }
1520
1521 #[test]
1522 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
1523 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1524 let directory = sectioned_directory(false, Vec::new());
1525 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1526 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1527 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1528 }
1529
1530 #[test]
1531 fn muted_chats_stay_in_others_until_the_user_turns_the_section_on() {
1532 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1533 let directory = Directory::default();
1534 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1535 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1536 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1537 assert!(sections[0].items[0].muted);
1538 assert_eq!(sections[0].items[0].avatar, AvatarSpec::Muted);
1539 assert_eq!(sections[0].items[1].avatar, AvatarSpec::Meeting);
1540 }
1541
1542 #[test]
1543 fn a_muted_chat_in_others_stays_bold_without_a_count() {
1544 let mut quiet = muted_chat("quiet");
1545 quiet.unread = true;
1546 let chats = vec![quiet];
1547 let mut directory = Directory::default();
1548 directory.unread_counts.insert("quiet".into(), 4);
1549 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1550 assert_eq!(sections[0].kind, SectionKind::Others);
1551 assert_eq!(sections[0].items[0].unread, Unread::Silent);
1552 assert_eq!(sections[0].unread_chats, 0);
1553 }
1554
1555 #[test]
1556 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
1557 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
1558 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
1559 assert!(!wants_older_chats(None, 1000., 0., None, false));
1560 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
1561 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
1562 }
1563
1564 #[test]
1565 fn a_running_load_never_consumes_the_trigger() {
1566 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
1567 }
1568
1569 #[test]
1570 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
1571 assert!(older_chats_trigger_resets((true, true), (true, false)));
1572 assert!(older_chats_trigger_resets((true, true), (false, false)));
1573 assert!(older_chats_trigger_resets((false, false), (true, false)));
1574 assert!(!older_chats_trigger_resets((true, false), (true, false)));
1575 assert!(!older_chats_trigger_resets((true, false), (true, true)));
1576 assert!(!older_chats_trigger_resets((false, false), (false, false)));
1577 }
1578
1579 #[test]
1580 fn empty_system_sections_are_hidden() {
1581 let chats = vec![chat("a", "group", false)];
1582 let directory = sectioned_directory(true, Vec::new());
1583 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1584 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1585 }
1586
1587 #[test]
1588 fn sections_follow_the_server_folder_order_with_system_folders() {
1589 let chats = vec![
1590 chat("a", "group", false),
1591 muted_chat("quiet"),
1592 meeting_chat("sync"),
1593 ];
1594 let directory = sectioned_directory(
1595 true,
1596 vec![
1597 folder("muted-id", FolderKind::Muted, &[]),
1598 folder("fav", FolderKind::Favorites, &[]),
1599 folder("recent-id", FolderKind::Recent, &[]),
1600 folder("meeting-id", FolderKind::Meeting, &[]),
1601 ],
1602 );
1603 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1604 let sections = build_sections(&input(&chats, &directory, &collapsed));
1605 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1606 assert!(sections[0].collapsed);
1607 assert_eq!(sections[0].name, MUTED_NAME);
1608 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1609 }
1610
1611 #[test]
1612 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
1613 let chats: Vec<ChatRecord> = (0..8)
1614 .map(|index| muted_chat(&format!("m{index}")))
1615 .collect();
1616 let directory = sectioned_directory(true, Vec::new());
1617 let collapsed = HashSet::new();
1618 let sections = build_sections(&input(&chats, &directory, &collapsed));
1619 let muted = &sections[1];
1620 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
1621 assert_eq!(muted.count, 8);
1622 assert_eq!(muted.hidden_count, 3);
1623 assert!(!muted.list_expanded);
1624
1625 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1626 let mut context = input(&chats, &directory, &collapsed);
1627 context.expanded_lists = &expanded;
1628 let sections = build_sections(&context);
1629 let muted = &sections[1];
1630 assert_eq!(muted.items.len(), 8);
1631 assert_eq!(muted.hidden_count, 0);
1632 assert!(muted.list_expanded);
1633 }
1634
1635 #[test]
1636 fn five_chats_need_no_see_more_even_when_marked_expanded() {
1637 let chats: Vec<ChatRecord> = (0..5)
1638 .map(|index| muted_chat(&format!("m{index}")))
1639 .collect();
1640 let directory = sectioned_directory(true, Vec::new());
1641 let collapsed = HashSet::new();
1642 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1643 let mut context = input(&chats, &directory, &collapsed);
1644 context.expanded_lists = &expanded;
1645 let muted = &build_sections(&context)[1];
1646 assert_eq!(muted.hidden_count, 0);
1647 assert!(!muted.list_expanded);
1648 }
1649
1650 #[test]
1651 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
1652 let mut quiet = muted_chat("quiet");
1653 quiet.unread = true;
1654 let chats = vec![
1655 quiet,
1656 ChatRecord {
1657 muted: true,
1658 ..meeting_chat("x")
1659 },
1660 ];
1661 let mut directory = sectioned_directory(true, Vec::new());
1662 directory.unread_counts.insert("quiet".into(), 4);
1663 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1664 let muted = &sections[1];
1665 assert_eq!(muted.items[0].unread, Unread::Silent);
1666 assert!(muted.items[0].unread.is_unread());
1667 assert_eq!(muted.unread_chats, 0);
1668 assert_eq!(unread_chat_count(&chats), 0);
1669 }
1670
1671 #[test]
1672 fn meeting_chats_keep_their_unread_count_in_others() {
1673 let mut sync = meeting_chat("sync");
1674 sync.unread = true;
1675 let chats = vec![sync];
1676 let mut directory = sectioned_directory(true, Vec::new());
1677 directory.unread_counts.insert("sync".into(), 3);
1678 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1679 assert_eq!(sections[0].id, OTHERS_ID);
1680 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1681 assert_eq!(sections[0].unread_chats, 1);
1682 }
1683}