BlueGit

ict rusty-teams

Files

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

typing.rs

typing.rs 10.8 KiB Download Raw
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use chrono::{DateTime, Utc};
5
6use crate::format::first_name;
7use crate::sidebar_model::Face;
8
9pub const SEND_INTERVAL: Duration = Duration::from_secs(20);
10pub const REMOTE_TIMEOUT: Duration = Duration::from_secs(22);
11const UNKNOWN_NAME: &str = "Someone";
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14struct Typer {
15 user_id: String,
16 name: String,
17 last_seen: Instant,
18 last_seen_at: DateTime<Utc>,
19}
20
21#[derive(Debug, Default)]
22pub struct TypingState {
23 conversations: HashMap<String, Vec<Typer>>,
24}
25
26impl TypingState {
27 pub fn start(
28 &mut self,
29 conversation_id: &str,
30 user_id: &str,
31 name: &str,
32 now: Instant,
33 at: DateTime<Utc>,
34 ) {
35 let typers = self
36 .conversations
37 .entry(conversation_id.to_owned())
38 .or_default();
39 match typers.iter_mut().find(|typer| typer.user_id == user_id) {
40 Some(typer) => {
41 typer.last_seen = now;
42 typer.last_seen_at = at;
43 if !name.is_empty() {
44 typer.name = name.to_owned();
45 }
46 }
47 None => typers.push(Typer {
48 user_id: user_id.to_owned(),
49 name: name.to_owned(),
50 last_seen: now,
51 last_seen_at: at,
52 }),
53 }
54 }
55
56 pub fn clear(&mut self, conversation_id: &str, user_id: &str) -> bool {
57 self.remove_where(conversation_id, |typer| typer.user_id == user_id)
58 }
59
60 pub fn message_from(
61 &mut self,
62 conversation_id: &str,
63 user_id: &str,
64 sent_at: DateTime<Utc>,
65 ) -> bool {
66 self.remove_where(conversation_id, |typer| {
67 typer.user_id == user_id && sent_at >= typer.last_seen_at
68 })
69 }
70
71 pub fn expire(&mut self, now: Instant) -> bool {
72 let before = self.conversations.values().map(Vec::len).sum::<usize>();
73 for typers in self.conversations.values_mut() {
74 typers.retain(|typer| now.duration_since(typer.last_seen) < REMOTE_TIMEOUT);
75 }
76 self.conversations.retain(|_, typers| !typers.is_empty());
77 before != self.conversations.values().map(Vec::len).sum::<usize>()
78 }
79
80 pub fn next_expiry(&self) -> Option<Instant> {
81 self.conversations
82 .values()
83 .flatten()
84 .map(|typer| typer.last_seen + REMOTE_TIMEOUT)
85 .min()
86 }
87
88 pub fn names(&self, conversation_id: &str) -> Vec<String> {
89 self.faces(conversation_id)
90 .into_iter()
91 .map(|face| face.name)
92 .collect()
93 }
94
95 pub fn faces(&self, conversation_id: &str) -> Vec<Face> {
96 self.conversations
97 .get(conversation_id)
98 .into_iter()
99 .flatten()
100 .map(|typer| Face {
101 user_id: Some(typer.user_id.clone()),
102 name: match typer.name.trim() {
103 "" => UNKNOWN_NAME.to_owned(),
104 name => name.to_owned(),
105 },
106 })
107 .collect()
108 }
109
110 pub fn is_active(&self, conversation_id: &str) -> bool {
111 self.conversations.contains_key(conversation_id)
112 }
113
114 fn remove_where(&mut self, conversation_id: &str, matches: impl Fn(&Typer) -> bool) -> bool {
115 let Some(typers) = self.conversations.get_mut(conversation_id) else {
116 return false;
117 };
118 let before = typers.len();
119 typers.retain(|typer| !matches(typer));
120 let changed = typers.len() != before;
121 if typers.is_empty() {
122 self.conversations.remove(conversation_id);
123 }
124 changed
125 }
126}
127
128pub fn typing_tooltip(names: &[String]) -> String {
129 match names {
130 [] => String::new(),
131 [only] => format!("{only} is typing"),
132 [first, second] => format!("{first} and {second} are typing"),
133 _ => format!("Typing\n{}", names.join("\n")),
134 }
135}
136
137pub fn preview_label(names: &[String], one_on_one: bool) -> String {
138 match names {
139 [] => String::new(),
140 [_] if one_on_one => "typing...".to_owned(),
141 [only] => format!("{} is typing...", first_name(only)),
142 _ => format!("{} people are typing...", names.len()),
143 }
144}
145
146#[derive(Debug, Default)]
147pub struct OutgoingTyping {
148 sent_at: Option<Instant>,
149}
150
151impl OutgoingTyping {
152 /// `Some(true)` asks for a Typing signal, `Some(false)` for a ClearTyping.
153 pub fn on_text(&mut self, has_text: bool, now: Instant) -> Option<bool> {
154 if !has_text {
155 return self.sent_at.take().map(|_| false);
156 }
157 let due = self
158 .sent_at
159 .is_none_or(|sent_at| now.duration_since(sent_at) >= SEND_INTERVAL);
160 due.then(|| {
161 self.sent_at = Some(now);
162 true
163 })
164 }
165
166 pub fn stop(&mut self) -> bool {
167 self.sent_at.take().is_some()
168 }
169
170 pub fn reset(&mut self) {
171 self.sent_at = None;
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 fn names(list: &[&str]) -> Vec<String> {
180 list.iter().map(|name| (*name).to_owned()).collect()
181 }
182
183 fn at(seconds: i64) -> DateTime<Utc> {
184 DateTime::from_timestamp(1_790_000_000 + seconds, 0).unwrap()
185 }
186
187 #[test]
188 fn tooltip_names_one_or_two_in_a_sentence_and_more_as_a_list() {
189 assert_eq!(typing_tooltip(&[]), "");
190 assert_eq!(
191 typing_tooltip(&names(&["Ada Lovelace"])),
192 "Ada Lovelace is typing"
193 );
194 assert_eq!(
195 typing_tooltip(&names(&["Ada Lovelace", "Alan Turing"])),
196 "Ada Lovelace and Alan Turing are typing"
197 );
198 assert_eq!(
199 typing_tooltip(&names(&["A B", "C D", "E F", "G H", "I J"])),
200 "Typing\nA B\nC D\nE F\nG H\nI J"
201 );
202 }
203
204 #[test]
205 fn faces_keep_order_and_fall_back_to_someone() {
206 let mut state = TypingState::default();
207 let now = Instant::now();
208 state.start("c", "u1", "Ada", now, at(0));
209 state.start("c", "u2", " ", now, at(0));
210 assert_eq!(
211 state.faces("c"),
212 vec![
213 Face {
214 user_id: Some("u1".into()),
215 name: "Ada".into()
216 },
217 Face {
218 user_id: Some("u2".into()),
219 name: "Someone".into()
220 },
221 ]
222 );
223 assert!(state.faces("other").is_empty());
224 }
225
226 #[test]
227 fn preview_label_depends_on_chat_kind_and_count() {
228 assert_eq!(preview_label(&names(&["Ada Lovelace"]), true), "typing...");
229 assert_eq!(
230 preview_label(&names(&["Ada Lovelace"]), false),
231 "Ada is typing..."
232 );
233 assert_eq!(
234 preview_label(&names(&["Ada Lovelace", "Alan Turing"]), false),
235 "2 people are typing..."
236 );
237 assert_eq!(preview_label(&[], false), "");
238 }
239
240 #[test]
241 fn start_refreshes_without_duplicating_and_keeps_order() {
242 let mut state = TypingState::default();
243 let now = Instant::now();
244 state.start("c", "u1", "Ada", now, at(0));
245 state.start("c", "u2", "Alan", now, at(0));
246 state.start("c", "u1", "", now + Duration::from_secs(5), at(5));
247 assert_eq!(state.names("c"), names(&["Ada", "Alan"]));
248 assert!(state.is_active("c"));
249 assert!(!state.is_active("other"));
250 }
251
252 #[test]
253 fn blank_names_read_as_someone() {
254 let mut state = TypingState::default();
255 state.start("c", "u1", " ", Instant::now(), at(0));
256 assert_eq!(state.names("c"), names(&["Someone"]));
257 }
258
259 #[test]
260 fn clear_removes_only_that_user() {
261 let mut state = TypingState::default();
262 let now = Instant::now();
263 state.start("c", "u1", "Ada", now, at(0));
264 state.start("c", "u2", "Alan", now, at(0));
265 assert!(state.clear("c", "u1"));
266 assert!(!state.clear("c", "u1"));
267 assert_eq!(state.names("c"), names(&["Alan"]));
268 assert!(state.clear("c", "u2"));
269 assert!(!state.is_active("c"));
270 }
271
272 #[test]
273 fn a_message_clears_its_sender_only_when_sent_after_the_typing() {
274 let mut state = TypingState::default();
275 let now = Instant::now();
276 state.start("c", "u1", "Ada", now, at(10));
277 assert!(!state.message_from("c", "u1", at(9)));
278 assert!(!state.message_from("c", "u2", at(11)));
279 assert!(!state.message_from("other", "u1", at(11)));
280 assert!(state.message_from("c", "u1", at(11)));
281 assert!(!state.is_active("c"));
282 }
283
284 #[test]
285 fn typers_expire_after_the_timeout_and_a_refresh_extends_it() {
286 let mut state = TypingState::default();
287 let start = Instant::now();
288 state.start("c", "u1", "Ada", start, at(0));
289 state.start("c", "u2", "Alan", start + Duration::from_secs(10), at(10));
290 assert_eq!(state.next_expiry(), Some(start + REMOTE_TIMEOUT));
291 assert!(!state.expire(start + REMOTE_TIMEOUT - Duration::from_millis(1)));
292 assert!(state.expire(start + REMOTE_TIMEOUT));
293 assert_eq!(state.names("c"), names(&["Alan"]));
294 assert_eq!(
295 state.next_expiry(),
296 Some(start + Duration::from_secs(10) + REMOTE_TIMEOUT)
297 );
298 assert!(state.expire(start + Duration::from_secs(32)));
299 assert_eq!(state.next_expiry(), None);
300 assert!(!state.expire(start + Duration::from_secs(100)));
301 }
302
303 #[test]
304 fn outgoing_sends_at_most_every_twenty_seconds_while_typing() {
305 let mut outgoing = OutgoingTyping::default();
306 let start = Instant::now();
307 assert_eq!(outgoing.on_text(true, start), Some(true));
308 assert_eq!(
309 outgoing.on_text(true, start + Duration::from_secs(19)),
310 None
311 );
312 assert_eq!(
313 outgoing.on_text(true, start + Duration::from_secs(20)),
314 Some(true)
315 );
316 }
317
318 #[test]
319 fn outgoing_clears_once_when_the_text_empties() {
320 let mut outgoing = OutgoingTyping::default();
321 let start = Instant::now();
322 assert_eq!(outgoing.on_text(false, start), None);
323 outgoing.on_text(true, start);
324 assert_eq!(outgoing.on_text(false, start), Some(false));
325 assert_eq!(outgoing.on_text(false, start), None);
326 assert_eq!(outgoing.on_text(true, start), Some(true));
327 }
328
329 #[test]
330 fn outgoing_stop_reports_only_after_a_typing_was_sent() {
331 let mut outgoing = OutgoingTyping::default();
332 assert!(!outgoing.stop());
333 outgoing.on_text(true, Instant::now());
334 assert!(outgoing.stop());
335 assert!(!outgoing.stop());
336 }
337
338 #[test]
339 fn outgoing_reset_forgets_without_a_clear() {
340 let mut outgoing = OutgoingTyping::default();
341 let start = Instant::now();
342 outgoing.on_text(true, start);
343 outgoing.reset();
344 assert_eq!(outgoing.on_text(false, start), None);
345 }
346}