BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / activity / feed.rs

feed.rs

feed.rs 26.9 KiB Download Raw
1use std::collections::{BTreeSet, HashMap};
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
5use store::ActivityRecord;
6
7use crate::notify::Incoming;
8use crate::reaction_model::{UNKNOWN_REACTOR, tooltip_text};
9
10pub const RETENTION_DAYS: i64 = 14;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
14 Messages,
15 Mention,
16 Reaction,
17}
18
19impl Kind {
20 fn key(self) -> &'static str {
21 match self {
22 Kind::Messages => "messages",
23 Kind::Mention => "mention",
24 Kind::Reaction => "reaction",
25 }
26 }
27
28 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
30 .into_iter()
31 .find(|kind| kind.key() == key)
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Filter {
37 #[default]
38 All,
39 Mentions,
40 Unread,
41}
42
43impl Filter {
44 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
45
46 pub fn key(self) -> &'static str {
47 match self {
48 Filter::All => "all",
49 Filter::Mentions => "mentions",
50 Filter::Unread => "unread",
51 }
52 }
53
54 pub fn from_key(key: &str) -> Option<Filter> {
55 Filter::ALL.into_iter().find(|filter| filter.key() == key)
56 }
57
58 pub fn label(self) -> &'static str {
59 match self {
60 Filter::All => "All",
61 Filter::Mentions => "@Mentions",
62 Filter::Unread => "Unread",
63 }
64 }
65
66 pub fn empty_label(self) -> &'static str {
67 match self {
68 Filter::All => "No activity yet",
69 Filter::Mentions => "No mentions",
70 Filter::Unread => "Nothing unread",
71 }
72 }
73
74 fn admits(self, entry: &Entry) -> bool {
75 match self {
76 Filter::All => true,
77 Filter::Mentions => entry.kind == Kind::Mention,
78 Filter::Unread => !entry.read,
79 }
80 }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Bucket {
85 Today,
86 Yesterday,
87 Earlier,
88}
89
90impl Bucket {
91 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
92 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
93 match days_ago {
94 ..=0 => Bucket::Today,
95 1 => Bucket::Yesterday,
96 _ => Bucket::Earlier,
97 }
98 }
99
100 pub fn label(self) -> &'static str {
101 match self {
102 Bucket::Today => "Today",
103 Bucket::Yesterday => "Yesterday",
104 Bucket::Earlier => "Earlier",
105 }
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct Actor {
111 pub user_id: Option<String>,
112 pub name: String,
113}
114
115impl Actor {
116 pub fn is_unresolved(&self) -> bool {
117 self.user_id.is_some() && (self.name.is_empty() || self.name == UNKNOWN_REACTOR)
118 }
119
120 pub fn display_name<'a>(&'a self, resolved: &'a HashMap<String, String>) -> &'a str {
121 if self.is_unresolved()
122 && let Some(name) = self
123 .user_id
124 .as_ref()
125 .and_then(|user_id| resolved.get(user_id))
126 {
127 return name;
128 }
129 &self.name
130 }
131}
132
133#[derive(Debug, Clone, PartialEq)]
134pub struct Entry {
135 pub id: i64,
136 pub conversation_id: String,
137 pub kind: Kind,
138 pub message_id: String,
139 pub actors: Vec<Actor>,
140 pub preview: String,
141 pub glyphs: Vec<String>,
142 pub count: u32,
143 pub updated_at: DateTime<Utc>,
144 pub read: bool,
145}
146
147impl Entry {
148 pub fn names(&self, resolved: &HashMap<String, String>) -> String {
149 let names: Vec<&str> = self
150 .actors
151 .iter()
152 .map(|actor| actor.display_name(resolved))
153 .collect();
154 tooltip_text(&names)
155 }
156
157 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
158 self.actors
159 .iter()
160 .filter(|actor| actor.is_unresolved())
161 .filter_map(|actor| actor.user_id.as_ref())
162 }
163
164 pub fn latest_actor(&self) -> Option<&Actor> {
165 self.actors.last()
166 }
167
168 pub fn to_record(&self) -> ActivityRecord {
169 ActivityRecord {
170 id: self.id,
171 conversation_id: self.conversation_id.clone(),
172 kind: self.kind.key().to_owned(),
173 message_id: self.message_id.clone(),
174 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
175 preview: self.preview.clone(),
176 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
177 count: self.count,
178 updated_at: self.updated_at,
179 read: self.read,
180 }
181 }
182
183 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
184 Some(Entry {
185 id: record.id,
186 kind: Kind::from_key(&record.kind)?,
187 conversation_id: record.conversation_id,
188 message_id: record.message_id,
189 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
190 preview: record.preview,
191 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
192 count: record.count,
193 updated_at: record.updated_at,
194 read: record.read,
195 })
196 }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct Sighting {
201 pub user_id: Option<String>,
202 pub name: String,
203 pub glyph: String,
204 pub created_at: Option<DateTime<Utc>>,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct ReactedMessage {
209 pub message_id: String,
210 pub preview: String,
211 pub sightings: Vec<Sighting>,
212}
213
214pub struct Section<'a> {
215 pub bucket: Bucket,
216 pub entries: Vec<&'a Entry>,
217}
218
219#[derive(Default)]
220pub struct Feed {
221 entries: Vec<Entry>,
222 next_id: i64,
223 dirty: BTreeSet<i64>,
224}
225
226pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
227 saved
228 .unwrap_or(now)
229 .clamp(now - Duration::days(RETENTION_DAYS), now)
230}
231
232impl Feed {
233 pub fn load(records: Vec<ActivityRecord>) -> Feed {
234 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
235 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
236 Feed {
237 entries,
238 next_id,
239 dirty: BTreeSet::new(),
240 }
241 }
242
243 pub fn add(&mut self, mut entry: Entry) -> i64 {
244 entry.id = self.next_id;
245 self.next_id += 1;
246 self.dirty.insert(entry.id);
247 let id = entry.id;
248 self.entries.push(entry);
249 id
250 }
251
252 pub fn get(&self, id: i64) -> Option<&Entry> {
253 self.entries.iter().find(|entry| entry.id == id)
254 }
255
256 pub fn unread_count(&self) -> usize {
257 self.entries.iter().filter(|entry| !entry.read).count()
258 }
259
260 pub fn take_dirty(&mut self) -> Vec<Entry> {
261 let dirty = std::mem::take(&mut self.dirty);
262 self.entries
263 .iter()
264 .filter(|entry| dirty.contains(&entry.id))
265 .cloned()
266 .collect()
267 }
268
269 pub fn sections(
270 &self,
271 filter: Filter,
272 today: NaiveDate,
273 offset: FixedOffset,
274 ) -> Vec<Section<'_>> {
275 let mut admitted: Vec<&Entry> = self
276 .entries
277 .iter()
278 .filter(|entry| filter.admits(entry))
279 .collect();
280 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
281 let mut sections: Vec<Section<'_>> = Vec::new();
282 for entry in admitted {
283 let bucket = Bucket::of(entry.updated_at, today, offset);
284 match sections.last_mut() {
285 Some(section) if section.bucket == bucket => section.entries.push(entry),
286 _ => sections.push(Section {
287 bucket,
288 entries: vec![entry],
289 }),
290 }
291 }
292 sections
293 }
294
295 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
296 let actor = Actor {
297 user_id: incoming.sender_id.clone(),
298 name: incoming.sender_name.clone(),
299 };
300 if incoming.mentions_me {
301 self.add(Entry {
302 id: 0,
303 conversation_id: incoming.conversation_id.clone(),
304 kind: Kind::Mention,
305 message_id: incoming.message_id.clone(),
306 actors: vec![actor],
307 preview,
308 glyphs: Vec::new(),
309 count: 1,
310 updated_at: incoming.created_at,
311 read: false,
312 });
313 return;
314 }
315 let open_row = self.entries.iter().position(|entry| {
316 entry.kind == Kind::Messages
317 && !entry.read
318 && entry.conversation_id == incoming.conversation_id
319 });
320 let Some(index) = open_row else {
321 self.add(Entry {
322 id: 0,
323 conversation_id: incoming.conversation_id.clone(),
324 kind: Kind::Messages,
325 message_id: incoming.message_id.clone(),
326 actors: vec![actor],
327 preview,
328 glyphs: Vec::new(),
329 count: 1,
330 updated_at: incoming.created_at,
331 read: false,
332 });
333 return;
334 };
335 let entry = &mut self.entries[index];
336 entry.count += 1;
337 entry.preview = preview;
338 entry.updated_at = incoming.created_at;
339 move_to_end(&mut entry.actors, actor);
340 self.dirty.insert(entry.id);
341 }
342
343 pub fn record_chat_preview(
344 &mut self,
345 conversation_id: &str,
346 actor: Actor,
347 preview: String,
348 at: DateTime<Utc>,
349 ) {
350 let known = self.entries.iter().any(|entry| {
351 entry.conversation_id == conversation_id
352 && entry.kind != Kind::Reaction
353 && entry.updated_at >= at
354 });
355 if known {
356 return;
357 }
358 let open_row = self.entries.iter().position(|entry| {
359 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
360 });
361 match open_row {
362 Some(index) => {
363 let entry = &mut self.entries[index];
364 entry.count += 1;
365 entry.preview = preview;
366 entry.updated_at = at;
367 move_to_end(&mut entry.actors, actor);
368 self.dirty.insert(entry.id);
369 }
370 None => {
371 self.add(Entry {
372 id: 0,
373 conversation_id: conversation_id.to_owned(),
374 kind: Kind::Messages,
375 message_id: String::new(),
376 actors: vec![actor],
377 preview,
378 glyphs: Vec::new(),
379 count: 1,
380 updated_at: at,
381 read: false,
382 });
383 }
384 }
385 }
386
387 pub fn record_reactions(
388 &mut self,
389 conversation_id: &str,
390 message: &ReactedMessage,
391 my_user_id: &str,
392 cutoff: DateTime<Utc>,
393 now: DateTime<Utc>,
394 ) {
395 for sighting in &message.sightings {
396 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
397 continue;
398 };
399 let existing = self.entries.iter().position(|entry| {
400 entry.kind == Kind::Reaction
401 && entry.conversation_id == conversation_id
402 && entry.message_id == message.message_id
403 });
404 let known = existing.is_some_and(|index| {
405 self.entries[index]
406 .actors
407 .iter()
408 .any(|actor| actor.user_id.as_deref() == Some(user_id))
409 });
410 if known {
411 if let Some(index) = existing {
412 self.add_glyph(index, &sighting.glyph);
413 }
414 continue;
415 }
416 let fresh = match sighting.created_at {
417 Some(created_at) => created_at > cutoff,
418 None => existing.is_some(),
419 };
420 if !fresh {
421 continue;
422 }
423 let actor = Actor {
424 user_id: Some(user_id.to_owned()),
425 name: sighting.name.clone(),
426 };
427 let at = sighting.created_at.unwrap_or(now);
428 match existing {
429 Some(index) => {
430 let entry = &mut self.entries[index];
431 entry.actors.push(actor);
432 entry.count = entry.actors.len() as u32;
433 entry.read = false;
434 entry.updated_at = entry.updated_at.max(at);
435 self.dirty.insert(entry.id);
436 self.add_glyph(index, &sighting.glyph);
437 }
438 None => {
439 self.add(Entry {
440 id: 0,
441 conversation_id: conversation_id.to_owned(),
442 kind: Kind::Reaction,
443 message_id: message.message_id.clone(),
444 actors: vec![actor],
445 preview: message.preview.clone(),
446 glyphs: vec![sighting.glyph.clone()],
447 count: 1,
448 updated_at: at,
449 read: false,
450 });
451 }
452 }
453 }
454 }
455
456 fn add_glyph(&mut self, index: usize, glyph: &str) {
457 let entry = &mut self.entries[index];
458 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
459 entry.glyphs.push(glyph.to_owned());
460 self.dirty.insert(entry.id);
461 }
462 }
463
464 pub fn mark_read(&mut self, id: i64) -> bool {
465 self.mark_where(|entry| entry.id == id)
466 }
467
468 pub fn mark_all_read(&mut self) -> bool {
469 self.mark_where(|_| true)
470 }
471
472 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
473 self.mark_where(|entry| entry.conversation_id == conversation_id)
474 }
475
476 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
477 self.mark_where(|entry| {
478 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
479 })
480 }
481
482 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
483 let mut changed = false;
484 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
485 if matches(entry) {
486 entry.read = true;
487 self.dirty.insert(entry.id);
488 changed = true;
489 }
490 }
491 changed
492 }
493}
494
495fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
496 actors.retain(|known| match (&known.user_id, &actor.user_id) {
497 (Some(known_id), Some(id)) => known_id != id,
498 _ => known.name != actor.name,
499 });
500 actors.push(actor);
501}
502
503#[cfg(test)]
504mod tests {
505 use chrono::TimeZone;
506
507 use super::*;
508 use crate::notify::{ChatKind, Preview};
509
510 #[test]
511 fn filters_round_trip_through_their_key() {
512 for filter in Filter::ALL {
513 assert_eq!(Filter::from_key(filter.key()), Some(filter));
514 }
515 assert_eq!(Filter::from_key("other"), None);
516 }
517
518 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
519 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
520 }
521
522 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
523 Incoming {
524 conversation_id: conversation_id.into(),
525 message_id: message_id.into(),
526 kind: ChatKind::Direct,
527 chat_title: "Chat".into(),
528 sender_id: Some(format!("id-{sender}")),
529 sender_name: sender.into(),
530 preview: Preview::Text(format!("text {message_id}")),
531 mentions_me: false,
532 muted: false,
533 signals: Default::default(),
534 created_at: at(9, minute),
535 }
536 }
537
538 fn record(feed: &mut Feed, incoming: &Incoming) {
539 feed.record_message(incoming, format!("text {}", incoming.message_id));
540 }
541
542 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
543 Sighting {
544 user_id: Some(format!("id-{user}")),
545 name: user.into(),
546 glyph: glyph.into(),
547 created_at,
548 }
549 }
550
551 fn react(feed: &mut Feed, sightings: &[Sighting]) {
552 let message = ReactedMessage {
553 message_id: "mine".into(),
554 preview: "my text".into(),
555 sightings: sightings.to_vec(),
556 };
557 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
558 }
559
560 fn all(feed: &Feed) -> Vec<&Entry> {
561 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
562 .into_iter()
563 .flat_map(|section| section.entries)
564 .collect()
565 }
566
567 fn offset() -> FixedOffset {
568 FixedOffset::east_opt(0).unwrap()
569 }
570
571 #[test]
572 fn three_messages_share_one_row_and_keep_the_first_message_id() {
573 let mut feed = Feed::default();
574 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
575 record(
576 &mut feed,
577 &incoming("chat", message_id, "Anna", index as u32),
578 );
579 }
580 let entries = all(&feed);
581 assert_eq!(entries.len(), 1);
582 assert_eq!(entries[0].count, 3);
583 assert_eq!(entries[0].message_id, "m1");
584 assert_eq!(entries[0].preview, "text m3");
585 assert_eq!(entries[0].updated_at, at(9, 2));
586 assert_eq!(feed.unread_count(), 1);
587 }
588
589 #[test]
590 fn latest_sender_moves_to_the_end() {
591 let mut feed = Feed::default();
592 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
593 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
594 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
595 let entries = all(&feed);
596 let entry = entries[0];
597 assert_eq!(entry.names(&HashMap::new()), "Ben and Anna");
598 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
599 }
600
601 #[test]
602 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
603 let mut feed = Feed::default();
604 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
605 let anna = Actor {
606 user_id: Some("id-Anna".into()),
607 name: "Anna".into(),
608 };
609 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
610 assert_eq!(all(&feed)[0].count, 1);
611 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
612 assert_eq!(all(&feed)[0].count, 2);
613 assert_eq!(all(&feed)[0].preview, "later");
614 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
615 let entries = all(&feed);
616 assert_eq!(entries.len(), 2);
617 assert_eq!(entries[0].message_id, "");
618 }
619
620 #[test]
621 fn message_after_read_opens_a_new_row() {
622 let mut feed = Feed::default();
623 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
624 feed.mark_conversation_read("chat");
625 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
626 let entries = all(&feed);
627 assert_eq!(entries.len(), 2);
628 assert_eq!(entries[0].message_id, "m2");
629 assert!(!entries[0].read);
630 assert!(entries[1].read);
631 assert_eq!(entries[1].count, 1);
632 }
633
634 #[test]
635 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
636 let mut feed = Feed::default();
637 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
638 let mut mention = incoming("chat", "m2", "Ben", 2);
639 mention.mentions_me = true;
640 record(&mut feed, &mention);
641 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
642 let entries = all(&feed);
643 assert_eq!(entries.len(), 2);
644 let mention_row = entries
645 .iter()
646 .find(|entry| entry.kind == Kind::Mention)
647 .unwrap();
648 assert_eq!(mention_row.message_id, "m2");
649 let messages_row = entries
650 .iter()
651 .find(|entry| entry.kind == Kind::Messages)
652 .unwrap();
653 assert_eq!(messages_row.count, 2);
654 assert_eq!(messages_row.message_id, "m1");
655 }
656
657 #[test]
658 fn reactions_bundle_per_message_and_become_unread_again() {
659 let mut feed = Feed::default();
660 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
661 feed.mark_all_read();
662 assert_eq!(feed.unread_count(), 0);
663 react(
664 &mut feed,
665 &[
666 sighting("Anna", "A", Some(at(9, 1))),
667 sighting("Ben", "B", Some(at(9, 5))),
668 ],
669 );
670 let entries = all(&feed);
671 assert_eq!(entries.len(), 1);
672 assert_eq!(entries[0].names(&HashMap::new()), "Anna and Ben");
673 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
674 assert_eq!(entries[0].count, 2);
675 assert_eq!(entries[0].updated_at, at(9, 5));
676 assert!(!entries[0].read);
677 assert_eq!(entries[0].preview, "my text");
678 }
679
680 #[test]
681 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
682 let mut feed = Feed::default();
683 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
684 feed.mark_all_read();
685 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
686 let entries = all(&feed);
687 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
688 assert!(entries[0].read);
689 }
690
691 #[test]
692 fn own_and_anonymous_reactions_are_ignored() {
693 let mut feed = Feed::default();
694 let anonymous = Sighting {
695 user_id: None,
696 ..sighting("Anna", "A", Some(at(9, 1)))
697 };
698 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
699 assert!(all(&feed).is_empty());
700 }
701
702 #[test]
703 fn old_reactions_on_first_sight_are_ignored() {
704 let mut feed = Feed::default();
705 react(
706 &mut feed,
707 &[
708 sighting("Anna", "A", Some(at(7, 0))),
709 sighting("Ben", "B", None),
710 ],
711 );
712 assert!(all(&feed).is_empty());
713 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
714 react(&mut feed, &[sighting("Dan", "D", None)]);
715 assert_eq!(all(&feed)[0].names(&HashMap::new()), "Cleo and Dan");
716 }
717
718 #[test]
719 fn reading_a_conversation_leaves_others_unread() {
720 let mut feed = Feed::default();
721 record(&mut feed, &incoming("a", "m1", "Anna", 1));
722 record(&mut feed, &incoming("b", "m2", "Ben", 2));
723 assert!(feed.mark_conversation_read("a"));
724 assert!(!feed.mark_conversation_read("a"));
725 assert_eq!(feed.unread_count(), 1);
726 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
727 assert_eq!(unread.conversation_id, "b");
728 }
729
730 #[test]
731 fn read_sync_only_covers_rows_up_to_the_read_time() {
732 let mut feed = Feed::default();
733 record(&mut feed, &incoming("a", "m1", "Anna", 1));
734 feed.mark_conversation_read("a");
735 record(&mut feed, &incoming("a", "m2", "Anna", 30));
736 record(&mut feed, &incoming("b", "m3", "Ben", 1));
737 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
738 assert!(!changed);
739 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
740 assert!(changed);
741 assert_eq!(feed.unread_count(), 1);
742 }
743
744 #[test]
745 fn mark_all_read_clears_the_count_and_reports_change_once() {
746 let mut feed = Feed::default();
747 record(&mut feed, &incoming("a", "m1", "Anna", 1));
748 record(&mut feed, &incoming("b", "m2", "Ben", 2));
749 assert!(feed.mark_all_read());
750 assert_eq!(feed.unread_count(), 0);
751 assert!(!feed.mark_all_read());
752 }
753
754 #[test]
755 fn filters_pick_mentions_and_unread() {
756 let mut feed = Feed::default();
757 record(&mut feed, &incoming("a", "m1", "Anna", 1));
758 let mut mention = incoming("b", "m2", "Ben", 2);
759 mention.mentions_me = true;
760 record(&mut feed, &mention);
761 feed.mark_conversation_read("a");
762 let today = at(9, 0).date_naive();
763 let count = |filter| {
764 feed.sections(filter, today, offset())
765 .iter()
766 .map(|section| section.entries.len())
767 .sum::<usize>()
768 };
769 assert_eq!(count(Filter::All), 2);
770 assert_eq!(count(Filter::Mentions), 1);
771 assert_eq!(count(Filter::Unread), 1);
772 }
773
774 #[test]
775 fn buckets_follow_the_local_day() {
776 let today = at(12, 0).date_naive();
777 let utc = offset();
778 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
779 assert_eq!(
780 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
781 Bucket::Yesterday
782 );
783 assert_eq!(
784 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
785 Bucket::Earlier
786 );
787 let east = FixedOffset::east_opt(2 * 3600).unwrap();
788 assert_eq!(
789 Bucket::of(at(23, 30) - Duration::days(1), today, east),
790 Bucket::Today
791 );
792 }
793
794 #[test]
795 fn sections_are_newest_first_and_grouped() {
796 let mut feed = Feed::default();
797 let mut old = incoming("a", "m1", "Anna", 1);
798 old.created_at = at(9, 0) - Duration::days(1);
799 record(&mut feed, &old);
800 record(&mut feed, &incoming("b", "m2", "Ben", 2));
801 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
802 let today = at(9, 0).date_naive();
803 let sections = feed.sections(Filter::All, today, offset());
804 let labels: Vec<&str> = sections
805 .iter()
806 .map(|section| section.bucket.label())
807 .collect();
808 assert_eq!(labels, ["Today", "Yesterday"]);
809 assert_eq!(sections[0].entries[0].conversation_id, "c");
810 }
811
812 #[test]
813 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
814 let mut feed = Feed::default();
815 record(&mut feed, &incoming("a", "m1", "Anna", 1));
816 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
817 let dirty = feed.take_dirty();
818 assert_eq!(dirty.len(), 2);
819 assert!(feed.take_dirty().is_empty());
820 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
821 assert_eq!(all(&reloaded).len(), 2);
822 let mut reloaded = reloaded;
823 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
824 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
825 assert_eq!(ids.len(), 1);
826 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
827 }
828
829 #[test]
830 fn start_time_defaults_to_now_and_is_clamped() {
831 let now = at(12, 0);
832 assert_eq!(start_time(None, now), now);
833 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
834 assert_eq!(
835 start_time(Some(now - Duration::days(30)), now),
836 now - Duration::days(RETENTION_DAYS)
837 );
838 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
839 }
840}