BlueGit

ict rusty-teams

Files

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

stack.rs

stack.rs 17.6 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);
11pub const FADE_IN: Duration = Duration::from_millis(150);
12pub const FAST_FADE: Duration = Duration::from_millis(150);
13pub const SLOW_FADE: Duration = Duration::from_secs(4);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Curve {
17 Linear,
18 EaseInCirc,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Fade {
23 from: f32,
24 to: f32,
25 start: Instant,
26 duration: Duration,
27 curve: Curve,
28}
29
30impl Fade {
31 pub fn new(from: f32, to: f32, start: Instant, duration: Duration, curve: Curve) -> Self {
32 Fade {
33 from,
34 to,
35 start,
36 duration,
37 curve,
38 }
39 }
40
41 #[cfg(test)]
42 pub fn shown(now: Instant) -> Self {
43 Fade::new(1., 1., now, Duration::ZERO, Curve::Linear)
44 }
45
46 pub fn value(&self, now: Instant) -> f32 {
47 if self.duration.is_zero() {
48 return self.to;
49 }
50 let progress = (now.saturating_duration_since(self.start).as_secs_f32()
51 / self.duration.as_secs_f32())
52 .clamp(0., 1.);
53 let eased = match self.curve {
54 Curve::Linear => progress,
55 Curve::EaseInCirc => 1. - (1. - progress * progress).sqrt(),
56 };
57 self.from + (self.to - self.from) * eased
58 }
59
60 pub fn is_leaving(&self) -> bool {
61 self.to == 0.
62 }
63
64 fn is_gone(&self, now: Instant) -> bool {
65 self.is_leaving() && now.saturating_duration_since(self.start) >= self.duration
66 }
67}
68
69#[derive(Debug, Clone, Copy)]
70pub struct ToastTimer {
71 first_shown: Instant,
72 started: Instant,
73 duration: Duration,
74 paused: Option<Instant>,
75 paused_total: Duration,
76}
77
78impl ToastTimer {
79 pub fn new(now: Instant, mention: bool) -> Self {
80 ToastTimer {
81 first_shown: now,
82 started: now,
83 duration: base_duration(mention),
84 paused: None,
85 paused_total: Duration::ZERO,
86 }
87 }
88
89 pub fn restart(&mut self, now: Instant, mention: bool) {
90 self.started = now;
91 self.duration = base_duration(mention);
92 if self.paused.is_some() {
93 self.paused = Some(now);
94 }
95 }
96
97 pub fn pause(&mut self, now: Instant) {
98 self.paused.get_or_insert(now);
99 }
100
101 pub fn resume(&mut self, now: Instant) {
102 if let Some(paused_at) = self.paused.take() {
103 self.paused_total += now.saturating_duration_since(paused_at);
104 self.started = now;
105 self.duration = RESUME_REMAINING;
106 }
107 }
108
109 fn elapsed(&self, now: Instant) -> Duration {
110 self.paused
111 .unwrap_or(now)
112 .saturating_duration_since(self.started)
113 }
114
115 pub fn expired(&self, now: Instant) -> bool {
116 if self.paused.is_some() {
117 return false;
118 }
119 self.elapsed(now) >= self.duration
120 || now
121 .saturating_duration_since(self.first_shown)
122 .saturating_sub(self.paused_total)
123 >= MAX_TOTAL
124 }
125}
126
127fn base_duration(mention: bool) -> Duration {
128 if mention {
129 MENTION_DURATION
130 } else {
131 MESSAGE_DURATION
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub enum ReplyState {
137 Closed,
138 Open,
139 Sent,
140 Failed,
141}
142
143#[derive(Debug, Clone)]
144pub struct ToastModel {
145 pub id: u64,
146 pub conversation_id: String,
147 pub message_id: String,
148 pub kind: ChatKind,
149 pub chat_title: String,
150 pub sender_id: Option<String>,
151 pub sender_name: String,
152 pub preview: Preview,
153 pub mentions_me: bool,
154 pub count: u32,
155 pub timer: ToastTimer,
156 pub reply: ReplyState,
157 pub reply_text: String,
158 pub hovered: bool,
159 pub time: String,
160 pub queued: bool,
161 pub dismissed: bool,
162 pub fade: Fade,
163}
164
165impl ToastModel {
166 pub fn holds_open(&self) -> bool {
167 self.reply != ReplyState::Closed
168 }
169
170 pub fn opacity(&self, now: Instant) -> f32 {
171 self.fade.value(now)
172 }
173
174 pub fn is_leaving(&self) -> bool {
175 self.fade.is_leaving()
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub struct PushOutcome {
181 pub id: u64,
182 pub bundled: bool,
183 pub became_mention: bool,
184}
185
186impl PushOutcome {
187 pub fn plays_sound(self, throttle_allows: bool) -> bool {
188 self.became_mention || (!self.bundled && throttle_allows)
189 }
190}
191
192#[derive(Default)]
193pub struct ToastStack {
194 toasts: Vec<ToastModel>,
195 next_id: u64,
196}
197
198impl ToastStack {
199 pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {
200 if let Some(existing) = self
201 .toasts
202 .iter_mut()
203 .find(|toast| toast.conversation_id == incoming.conversation_id)
204 {
205 let became_mention = incoming.mentions_me && !existing.mentions_me;
206 existing.count += 1;
207 existing.mentions_me |= incoming.mentions_me;
208 existing.message_id = incoming.message_id.clone();
209 existing.sender_id = incoming.sender_id.clone();
210 existing.sender_name = incoming.sender_name.clone();
211 existing.preview = incoming.preview.clone();
212 let mention = existing.mentions_me;
213 existing.timer.restart(now, mention);
214 return PushOutcome {
215 id: existing.id,
216 bundled: true,
217 became_mention,
218 };
219 }
220 self.next_id += 1;
221 let queued = self.toasts.len() >= MAX_VISIBLE;
222 self.toasts.push(ToastModel {
223 id: self.next_id,
224 conversation_id: incoming.conversation_id.clone(),
225 message_id: incoming.message_id.clone(),
226 kind: incoming.kind.clone(),
227 chat_title: incoming.chat_title.clone(),
228 sender_id: incoming.sender_id.clone(),
229 sender_name: incoming.sender_name.clone(),
230 preview: incoming.preview.clone(),
231 mentions_me: incoming.mentions_me,
232 count: 1,
233 timer: ToastTimer::new(now, incoming.mentions_me),
234 reply: ReplyState::Closed,
235 reply_text: String::new(),
236 hovered: false,
237 time: String::new(),
238 queued,
239 dismissed: false,
240 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
241 });
242 PushOutcome {
243 id: self.next_id,
244 bundled: false,
245 became_mention: false,
246 }
247 }
248
249 pub fn get(&self, id: u64) -> Option<&ToastModel> {
250 self.toasts.iter().find(|toast| toast.id == id)
251 }
252
253 pub fn get_mut(&mut self, id: u64) -> Option<&mut ToastModel> {
254 self.toasts.iter_mut().find(|toast| toast.id == id)
255 }
256
257 pub fn remove(&mut self, id: u64) -> Option<ToastModel> {
258 let index = self.toasts.iter().position(|toast| toast.id == id)?;
259 Some(self.toasts.remove(index))
260 }
261
262 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
263 let ids: Vec<u64> = self
264 .toasts
265 .iter()
266 .filter(|toast| toast.conversation_id == conversation_id)
267 .map(|toast| toast.id)
268 .collect();
269 self.toasts
270 .retain(|toast| toast.conversation_id != conversation_id);
271 ids
272 }
273
274 pub fn visible(&self) -> &[ToastModel] {
275 let shown = self
276 .toasts
277 .iter()
278 .position(|toast| toast.queued)
279 .unwrap_or(self.toasts.len());
280 &self.toasts[..shown]
281 }
282
283 pub fn queued_count(&self) -> usize {
284 self.toasts.len() - self.visible().len()
285 }
286
287 pub fn promote(&mut self, now: Instant, fade_in: Duration) {
288 for toast in self.toasts.iter_mut().take(MAX_VISIBLE) {
289 if toast.queued {
290 toast.queued = false;
291 toast.timer = ToastTimer::new(now, toast.mentions_me);
292 toast.fade = Fade::new(0., 1., now, fade_in, Curve::Linear);
293 }
294 }
295 }
296
297 pub fn fade_out(&mut self, id: u64, now: Instant, duration: Duration) {
298 if let Some(toast) = self.get_mut(id)
299 && !toast.is_leaving()
300 {
301 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::EaseInCirc);
302 }
303 }
304
305 pub fn dismiss(&mut self, id: u64, now: Instant, duration: Duration) {
306 let Some(index) = self.toasts.iter().position(|toast| toast.id == id) else {
307 return;
308 };
309 if self.toasts[index].queued {
310 self.toasts.remove(index);
311 return;
312 }
313 let toast = &mut self.toasts[index];
314 if !toast.dismissed {
315 toast.dismissed = true;
316 toast.hovered = false;
317 toast.fade = Fade::new(toast.opacity(now), 0., now, duration, Curve::Linear);
318 }
319 }
320
321 pub fn restore(&mut self, now: Instant, duration: Duration) {
322 for toast in self
323 .toasts
324 .iter_mut()
325 .filter(|toast| toast.is_leaving() && !toast.dismissed)
326 {
327 toast.fade = Fade::new(toast.opacity(now), 1., now, duration, Curve::Linear);
328 }
329 }
330
331 pub fn any_hovered(&self) -> bool {
332 self.toasts.iter().any(|toast| toast.hovered)
333 }
334
335 pub fn ids(&self) -> Vec<u64> {
336 self.toasts.iter().map(|toast| toast.id).collect()
337 }
338
339 pub fn gone(&self, now: Instant) -> Vec<u64> {
340 self.toasts
341 .iter()
342 .filter(|toast| toast.fade.is_gone(now))
343 .map(|toast| toast.id)
344 .collect()
345 }
346
347 pub fn is_empty(&self) -> bool {
348 self.toasts.is_empty()
349 }
350
351 pub fn expired(&self, now: Instant) -> Vec<u64> {
352 self.toasts
353 .iter()
354 .filter(|toast| {
355 !toast.queued
356 && !toast.is_leaving()
357 && !toast.holds_open()
358 && toast.timer.expired(now)
359 })
360 .map(|toast| toast.id)
361 .collect()
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 fn incoming(conversation: &str, mention: bool) -> Incoming {
370 Incoming {
371 conversation_id: conversation.into(),
372 message_id: "m".into(),
373 kind: ChatKind::Direct,
374 chat_title: "Chat".into(),
375 sender_id: None,
376 sender_name: "Mara".into(),
377 preview: Preview::Text("Hello".into()),
378 mentions_me: mention,
379 muted: false,
380 }
381 }
382
383 #[test]
384 fn same_chat_bundles_into_one_toast_with_counter() {
385 let mut stack = ToastStack::default();
386 let now = Instant::now();
387 let first = stack.push(&incoming("a", false), now);
388 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
389 assert!(!first.bundled);
390 assert!(second.bundled);
391 assert_eq!(first.id, second.id);
392 assert_eq!(stack.get(first.id).unwrap().count, 2);
393 assert_eq!(stack.visible().len(), 1);
394 }
395
396 #[test]
397 fn bundling_restarts_timer() {
398 let mut stack = ToastStack::default();
399 let now = Instant::now();
400 let id = stack.push(&incoming("a", false), now).id;
401 stack.push(&incoming("a", false), now + Duration::from_secs(5));
402 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
403 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
404 }
405
406 #[test]
407 fn mention_in_burst_upgrades_and_plays_sound() {
408 let mut stack = ToastStack::default();
409 let now = Instant::now();
410 stack.push(&incoming("a", false), now);
411 let outcome = stack.push(&incoming("a", true), now);
412 assert!(outcome.became_mention);
413 assert!(outcome.plays_sound(false));
414 assert!(stack.get(outcome.id).unwrap().mentions_me);
415 let again = stack.push(&incoming("a", true), now);
416 assert!(!again.plays_sound(true));
417 }
418
419 #[test]
420 fn only_first_of_burst_plays_sound() {
421 let mut stack = ToastStack::default();
422 let now = Instant::now();
423 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
424 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
425 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
426 }
427
428 fn visible_chats(stack: &ToastStack) -> Vec<&str> {
429 stack
430 .visible()
431 .iter()
432 .map(|toast| toast.conversation_id.as_str())
433 .collect()
434 }
435
436 #[test]
437 fn shows_first_three_and_queues_the_rest() {
438 let mut stack = ToastStack::default();
439 let now = Instant::now();
440 for chat in ["a", "b", "c", "d", "e"] {
441 stack.push(&incoming(chat, false), now);
442 }
443 assert_eq!(visible_chats(&stack), ["a", "b", "c"]);
444 assert_eq!(stack.queued_count(), 2);
445 }
446
447 #[test]
448 fn queued_toast_starts_its_timer_when_promoted() {
449 let mut stack = ToastStack::default();
450 let start = Instant::now();
451 let ids: Vec<u64> = ["a", "b", "c", "d"]
452 .into_iter()
453 .map(|chat| stack.push(&incoming(chat, false), start).id)
454 .collect();
455 let later = start + Duration::from_secs(30);
456 assert!(!stack.expired(later).contains(&ids[3]));
457 stack.remove(ids[0]);
458 stack.promote(later, FADE_IN);
459 assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
460 assert!(!stack.expired(later + Duration::from_secs(5)).contains(&ids[3]));
461 assert!(stack.expired(later + Duration::from_secs(6)).contains(&ids[3]));
462 }
463
464 #[test]
465 fn slow_fade_stays_visible_then_drops_and_is_gone() {
466 let mut stack = ToastStack::default();
467 let now = Instant::now();
468 let id = stack.push(&incoming("a", false), now).id;
469 let hide_at = now + Duration::from_secs(6);
470 stack.fade_out(id, hide_at, SLOW_FADE);
471 let toast = stack.get(id).unwrap();
472 assert!(toast.opacity(hide_at + Duration::from_secs(2)) > 0.8);
473 assert!(stack.gone(hide_at + Duration::from_secs(3)).is_empty());
474 assert_eq!(stack.gone(hide_at + SLOW_FADE), vec![id]);
475 }
476
477 #[test]
478 fn restore_brings_a_fading_toast_back() {
479 let mut stack = ToastStack::default();
480 let now = Instant::now();
481 let id = stack.push(&incoming("a", false), now).id;
482 stack.fade_out(id, now, SLOW_FADE);
483 stack.restore(now + Duration::from_secs(3), FAST_FADE);
484 let toast = stack.get(id).unwrap();
485 assert!(!toast.is_leaving());
486 assert_eq!(toast.opacity(now + Duration::from_secs(4)), 1.);
487 assert!(stack.gone(now + Duration::from_secs(10)).is_empty());
488 }
489
490 #[test]
491 fn hiding_a_queued_toast_drops_it_at_once() {
492 let mut stack = ToastStack::default();
493 let now = Instant::now();
494 let ids: Vec<u64> = ["a", "b", "c", "d"]
495 .into_iter()
496 .map(|chat| stack.push(&incoming(chat, false), now).id)
497 .collect();
498 stack.dismiss(ids[3], now, FAST_FADE);
499 assert!(stack.get(ids[3]).is_none());
500 assert_eq!(stack.queued_count(), 0);
501 }
502
503 #[test]
504 fn dismiss_cuts_a_slow_fade_short_and_hover_does_not_undo_it() {
505 let mut stack = ToastStack::default();
506 let now = Instant::now();
507 let id = stack.push(&incoming("a", false), now).id;
508 stack.fade_out(id, now, SLOW_FADE);
509 stack.dismiss(id, now + Duration::from_secs(1), FAST_FADE);
510 stack.restore(now + Duration::from_millis(1050), FAST_FADE);
511 assert_eq!(stack.gone(now + Duration::from_millis(1150)), vec![id]);
512 }
513
514 #[test]
515 fn mention_lasts_ten_seconds() {
516 let now = Instant::now();
517 let timer = ToastTimer::new(now, true);
518 assert!(!timer.expired(now + Duration::from_secs(9)));
519 assert!(timer.expired(now + Duration::from_secs(10)));
520 }
521
522 #[test]
523 fn hard_cap_beats_restarts() {
524 let mut stack = ToastStack::default();
525 let start = Instant::now();
526 let id = stack.push(&incoming("a", false), start).id;
527 for second in [5, 10, 15, 19] {
528 stack.push(&incoming("a", false), start + Duration::from_secs(second));
529 }
530 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
531 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
532 }
533
534 #[test]
535 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
536 let now = Instant::now();
537 let mut timer = ToastTimer::new(now, false);
538 timer.pause(now + Duration::from_secs(1));
539 assert!(!timer.expired(now + Duration::from_secs(60)));
540 let resumed = now + Duration::from_secs(60);
541 timer.resume(resumed);
542 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
543 assert!(timer.expired(resumed + Duration::from_secs(2)));
544 }
545
546 #[test]
547 fn open_reply_field_holds_toast() {
548 let mut stack = ToastStack::default();
549 let now = Instant::now();
550 let id = stack.push(&incoming("a", false), now).id;
551 stack.get_mut(id).unwrap().reply = ReplyState::Open;
552 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
553 }
554
555 #[test]
556 fn remove_conversation_returns_ids() {
557 let mut stack = ToastStack::default();
558 let now = Instant::now();
559 let id = stack.push(&incoming("a", false), now).id;
560 stack.push(&incoming("b", false), now);
561 assert_eq!(stack.remove_conversation("a"), vec![id]);
562 assert_eq!(stack.visible().len(), 1);
563 }
564}