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 signals: Default::default(),
381 created_at: chrono::Utc::now(),
382 }
383 }
384
385 #[test]
386 fn same_chat_bundles_into_one_toast_with_counter() {
387 let mut stack = ToastStack::default();
388 let now = Instant::now();
389 let first = stack.push(&incoming("a", false), now);
390 let second = stack.push(&incoming("a", false), now + Duration::from_secs(2));
391 assert!(!first.bundled);
392 assert!(second.bundled);
393 assert_eq!(first.id, second.id);
394 assert_eq!(stack.get(first.id).unwrap().count, 2);
395 assert_eq!(stack.visible().len(), 1);
396 }
397
398 #[test]
399 fn bundling_restarts_timer() {
400 let mut stack = ToastStack::default();
401 let now = Instant::now();
402 let id = stack.push(&incoming("a", false), now).id;
403 stack.push(&incoming("a", false), now + Duration::from_secs(5));
404 assert!(stack.expired(now + Duration::from_secs(7)).is_empty());
405 assert_eq!(stack.expired(now + Duration::from_secs(11)), vec![id]);
406 }
407
408 #[test]
409 fn mention_in_burst_upgrades_and_plays_sound() {
410 let mut stack = ToastStack::default();
411 let now = Instant::now();
412 stack.push(&incoming("a", false), now);
413 let outcome = stack.push(&incoming("a", true), now);
414 assert!(outcome.became_mention);
415 assert!(outcome.plays_sound(false));
416 assert!(stack.get(outcome.id).unwrap().mentions_me);
417 let again = stack.push(&incoming("a", true), now);
418 assert!(!again.plays_sound(true));
419 }
420
421 #[test]
422 fn only_first_of_burst_plays_sound() {
423 let mut stack = ToastStack::default();
424 let now = Instant::now();
425 assert!(stack.push(&incoming("a", false), now).plays_sound(true));
426 assert!(!stack.push(&incoming("a", false), now).plays_sound(true));
427 assert!(!stack.push(&incoming("b", false), now).plays_sound(false));
428 }
429
430 fn visible_chats(stack: &ToastStack) -> Vec<&str> {
431 stack
432 .visible()
433 .iter()
434 .map(|toast| toast.conversation_id.as_str())
435 .collect()
436 }
437
438 #[test]
439 fn shows_first_three_and_queues_the_rest() {
440 let mut stack = ToastStack::default();
441 let now = Instant::now();
442 for chat in ["a", "b", "c", "d", "e"] {
443 stack.push(&incoming(chat, false), now);
444 }
445 assert_eq!(visible_chats(&stack), ["a", "b", "c"]);
446 assert_eq!(stack.queued_count(), 2);
447 }
448
449 #[test]
450 fn queued_toast_starts_its_timer_when_promoted() {
451 let mut stack = ToastStack::default();
452 let start = Instant::now();
453 let ids: Vec<u64> = ["a", "b", "c", "d"]
454 .into_iter()
455 .map(|chat| stack.push(&incoming(chat, false), start).id)
456 .collect();
457 let later = start + Duration::from_secs(30);
458 assert!(!stack.expired(later).contains(&ids[3]));
459 stack.remove(ids[0]);
460 stack.promote(later, FADE_IN);
461 assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
462 assert!(!stack.expired(later + Duration::from_secs(5)).contains(&ids[3]));
463 assert!(stack.expired(later + Duration::from_secs(6)).contains(&ids[3]));
464 }
465
466 #[test]
467 fn slow_fade_stays_visible_then_drops_and_is_gone() {
468 let mut stack = ToastStack::default();
469 let now = Instant::now();
470 let id = stack.push(&incoming("a", false), now).id;
471 let hide_at = now + Duration::from_secs(6);
472 stack.fade_out(id, hide_at, SLOW_FADE);
473 let toast = stack.get(id).unwrap();
474 assert!(toast.opacity(hide_at + Duration::from_secs(2)) > 0.8);
475 assert!(stack.gone(hide_at + Duration::from_secs(3)).is_empty());
476 assert_eq!(stack.gone(hide_at + SLOW_FADE), vec![id]);
477 }
478
479 #[test]
480 fn restore_brings_a_fading_toast_back() {
481 let mut stack = ToastStack::default();
482 let now = Instant::now();
483 let id = stack.push(&incoming("a", false), now).id;
484 stack.fade_out(id, now, SLOW_FADE);
485 stack.restore(now + Duration::from_secs(3), FAST_FADE);
486 let toast = stack.get(id).unwrap();
487 assert!(!toast.is_leaving());
488 assert_eq!(toast.opacity(now + Duration::from_secs(4)), 1.);
489 assert!(stack.gone(now + Duration::from_secs(10)).is_empty());
490 }
491
492 #[test]
493 fn hiding_a_queued_toast_drops_it_at_once() {
494 let mut stack = ToastStack::default();
495 let now = Instant::now();
496 let ids: Vec<u64> = ["a", "b", "c", "d"]
497 .into_iter()
498 .map(|chat| stack.push(&incoming(chat, false), now).id)
499 .collect();
500 stack.dismiss(ids[3], now, FAST_FADE);
501 assert!(stack.get(ids[3]).is_none());
502 assert_eq!(stack.queued_count(), 0);
503 }
504
505 #[test]
506 fn dismiss_cuts_a_slow_fade_short_and_hover_does_not_undo_it() {
507 let mut stack = ToastStack::default();
508 let now = Instant::now();
509 let id = stack.push(&incoming("a", false), now).id;
510 stack.fade_out(id, now, SLOW_FADE);
511 stack.dismiss(id, now + Duration::from_secs(1), FAST_FADE);
512 stack.restore(now + Duration::from_millis(1050), FAST_FADE);
513 assert_eq!(stack.gone(now + Duration::from_millis(1150)), vec![id]);
514 }
515
516 #[test]
517 fn mention_lasts_ten_seconds() {
518 let now = Instant::now();
519 let timer = ToastTimer::new(now, true);
520 assert!(!timer.expired(now + Duration::from_secs(9)));
521 assert!(timer.expired(now + Duration::from_secs(10)));
522 }
523
524 #[test]
525 fn hard_cap_beats_restarts() {
526 let mut stack = ToastStack::default();
527 let start = Instant::now();
528 let id = stack.push(&incoming("a", false), start).id;
529 for second in [5, 10, 15, 19] {
530 stack.push(&incoming("a", false), start + Duration::from_secs(second));
531 }
532 assert!(stack.expired(start + Duration::from_secs(19)).is_empty());
533 assert_eq!(stack.expired(start + Duration::from_secs(20)), vec![id]);
534 }
535
536 #[test]
537 fn pause_stops_expiry_and_resume_leaves_two_seconds() {
538 let now = Instant::now();
539 let mut timer = ToastTimer::new(now, false);
540 timer.pause(now + Duration::from_secs(1));
541 assert!(!timer.expired(now + Duration::from_secs(60)));
542 let resumed = now + Duration::from_secs(60);
543 timer.resume(resumed);
544 assert!(!timer.expired(resumed + Duration::from_millis(1900)));
545 assert!(timer.expired(resumed + Duration::from_secs(2)));
546 }
547
548 #[test]
549 fn open_reply_field_holds_toast() {
550 let mut stack = ToastStack::default();
551 let now = Instant::now();
552 let id = stack.push(&incoming("a", false), now).id;
553 stack.get_mut(id).unwrap().reply = ReplyState::Open;
554 assert!(stack.expired(now + Duration::from_secs(60)).is_empty());
555 }
556
557 #[test]
558 fn remove_conversation_returns_ids() {
559 let mut stack = ToastStack::default();
560 let now = Instant::now();
561 let id = stack.push(&incoming("a", false), now).id;
562 stack.push(&incoming("b", false), now);
563 assert_eq!(stack.remove_conversation("a"), vec![id]);
564 assert_eq!(stack.visible().len(), 1);
565 }
566}