BlueGit

ict rusty-teams

Files

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

reaction_model.rs

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