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