BlueGit

ict rusty-teams

Files

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

app_state.rs

app_state.rs 17.6 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use store::{ChatRecord, Sidebar, Store};
8use teams_core::{ChatApp, CoreEvent, ImageRef};
9
10use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11use crate::card_state::{CardState, TaskDialogState};
12use crate::data::{self, Directory};
13
14const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Selection {
18 Chat(String),
19 Channel(String),
20}
21
22impl Selection {
23 pub fn conversation_id(&self) -> &str {
24 match self {
25 Selection::Chat(id) | Selection::Channel(id) => id,
26 }
27 }
28}
29
30pub enum AppEvent {
31 Sidebar,
32 Selection,
33 Messages(String),
34 Images(Vec<String>),
35 Jump,
36 Status,
37 Directory,
38 Cards(String),
39 TaskDialog,
40}
41
42#[derive(Debug, Clone, Copy, Default)]
43pub struct Mode {
44 pub demo: bool,
45 pub read_only: bool,
46 pub demo_sync: Option<std::time::Duration>,
47}
48
49pub struct AppState {
50 pub store: Arc<Store>,
51 pub engine: Option<Arc<Engine>>,
52 pub sidebar: Sidebar,
53 pub favorite_ids: Vec<String>,
54 pub selection: Option<Selection>,
55 pub new_chat: bool,
56 pub connection: ConnectionState,
57 pub live: LiveState,
58 pub last_sync: Option<DateTime<Utc>>,
59 pub mode: Mode,
60 pub directory: Directory,
61 pub collapsed: HashSet<String>,
62 pub start_on_channels: bool,
63 pub pending_jump: Option<(String, String)>,
64 pub cards: CardState,
65 pub task_dialog: Option<TaskDialogState>,
66 pub bot_apps: HashMap<String, Vec<ChatApp>>,
67 pub bot_apps_pending: HashSet<String>,
68}
69
70pub struct AppHandle(pub Entity<AppState>);
71
72impl Global for AppHandle {}
73
74impl EventEmitter<AppEvent> for AppState {}
75
76pub fn chat_title(chat: &ChatRecord) -> String {
77 if !chat.title.trim().is_empty() {
78 chat.title.clone()
79 } else if !chat.member_summary.trim().is_empty() {
80 chat.member_summary.clone()
81 } else {
82 "Chat".to_owned()
83 }
84}
85
86pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
87 match selection {
88 Selection::Chat(id) => sidebar
89 .chats
90 .iter()
91 .find(|chat| &chat.id == id)
92 .map(chat_title)
93 .unwrap_or_else(|| "Chat".to_owned()),
94 Selection::Channel(id) => sidebar
95 .teams
96 .iter()
97 .find_map(|team| {
98 team.channels
99 .iter()
100 .find(|channel| &channel.id == id)
101 .map(|channel| format!("{} / {}", team.team.name, channel.name))
102 })
103 .unwrap_or_else(|| "Channel".to_owned()),
104 }
105}
106
107impl AppState {
108 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
109 let sidebar = store.sidebar().unwrap_or_default();
110 let mut state = AppState {
111 store,
112 engine: None,
113 sidebar,
114 favorite_ids: Vec::new(),
115 selection: None,
116 new_chat: false,
117 connection: if mode.demo {
118 ConnectionState::Online
119 } else {
120 ConnectionState::Connecting
121 },
122 live: LiveState::Off,
123 last_sync: None,
124 mode,
125 directory: Directory::default(),
126 collapsed: HashSet::new(),
127 start_on_channels: false,
128 pending_jump: None,
129 cards: CardState::default(),
130 task_dialog: None,
131 bot_apps: HashMap::new(),
132 bot_apps_pending: HashSet::new(),
133 };
134 state.collapsed = state.load_collapsed();
135 if !mode.demo {
136 state.directory.load_cached_presence(&state.store);
137 state.reload_directory();
138 }
139 state
140 }
141
142 fn load_collapsed(&self) -> HashSet<String> {
143 self.store
144 .meta(COLLAPSED_META_KEY)
145 .ok()
146 .flatten()
147 .map(|value| {
148 value
149 .lines()
150 .map(str::to_owned)
151 .filter(|id| !id.is_empty())
152 .collect()
153 })
154 .unwrap_or_default()
155 }
156
157 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
158 if !self.collapsed.remove(section_id) {
159 self.collapsed.insert(section_id.to_owned());
160 }
161 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
162 ids.sort_unstable();
163 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
164 cx.emit(AppEvent::Sidebar);
165 cx.notify();
166 }
167
168 pub fn reload_directory(&mut self) {
169 self.directory.me = data::me(&self.store);
170 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
171 self.directory.pinned_channels = data::pinned_channels(&self.store);
172 if self.directory.pinned_channels.is_empty() {
173 let known: HashSet<&str> = self
174 .sidebar
175 .teams
176 .iter()
177 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
178 .collect();
179 self.directory.pinned_channels = self
180 .favorite_ids
181 .iter()
182 .filter(|id| known.contains(id.as_str()))
183 .cloned()
184 .collect();
185 }
186 self.resolve_pending_avatars();
187 self.sync_presence();
188 self.directory.unread_counts = match &self.engine {
189 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
190 None => Default::default(),
191 };
192 }
193
194 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
195 let wanted = self.directory.missing_avatars(user_ids);
196 if wanted.is_empty() {
197 return;
198 }
199 let mut changed = false;
200 let mut uncached = Vec::new();
201 for user_id in wanted {
202 match data::cached_avatar(&self.store, &user_id) {
203 Some(cached) => {
204 self.directory.set_avatar(&user_id, cached);
205 changed = true;
206 }
207 None => uncached.push(user_id),
208 }
209 }
210 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
211 self.directory.mark_avatars_pending(&uncached);
212 let done = data::fetch_avatars(&engine, uncached);
213 self.on_done(done, cx, |state, cx| {
214 state.resolve_pending_avatars();
215 cx.emit(AppEvent::Directory);
216 cx.notify();
217 });
218 changed = true;
219 }
220 if changed {
221 cx.emit(AppEvent::Directory);
222 cx.notify();
223 }
224 }
225
226 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
227 let Some(engine) = self.engine.clone() else {
228 return;
229 };
230 let wanted = self
231 .directory
232 .images_to_request(images.iter().map(|image| image.url.clone()));
233 let mut changed = false;
234 for image in images
235 .into_iter()
236 .filter(|image| wanted.contains(&image.url))
237 {
238 match engine.image_path(&image) {
239 Some(path) => {
240 self.directory.set_image(&image.url, &path);
241 changed = true;
242 }
243 None => {
244 let done = data::fetch_image(&engine, image);
245 self.on_done(done, cx, |_, _| {});
246 }
247 }
248 }
249 if changed {
250 cx.emit(AppEvent::Images(wanted));
251 cx.notify();
252 }
253 }
254
255 pub fn jump_to_message(
256 &mut self,
257 selection: Selection,
258 message_id: String,
259 cx: &mut Context<Self>,
260 ) {
261 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
262 if self.selection.as_ref() == Some(&selection) {
263 cx.emit(AppEvent::Jump);
264 } else {
265 self.select(selection, cx);
266 }
267 }
268
269 fn on_done(
270 &self,
271 done: data::Done,
272 cx: &mut Context<Self>,
273 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
274 ) {
275 cx.spawn(async move |this, cx| {
276 let _ = done.await;
277 this.update(cx, |state, cx| then(state, cx)).ok();
278 })
279 .detach();
280 }
281
282 fn resolve_pending_avatars(&mut self) {
283 for user_id in self.directory.pending_avatars() {
284 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
285 self.directory.set_avatar(&user_id, cached);
286 }
287 }
288 }
289
290 fn sync_presence(&mut self) -> Vec<String> {
291 let Some(engine) = self.engine.clone() else {
292 return Vec::new();
293 };
294 self.directory
295 .requested_presence_ids()
296 .into_iter()
297 .filter(|user_id| {
298 data::presence_kind(&engine, user_id)
299 .is_some_and(|kind| self.directory.set_presence(user_id, kind))
300 })
301 .collect()
302 }
303
304 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
305 let now = Instant::now();
306 let pushed = self.live == LiveState::Live;
307 let wanted = self.directory.stale_presence(user_ids, now, pushed);
308 if wanted.is_empty() {
309 return;
310 }
311 self.directory.mark_presence_pending(&wanted);
312 if let Some(engine) = self.engine.clone() {
313 self.directory.mark_presence_requested(&wanted, now);
314 drop(data::watch_presence(&engine, wanted.clone()));
315 let done = data::refresh_presence(&engine, wanted.clone());
316 self.on_done(done, cx, move |state, cx| {
317 state.sync_presence();
318 state.directory.save_presence(&state.store, &wanted);
319 state.directory.settle_presence(&wanted);
320 cx.emit(AppEvent::Directory);
321 cx.notify();
322 });
323 }
324 }
325
326 pub fn move_chat(
327 &mut self,
328 conversation_id: &str,
329 folder_id: Option<&str>,
330 cx: &mut Context<Self>,
331 ) {
332 if self.mode.read_only {
333 return;
334 }
335 let previous_folder = self
336 .directory
337 .folder_of(conversation_id)
338 .map(|folder| folder.id.clone());
339 self.directory.assign(conversation_id, folder_id);
340 if let Some(engine) = self.engine.clone() {
341 let previous = previous_folder.clone();
342 let done = match (folder_id, previous.as_deref()) {
343 (Some(folder_id), _) => {
344 Some(data::move_to_folder(&engine, conversation_id, folder_id))
345 }
346 (None, Some(previous)) => {
347 Some(data::remove_from_folder(&engine, conversation_id, previous))
348 }
349 (None, None) => None,
350 };
351 if let Some(done) = done {
352 self.on_done(done, cx, |state, cx| {
353 state.reload_directory();
354 cx.emit(AppEvent::Sidebar);
355 cx.notify();
356 });
357 }
358 }
359 cx.emit(AppEvent::Sidebar);
360 cx.notify();
361 }
362
363 pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
364 let favorites = self.directory.favorites().map(|folder| folder.id.clone());
365 self.move_chat(conversation_id, favorites.as_deref(), cx);
366 }
367
368 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
369 if self.mode.demo {
370 if let Some(chat) = self
371 .sidebar
372 .chats
373 .iter()
374 .find(|chat| chat.id == conversation_id)
375 {
376 let mut read = chat.clone();
377 read.unread = false;
378 let _ = self.store.upsert_chats(&[read]);
379 self.reload_sidebar(cx);
380 }
381 return;
382 }
383 if self.mode.read_only {
384 return;
385 }
386 if let Some(engine) = self.engine.clone() {
387 let _ = self
388 .store
389 .mark_chat_read(conversation_id, chrono::Utc::now());
390 self.reload_sidebar(cx);
391 let conversation_id = conversation_id.to_owned();
392 drop(crate::runtime::spawn(async move {
393 engine.mark_read(&conversation_id).await
394 }));
395 }
396 }
397
398 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
399 self.new_chat = true;
400 cx.emit(AppEvent::Selection);
401 cx.notify();
402 }
403
404 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
405 if !self.new_chat {
406 return;
407 }
408 self.new_chat = false;
409 cx.emit(AppEvent::Selection);
410 cx.notify();
411 }
412
413 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
414 let was_drafting = std::mem::take(&mut self.new_chat);
415 if !was_drafting && self.selection.as_ref() == Some(&selection) {
416 return;
417 }
418 self.selection = Some(selection);
419 cx.emit(AppEvent::Selection);
420 cx.notify();
421 }
422
423 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
424 if let Ok(sidebar) = self.store.sidebar() {
425 self.sidebar = sidebar;
426 self.apply_bot_titles();
427 }
428 if !self.mode.demo {
429 self.reload_directory();
430 }
431 cx.emit(AppEvent::Sidebar);
432 cx.notify();
433 }
434
435 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
436 match event {
437 BackendEvent::Connection(connection) => {
438 self.connection = connection;
439 cx.emit(AppEvent::Status);
440 }
441 BackendEvent::Engine(engine) => {
442 self.engine = Some(engine);
443 let waiting = self.directory.waiting_presence_ids();
444 self.request_presence(waiting, cx);
445 cx.emit(AppEvent::Status);
446 }
447 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
448 BackendEvent::Core(
449 CoreEvent::MessagesChanged { conversation_id }
450 | CoreEvent::ReceiptsChanged { conversation_id },
451 ) => {
452 cx.emit(AppEvent::Messages(conversation_id));
453 }
454 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
455 if let Some(engine) = &self.engine {
456 for key in &keys {
457 let image = ImageRef {
458 id: String::new(),
459 url: key.clone(),
460 width: None,
461 height: None,
462 };
463 if let Some(path) = engine.image_path(&image) {
464 self.directory.set_image(key, &path);
465 }
466 }
467 }
468 cx.emit(AppEvent::Images(keys));
469 }
470 BackendEvent::Core(CoreEvent::PresenceChanged) => {
471 let changed = self.sync_presence();
472 self.directory.save_presence(&self.store, &changed);
473 cx.emit(AppEvent::Directory);
474 cx.notify();
475 }
476 BackendEvent::Core(_) => {
477 if !self.mode.demo {
478 self.reload_directory();
479 }
480 cx.emit(AppEvent::Directory);
481 }
482 BackendEvent::Live(live) => {
483 self.live = live;
484 cx.emit(AppEvent::Status);
485 }
486 BackendEvent::Favorites(ids) => {
487 self.favorite_ids = ids;
488 if !self.mode.demo {
489 self.reload_directory();
490 }
491 cx.emit(AppEvent::Sidebar);
492 }
493 BackendEvent::Synced(time) => {
494 self.last_sync = Some(time);
495 cx.emit(AppEvent::Status);
496 }
497 }
498 cx.notify();
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
505
506 use super::{Selection, chat_title, selection_title};
507 use store::Sidebar;
508
509 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
510 ChatRecord {
511 id: id.into(),
512 kind: "group".into(),
513 title: title.into(),
514 member_summary: "Member".into(),
515 last_message_at: None,
516 last_read_at: None,
517 unread,
518 ..Default::default()
519 }
520 }
521
522 fn sidebar() -> Sidebar {
523 Sidebar {
524 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
525 teams: vec![SidebarTeam {
526 team: TeamRecord {
527 id: "t".into(),
528 name: "Team".into(),
529 },
530 channels: vec![ChannelRecord {
531 id: "ch".into(),
532 team_id: "t".into(),
533 name: "General".into(),
534 membership_type: None,
535 last_message_at: None,
536 unread: false,
537 }],
538 hidden: false,
539 hidden_channel_ids: Vec::new(),
540 }],
541 }
542 }
543
544 #[test]
545 fn empty_chat_title_falls_back_to_members() {
546 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
547 }
548
549 #[test]
550 fn selection_titles() {
551 assert_eq!(
552 selection_title(&sidebar(), &Selection::Channel("ch".into())),
553 "Team / General"
554 );
555 assert_eq!(
556 selection_title(&sidebar(), &Selection::Chat("c1".into())),
557 "First"
558 );
559 }
560}