BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 23.7 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{ChatApp, CoreEvent, ImageRef};
10
11use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12use crate::card_state::{CardState, TaskDialogState};
13use crate::data::{self, Directory};
14use crate::notice::Notice;
15use crate::notify;
16use crate::typing::TypingState;
17
18const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
19const RECENT_MESSAGES_FOR_TYPING: usize = 5;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Selection {
23 Chat(String),
24 Channel(String),
25}
26
27impl Selection {
28 pub fn conversation_id(&self) -> &str {
29 match self {
30 Selection::Chat(id) | Selection::Channel(id) => id,
31 }
32 }
33}
34
35pub enum AppEvent {
36 Sidebar,
37 Selection,
38 Messages(String),
39 Images(Vec<String>),
40 Jump,
41 Status,
42 Directory,
43 Cards(String),
44 TaskDialog,
45 Typing,
46}
47
48#[derive(Debug, Clone, Copy, Default)]
49pub struct Mode {
50 pub demo: bool,
51 pub read_only: bool,
52 pub demo_sync: Option<std::time::Duration>,
53}
54
55pub struct AppState {
56 pub store: Arc<Store>,
57 pub engine: Option<Arc<Engine>>,
58 pub sidebar: Sidebar,
59 pub favorite_ids: Vec<String>,
60 pub selection: Option<Selection>,
61 pub new_chat: bool,
62 pub connection: ConnectionState,
63 pub live: LiveState,
64 pub last_sync: Option<DateTime<Utc>>,
65 pub mode: Mode,
66 pub directory: Directory,
67 pub collapsed: HashSet<String>,
68 pub followed_channels: HashSet<String>,
69 pub start_on_channels: bool,
70 pub pending_jump: Option<(String, String)>,
71 pub cards: CardState,
72 pub task_dialog: Option<TaskDialogState>,
73 pub bot_apps: HashMap<String, Vec<ChatApp>>,
74 pub bot_apps_pending: HashSet<String>,
75 pub notice: Option<Notice>,
76 pub notice_count: u64,
77 pub keep_unread: Option<String>,
78 pub typing: TypingState,
79 typing_timer_running: bool,
80}
81
82pub struct AppHandle(pub Entity<AppState>);
83
84impl Global for AppHandle {}
85
86impl EventEmitter<AppEvent> for AppState {}
87
88pub fn chat_title(chat: &ChatRecord) -> String {
89 if !chat.title.trim().is_empty() {
90 chat.title.clone()
91 } else if !chat.member_summary.trim().is_empty() {
92 chat.member_summary.clone()
93 } else {
94 "Chat".to_owned()
95 }
96}
97
98pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
99 match selection {
100 Selection::Chat(id) => sidebar
101 .chats
102 .iter()
103 .find(|chat| &chat.id == id)
104 .map(chat_title)
105 .unwrap_or_else(|| "Chat".to_owned()),
106 Selection::Channel(id) => sidebar
107 .teams
108 .iter()
109 .find_map(|team| {
110 team.channels
111 .iter()
112 .find(|channel| &channel.id == id)
113 .map(|channel| format!("{} / {}", team.team.name, channel.name))
114 })
115 .unwrap_or_else(|| "Channel".to_owned()),
116 }
117}
118
119impl AppState {
120 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
121 let sidebar = store.sidebar().unwrap_or_default();
122 let mut state = AppState {
123 store,
124 engine: None,
125 sidebar,
126 favorite_ids: Vec::new(),
127 selection: None,
128 new_chat: false,
129 connection: if mode.demo {
130 ConnectionState::Online
131 } else {
132 ConnectionState::Connecting
133 },
134 live: LiveState::Off,
135 last_sync: None,
136 mode,
137 directory: Directory::default(),
138 collapsed: HashSet::new(),
139 followed_channels: HashSet::new(),
140 start_on_channels: false,
141 pending_jump: None,
142 cards: CardState::default(),
143 task_dialog: None,
144 bot_apps: HashMap::new(),
145 bot_apps_pending: HashSet::new(),
146 notice: None,
147 notice_count: 0,
148 keep_unread: None,
149 typing: TypingState::default(),
150 typing_timer_running: false,
151 };
152 state.collapsed = state.load_collapsed();
153 state.followed_channels = notify::load_followed_channels(&state.store);
154 if !mode.demo {
155 state.directory.load_cached_presence(&state.store);
156 state.reload_directory();
157 }
158 state
159 }
160
161 fn load_collapsed(&self) -> HashSet<String> {
162 self.store
163 .meta(COLLAPSED_META_KEY)
164 .ok()
165 .flatten()
166 .map(|value| {
167 value
168 .lines()
169 .map(str::to_owned)
170 .filter(|id| !id.is_empty())
171 .collect()
172 })
173 .unwrap_or_default()
174 }
175
176 pub fn toggle_followed_channel(&mut self, channel_id: &str, cx: &mut Context<Self>) {
177 if !self.followed_channels.remove(channel_id) {
178 self.followed_channels.insert(channel_id.to_owned());
179 }
180 notify::save_followed_channels(&self.store, &self.followed_channels);
181 cx.notify();
182 }
183
184 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
185 if !self.collapsed.remove(section_id) {
186 self.collapsed.insert(section_id.to_owned());
187 }
188 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
189 ids.sort_unstable();
190 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
191 cx.emit(AppEvent::Sidebar);
192 cx.notify();
193 }
194
195 pub fn reload_directory(&mut self) {
196 self.directory.me = data::me(&self.store);
197 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
198 self.directory.pinned_channels = data::pinned_channels(&self.store);
199 if self.directory.pinned_channels.is_empty() {
200 let known: HashSet<&str> = self
201 .sidebar
202 .teams
203 .iter()
204 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
205 .collect();
206 self.directory.pinned_channels = self
207 .favorite_ids
208 .iter()
209 .filter(|id| known.contains(id.as_str()))
210 .cloned()
211 .collect();
212 }
213 self.resolve_pending_avatars();
214 self.sync_presence();
215 self.directory.unread_counts = match &self.engine {
216 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
217 None => Default::default(),
218 };
219 }
220
221 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
222 let wanted = self.directory.missing_avatars(user_ids);
223 if wanted.is_empty() {
224 return;
225 }
226 let mut changed = false;
227 let mut uncached = Vec::new();
228 for user_id in wanted {
229 match data::cached_avatar(&self.store, &user_id) {
230 Some(cached) => {
231 self.directory.set_avatar(&user_id, cached);
232 changed = true;
233 }
234 None => uncached.push(user_id),
235 }
236 }
237 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
238 self.directory.mark_avatars_pending(&uncached);
239 let done = data::fetch_avatars(&engine, uncached);
240 self.on_done(done, cx, |state, cx| {
241 state.resolve_pending_avatars();
242 cx.emit(AppEvent::Directory);
243 cx.notify();
244 });
245 changed = true;
246 }
247 if changed {
248 cx.emit(AppEvent::Directory);
249 cx.notify();
250 }
251 }
252
253 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
254 let Some(engine) = self.engine.clone() else {
255 return;
256 };
257 let wanted = self
258 .directory
259 .images_to_request(images.iter().map(|image| image.url.clone()));
260 let mut changed = false;
261 for image in images
262 .into_iter()
263 .filter(|image| wanted.contains(&image.url))
264 {
265 match engine.image_path(&image) {
266 Some(path) => {
267 self.directory.set_image(&image.url, &path);
268 changed = true;
269 }
270 None => {
271 let done = data::fetch_image(&engine, image);
272 self.on_done(done, cx, |_, _| {});
273 }
274 }
275 }
276 if changed {
277 cx.emit(AppEvent::Images(wanted));
278 cx.notify();
279 }
280 }
281
282 pub fn jump_to_message(
283 &mut self,
284 selection: Selection,
285 message_id: String,
286 cx: &mut Context<Self>,
287 ) {
288 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
289 if self.selection.as_ref() == Some(&selection) {
290 cx.emit(AppEvent::Jump);
291 } else {
292 self.select(selection, cx);
293 }
294 }
295
296 fn on_done(
297 &self,
298 done: data::Done,
299 cx: &mut Context<Self>,
300 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
301 ) {
302 cx.spawn(async move |this, cx| {
303 let _ = done.await;
304 this.update(cx, |state, cx| then(state, cx)).ok();
305 })
306 .detach();
307 }
308
309 fn resolve_pending_avatars(&mut self) {
310 for user_id in self.directory.pending_avatars() {
311 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
312 self.directory.set_avatar(&user_id, cached);
313 }
314 }
315 }
316
317 fn sync_presence(&mut self) -> Vec<String> {
318 let Some(engine) = self.engine.clone() else {
319 return Vec::new();
320 };
321 self.directory
322 .requested_presence_ids()
323 .into_iter()
324 .filter(|user_id| {
325 data::presence_kind(&engine, user_id)
326 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
327 })
328 .collect()
329 }
330
331 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
332 let now = Instant::now();
333 let pushed = self.live == LiveState::Live;
334 let wanted = self.directory.stale_presence(user_ids, now, pushed);
335 if wanted.is_empty() {
336 return;
337 }
338 self.directory.mark_presence_pending(&wanted);
339 if let Some(engine) = self.engine.clone() {
340 self.directory.mark_presence_requested(&wanted, now);
341 drop(data::watch_presence(&engine, wanted.clone()));
342 let done = data::refresh_presence(&engine, wanted.clone());
343 self.on_done(done, cx, move |state, cx| {
344 state.sync_presence();
345 state.directory.save_presence(&state.store, &wanted);
346 state.directory.settle_presence(&wanted);
347 cx.emit(AppEvent::Directory);
348 cx.notify();
349 });
350 }
351 }
352
353 pub fn move_chat(
354 &mut self,
355 conversation_id: &str,
356 folder_id: Option<&str>,
357 cx: &mut Context<Self>,
358 ) {
359 if self.mode.read_only {
360 return;
361 }
362 let previous_folder = self
363 .directory
364 .folder_of(conversation_id)
365 .map(|folder| folder.id.clone());
366 self.directory.assign(conversation_id, folder_id);
367 if let Some(engine) = self.engine.clone() {
368 let previous = previous_folder.clone();
369 let done = match (folder_id, previous.as_deref()) {
370 (Some(folder_id), _) => {
371 Some(data::move_to_folder(&engine, conversation_id, folder_id))
372 }
373 (None, Some(previous)) => {
374 Some(data::remove_from_folder(&engine, conversation_id, previous))
375 }
376 (None, None) => None,
377 };
378 if let Some(done) = done {
379 self.on_done(done, cx, |state, cx| {
380 state.reload_directory();
381 cx.emit(AppEvent::Sidebar);
382 cx.notify();
383 });
384 }
385 }
386 cx.emit(AppEvent::Sidebar);
387 cx.notify();
388 }
389
390 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
391 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
392 self.move_chat(conversation_id, favorites.as_deref(), cx);
393 }
394
395 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
396 if self.keeps_unread(conversation_id) {
397 self.keep_unread = None;
398 }
399 if self.mode.demo {
400 if let Some(chat) = self
401 .sidebar
402 .chats
403 .iter()
404 .find(|chat| chat.id == conversation_id)
405 {
406 let mut read = chat.clone();
407 read.unread = false;
408 let _ = self.store.upsert_chats(&[read]);
409 self.reload_sidebar(cx);
410 }
411 return;
412 }
413 if self.mode.read_only {
414 return;
415 }
416 if let Some(engine) = self.engine.clone() {
417 let _ = self
418 .store
419 .mark_chat_read(conversation_id, chrono::Utc::now());
420 self.reload_sidebar(cx);
421 let conversation_id = conversation_id.to_owned();
422 drop(crate::runtime::spawn(async move {
423 engine.mark_read(&conversation_id).await
424 }));
425 }
426 }
427
428 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
429 self.new_chat = true;
430 cx.emit(AppEvent::Selection);
431 cx.notify();
432 }
433
434 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
435 if !self.new_chat {
436 return;
437 }
438 self.new_chat = false;
439 cx.emit(AppEvent::Selection);
440 cx.notify();
441 }
442
443 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
444 let was_drafting = std::mem::take(&mut self.new_chat);
445 if !was_drafting && self.selection.as_ref() == Some(&selection) {
446 return;
447 }
448 self.selection = Some(selection);
449 self.keep_unread = None;
450 cx.emit(AppEvent::Selection);
451 cx.notify();
452 }
453
454 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
455 let is_me = self
456 .directory
457 .me
458 .as_ref()
459 .is_some_and(|me| me.user_id == event.user_id);
460 if is_me {
461 return;
462 }
463 if event.active {
464 self.typing.start(
465 &event.conversation_id,
466 &event.user_id,
467 &event.display_name,
468 Instant::now(),
469 event.received_at,
470 );
471 self.schedule_typing_expiry(cx);
472 } else {
473 self.typing.clear(&event.conversation_id, &event.user_id);
474 }
475 cx.emit(AppEvent::Typing);
476 cx.notify();
477 }
478
479 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
480 if !self.typing.is_active(conversation_id) {
481 return;
482 }
483 let Ok(recent) = self
484 .store
485 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
486 else {
487 return;
488 };
489 let mut changed = false;
490 for message in recent {
491 if let Some(sender_id) = message.sender_id.as_deref() {
492 changed |= self
493 .typing
494 .message_from(conversation_id, sender_id, message.created_at);
495 }
496 }
497 if changed {
498 cx.emit(AppEvent::Typing);
499 cx.notify();
500 }
501 }
502
503 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
504 if self.typing_timer_running {
505 return;
506 }
507 self.typing_timer_running = true;
508 cx.spawn(async move |this, cx| {
509 loop {
510 let next = this.update(cx, |state, _| {
511 let next = state.typing.next_expiry();
512 state.typing_timer_running = next.is_some();
513 next
514 });
515 let Ok(Some(next)) = next else { return };
516 cx.background_executor()
517 .timer(next.saturating_duration_since(Instant::now()))
518 .await;
519 let alive = this.update(cx, |state, cx| {
520 if state.typing.expire(Instant::now()) {
521 cx.emit(AppEvent::Typing);
522 cx.notify();
523 }
524 });
525 if alive.is_err() {
526 return;
527 }
528 }
529 })
530 .detach();
531 }
532
533 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
534 if let Ok(sidebar) = self.store.sidebar() {
535 self.sidebar = sidebar;
536 self.apply_bot_titles();
537 }
538 if !self.mode.demo {
539 self.reload_directory();
540 }
541 cx.emit(AppEvent::Sidebar);
542 cx.notify();
543 }
544
545 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
546 match event {
547 BackendEvent::Connection(connection) => {
548 self.connection = connection;
549 cx.emit(AppEvent::Status);
550 }
551 BackendEvent::Engine(engine) => {
552 self.engine = Some(engine);
553 let waiting = self.directory.waiting_presence_ids();
554 self.request_presence(waiting, cx);
555 cx.emit(AppEvent::Status);
556 }
557 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
558 BackendEvent::Core(
559 CoreEvent::MessagesChanged { conversation_id }
560 | CoreEvent::ReceiptsChanged { conversation_id },
561 ) => {
562 self.clear_typists_who_sent(&conversation_id, cx);
563 cx.emit(AppEvent::Messages(conversation_id));
564 }
565 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
566 if let Some(engine) = &self.engine {
567 for key in &keys {
568 let image = ImageRef {
569 id: String::new(),
570 url: key.clone(),
571 width: None,
572 height: None,
573 };
574 if let Some(path) = engine.image_path(&image) {
575 self.directory.set_image(key, &path);
576 }
577 }
578 }
579 cx.emit(AppEvent::Images(keys));
580 }
581 BackendEvent::Core(CoreEvent::PresenceChanged) => {
582 let changed = self.sync_presence();
583 self.directory.save_presence(&self.store, &changed);
584 cx.emit(AppEvent::Directory);
585 cx.notify();
586 }
587 BackendEvent::Core(_) => {
588 if !self.mode.demo {
589 self.reload_directory();
590 }
591 cx.emit(AppEvent::Directory);
592 }
593 BackendEvent::Typing(event) => self.apply_typing(event, cx),
594 BackendEvent::Live(live) => {
595 self.live = live;
596 cx.emit(AppEvent::Status);
597 }
598 BackendEvent::Favorites(ids) => {
599 self.favorite_ids = ids;
600 if !self.mode.demo {
601 self.reload_directory();
602 }
603 cx.emit(AppEvent::Sidebar);
604 }
605 BackendEvent::Synced(time) => {
606 self.last_sync = Some(time);
607 cx.emit(AppEvent::Status);
608 }
609 }
610 cx.notify();
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use std::sync::Arc;
617
618 use chatsvc::TypingEvent;
619 use chrono::{Duration, Utc};
620 use gpui_kit::{AppContext as _, TestAppContext};
621 use store::{ChannelRecord, ChatRecord, MessageRecord, SidebarTeam, Store, TeamRecord};
622 use teams_core::CoreEvent;
623
624 use super::{AppState, Mode, Selection, chat_title, selection_title};
625 use crate::backend::BackendEvent;
626 use crate::data::Person;
627 use store::Sidebar;
628
629 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
630 ChatRecord {
631 id: id.into(),
632 kind: "group".into(),
633 title: title.into(),
634 member_summary: "Member".into(),
635 last_message_at: None,
636 last_read_at: None,
637 unread,
638 ..Default::default()
639 }
640 }
641
642 fn sidebar() -> Sidebar {
643 Sidebar {
644 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
645 teams: vec![SidebarTeam {
646 team: TeamRecord {
647 id: "t".into(),
648 name: "Team".into(),
649 },
650 channels: vec![ChannelRecord {
651 id: "ch".into(),
652 team_id: "t".into(),
653 name: "General".into(),
654 membership_type: None,
655 last_message_at: None,
656 unread: false,
657 }],
658 hidden: false,
659 hidden_channel_ids: Vec::new(),
660 }],
661 }
662 }
663
664 #[test]
665 fn empty_chat_title_falls_back_to_members() {
666 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
667 }
668
669 #[test]
670 fn selection_titles() {
671 assert_eq!(
672 selection_title(&sidebar(), &Selection::Channel("ch".into())),
673 "Team / General"
674 );
675 assert_eq!(
676 selection_title(&sidebar(), &Selection::Chat("c1".into())),
677 "First"
678 );
679 }
680
681 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
682 BackendEvent::Typing(TypingEvent {
683 conversation_id: "c1".into(),
684 user_id: user_id.into(),
685 display_name: format!("Name {user_id}"),
686 active,
687 received_at: Utc::now(),
688 })
689 }
690
691 #[gpui_kit::test]
692 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
693 cx.update(gpui_kit::init);
694 let store = Arc::new(Store::open_in_memory().unwrap());
695 let app = cx.update(|cx| {
696 cx.new(|_| {
697 let mut state = AppState::new(store.clone(), Mode::default());
698 state.directory.me = Some(Person {
699 user_id: "me".into(),
700 display_name: "Me".into(),
701 });
702 state
703 })
704 });
705 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
706 cx.update(|cx| {
707 app.update(cx, |state, cx| {
708 state.apply(typing_event("me", true), cx);
709 state.apply(typing_event("ada", true), cx);
710 })
711 });
712 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
713
714 let message = MessageRecord {
715 conversation_id: "c1".into(),
716 message_id: "m1".into(),
717 sender_id: Some("ada".into()),
718 created_at: Utc::now() + Duration::seconds(1),
719 ..Default::default()
720 };
721 store.upsert_messages(&[message]).unwrap();
722 cx.update(|cx| {
723 app.update(cx, |state, cx| {
724 state.apply(
725 BackendEvent::Core(CoreEvent::MessagesChanged {
726 conversation_id: "c1".into(),
727 }),
728 cx,
729 )
730 })
731 });
732 assert!(names(cx).is_empty());
733
734 cx.update(|cx| {
735 app.update(cx, |state, cx| {
736 state.apply(typing_event("ada", true), cx);
737 state.apply(typing_event("ada", false), cx);
738 })
739 });
740 assert!(names(cx).is_empty());
741 }
742}