BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / stack.rs

stack.rs

stack.rs 11.1 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use super::rules::{ChatKind, Incoming, Preview};
4
5pub const MAX_VISIBLE: usize = 3;
6pub const MESSAGE_DURATION: Duration = Duration::from_secs(6);
7pub const MENTION_DURATION: Duration = Duration::from_secs(10);
8pub const MAX_TOTAL: Duration = Duration::from_secs(20);
9pub const RESUME_REMAINING: Duration = Duration::from_secs(2);
10pub const SENT_DURATION: Duration = Duration::from_millis(1500);
11
12#[derive(Debug, Clone, Copy)]
13pub struct ToastTimer {
14 first_shown: Instant,
15 started: Instant,
16 duration: Duration,
17 paused: Option<Instant>,
18 paused_total: Duration,
19}
20
21impl ToastTimer {
22 pub fn new(now: Instant, mention: bool) -> Self {
23 ToastTimer {
24 first_shown: now,
25 started: now,
26 duration: base_duration(mention),
27 paused: None,
28 paused_total: Duration::ZERO,
29 }
30 }
31
32 pub fn restart(&mut self, now: Instant, mention: bool) {
33 self.started = now;
34 self.duration = base_duration(mention);
35 if self.paused.is_some() {
36 self.paused = Some(now);
37 }
38 }
39
40 pub fn pause(&mut self, now: Instant) {
41 self.paused.get_or_insert(now);
42 }
43
44 pub fn resume(&mut self, now: Instant) {
45 if let Some(paused_at) = self.paused.take() {
46 self.paused_total += now.saturating_duration_since(paused_at);
47 self.started = now;
48 self.duration = RESUME_REMAINING;
49 }
50 }
51
52 pub fn is_paused(&self) -> bool {
53 self.paused.is_some()
54 }
55
56 fn elapsed(&self, now: Instant) -> Duration {
57 self.paused
58 .unwrap_or(now)
59 .saturating_duration_since(self.started)
60 }
61
62 pub fn fraction_left(&self, now: Instant) -> f32 {
63 let left = self.duration.saturating_sub(self.elapsed(now));
64 (left.as_secs_f32() / self.duration.as_secs_f32()).clamp(0., 1.)
65 }
66
67 pub fn expired(&self, now: Instant) -> bool {
68 if self.paused.is_some() {
69 return false;
70 }
71 self.elapsed(now) >= self.duration
72 || now
73 .saturating_duration_since(self.first_shown)
74 .saturating_sub(self.paused_total)
75 >= MAX_TOTAL
76 }
77}
78
79fn base_duration(mention: bool) -> Duration {
80 if mention {
81 MENTION_DURATION
82 } else {
83 MESSAGE_DURATION
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum ReplyState {
89 Closed,
90 Open,
91 Sent,
92 Failed,
93}
94
95#[derive(Debug, Clone)]
96pub struct ToastModel {
97 pub id: u64,
98 pub conversation_id: String,
99 pub message_id: String,
100 pub kind: ChatKind,
101 pub chat_title: String,
102 pub sender_id: Option<String>,
103 pub sender_name: String,
104 pub preview: Preview,
105 pub mentions_me: bool,
106 pub count: u32,
107 pub timer: ToastTimer,
108 pub reply: ReplyState,
109 pub reply_text: String,
110 pub hovered: bool,
111 pub time: String,
112}
113
114impl ToastModel {
115 pub fn holds_open(&self) -> bool {
116 self.reply != ReplyState::Closed
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct PushOutcome {
122 pub id: u64,
123 pub bundled: bool,
124 pub became_mention: bool,
125}
126
127impl PushOutcome {
128 pub fn plays_sound(self, throttle_allows: bool) -> bool {
129 self.became_mention || (!self.bundled && throttle_allows)
130 }
131}
132
133#[derive(Default)]
134pub struct ToastStack {
135 toasts: Vec<ToastModel>,
136 next_id: u64,
137}
138
139impl ToastStack {
140 pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {
141 if let Some(existing) = self
142 .toasts
143 .iter_mut()
144 .find(|toast| toast.conversation_id == incoming.conversation_id)
145 {
146 let became_mention = incoming.mentions_me && !existing.mentions_me;
147 existing.count += 1;
148 existing.mentions_me |= incoming.mentions_me;
149 existing.message_id = incoming.message_id.clone();
150 existing.sender_id = incoming.sender_id.clone();
151 existing.sender_name = incoming.sender_name.clone();
152 existing.preview = incoming.preview.clone();
153 let mention = existing.mentions_me;
154 existing.timer.restart(now, mention);
155 return PushOutcome {
156 id: existing.id,
157 bundled: true,
158 became_mention,
159 };
160 }
161 self.next_id += 1;
162 self.toasts.push(ToastModel {
163 id: self.next_id,
164 conversation_id: incoming.conversation_id.clone(),
165 message_id: incoming.message_id.clone(),
166 kind: incoming.kind.clone(),
167 chat_title: incoming.chat_title.clone(),
168 sender_id: incoming.sender_id.clone(),
169 sender_name: incoming.sender_name.clone(),
170 preview: incoming.preview.clone(),
171 mentions_me: incoming.mentions_me,
172 count: 1,
173 timer: ToastTimer::new(now, incoming.mentions_me),
174 reply: ReplyState::Closed,
175 reply_text: String::new(),
176 hovered: false,
177 time: String::new(),
178 });
179 PushOutcome {
180 id: self.next_id,
181 bundled: false,
182 became_mention: false,
183 }
184 }
185
186 pub fn get(&self, id: u64) -> Option<&ToastModel> {
187 self.toasts.iter().find(|toast| toast.id == id)
188 }
189
190 pub fn get_mut(&mut self, id: u64) -> Option<&mut ToastModel> {
191 self.toasts.iter_mut().find(|toast| toast.id == id)
192 }
193
194 pub fn remove(&mut self, id: u64) -> Option<ToastModel> {
195 let index = self.toasts.iter().position(|toast| toast.id == id)?;
196 Some(self.toasts.remove(index))
197 }
198
199 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
200 let ids: Vec<u64> = self
201 .toasts
202 .iter()
203 .filter(|toast| toast.conversation_id == conversation_id)
204 .map(|toast| toast.id)
205 .collect();
206 self.toasts
207 .retain(|toast| toast.conversation_id != conversation_id);
208 ids
209 }
210
211 pub fn visible(&self) -> &[ToastModel] {
212 let start = self.toasts.len().saturating_sub(MAX_VISIBLE);
213 &self.toasts[start..]
214 }
215
216 pub fn hidden_count(&self) -> usize {
217 self.toasts.len().saturating_sub(MAX_VISIBLE)
218 }
219
220 pub fn is_empty(&self) -> bool {
221 self.toasts.is_empty()
222 }
223
224 pub fn expired(&self, now: Instant) -> Vec<u64> {
225 self.toasts
226 .iter()
227 .filter(|toast| !toast.holds_open() && toast.timer.expired(now))
228 .map(|toast| toast.id)
229 .collect()
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 fn incoming(conversation: &str, mention: bool) -> Incoming {
238 Incoming {
239 conversation_id: conversation.into(),
240 message_id: "m".into(),
241 kind: ChatKind::Direct,
242 chat_title: "Chat".into(),
243 sender_id: None,
244 sender_name: "Mara".into(),
245 preview: Preview::Text("Hallo".into()),
246 mentions_me: mention,
247 muted: false,
248 }
249 }
250
251 #[test]
252 fn same_chat_bundles_into_one_toast_with_counter() {
253 let mut stack = ToastStack::default();
254 let now = Instant::now();
255 let first = stack.push(&incoming("a", false), now);
256 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
257 assert!(!first.bundled);
258 assert!(second.bundled);
259 assert_eq!(first.id, second.id);
260 assert_eq!(stack.get(first.id).unwrap().count, 2);
261 assert_eq!(stack.visible().len(), 1);
262 }
263
264 #[test]
265 fn bundling_restarts_timer() {
266 let mut stack = ToastStack::default();
267 let now = Instant::now();
268 let id = stack.push(&incoming("a", false), now).id;
269 stack.push(&incoming("a", false), now + Duration::from_secs(5));
270 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
271 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
272 }
273
274 #[test]
275 fn mention_in_burst_upgrades_and_plays_sound() {
276 let mut stack = ToastStack::default();
277 let now = Instant::now();
278 stack.push(&incoming("a", false), now);
279 let outcome = stack.push(&incoming("a", true), now);
280 assert!(outcome.became_mention);
281 assert!(outcome.plays_sound(false));
282 assert!(stack.get(outcome.id).unwrap().mentions_me);
283 let again = stack.push(&incoming("a", true), now);
284 assert!(!again.plays_sound(true));
285 }
286
287 #[test]
288 fn only_first_of_burst_plays_sound() {
289 let mut stack = ToastStack::default();
290 let now = Instant::now();
291 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
292 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
293 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
294 }
295
296 #[test]
297 fn shows_three_newest_and_counts_the_rest() {
298 let mut stack = ToastStack::default();
299 let now = Instant::now();
300 for chat in ["a", "b", "c", "d", "e"] {
301 stack.push(&incoming(chat, false), now);
302 }
303 let visible: Vec<&str> = stack
304 .visible()
305 .iter()
306 .map(|toast| toast.conversation_id.as_str())
307 .collect();
308 assert_eq!(visible, ["c", "d", "e"]);
309 assert_eq!(stack.hidden_count(), 2);
310 }
311
312 #[test]
313 fn mention_lasts_ten_seconds() {
314 let now = Instant::now();
315 let timer = ToastTimer::new(now, true);
316 assert!(!timer.expired(now + Duration::from_secs(9)));
317 assert!(timer.expired(now + Duration::from_secs(10)));
318 }
319
320 #[test]
321 fn hard_cap_beats_restarts() {
322 let mut stack = ToastStack::default();
323 let start = Instant::now();
324 let id = stack.push(&incoming("a", false), start).id;
325 for second in [5, 10, 15, 19] {
326 stack.push(&incoming("a", false), start + Duration::from_secs(second));
327 }
328 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
329 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
330 }
331
332 #[test]
333 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
334 let now = Instant::now();
335 let mut timer = ToastTimer::new(now, false);
336 timer.pause(now + Duration::from_secs(1));
337 assert!(!timer.expired(now + Duration::from_secs(60)));
338 let resumed = now + Duration::from_secs(60);
339 timer.resume(resumed);
340 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
341 assert!(timer.expired(resumed + Duration::from_secs(2)));
342 }
343
344 #[test]
345 fn open_reply_field_holds_toast() {
346 let mut stack = ToastStack::default();
347 let now = Instant::now();
348 let id = stack.push(&incoming("a", false), now).id;
349 stack.get_mut(id).unwrap().reply = ReplyState::Open;
350 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
351 }
352
353 #[test]
354 fn remove_conversation_returns_ids() {
355 let mut stack = ToastStack::default();
356 let now = Instant::now();
357 let id = stack.push(&incoming("a", false), now).id;
358 stack.push(&incoming("b", false), now);
359 assert_eq!(stack.remove_conversation("a"), vec![id]);
360 assert_eq!(stack.visible().len(), 1);
361 }
362}