BlueGit

ict rusty-teams

Files

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

profile_state.rs

profile_state.rs 7.2 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::Instant;
4
5use gpui_kit::*;
6use teams_core::PersonProfile;
7
8use crate::app_state::{AppEvent, AppState, Selection};
9use crate::data::existing_one_on_one;
10use crate::demo_profiles;
11use crate::notice::short_error;
12use crate::profile_model::is_stale;
13
14#[derive(Default)]
15pub struct ProfileEntry {
16 pub profile: Option<Arc<PersonProfile>>,
17 pub fetching: bool,
18 pub failed: bool,
19 fetched_at: Option<Instant>,
20}
21
22impl ProfileEntry {
23 fn is_fresh(&self, now: Instant) -> bool {
24 self.profile.is_some() && self.fetched_at.is_some_and(|at| !is_stale(at, now))
25 }
26}
27
28pub struct ProfileRequest {
29 pub user_id: String,
30 pub anchor: Point<Pixels>,
31}
32
33pub type ProfileCache = HashMap<String, ProfileEntry>;
34
35impl AppState {
36 pub fn open_profile_card(
37 &mut self,
38 user_id: &str,
39 anchor: Point<Pixels>,
40 cx: &mut Context<Self>,
41 ) {
42 self.profile_request = Some(ProfileRequest {
43 user_id: user_id.to_owned(),
44 anchor,
45 });
46 self.request_profile(user_id, false, cx);
47 self.request_avatars(vec![user_id.to_owned()], cx);
48 cx.emit(AppEvent::Profile);
49 cx.notify();
50 }
51
52 pub fn take_profile_request(&mut self) -> Option<ProfileRequest> {
53 self.profile_request.take()
54 }
55
56 pub fn request_profile(&mut self, user_id: &str, force: bool, cx: &mut Context<Self>) {
57 let now = Instant::now();
58 let entry = self.profiles.entry(user_id.to_owned()).or_default();
59 if entry.fetching || (!force && entry.is_fresh(now)) {
60 return;
61 }
62 let owned_id = user_id.to_owned();
63 let receiver = if self.mode.demo {
64 crate::runtime::spawn(demo_profiles::load(owned_id.clone()))
65 } else if let Some(engine) = self.engine.clone() {
66 let id = owned_id.clone();
67 crate::runtime::spawn(async move {
68 engine
69 .person_profile(&id)
70 .await
71 .map_err(|error| short_error(&error))
72 })
73 } else {
74 entry.failed = true;
75 cx.notify();
76 return;
77 };
78 entry.fetching = true;
79 entry.failed = false;
80 cx.notify();
81 cx.spawn(async move |this, cx| {
82 let result = receiver
83 .await
84 .unwrap_or_else(|_| Err("cancelled".to_owned()));
85 this.update(cx, |state, cx| state.finish_profile(&owned_id, result, cx))
86 .ok();
87 })
88 .detach();
89 }
90
91 fn finish_profile(
92 &mut self,
93 user_id: &str,
94 result: Result<PersonProfile, String>,
95 cx: &mut Context<Self>,
96 ) {
97 let entry = self.profiles.entry(user_id.to_owned()).or_default();
98 entry.fetching = false;
99 match result {
100 Ok(profile) => {
101 let related: Vec<String> = profile
102 .manager
103 .iter()
104 .chain(&profile.direct_reports)
105 .map(|person| person.id.clone())
106 .collect();
107 entry.profile = Some(Arc::new(profile));
108 entry.failed = false;
109 entry.fetched_at = Some(Instant::now());
110 self.request_avatars(related, cx);
111 }
112 Err(_) => entry.failed = true,
113 }
114 cx.notify();
115 }
116
117 pub fn copy_profile_email(&mut self, email: &str, cx: &mut Context<Self>) {
118 cx.write_to_clipboard(ClipboardItem::new_string(email.to_owned()));
119 self.raise_notice("Email copied".to_owned(), None, cx);
120 }
121
122 /// KVT issue #6: een regel van de contactkaart (mail, telefoon, kantoor) naar het klembord.
123 pub fn copy_profile_detail(&mut self, value: &str, cx: &mut Context<Self>) {
124 cx.write_to_clipboard(ClipboardItem::new_string(value.to_owned()));
125 let notice = app_base::ui_locale::tr("kvt.profile.copied").replace("%{value}", value);
126 self.raise_notice(notice, None, cx);
127 }
128
129 pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
130 self.with_one_on_one(user_id, cx, |state, chat_id, cx| {
131 state.select(Selection::Chat(chat_id.to_owned()), cx)
132 });
133 }
134
135 /// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.
136 pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {
137 self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {
138 if with_video {
139 state.start_chat_video_call(chat_id, cx);
140 } else {
141 state.start_chat_call(chat_id, cx);
142 }
143 });
144 }
145
146 fn with_one_on_one(
147 &mut self,
148 user_id: &str,
149 cx: &mut Context<Self>,
150 then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,
151 ) {
152 let existing =
153 existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
154 .map(|chat| chat.id.clone());
155 if let Some(chat_id) = existing {
156 then(self, &chat_id, cx);
157 return;
158 }
159 if self.mode.read_only {
160 self.raise_notice("Read-only mode: chat not created".to_owned(), None, cx);
161 return;
162 }
163 let Some(engine) = self.engine.clone() else {
164 self.raise_notice("No chat with this person yet".to_owned(), None, cx);
165 return;
166 };
167 let user_id = user_id.to_owned();
168 let receiver = crate::runtime::spawn(async move {
169 engine
170 .create_one_on_one(&user_id)
171 .await
172 .map_err(|error| short_error(&error))
173 });
174 cx.spawn(async move |this, cx| {
175 let outcome = receiver
176 .await
177 .unwrap_or_else(|_| Err("cancelled".to_owned()));
178 this.update(cx, |state, cx| match outcome {
179 Ok(chat_id) => {
180 state.reload_sidebar(cx);
181 then(state, &chat_id, cx);
182 }
183 Err(reason) => {
184 state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
185 }
186 })
187 .ok();
188 })
189 .detach();
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use std::sync::Arc;
196
197 use gpui_kit::{AppContext as _, TestAppContext};
198 use store::Store;
199
200 use crate::app_state::{AppState, Mode};
201
202 #[gpui_kit::test]
203 fn a_contact_detail_lands_on_the_clipboard(cx: &mut TestAppContext) {
204 cx.update(gpui_kit::init);
205 let store = Arc::new(Store::open_in_memory().unwrap());
206 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
207 cx.update(|cx| {
208 app.update(cx, |state, cx| {
209 state.copy_profile_detail("ada@example.com", cx);
210 assert!(
211 state
212 .notice
213 .as_ref()
214 .unwrap()
215 .text
216 .contains("ada@example.com")
217 );
218 })
219 });
220 let copied = cx.read_from_clipboard().and_then(|item| item.text());
221 assert_eq!(copied.as_deref(), Some("ada@example.com"));
222 }
223}