BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

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