BlueGit

ict rusty-teams

Files

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

app_state.rs

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