BlueGit

ict rusty-teams

Files

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

app_state.rs

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