BlueGit

ict rusty-teams

Files

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

app_state.rs

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