BlueGit

ict rusty-teams

Files

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

reaction_model.rs

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