BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / bubbles.rs

bubbles.rs

bubbles.rs 2.0 KiB Download Raw
1use std::time::{Duration, Instant};
2
3pub const BUBBLE_SHOWN: Duration = Duration::from_secs(5);
4pub const BUBBLE_MAX: usize = 3;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct ChatBubble {
8 pub id: String,
9 pub sender_id: Option<String>,
10 pub name: String,
11 pub text: String,
12 pub at: Instant,
13}
14
15pub fn push_bubble(bubbles: &mut Vec<ChatBubble>, bubble: ChatBubble) {
16 if bubbles.iter().any(|shown| shown.id == bubble.id) {
17 return;
18 }
19 bubbles.push(bubble);
20 let surplus = bubbles.len().saturating_sub(BUBBLE_MAX);
21 bubbles.drain(..surplus);
22}
23
24pub fn shown_bubbles(bubbles: &[ChatBubble], now: Instant) -> Vec<&ChatBubble> {
25 bubbles
26 .iter()
27 .filter(|bubble| now.saturating_duration_since(bubble.at) < BUBBLE_SHOWN)
28 .collect()
29}
30
31#[cfg(test)]
32mod tests {
33 use super::*;
34
35 fn bubble(id: &str, at: Instant) -> ChatBubble {
36 ChatBubble {
37 id: id.to_owned(),
38 sender_id: None,
39 name: "Ana".to_owned(),
40 text: "hello".to_owned(),
41 at,
42 }
43 }
44
45 #[test]
46 fn only_the_newest_three_stay() {
47 let now = Instant::now();
48 let mut bubbles = Vec::new();
49 for id in ["a", "b", "c", "d"] {
50 push_bubble(&mut bubbles, bubble(id, now));
51 }
52 let ids: Vec<&str> = bubbles.iter().map(|shown| shown.id.as_str()).collect();
53 assert_eq!(ids, ["b", "c", "d"]);
54 }
55
56 #[test]
57 fn a_message_never_shows_twice() {
58 let now = Instant::now();
59 let mut bubbles = Vec::new();
60 push_bubble(&mut bubbles, bubble("a", now));
61 push_bubble(&mut bubbles, bubble("a", now));
62 assert_eq!(bubbles.len(), 1);
63 }
64
65 #[test]
66 fn bubbles_vanish_after_five_seconds() {
67 let now = Instant::now();
68 let bubbles = vec![bubble("a", now)];
69 assert_eq!(
70 shown_bubbles(&bubbles, now + Duration::from_secs(4)).len(),
71 1
72 );
73 assert!(shown_bubbles(&bubbles, now + BUBBLE_SHOWN).is_empty());
74 }
75}