BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / sidebar_load.rs

sidebar_load.rs

sidebar_load.rs 6.0 KiB Download Raw
1use std::collections::HashMap;
2
3use gpui_kit::*;
4use store::{ChatRecord, MessageImportance, Sidebar, Store};
5
6use crate::app_state::{AppState, Selection};
7use crate::backend::Engine;
8use crate::data;
9
10#[derive(Default)]
11pub struct SidebarLoad {
12 running: bool,
13 requested_again: bool,
14 local_changes: u64,
15}
16
17impl SidebarLoad {
18 pub fn local_change(&mut self) {
19 self.local_changes += 1;
20 }
21}
22
23#[derive(Default)]
24pub struct Unread {
25 pub counts: HashMap<String, u32>,
26 pub importance: HashMap<String, MessageImportance>,
27}
28
29pub struct LoadedSidebar {
30 pub sidebar: Sidebar,
31 pub unread: Unread,
32}
33
34pub fn unread_of(engine: Option<&Engine>, chats: &[ChatRecord]) -> Unread {
35 match engine {
36 Some(engine) => Unread {
37 counts: data::unread_counts(engine, chats),
38 importance: data::unread_importance(engine, chats),
39 },
40 None => Unread::default(),
41 }
42}
43
44fn load(store: &Store, engine: Option<&Engine>) -> Option<LoadedSidebar> {
45 let sidebar = store.sidebar().ok()?;
46 let unread = unread_of(engine, &sidebar.chats);
47 Some(LoadedSidebar { sidebar, unread })
48}
49
50impl AppState {
51 pub fn reload_sidebar_after_sync(&mut self, cx: &mut Context<Self>) {
52 if self.sidebar_load.running {
53 self.sidebar_load.requested_again = true;
54 return;
55 }
56 self.sidebar_load.running = true;
57 cx.spawn(async move |this, cx| {
58 loop {
59 let Ok((store, engine, local_changes)) = this.update(cx, |state, _| {
60 state.sidebar_load.requested_again = false;
61 (
62 state.store.clone(),
63 state.engine.clone(),
64 state.sidebar_load.local_changes,
65 )
66 }) else {
67 return;
68 };
69 let loaded = cx
70 .background_spawn(async move { load(&store, engine.as_deref()) })
71 .await;
72 let again = this.update(cx, |state, cx| {
73 let stale = state.sidebar_load.local_changes != local_changes;
74 if let Some(loaded) = loaded.filter(|_| !stale) {
75 state.adopt_synced_sidebar(loaded, cx);
76 }
77 let again = state.sidebar_load.requested_again || stale;
78 state.sidebar_load.running = again;
79 again
80 });
81 if !matches!(again, Ok(true)) {
82 return;
83 }
84 }
85 })
86 .detach();
87 }
88
89 fn adopt_synced_sidebar(&mut self, loaded: LoadedSidebar, cx: &mut Context<Self>) {
90 let selected = match &self.selection {
91 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
92 _ => None,
93 };
94 let is_listed =
95 |chats: &[ChatRecord], chat_id: &str| chats.iter().any(|chat| chat.id == chat_id);
96 let was_listed = selected
97 .as_deref()
98 .is_some_and(|chat_id| is_listed(&self.sidebar.chats, chat_id));
99 let removed = was_listed
100 && selected
101 .as_deref()
102 .is_some_and(|chat_id| !is_listed(&loaded.sidebar.chats, chat_id));
103 let next = selected
104 .as_deref()
105 .filter(|_| removed)
106 .and_then(|chat_id| self.next_chat_after(chat_id));
107 self.adopt_loaded_sidebar(loaded, cx);
108 self.warm_recent_chats();
109 if removed {
110 self.leave_removed_selection(next, cx);
111 }
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use std::sync::Arc;
118
119 use gpui_kit::{AppContext, TestAppContext};
120 use store::{ChatRecord, Store};
121 use teams_core::CoreEvent;
122
123 use crate::app_state::{AppState, Mode, Selection};
124 use crate::backend::BackendEvent;
125
126 fn chat(id: &str) -> ChatRecord {
127 ChatRecord {
128 id: id.into(),
129 kind: "group".into(),
130 title: id.into(),
131 ..Default::default()
132 }
133 }
134
135 fn listed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) -> Vec<String> {
136 cx.update(|cx| app.read(cx).sidebar.chats.iter().map(|chat| chat.id.clone()).collect())
137 }
138
139 fn sidebar_changed(app: &gpui_kit::Entity<AppState>, cx: &mut TestAppContext) {
140 cx.update(|cx| {
141 app.update(cx, |state, cx| {
142 state.apply(BackendEvent::Core(CoreEvent::SidebarChanged), cx)
143 })
144 });
145 }
146
147 #[gpui_kit::test]
148 fn a_synced_sidebar_loads_in_the_background_and_bursts_load_once_more(
149 cx: &mut TestAppContext,
150 ) {
151 cx.update(gpui_kit::init);
152 let store = Arc::new(Store::open_in_memory().unwrap());
153 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
154 store.upsert_chats(&[chat("first")]).unwrap();
155 sidebar_changed(&app, cx);
156 assert!(listed(&app, cx).is_empty());
157 store.upsert_chats(&[chat("second")]).unwrap();
158 sidebar_changed(&app, cx);
159 cx.run_until_parked();
160 let mut chats = listed(&app, cx);
161 chats.sort();
162 assert_eq!(chats, vec!["first".to_owned(), "second".to_owned()]);
163 }
164
165 #[gpui_kit::test]
166 fn a_selected_chat_gone_after_sync_moves_the_selection_on(cx: &mut TestAppContext) {
167 cx.update(gpui_kit::init);
168 let store = Arc::new(Store::open_in_memory().unwrap());
169 store.upsert_chats(&[chat("kept"), chat("gone")]).unwrap();
170 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
171 cx.update(|cx| {
172 app.update(cx, |state, cx| {
173 state.reload_sidebar(cx);
174 state.selection = Some(Selection::Chat("gone".into()));
175 })
176 });
177 store.remove_chats(&["gone".to_owned()]).unwrap();
178 sidebar_changed(&app, cx);
179 cx.run_until_parked();
180 let selection = cx.update(|cx| app.read(cx).selection.clone());
181 assert_eq!(selection, Some(Selection::Chat("kept".into())));
182 }
183}