BlueGit

ict rusty-teams

Files

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

reaction_model.rs

fb874ac1 History
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 click_glyph: crate::rows::reaction_glyph(reaction_type),
133 count: reactors.len(),
134 mine: false,
135 reactors,
136 }
137 }
138
139 fn utc(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
140 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0)
141 .unwrap()
142 }
143
144 #[test]
145 fn faces_show_up_to_three_people_then_a_count() {
146 assert!(!shows_faces(0));
147 assert!(shows_faces(1));
148 assert!(shows_faces(3));
149 assert!(!shows_faces(4));
150 }
151
152 #[test]
153 fn tooltip_lists_names_then_others() {
154 assert_eq!(tooltip_text(&["Priya Nair"]), "Priya Nair");
155 assert_eq!(tooltip_text(&["Priya Nair", "Lea"]), "Priya Nair and Lea");
156 assert_eq!(tooltip_text(&["A", "B", "C"]), "A, B and C");
157 assert_eq!(
158 tooltip_text(&["Jonas Ortega", "Tobias Klein", "C", "D", "E"]),
159 "Jonas Ortega, Tobias Klein and 3 others"
160 );
161 }
162
163 #[test]
164 fn time_label_reads_today_yesterday_or_date() {
165 let now = FixedOffset::east_opt(0)
166 .unwrap()
167 .with_ymd_and_hms(2026, 10, 8, 12, 0, 0)
168 .unwrap();
169 assert_eq!(reaction_time_label(utc(8, 1, 5), &now), "today at 01:05");
170 assert_eq!(
171 reaction_time_label(utc(7, 17, 31), &now),
172 "yesterday at 17:31"
173 );
174 assert_eq!(reaction_time_label(utc(4, 17, 31), &now), "Oct 4 at 17:31");
175 }
176
177 #[test]
178 fn tabs_appear_only_for_several_kinds() {
179 let one = vec![chip("like", vec![reactor("A", None)])];
180 assert!(reaction_tabs(&one).is_empty());
181 let two = vec![
182 chip("like", vec![reactor("A", None), reactor("B", None)]),
183 chip("heart", vec![reactor("C", None)]),
184 ];
185 let tabs = reaction_tabs(&two);
186 assert_eq!(tabs.len(), 3);
187 assert_eq!((tabs[0].glyph.clone(), tabs[0].count), (None, 3));
188 assert_eq!(tabs[1].count, 2);
189 assert_eq!(tabs[2].count, 1);
190 }
191
192 #[test]
193 fn entries_are_newest_first_and_filtered_by_tab() {
194 let chips = vec![
195 chip(
196 "like",
197 vec![
198 reactor("old", Some(utc(1, 9, 0))),
199 reactor("none", None),
200 reactor("new", Some(utc(1, 9, 0) + Duration::hours(2))),
201 ],
202 ),
203 chip("heart", vec![reactor("mid", Some(utc(1, 10, 0)))]),
204 ];
205 let names = |entries: Vec<ReactionEntry>| -> Vec<String> {
206 entries
207 .into_iter()
208 .map(|entry| entry.reactor.name)
209 .collect()
210 };
211 assert_eq!(
212 names(reaction_entries(&chips, None)),
213 ["new", "mid", "old", "none"]
214 );
215 let like = chips[0].glyph();
216 assert_eq!(
217 names(reaction_entries(&chips, Some(&like))),
218 ["new", "old", "none"]
219 );
220 }
221}