BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / reaction_model.rs

reaction_model.rs

reaction_model.rs 6.4 KiB Download Raw
1use std::fmt::Display;
2
3use chrono::{DateTime, Datelike, TimeZone, Utc};
4
5use crate::rows::ReactionChip;
6
7const FACE_LIMIT: usize = 3;
8const TOOLTIP_NAME_LIMIT: usize = 3;
9const TOOLTIP_LEAD_NAMES: usize = 2;
10pub const UNKNOWN_REACTOR: &str = "Unknown";
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Reactor {
14 pub user_id: Option<String>,
15 pub name: String,
16 pub created_at: Option<DateTime<Utc>>,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct ReactionTab {
21 pub glyph: Option<String>,
22 pub label: String,
23 pub count: usize,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ReactionEntry {
28 pub reactor: Reactor,
29 pub label: String,
30}
31
32pub fn shows_faces(count: usize) -> bool {
33 (1..=FACE_LIMIT).contains(&count)
34}
35
36pub fn tooltip_text(names: &[&str]) -> String {
37 match names {
38 [] => String::new(),
39 [only] => (*only).to_owned(),
40 names if names.len() <= TOOLTIP_NAME_LIMIT => {
41 let (last, lead) = names.split_last().expect("not empty");
42 format!("{} and {last}", lead.join(", "))
43 }
44 names => format!(
45 "{} and {} others",
46 names[..TOOLTIP_LEAD_NAMES].join(", "),
47 names.len() - TOOLTIP_LEAD_NAMES
48 ),
49 }
50}
51
52pub fn chip_tooltip(chip: &ReactionChip) -> String {
53 let names: Vec<&str> = chip
54 .reactors
55 .iter()
56 .map(|reactor| reactor.name.as_str())
57 .collect();
58 tooltip_text(&names)
59}
60
61pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String
62where
63 Zone: TimeZone,
64 Zone::Offset: Display,
65{
66 let local = time.with_timezone(&now.timezone());
67 let day = local.date_naive();
68 let today = now.date_naive();
69 let clock = local.format("%H:%M");
70 if day == today {
71 format!("today at {clock}")
72 } else if today.pred_opt() == Some(day) {
73 format!("yesterday at {clock}")
74 } else if day.year() == today.year() {
75 format!("{} at {clock}", local.format("%b %-d"))
76 } else {
77 format!("{} at {clock}", local.format("%b %-d, %Y"))
78 }
79}
80
81pub fn reaction_tabs(chips: &[ReactionChip]) -> Vec<ReactionTab> {
82 if chips.len() < 2 {
83 return Vec::new();
84 }
85 let total = chips.iter().map(|chip| chip.reactors.len()).sum();
86 std::iter::once(ReactionTab {
87 glyph: None,
88 label: "All".to_owned(),
89 count: total,
90 })
91 .chain(chips.iter().map(|chip| ReactionTab {
92 glyph: Some(chip.glyph()),
93 label: chip.label.clone(),
94 count: chip.reactors.len(),
95 }))
96 .collect()
97}
98
99pub fn reaction_entries(chips: &[ReactionChip], tab: Option<&str>) -> Vec<ReactionEntry> {
100 let mut entries: Vec<ReactionEntry> = chips
101 .iter()
102 .filter(|chip| tab.is_none_or(|glyph| chip.glyph() == glyph))
103 .flat_map(|chip| {
104 chip.reactors.iter().map(|reactor| ReactionEntry {
105 reactor: reactor.clone(),
106 label: chip.label.clone(),
107 })
108 })
109 .collect();
110 entries.sort_by_key(|entry| std::cmp::Reverse(entry.reactor.created_at));
111 entries
112}
113
114#[cfg(test)]
115mod tests {
116 use chrono::{Duration, FixedOffset};
117
118 use super::*;
119
120 fn reactor(name: &str, created_at: Option<DateTime<Utc>>) -> Reactor {
121 Reactor {
122 user_id: None,
123 name: name.to_owned(),
124 created_at,
125 }
126 }
127
128 fn chip(reaction_type: &str, reactors: Vec<Reactor>) -> ReactionChip {
129 ReactionChip {
130 reaction_type: reaction_type.to_owned(),
131 label: crate::rows::reaction_label(reaction_type),
132 count: reactors.len(),
133 mine: false,
134 reactors,
135 }
136 }
137
138 fn utc(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
139 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0)
140 .unwrap()
141 }
142
143 #[test]
144 fn faces_show_up_to_three_people_then_a_count() {
145 assert!(!shows_faces(0));
146 assert!(shows_faces(1));
147 assert!(shows_faces(3));
148 assert!(!shows_faces(4));
149 }
150
151 #[test]
152 fn tooltip_lists_names_then_others() {
153 assert_eq!(tooltip_text(&["Priya Nair"]), "Priya Nair");
154 assert_eq!(tooltip_text(&["Priya Nair", "Lea"]), "Priya Nair and Lea");
155 assert_eq!(tooltip_text(&["A", "B", "C"]), "A, B and C");
156 assert_eq!(
157 tooltip_text(&["Jonas Ortega", "Tobias Klein", "C", "D", "E"]),
158 "Jonas Ortega, Tobias Klein and 3 others"
159 );
160 }
161
162 #[test]
163 fn time_label_reads_today_yesterday_or_date() {
164 let now = FixedOffset::east_opt(0)
165 .unwrap()
166 .with_ymd_and_hms(2026, 10, 8, 12, 0, 0)
167 .unwrap();
168 assert_eq!(reaction_time_label(utc(8, 1, 5), &now), "today at 01:05");
169 assert_eq!(
170 reaction_time_label(utc(7, 17, 31), &now),
171 "yesterday at 17:31"
172 );
173 assert_eq!(reaction_time_label(utc(4, 17, 31), &now), "Oct 4 at 17:31");
174 }
175
176 #[test]
177 fn tabs_appear_only_for_several_kinds() {
178 let one = vec![chip("like", vec![reactor("A", None)])];
179 assert!(reaction_tabs(&one).is_empty());
180 let two = vec![
181 chip("like", vec![reactor("A", None), reactor("B", None)]),
182 chip("heart", vec![reactor("C", None)]),
183 ];
184 let tabs = reaction_tabs(&two);
185 assert_eq!(tabs.len(), 3);
186 assert_eq!((tabs[0].glyph.clone(), tabs[0].count), (None, 3));
187 assert_eq!(tabs[1].count, 2);
188 assert_eq!(tabs[2].count, 1);
189 }
190
191 #[test]
192 fn entries_are_newest_first_and_filtered_by_tab() {
193 let chips = vec![
194 chip(
195 "like",
196 vec![
197 reactor("old", Some(utc(1, 9, 0))),
198 reactor("none", None),
199 reactor("new", Some(utc(1, 9, 0) + Duration::hours(2))),
200 ],
201 ),
202 chip("heart", vec![reactor("mid", Some(utc(1, 10, 0)))]),
203 ];
204 let names = |entries: Vec<ReactionEntry>| -> Vec<String> {
205 entries
206 .into_iter()
207 .map(|entry| entry.reactor.name)
208 .collect()
209 };
210 assert_eq!(
211 names(reaction_entries(&chips, None)),
212 ["new", "mid", "old", "none"]
213 );
214 let like = chips[0].glyph();
215 assert_eq!(
216 names(reaction_entries(&chips, Some(&like))),
217 ["new", "old", "none"]
218 );
219 }
220}