BlueGit

ict rusty-teams

Files

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

app_state.rs

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