BlueGit

ict rusty-teams

Files

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

sidebar_model.rs

sidebar_model.rs 19.2 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, FixedOffset, Utc};
4use store::{ChatRecord, Sidebar};
5
6use crate::app_state::chat_title;
7use crate::data::{
8 Directory, FolderKind, Person, face_members, is_one_on_one, others, unread_count,
9};
10use crate::format;
11use crate::typing::{TypingState, preview_label};
12
13pub const FAVORITES_FALLBACK_NAME: &str = "Pinned";
14pub const OTHERS_NAME: &str = "Other chats";
15pub const OTHERS_ID: &str = "others";
16pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
17pub const DELETED_PREVIEW: &str = "Message deleted";
18const OWN_PREFIX: &str = "You";
19const GROUP_KIND: &str = "group";
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Preview {
23 Empty,
24 Deleted,
25 Typing(String),
26 Text {
27 prefix: Option<String>,
28 text: String,
29 },
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Unread {
34 None,
35 Dot,
36 Count(u32),
37}
38
39impl Unread {
40 pub fn is_unread(self) -> bool {
41 self != Unread::None
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Face {
47 pub user_id: Option<String>,
48 pub name: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum AvatarSpec {
53 Single(Face),
54 Pair(Face, Face),
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct ChatItem {
59 pub id: String,
60 pub title: String,
61 pub time_label: String,
62 pub preview: Preview,
63 pub unread: Unread,
64 pub muted: bool,
65 pub is_group: bool,
66 pub member_count: usize,
67 pub avatar: AvatarSpec,
68 pub presence_user: Option<String>,
69 pub folder_id: Option<String>,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum SectionKind {
74 Favorites,
75 Folder,
76 Others,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct Section {
81 pub id: String,
82 pub name: String,
83 pub kind: SectionKind,
84 pub collapsed: bool,
85 pub count: usize,
86 pub unread_chats: u32,
87 pub items: Vec<ChatItem>,
88 pub show_empty_hint: bool,
89}
90
91pub struct SectionInput<'a> {
92 pub chats: &'a [ChatRecord],
93 pub directory: &'a Directory,
94 pub collapsed: &'a HashSet<String>,
95 pub typing: &'a TypingState,
96 pub now: DateTime<Utc>,
97 pub offset: FixedOffset,
98}
99
100pub fn preview_for(chat: &ChatRecord, me: Option<&Person>) -> Preview {
101 if chat.last_message_deleted {
102 return Preview::Deleted;
103 }
104 let Some(text) = chat
105 .last_message_preview
106 .as_deref()
107 .map(str::trim)
108 .filter(|text| !text.is_empty())
109 else {
110 return Preview::Empty;
111 };
112 let from_me = match (chat.last_message_sender_id.as_deref(), me) {
113 (Some(sender), Some(me)) => sender == me.user_id,
114 _ => false,
115 };
116 let prefix = if from_me {
117 Some(OWN_PREFIX.to_owned())
118 } else if is_one_on_one(chat) {
119 None
120 } else {
121 chat.last_message_sender_name
122 .as_deref()
123 .map(|name| format::first_name(name).to_owned())
124 .filter(|name| !name.is_empty())
125 };
126 Preview::Text {
127 prefix,
128 text: text.to_owned(),
129 }
130}
131
132pub fn avatar_for(chat: &ChatRecord, me: Option<&Person>) -> AvatarSpec {
133 let faces = face_members(chat, me);
134 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
135 if is_one_on_one(chat) || faces.len() < 2 {
136 return AvatarSpec::Single(match faces.into_iter().next() {
137 Some(first) => face(first),
138 None => Face {
139 user_id: None,
140 name: chat_title(chat),
141 },
142 });
143 }
144 let mut iterator = faces.into_iter();
145 let (first, second) = (iterator.next(), iterator.next());
146 match (first, second) {
147 (Some(first), Some(second)) => AvatarSpec::Pair(face(first), face(second)),
148 _ => AvatarSpec::Single(Face {
149 user_id: None,
150 name: chat_title(chat),
151 }),
152 }
153}
154
155pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<&str>) -> ChatItem {
156 let me = input.directory.me.as_ref();
157 let unread = if chat.unread {
158 unread_count(input.directory, chat)
159 .filter(|count| *count > 0)
160 .map_or(Unread::Dot, Unread::Count)
161 } else {
162 Unread::None
163 };
164 let presence_user = is_one_on_one(chat)
165 .then(|| {
166 others(chat, me)
167 .into_iter()
168 .find_map(|(user_id, _)| user_id)
169 })
170 .flatten();
171 let typing_names = input.typing.names(&chat.id);
172 let preview = if typing_names.is_empty() {
173 preview_for(chat, me)
174 } else {
175 Preview::Typing(preview_label(&typing_names, is_one_on_one(chat)))
176 };
177 ChatItem {
178 id: chat.id.clone(),
179 title: chat_title(chat),
180 time_label: chat
181 .last_message_at
182 .map(|time| {
183 format::list_time_label(
184 time,
185 input.now.with_timezone(&input.offset).date_naive(),
186 input.offset,
187 )
188 })
189 .unwrap_or_default(),
190 preview,
191 unread,
192 muted: chat.muted,
193 is_group: chat.kind == GROUP_KIND,
194 member_count: chat.members.len(),
195 avatar: avatar_for(chat, me),
196 presence_user,
197 folder_id: folder_id.map(str::to_owned),
198 }
199}
200
201pub fn unread_chat_count(chats: &[ChatRecord]) -> u32 {
202 chats
203 .iter()
204 .filter(|chat| chat.unread && !chat.muted)
205 .count() as u32
206}
207
208pub fn any_unread_channel(sidebar: &Sidebar) -> bool {
209 sidebar
210 .teams
211 .iter()
212 .any(|team| team.channels.iter().any(|channel| channel.unread))
213}
214
215pub fn build_sections(input: &SectionInput<'_>) -> Vec<Section> {
216 let by_id: HashMap<&str, &ChatRecord> = input
217 .chats
218 .iter()
219 .map(|chat| (chat.id.as_str(), chat))
220 .collect();
221 let mut placed: HashSet<&str> = HashSet::new();
222 let mut sections = Vec::new();
223 for folder in &input.directory.folders {
224 let items: Vec<ChatItem> = folder
225 .conversation_ids
226 .iter()
227 .filter_map(|id| by_id.get(id.as_str()).copied())
228 .filter(|chat| placed.insert(chat.id.as_str()))
229 .map(|chat| chat_item(chat, input, Some(&folder.id)))
230 .collect();
231 let (kind, name) = match folder.kind {
232 FolderKind::Favorites => (
233 SectionKind::Favorites,
234 if folder.name.trim().is_empty() {
235 FAVORITES_FALLBACK_NAME.to_owned()
236 } else {
237 folder.name.clone()
238 },
239 ),
240 FolderKind::UserCreated => (SectionKind::Folder, folder.name.clone()),
241 };
242 sections.push(section(folder.id.clone(), name, kind, items, input));
243 }
244 let rest: Vec<ChatItem> = input
245 .chats
246 .iter()
247 .filter(|chat| !placed.contains(chat.id.as_str()))
248 .map(|chat| chat_item(chat, input, None))
249 .collect();
250 sections.push(section(
251 OTHERS_ID.to_owned(),
252 OTHERS_NAME.to_owned(),
253 SectionKind::Others,
254 rest,
255 input,
256 ));
257 sections
258}
259
260pub fn next_chat_id(sections: &[Section], removed_id: &str) -> Option<String> {
261 let visible: Vec<&str> = sections
262 .iter()
263 .filter(|section| !section.collapsed)
264 .flat_map(|section| section.items.iter().map(|item| item.id.as_str()))
265 .collect();
266 let position = visible.iter().position(|id| *id == removed_id)?;
267 visible
268 .get(position + 1)
269 .or_else(|| {
270 position
271 .checked_sub(1)
272 .and_then(|previous| visible.get(previous))
273 })
274 .map(|id| (*id).to_owned())
275}
276
277fn section(
278 id: String,
279 name: String,
280 kind: SectionKind,
281 items: Vec<ChatItem>,
282 input: &SectionInput<'_>,
283) -> Section {
284 let collapsed = input.collapsed.contains(&id);
285 let unread_chats = items
286 .iter()
287 .filter(|item| item.unread.is_unread() && !item.muted)
288 .count() as u32;
289 Section {
290 collapsed,
291 count: items.len(),
292 unread_chats,
293 show_empty_hint: items.is_empty() && !collapsed && kind != SectionKind::Others,
294 id,
295 name,
296 kind,
297 items,
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use chrono::TimeZone;
304 use store::MemberRecord;
305
306 use super::*;
307 use crate::data::FolderInfo;
308
309 fn me() -> Person {
310 Person {
311 user_id: "me".into(),
312 display_name: "Me Myself".into(),
313 }
314 }
315
316 fn chat(id: &str, kind: &str, unread: bool) -> ChatRecord {
317 ChatRecord {
318 id: id.into(),
319 kind: kind.into(),
320 title: id.to_uppercase(),
321 unread,
322 last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 7, 9, 30, 0).unwrap()),
323 members: vec![
324 MemberRecord {
325 user_id: Some("me".into()),
326 display_name: "Me Myself".into(),
327 },
328 MemberRecord {
329 user_id: Some("ada".into()),
330 display_name: "Ada Example".into(),
331 },
332 MemberRecord {
333 user_id: Some("bob".into()),
334 display_name: "Bob Sample".into(),
335 },
336 ],
337 ..Default::default()
338 }
339 }
340
341 fn folder(id: &str, kind: FolderKind, ids: &[&str]) -> FolderInfo {
342 FolderInfo {
343 id: id.into(),
344 name: format!("name-{id}"),
345 kind,
346 conversation_ids: ids.iter().map(|id| (*id).to_owned()).collect(),
347 }
348 }
349
350 fn input<'a>(
351 chats: &'a [ChatRecord],
352 directory: &'a Directory,
353 collapsed: &'a HashSet<String>,
354 ) -> SectionInput<'a> {
355 typing_input(chats, directory, collapsed, &NO_TYPING)
356 }
357
358 static NO_TYPING: std::sync::LazyLock<TypingState> =
359 std::sync::LazyLock::new(TypingState::default);
360
361 fn typing_input<'a>(
362 chats: &'a [ChatRecord],
363 directory: &'a Directory,
364 collapsed: &'a HashSet<String>,
365 typing: &'a TypingState,
366 ) -> SectionInput<'a> {
367 SectionInput {
368 chats,
369 directory,
370 collapsed,
371 typing,
372 now: Utc.with_ymd_and_hms(2026, 10, 7, 12, 0, 0).unwrap(),
373 offset: FixedOffset::east_opt(0).unwrap(),
374 }
375 }
376
377 #[test]
378 fn next_chat_is_the_following_row_then_the_previous_one() {
379 let chats = [
380 chat("a", "group", false),
381 chat("b", "group", false),
382 chat("c", "group", false),
383 ];
384 let directory = Directory::default();
385 let collapsed = HashSet::new();
386 let sections = build_sections(&input(&chats, &directory, &collapsed));
387 assert_eq!(next_chat_id(&sections, "a"), Some("b".to_owned()));
388 assert_eq!(next_chat_id(&sections, "c"), Some("b".to_owned()));
389 assert_eq!(next_chat_id(&sections, "zzz"), None);
390 let single = [chat("a", "group", false)];
391 let sections = build_sections(&input(&single, &directory, &collapsed));
392 assert_eq!(next_chat_id(&sections, "a"), None);
393 }
394
395 #[test]
396 fn muted_chats_stay_out_of_unread_counts() {
397 let mut quiet = chat("a", "group", true);
398 quiet.muted = true;
399 let chats = [quiet, chat("b", "group", true)];
400 assert_eq!(unread_chat_count(&chats), 1);
401 let directory = Directory::default();
402 let collapsed = HashSet::new();
403 let sections = build_sections(&input(&chats, &directory, &collapsed));
404 assert_eq!(sections[0].unread_chats, 1);
405 assert!(sections[0].items[0].muted);
406 assert!(sections[0].items[0].unread.is_unread());
407 }
408
409 #[test]
410 fn preview_prefix_is_you_for_own_and_first_name_for_groups() {
411 let mut group = chat("g", "group", false);
412 group.last_message_preview = Some("Hello".into());
413 group.last_message_sender_id = Some("ada".into());
414 group.last_message_sender_name = Some("Ada Example".into());
415 assert_eq!(
416 preview_for(&group, Some(&me())),
417 Preview::Text {
418 prefix: Some("Ada".into()),
419 text: "Hello".into()
420 }
421 );
422 group.last_message_sender_id = Some("me".into());
423 assert_eq!(
424 preview_for(&group, Some(&me())),
425 Preview::Text {
426 prefix: Some("You".into()),
427 text: "Hello".into()
428 }
429 );
430 let mut direct = chat("d", "oneOnOne", false);
431 direct.last_message_preview = Some("Hi".into());
432 direct.last_message_sender_id = Some("ada".into());
433 direct.last_message_sender_name = Some("Ada Example".into());
434 assert_eq!(
435 preview_for(&direct, Some(&me())),
436 Preview::Text {
437 prefix: None,
438 text: "Hi".into()
439 }
440 );
441 }
442
443 #[test]
444 fn deleted_and_blank_previews() {
445 let mut deleted = chat("d", "group", false);
446 deleted.last_message_deleted = true;
447 deleted.last_message_preview = Some("secret".into());
448 assert_eq!(preview_for(&deleted, None), Preview::Deleted);
449 assert_eq!(
450 preview_for(&chat("e", "group", false), None),
451 Preview::Empty
452 );
453 }
454
455 #[test]
456 fn sections_follow_folder_order_and_leave_the_rest_for_others() {
457 let chats = vec![
458 chat("a", "group", false),
459 chat("b", "oneOnOne", true),
460 chat("c", "group", false),
461 chat("d", "group", false),
462 ];
463 let directory = Directory {
464 me: Some(me()),
465 folders: vec![
466 folder("fav", FolderKind::Favorites, &["c"]),
467 folder("work", FolderKind::UserCreated, &["b", "gone", "a"]),
468 folder("todo", FolderKind::UserCreated, &[]),
469 ],
470 ..Default::default()
471 };
472 let collapsed = HashSet::new();
473 let sections = build_sections(&input(&chats, &directory, &collapsed));
474 let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect();
475 assert_eq!(ids, vec!["fav", "work", "todo", OTHERS_ID]);
476 let work: Vec<&str> = sections[1]
477 .items
478 .iter()
479 .map(|item| item.id.as_str())
480 .collect();
481 assert_eq!(work, vec!["b", "a"]);
482 assert_eq!(sections[1].count, 2);
483 assert_eq!(sections[2].count, 0);
484 assert!(sections[2].show_empty_hint);
485 let others: Vec<&str> = sections[3]
486 .items
487 .iter()
488 .map(|item| item.id.as_str())
489 .collect();
490 assert_eq!(others, vec!["d"]);
491 assert!(!sections[3].show_empty_hint);
492 }
493
494 #[test]
495 fn collapsed_sections_keep_the_aggregated_unread() {
496 let chats = vec![
497 chat("a", "group", true),
498 chat("b", "group", true),
499 chat("c", "group", false),
500 ];
501 let directory = Directory {
502 folders: vec![folder("work", FolderKind::UserCreated, &["a", "b", "c"])],
503 ..Default::default()
504 };
505 let collapsed: HashSet<String> = ["work".to_owned()].into();
506 let sections = build_sections(&input(&chats, &directory, &collapsed));
507 assert!(sections[0].collapsed);
508 assert_eq!(sections[0].unread_chats, 2);
509 assert_eq!(sections[0].count, 3);
510 assert!(!sections[0].show_empty_hint);
511 }
512
513 #[test]
514 fn collapsed_empty_folder_hides_the_hint() {
515 let directory = Directory {
516 folders: vec![folder("todo", FolderKind::UserCreated, &[])],
517 ..Default::default()
518 };
519 let collapsed: HashSet<String> = ["todo".to_owned()].into();
520 let sections = build_sections(&input(&[], &directory, &collapsed));
521 assert!(!sections[0].show_empty_hint);
522 }
523
524 #[test]
525 fn favorites_without_a_server_name_say_angeheftet() {
526 let mut favorites = folder("fav", FolderKind::Favorites, &[]);
527 favorites.name = String::new();
528 let directory = Directory {
529 folders: vec![favorites],
530 ..Default::default()
531 };
532 let sections = build_sections(&input(&[], &directory, &HashSet::new()));
533 assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
534 }
535
536 #[test]
537 fn unread_is_a_count_when_known_else_a_dot() {
538 let chats = vec![
539 chat("a", "group", true),
540 chat("b", "group", true),
541 chat("c", "group", false),
542 ];
543 let mut directory = Directory::default();
544 directory.unread_counts.insert("a".into(), 5);
545 let collapsed = HashSet::new();
546 let context = input(&chats, &directory, &collapsed);
547 assert_eq!(
548 chat_item(&chats[0], &context, None).unread,
549 Unread::Count(5)
550 );
551 assert_eq!(chat_item(&chats[1], &context, None).unread, Unread::Dot);
552 assert_eq!(chat_item(&chats[2], &context, None).unread, Unread::None);
553 assert_eq!(unread_chat_count(&chats), 2);
554 }
555
556 #[test]
557 fn one_on_one_has_presence_and_a_single_face_groups_have_a_pair() {
558 let directory = Directory {
559 me: Some(me()),
560 ..Default::default()
561 };
562 let collapsed = HashSet::new();
563 let chats = vec![chat("d", "oneOnOne", false), chat("g", "group", false)];
564 let context = input(&chats, &directory, &collapsed);
565 let direct = chat_item(&chats[0], &context, None);
566 assert_eq!(direct.presence_user.as_deref(), Some("ada"));
567 assert!(
568 matches!(direct.avatar, AvatarSpec::Single(ref face) if face.name == "Ada Example")
569 );
570 let group = chat_item(&chats[1], &context, None);
571 assert_eq!(group.presence_user, None);
572 assert!(matches!(group.avatar, AvatarSpec::Pair(..)));
573 }
574
575 #[test]
576 fn typing_replaces_the_preview_even_in_muted_chats() {
577 let mut direct = chat("d", "oneOnOne", false);
578 direct.last_message_preview = Some("Earlier".into());
579 direct.muted = true;
580 let group = chat("g", "group", false);
581 let chats = vec![direct, group];
582 let directory = Directory::default();
583 let collapsed = HashSet::new();
584 let now = std::time::Instant::now();
585 let mut typing = TypingState::default();
586 typing.start("d", "ada", "Ada Example", now, Utc::now());
587 typing.start("g", "ada", "Ada Example", now, Utc::now());
588 let context = typing_input(&chats, &directory, &collapsed, &typing);
589 assert_eq!(
590 chat_item(&chats[0], &context, None).preview,
591 Preview::Typing("typing...".into())
592 );
593 assert_eq!(
594 chat_item(&chats[1], &context, None).preview,
595 Preview::Typing("Ada is typing...".into())
596 );
597 typing.clear("d", "ada");
598 let context = typing_input(&chats, &directory, &collapsed, &typing);
599 assert_eq!(
600 chat_item(&chats[0], &context, None).preview,
601 Preview::Text {
602 prefix: None,
603 text: "Earlier".into()
604 }
605 );
606 }
607
608 #[test]
609 fn time_label_uses_the_list_rules() {
610 let chats = vec![chat("a", "group", false)];
611 let directory = Directory::default();
612 let collapsed = HashSet::new();
613 let item = chat_item(&chats[0], &input(&chats, &directory, &collapsed), None);
614 assert_eq!(item.time_label, "09:30");
615 }
616}