BlueGit

ict rusty-teams

Files

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

app_state.rs

396af7fa History
app_state.rs 15.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 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 conversation_id = conversation_id.to_owned();
362 drop(crate::runtime::spawn(async move {
363 engine.mark_read(&conversation_id).await
364 }));
365 }
366 }
367
368 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
369 if self.selection.as_ref() == Some(&selection) {
370 return;
371 }
372 self.selection = Some(selection);
373 cx.emit(AppEvent::Selection);
374 cx.notify();
375 }
376
377 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
378 if let Ok(sidebar) = self.store.sidebar() {
379 self.sidebar = sidebar;
380 }
381 if !self.mode.demo {
382 self.reload_directory();
383 }
384 cx.emit(AppEvent::Sidebar);
385 cx.notify();
386 }
387
388 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
389 match event {
390 BackendEvent::Connection(connection) => {
391 self.connection = connection;
392 cx.emit(AppEvent::Status);
393 }
394 BackendEvent::Engine(engine) => {
395 self.engine = Some(engine);
396 cx.emit(AppEvent::Status);
397 }
398 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx),
399 BackendEvent::Core(
400 CoreEvent::MessagesChanged { conversation_id }
401 | CoreEvent::ReceiptsChanged { conversation_id },
402 ) => {
403 cx.emit(AppEvent::Messages(conversation_id));
404 }
405 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
406 if let Some(engine) = &self.engine {
407 for key in &keys {
408 let image = ImageRef {
409 id: String::new(),
410 url: key.clone(),
411 width: None,
412 height: None,
413 };
414 if let Some(path) = engine.image_path(&image) {
415 self.directory.set_image(key, &path);
416 }
417 }
418 }
419 cx.emit(AppEvent::Images(keys));
420 }
421 BackendEvent::Core(_) => {
422 if !self.mode.demo {
423 self.reload_directory();
424 }
425 cx.emit(AppEvent::Directory);
426 }
427 BackendEvent::Live(live) => {
428 self.live = live;
429 cx.emit(AppEvent::Status);
430 }
431 BackendEvent::Favorites(ids) => {
432 self.favorite_ids = ids;
433 if !self.mode.demo {
434 self.reload_directory();
435 }
436 cx.emit(AppEvent::Sidebar);
437 }
438 BackendEvent::Synced(time) => {
439 self.last_sync = Some(time);
440 cx.emit(AppEvent::Status);
441 }
442 }
443 cx.notify();
444 }
445}
446
447#[cfg(test)]
448mod tests {
449 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
450
451 use super::{Selection, chat_title, selection_title};
452 use store::Sidebar;
453
454 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
455 ChatRecord {
456 id: id.into(),
457 kind: "group".into(),
458 title: title.into(),
459 member_summary: "Member".into(),
460 last_message_at: None,
461 last_read_at: None,
462 unread,
463 ..Default::default()
464 }
465 }
466
467 fn sidebar() -> Sidebar {
468 Sidebar {
469 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
470 teams: vec![SidebarTeam {
471 team: TeamRecord {
472 id: "t".into(),
473 name: "Team".into(),
474 },
475 channels: vec![ChannelRecord {
476 id: "ch".into(),
477 team_id: "t".into(),
478 name: "General".into(),
479 membership_type: None,
480 last_message_at: None,
481 unread: false,
482 }],
483 hidden: false,
484 hidden_channel_ids: Vec::new(),
485 }],
486 }
487 }
488
489 #[test]
490 fn empty_chat_title_falls_back_to_members() {
491 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
492 }
493
494 #[test]
495 fn selection_titles() {
496 assert_eq!(
497 selection_title(&sidebar(), &Selection::Channel("ch".into())),
498 "Team / General"
499 );
500 assert_eq!(
501 selection_title(&sidebar(), &Selection::Chat("c1".into())),
502 "First"
503 );
504 }
505}