BlueGit

ict rusty-teams

Files

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

app_state.rs

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