BlueGit

ict rusty-teams

Files

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

stack.rs

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