BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

e7ea3d7f 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 team: store::TeamRecord {
917 id: id.into(),
918 name: id.into(),
919 },
920 channels: channel_ids
921 .iter()
922 .map(|channel_id| ChannelRecord {
923 id: (*channel_id).into(),
924 team_id: id.into(),
925 name: (*channel_id).into(),
926 membership_type: None,
927 last_message_at: None,
928 unread: false,
929 })
930 .collect(),
931 hidden,
932 hidden_channel_ids: hidden_channel_ids
933 .iter()
934 .map(|id| (*id).to_owned())
935 .collect(),
936 notifications: HashMap::new(),
937 mentions: Default::default(),
938 }
939 }
940
941 fn with_unread(mut entry: SidebarTeam, unread_ids: &[&str]) -> SidebarTeam {
942 for channel in &mut entry.channels {
943 channel.unread = unread_ids.contains(&channel.id.as_str());
944 }
945 entry
946 }
947
948 #[test]
949 fn unread_shown_channel_is_bold_and_highlighted() {
950 let bold = NameStyle {
951 weight: NameWeight::Bold,
952 highlighted: true,
953 };
954 let plain = NameStyle {
955 weight: NameWeight::Regular,
956 highlighted: false,
957 };
958 assert_eq!(channel_name_style(true, true, false), bold);
959 assert_eq!(channel_name_style(false, true, false), plain);
960 assert_eq!(channel_name_style(true, false, false), plain);
961 assert_eq!(
962 channel_name_style(true, true, true),
963 NameStyle {
964 weight: NameWeight::Regular,
965 highlighted: true,
966 }
967 );
968 }
969
970 #[test]
971 fn collapsed_team_with_an_unread_shown_channel_is_semibold() {
972 let entry = with_unread(team("t1", false, &["a", "b"], &["b"]), &["a"]);
973 let semibold = NameStyle {
974 weight: NameWeight::Semibold,
975 highlighted: true,
976 };
977 assert_eq!(team_name_style(&entry, false), semibold);
978 assert_eq!(team_name_style(&entry, true), NameStyle::PLAIN);
979 let only_hidden = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
980 assert_eq!(team_name_style(&only_hidden, false), NameStyle::PLAIN);
981 }
982
983 #[test]
984 fn muted_channel_shows_no_unread_unless_personally_mentioned() {
985 let mut entry = with_unread(team("t1", false, &["a"], &[]), &["a"]);
986 entry.notifications.insert(
987 "a".into(),
988 store::ChannelNotifications {
989 level: ChannelNotificationLevel::Off,
990 include_replies: false,
991 },
992 );
993 assert!(!channel_shows_unread(&entry, &entry.channels[0]));
994 assert_eq!(team_name_style(&entry, false), NameStyle::PLAIN);
995 entry.mentions.insert(
996 "a".into(),
997 store::ChannelMentions {
998 personal: 1,
999 ..Default::default()
1000 },
1001 );
1002 assert!(channel_shows_unread(&entry, &entry.channels[0]));
1003 }
1004
1005 #[test]
1006 fn rail_dot_counts_shown_channels_of_shown_teams_only() {
1007 let sidebar = |teams: Vec<SidebarTeam>| Sidebar {
1008 teams,
1009 ..Sidebar::default()
1010 };
1011 let hidden_channel = with_unread(team("t1", false, &["a", "b"], &["b"]), &["b"]);
1012 let hidden_team = with_unread(team("t2", true, &["c"], &[]), &["c"]);
1013 assert!(!any_unread_channel(&sidebar(vec![
1014 hidden_channel,
1015 hidden_team
1016 ])));
1017 let shown = with_unread(team("t1", false, &["a"], &[]), &["a"]);
1018 let both = sidebar(vec![shown]);
1019 assert!(any_unread_channel(&both));
1020 assert!(channel_unread(&both, "a"));
1021 assert!(!channel_unread(&both, "missing"));
1022 }
1023
1024 #[test]
1025 fn visible_channels_list_pinned_first_then_open_teams() {
1026 let teams = [
1027 team("t1", false, &["a", "b", "c"], &["b"]),
1028 team("t2", false, &["d", "e"], &[]),
1029 team("t3", true, &["f"], &[]),
1030 ];
1031 let pinned = ["e".to_owned(), "missing".to_owned()];
1032 let order = |selected: Option<&str>,
1033 hidden_teams_open: bool,
1034 collapsed: &[&str],
1035 revealed: &[&str]| {
1036 let to_set = |ids: &[&str]| {
1037 ids.iter()
1038 .map(|id| (*id).to_owned())
1039 .collect::<HashSet<_>>()
1040 };
1041 let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
1042 let input = ChannelOrderInput {
1043 teams: &teams,
1044 pinned_ids: &pinned,
1045 collapsed_teams: &collapsed,
1046 revealed_channel_teams: &revealed,
1047 hidden_teams_open,
1048 selected_channel: selected,
1049 };
1050 visible_channel_ids(&input)
1051 .into_iter()
1052 .map(str::to_owned)
1053 .collect::<Vec<_>>()
1054 };
1055 assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
1056 assert_eq!(
1057 order(Some("b"), false, &[], &[]),
1058 vec!["e", "a", "b", "c", "d"]
1059 );
1060 assert_eq!(
1061 order(Some("f"), false, &[], &[]),
1062 vec!["e", "a", "c", "d", "f"]
1063 );
1064 assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
1065 assert_eq!(
1066 order(None, true, &["t2"], &["t1"]),
1067 vec!["e", "a", "c", "b", "f"]
1068 );
1069 }
1070
1071 fn with_mentions(mut entry: SidebarTeam, mentions: &[(&str, u32, u32, u32)]) -> SidebarTeam {
1072 for (channel_id, personal, channel, team) in mentions {
1073 entry.mentions.insert(
1074 (*channel_id).to_owned(),
1075 store::ChannelMentions {
1076 personal: *personal,
1077 channel: *channel,
1078 team: *team,
1079 },
1080 );
1081 }
1082 entry
1083 }
1084
1085 #[test]
1086 fn channel_badges_prefer_the_count_then_channel_then_team() {
1087 let entry = with_mentions(
1088 team("t", false, &["a", "b", "c", "d"], &[]),
1089 &[("a", 2, 1, 1), ("b", 0, 3, 1), ("c", 0, 0, 1)],
1090 );
1091 assert_eq!(channel_badge(&entry, "a"), Some(MentionBadge::Count(2)));
1092 assert_eq!(channel_badge(&entry, "b"), Some(MentionBadge::Channel));
1093 assert_eq!(channel_badge(&entry, "c"), Some(MentionBadge::Team));
1094 assert_eq!(channel_badge(&entry, "d"), None);
1095 }
1096
1097 #[test]
1098 fn the_collapsed_team_sums_counts_of_all_channels_and_icons_of_shown_ones() {
1099 let entry = with_unread(
1100 with_mentions(
1101 team("t", false, &["a", "b", "c"], &["b", "c"]),
1102 &[("a", 1, 0, 0), ("b", 2, 0, 0), ("c", 0, 1, 0)],
1103 ),
1104 &["a", "b", "c"],
1105 );
1106 assert_eq!(team_badge(&entry, false), Some(MentionBadge::Count(3)));
1107 assert_eq!(team_badge(&entry, true), None);
1108 let icons_only = with_unread(
1109 with_mentions(
1110 team("t", false, &["a", "c"], &["c"]),
1111 &[("a", 0, 0, 1), ("c", 0, 1, 0)],
1112 ),
1113 &["a", "c"],
1114 );
1115 assert_eq!(team_badge(&icons_only, false), Some(MentionBadge::Team));
1116 let read = with_mentions(team("t", false, &["a"], &[]), &[("a", 1, 0, 0)]);
1117 assert_eq!(team_badge(&read, false), None);
1118 }
1119
1120 #[test]
1121 fn a_hidden_channel_with_a_personal_mention_is_pulled_into_the_list() {
1122 let entry = with_unread(
1123 with_mentions(
1124 team("t", false, &["a", "b", "c"], &["b", "c"]),
1125 &[("b", 1, 0, 0), ("c", 0, 1, 0)],
1126 ),
1127 &["b", "c"],
1128 );
1129 assert!(channel_shown(&entry, "b"));
1130 assert!(!channel_shown(&entry, "c"));
1131 assert!(team_has_unread(&entry));
1132 let rows = team_channel_rows(&entry, false, false, |_| false);
1133 let shown: Vec<&str> = rows
1134 .shown
1135 .iter()
1136 .map(|channel| channel.id.as_str())
1137 .collect();
1138 assert_eq!(shown, ["a", "b"]);
1139 assert_eq!(rows.hidden_count, 1);
1140 assert!(rows.revealed.is_empty());
1141 }
1142
1143 #[test]
1144 fn a_hidden_team_with_a_hoisted_channel_shows_only_that_channel_in_the_main_list() {
1145 let teams = [
1146 team("t1", false, &["a"], &[]),
1147 with_mentions(team("t2", true, &["b", "c"], &["c"]), &[("c", 1, 0, 0)]),
1148 ];
1149 assert!(team_hoisted(&teams[1]));
1150 assert!(!team_hoisted(&teams[0]));
1151 let rows = team_channel_rows(&teams[1], true, true, |_| true);
1152 let shown: Vec<&str> = rows
1153 .shown
1154 .iter()
1155 .map(|channel| channel.id.as_str())
1156 .collect();
1157 assert_eq!(shown, ["c"]);
1158 assert_eq!(rows.hidden_count, 0);
1159 let empty = HashSet::new();
1160 let input = ChannelOrderInput {
1161 teams: &teams,
1162 pinned_ids: &[],
1163 collapsed_teams: &empty,
1164 revealed_channel_teams: &empty,
1165 hidden_teams_open: false,
1166 selected_channel: None,
1167 };
1168 assert_eq!(visible_channel_ids(&input), ["a", "c"]);
1169 let open = ChannelOrderInput {
1170 hidden_teams_open: true,
1171 ..input
1172 };
1173 assert_eq!(visible_channel_ids(&open), ["a", "c", "b"]);
1174 }
1175
1176 #[test]
1177 fn muted_chats_stay_out_of_unread_counts() {
1178 let mut quiet = chat("a", "group", true);
1179 quiet.muted = true;
1180 let chats = [quiet, chat("b", "group", true)];
1181 assert_eq!(unread_chat_count(&chats), 1);
1182 let directory = sectioned_directory(true, Vec::new());
1183 let collapsed = HashSet::new();
1184 let sections = build_sections(&input(&chats, &directory, &collapsed));
1185 assert_eq!(sections[0].unread_chats, 1);
1186 assert_eq!(sections[1].kind, SectionKind::Muted);
1187 assert!(sections[1].items[0].muted);
1188 assert!(sections[1].items[0].unread.is_unread());
1189 }
1190
1191 #[test]
1192 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
1193 let mut group = chat("g", "group", false);
1194 group.last_message_preview = Some("Hello".into());
1195 group.last_message_sender_id = Some("ada".into());
1196 group.last_message_sender_name = Some("Ada Example".into());
1197 assert_eq!(
1198 preview_for(&group, Some(&me())),
1199 Preview::Text {
1200 prefix: Some("Ada".into()),
1201 text: "Hello".into()
1202 }
1203 );
1204 group.last_message_sender_id = Some("me".into());
1205 assert_eq!(
1206 preview_for(&group, Some(&me())),
1207 Preview::Text {
1208 prefix: Some("You".into()),
1209 text: "Hello".into()
1210 }
1211 );
1212 let mut direct = chat("d", "oneOnOne", false);
1213 direct.last_message_preview = Some("Hi".into());
1214 direct.last_message_sender_id = Some("ada".into());
1215 direct.last_message_sender_name = Some("Ada Example".into());
1216 assert_eq!(
1217 preview_for(&direct, Some(&me())),
1218 Preview::Text {
1219 prefix: None,
1220 text: "Hi".into()
1221 }
1222 );
1223 }
1224
1225 #[test]
1226 fn deleted_and_blank_previews() {
1227 let mut deleted = chat("d", "group", false);
1228 deleted.last_message_deleted = true;
1229 deleted.last_message_preview = Some("secret".into());
1230 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
1231 assert_eq!(
1232 preview_for(&chat("e", "group", false), None),
1233 Preview::Empty
1234 );
1235 }
1236
1237 #[test]
1238 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
1239 let chats = vec![
1240 chat("a", "group", false),
1241 chat("b", "oneOnOne", true),
1242 chat("c", "group", false),
1243 chat("d", "group", false),
1244 ];
1245 let directory = Directory {
1246 me: Some(me()),
1247 folders: vec![
1248 folder("fav", FolderKind::Favorites, &["c"]),
1249 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
1250 folder("todo", FolderKind::UserCreated, &[]),
1251 ],
1252 ..Default::default()
1253 };
1254 let collapsed = HashSet::new();
1255 let sections = build_sections(&input(&chats, &directory, &collapsed));
1256 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
1257 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
1258 let work: Vec<&str> = sections[1]
1259 .items
1260 .iter()
1261 .map(|item| item.id.as_str())
1262 .collect();
1263 assert_eq!(work, vec!["b", "a"]);
1264 assert_eq!(sections[1].count, 2);
1265 assert_eq!(sections[2].count, 0);
1266 assert!(sections[2].show_empty_hint);
1267 let others: Vec<&str> = sections[3]
1268 .items
1269 .iter()
1270 .map(|item| item.id.as_str())
1271 .collect();
1272 assert_eq!(others, vec!["d"]);
1273 assert!(!sections[3].show_empty_hint);
1274 }
1275
1276 #[test]
1277 fn collapsed_sections_keep_the_aggregated_unread() {
1278 let chats = vec![
1279 chat("a", "group", true),
1280 chat("b", "group", true),
1281 chat("c", "group", false),
1282 ];
1283 let directory = Directory {
1284 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
1285 ..Default::default()
1286 };
1287 let collapsed: HashSet<String> = ["work".to_owned()].into();
1288 let sections = build_sections(&input(&chats, &directory, &collapsed));
1289 assert!(sections[0].collapsed);
1290 assert_eq!(sections[0].unread_chats, 2);
1291 assert_eq!(sections[0].count, 3);
1292 assert!(!sections[0].show_empty_hint);
1293 }
1294
1295 #[test]
1296 fn collapsed_empty_folder_hides_the_hint() {
1297 let directory = Directory {
1298 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
1299 ..Default::default()
1300 };
1301 let collapsed: HashSet<String> = ["todo".to_owned()].into();
1302 let sections = build_sections(&input(&[], &directory, &collapsed));
1303 assert!(!sections[0].show_empty_hint);
1304 }
1305
1306 #[test]
1307 fn favorites_without_a_server_name_say_angeheftet() {
1308 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
1309 favorites.name = String::new();
1310 let directory = Directory {
1311 folders: vec![favorites],
1312 ..Default::default()
1313 };
1314 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
1315 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1316 }
1317
1318 #[test]
1319 fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1320 let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1321 let mut directory = Directory::default();
1322 directory
1323 .unread_importance
1324 .insert("a".into(), MessageImportance::Urgent);
1325 directory
1326 .unread_importance
1327 .insert("b".into(), MessageImportance::High);
1328 let collapsed = HashSet::new();
1329 let context = input(&chats, &directory, &collapsed);
1330 assert_eq!(
1331 chat_item(&chats[0], &context, None).importance,
1332 MessageImportance::Urgent
1333 );
1334 assert_eq!(
1335 chat_item(&chats[1], &context, None).importance,
1336 MessageImportance::Normal
1337 );
1338 }
1339
1340 #[test]
1341 fn unread_is_a_count_when_known_else_a_dot() {
1342 let chats = vec![
1343 chat("a", "group", true),
1344 chat("b", "group", true),
1345 chat("c", "group", false),
1346 ];
1347 let mut directory = Directory::default();
1348 directory.unread_counts.insert("a".into(), 5);
1349 let collapsed = HashSet::new();
1350 let context = input(&chats, &directory, &collapsed);
1351 assert_eq!(
1352 chat_item(&chats[0], &context, None).unread,
1353 Unread::Count(5)
1354 );
1355 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
1356 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
1357 assert_eq!(unread_chat_count(&chats), 2);
1358 }
1359
1360 #[test]
1361 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
1362 let directory = Directory {
1363 me: Some(me()),
1364 ..Default::default()
1365 };
1366 let collapsed = HashSet::new();
1367 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
1368 let context = input(&chats, &directory, &collapsed);
1369 let direct = chat_item(&chats[0], &context, None);
1370 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
1371 assert!(
1372 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
1373 );
1374 let group = chat_item(&chats[1], &context, None);
1375 assert_eq!(group.presence_user, None);
1376 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
1377 assert_eq!(
1378 avatar_for(&meeting_chat("meeting-1"), None),
1379 AvatarSpec::Meeting
1380 );
1381 }
1382
1383 #[test]
1384 fn the_notes_chat_shows_my_face_and_my_presence() {
1385 let directory = Directory {
1386 me: Some(me()),
1387 ..Default::default()
1388 };
1389 let collapsed = HashSet::new();
1390 let mut notes = chat(teams_core::NOTES_CHAT_ID, "oneOnOne", false);
1391 notes.title = "Me Myself (You)".into();
1392 notes
1393 .members
1394 .retain(|member| member.user_id.as_deref() == Some("me"));
1395 let chats = vec![notes];
1396 let context = input(&chats, &directory, &collapsed);
1397 let item = chat_item(&chats[0], &context, None);
1398 assert_eq!(item.title, "Me Myself (You)");
1399 assert_eq!(item.presence_user.as_deref(), Some("me"));
1400 assert!(
1401 matches!(item.avatar, AvatarSpec::Single(ref face) if face.user_id.as_deref() == Some("me"))
1402 );
1403 }
1404
1405 #[test]
1406 fn a_one_on_one_with_a_bot_shows_the_bot_tile_and_no_presence() {
1407 let directory = Directory {
1408 me: Some(me()),
1409 ..Default::default()
1410 };
1411 let collapsed = HashSet::new();
1412 let mut echo = chat("echo", "oneOnOne", false);
1413 echo.title = "Echo".into();
1414 echo.members.truncate(1);
1415 echo.members.push(MemberRecord {
1416 user_id: Some("28:bot-echo".into()),
1417 display_name: "Echo".into(),
1418 });
1419 echo.last_message_preview = Some("Recording is ready".into());
1420 let chats = vec![echo];
1421 let context = input(&chats, &directory, &collapsed);
1422 let item = chat_item(&chats[0], &context, None);
1423 assert_eq!(item.title, "Echo");
1424 assert_eq!(item.presence_user, None);
1425 assert!(
1426 matches!(item.avatar, AvatarSpec::Bot(ref face) if face.user_id.as_deref() == Some("28:bot-echo"))
1427 );
1428 assert_eq!(item.preview, Preview::Event("Recording is ready".into()));
1429 }
1430
1431 #[test]
1432 fn an_event_label_from_a_person_stays_plain_text() {
1433 let mut direct = chat("d", "oneOnOne", false);
1434 direct.last_message_preview = Some("Recording is ready".into());
1435 direct.last_message_sender_id = Some("ada".into());
1436 assert_eq!(
1437 preview_for(&direct, Some(&me())),
1438 Preview::Text {
1439 prefix: None,
1440 text: "Recording is ready".into()
1441 }
1442 );
1443 }
1444
1445 #[test]
1446 fn typing_replaces_the_preview_even_in_muted_chats() {
1447 let mut direct = chat("d", "oneOnOne", false);
1448 direct.last_message_preview = Some("Earlier".into());
1449 direct.muted = true;
1450 let group = chat("g", "group", false);
1451 let chats = vec![direct, group];
1452 let directory = Directory::default();
1453 let collapsed = HashSet::new();
1454 let now = std::time::Instant::now();
1455 let mut typing = TypingState::default();
1456 typing.start("d", "ada", "Ada Example", now, Utc::now());
1457 typing.start("g", "ada", "Ada Example", now, Utc::now());
1458 let context = typing_input(&chats, &directory, &collapsed, &typing);
1459 assert_eq!(
1460 chat_item(&chats[0], &context, None).preview,
1461 Preview::Typing("typing...".into())
1462 );
1463 assert_eq!(
1464 chat_item(&chats[1], &context, None).preview,
1465 Preview::Typing("Ada is typing...".into())
1466 );
1467 typing.clear("d", "ada");
1468 let context = typing_input(&chats, &directory, &collapsed, &typing);
1469 assert_eq!(
1470 chat_item(&chats[0], &context, None).preview,
1471 Preview::Text {
1472 prefix: None,
1473 text: "Earlier".into()
1474 }
1475 );
1476 }
1477
1478 #[test]
1479 fn time_label_uses_the_list_rules() {
1480 let chats = vec![chat("a", "group", false)];
1481 let directory = Directory::default();
1482 let collapsed = HashSet::new();
1483 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
1484 assert_eq!(item.time_label, "09:30");
1485 }
1486
1487 #[test]
1488 fn muted_chats_leave_others_unless_pinned_or_in_a_custom_section_and_meeting_chats_stay() {
1489 let chats = vec![
1490 chat("plain", "group", false),
1491 muted_chat("quiet"),
1492 muted_chat("pinned-quiet"),
1493 meeting_chat("sync"),
1494 meeting_chat("custom-sync"),
1495 ChatRecord {
1496 muted: true,
1497 ..meeting_chat("quiet-sync")
1498 },
1499 ];
1500 let directory = sectioned_directory(
1501 true,
1502 vec![
1503 folder("fav", FolderKind::Favorites, &["pinned-quiet"]),
1504 folder("work", FolderKind::UserCreated, &["custom-sync"]),
1505 ],
1506 );
1507 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1508 assert_eq!(
1509 section_ids(&sections),
1510 vec!["fav", "work", OTHERS_ID, MUTED_ID]
1511 );
1512 assert_eq!(item_ids(&sections[0]), vec!["pinned-quiet"]);
1513 assert_eq!(item_ids(&sections[1]), vec!["custom-sync"]);
1514 assert_eq!(item_ids(&sections[2]), vec!["plain", "sync"]);
1515 assert_eq!(item_ids(&sections[3]), vec!["quiet", "quiet-sync"]);
1516 assert_eq!(sections[3].kind, SectionKind::Muted);
1517 assert_eq!(sections[3].count, 2);
1518 }
1519
1520 #[test]
1521 fn turning_the_muted_section_off_puts_its_chats_back_in_others() {
1522 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1523 let directory = sectioned_directory(false, Vec::new());
1524 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1525 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1526 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1527 }
1528
1529 #[test]
1530 fn muted_chats_stay_in_others_until_the_user_turns_the_section_on() {
1531 let chats = vec![muted_chat("quiet"), meeting_chat("sync")];
1532 let directory = Directory::default();
1533 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1534 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1535 assert_eq!(item_ids(&sections[0]), vec!["quiet", "sync"]);
1536 assert!(sections[0].items[0].muted);
1537 assert_eq!(sections[0].items[0].avatar, AvatarSpec::Muted);
1538 assert_eq!(sections[0].items[1].avatar, AvatarSpec::Meeting);
1539 }
1540
1541 #[test]
1542 fn a_muted_chat_in_others_stays_bold_without_a_count() {
1543 let mut quiet = muted_chat("quiet");
1544 quiet.unread = true;
1545 let chats = vec![quiet];
1546 let mut directory = Directory::default();
1547 directory.unread_counts.insert("quiet".into(), 4);
1548 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1549 assert_eq!(sections[0].kind, SectionKind::Others);
1550 assert_eq!(sections[0].items[0].unread, Unread::Silent);
1551 assert_eq!(sections[0].unread_chats, 0);
1552 }
1553
1554 #[test]
1555 fn older_chats_load_only_when_the_end_of_other_chats_is_on_screen_once_per_scroll_position() {
1556 assert!(wants_older_chats(Some(900.), 1000., 0., None, false));
1557 assert!(!wants_older_chats(Some(1500.), 1000., 0., None, false));
1558 assert!(!wants_older_chats(None, 1000., 0., None, false));
1559 assert!(!wants_older_chats(Some(900.), 1000., 0., Some(0.), false));
1560 assert!(wants_older_chats(Some(900.), 1000., 120., Some(0.), false));
1561 }
1562
1563 #[test]
1564 fn a_running_load_never_consumes_the_trigger() {
1565 assert!(!wants_older_chats(Some(900.), 1000., 0., None, true));
1566 }
1567
1568 #[test]
1569 fn the_trigger_resets_when_a_load_ends_or_more_chats_appear_but_not_while_idle() {
1570 assert!(older_chats_trigger_resets((true, true), (true, false)));
1571 assert!(older_chats_trigger_resets((true, true), (false, false)));
1572 assert!(older_chats_trigger_resets((false, false), (true, false)));
1573 assert!(!older_chats_trigger_resets((true, false), (true, false)));
1574 assert!(!older_chats_trigger_resets((true, false), (true, true)));
1575 assert!(!older_chats_trigger_resets((false, false), (false, false)));
1576 }
1577
1578 #[test]
1579 fn empty_system_sections_are_hidden() {
1580 let chats = vec![chat("a", "group", false)];
1581 let directory = sectioned_directory(true, Vec::new());
1582 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1583 assert_eq!(section_ids(&sections), vec![OTHERS_ID]);
1584 }
1585
1586 #[test]
1587 fn sections_follow_the_server_folder_order_with_system_folders() {
1588 let chats = vec![
1589 chat("a", "group", false),
1590 muted_chat("quiet"),
1591 meeting_chat("sync"),
1592 ];
1593 let directory = sectioned_directory(
1594 true,
1595 vec![
1596 folder("muted-id", FolderKind::Muted, &[]),
1597 folder("fav", FolderKind::Favorites, &[]),
1598 folder("recent-id", FolderKind::Recent, &[]),
1599 folder("meeting-id", FolderKind::Meeting, &[]),
1600 ],
1601 );
1602 let collapsed: HashSet<String> = ["muted-id".to_owned()].into();
1603 let sections = build_sections(&input(&chats, &directory, &collapsed));
1604 assert_eq!(section_ids(&sections), vec!["muted-id", "fav", "recent-id"]);
1605 assert!(sections[0].collapsed);
1606 assert_eq!(sections[0].name, MUTED_NAME);
1607 assert_eq!(item_ids(&sections[2]), vec!["a", "sync"]);
1608 }
1609
1610 #[test]
1611 fn newest_five_show_then_see_more_expands_and_see_less_collapses() {
1612 let chats: Vec<ChatRecord> = (0..8)
1613 .map(|index| muted_chat(&format!("m{index}")))
1614 .collect();
1615 let directory = sectioned_directory(true, Vec::new());
1616 let collapsed = HashSet::new();
1617 let sections = build_sections(&input(&chats, &directory, &collapsed));
1618 let muted = &sections[1];
1619 assert_eq!(item_ids(muted), vec!["m0", "m1", "m2", "m3", "m4"]);
1620 assert_eq!(muted.count, 8);
1621 assert_eq!(muted.hidden_count, 3);
1622 assert!(!muted.list_expanded);
1623
1624 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1625 let mut context = input(&chats, &directory, &collapsed);
1626 context.expanded_lists = &expanded;
1627 let sections = build_sections(&context);
1628 let muted = &sections[1];
1629 assert_eq!(muted.items.len(), 8);
1630 assert_eq!(muted.hidden_count, 0);
1631 assert!(muted.list_expanded);
1632 }
1633
1634 #[test]
1635 fn five_chats_need_no_see_more_even_when_marked_expanded() {
1636 let chats: Vec<ChatRecord> = (0..5)
1637 .map(|index| muted_chat(&format!("m{index}")))
1638 .collect();
1639 let directory = sectioned_directory(true, Vec::new());
1640 let collapsed = HashSet::new();
1641 let expanded: HashSet<String> = [MUTED_ID.to_owned()].into();
1642 let mut context = input(&chats, &directory, &collapsed);
1643 context.expanded_lists = &expanded;
1644 let muted = &build_sections(&context)[1];
1645 assert_eq!(muted.hidden_count, 0);
1646 assert!(!muted.list_expanded);
1647 }
1648
1649 #[test]
1650 fn muted_section_keeps_unread_bold_without_a_badge_or_a_count() {
1651 let mut quiet = muted_chat("quiet");
1652 quiet.unread = true;
1653 let chats = vec![
1654 quiet,
1655 ChatRecord {
1656 muted: true,
1657 ..meeting_chat("x")
1658 },
1659 ];
1660 let mut directory = sectioned_directory(true, Vec::new());
1661 directory.unread_counts.insert("quiet".into(), 4);
1662 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1663 let muted = &sections[1];
1664 assert_eq!(muted.items[0].unread, Unread::Silent);
1665 assert!(muted.items[0].unread.is_unread());
1666 assert_eq!(muted.unread_chats, 0);
1667 assert_eq!(unread_chat_count(&chats), 0);
1668 }
1669
1670 #[test]
1671 fn meeting_chats_keep_their_unread_count_in_others() {
1672 let mut sync = meeting_chat("sync");
1673 sync.unread = true;
1674 let chats = vec![sync];
1675 let mut directory = sectioned_directory(true, Vec::new());
1676 directory.unread_counts.insert("sync".into(), 3);
1677 let sections = build_sections(&input(&chats, &directory, &HashSet::new()));
1678 assert_eq!(sections[0].id, OTHERS_ID);
1679 assert_eq!(sections[0].items[0].unread, Unread::Count(3));
1680 assert_eq!(sections[0].unread_chats, 1);
1681 }
1682}