BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / format.rs

format.rs

8675fa6c History
format.rs 12.0 KiB Download Raw
1use std::cell::Cell;
2
3use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, Utc, Weekday};
4
5use crate::theme;
6
7const BADGE_CAP: u32 = 99;
8const WEEKDAY_WINDOW_DAYS: i64 = 6;
9const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
10const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
11const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct DateStyle {
15 day_month: &'static str,
16 day_month_year: &'static str,
17 clock: &'static str,
18}
19
20thread_local! {
21 static DATE_STYLE: Cell<Option<DateStyle>> = const { Cell::new(None) };
22}
23
24pub fn set_date_locale(locale: Option<&str>) {
25 DATE_STYLE.with(|style| style.set(locale.map(date_style)));
26}
27
28fn current_date_style() -> Option<DateStyle> {
29 DATE_STYLE.with(Cell::get)
30}
31
32/// Numeric day and month in the order of the account's display language, as `Intl.DateTimeFormat` does in Teams.
33pub fn date_style(locale: &str) -> DateStyle {
34 let locale = locale.to_ascii_lowercase();
35 let language = locale.split(['-', '_']).next().unwrap_or_default();
36 let twelve_hour = TWELVE_HOUR_LOCALES.contains(&locale.as_str());
37 let clock = match language {
38 _ if !twelve_hour => "%H:%M",
39 _ if locale == "en-au" || locale == "en-nz" || locale == "en-in" => "%-I:%M %P",
40 _ => "%-I:%M %p",
41 };
42 let (day_month, day_month_year) = match language {
43 _ if locale == "en-us" || locale == "en-ph" || locale == "en-ca" => ("%-m/%-d", "%-m/%-d/%Y"),
44 "ja" | "zh" => ("%-m/%-d", "%Y/%-m/%-d"),
45 "nl" => ("%-d-%-m", "%-d-%-m-%Y"),
46 "sv" => ("%-d/%-m", "%Y-%m-%d"),
47 language if DOTTED_LOCALES.contains(&language) => ("%-d.%-m.", "%-d.%-m.%Y"),
48 language if PADDED_DOT_LOCALES.contains(&language) => ("%d.%m", "%d.%m.%Y"),
49 _ => ("%d/%m", "%d/%m/%Y"),
50 };
51 DateStyle {
52 day_month,
53 day_month_year,
54 clock,
55 }
56}
57
58pub fn palette_index(key: &str) -> usize {
59 let mut hash: u32 = 0x811c_9dc5;
60 for byte in key.bytes() {
61 hash ^= u32::from(byte);
62 hash = hash.wrapping_mul(0x0100_0193);
63 }
64 hash as usize % theme::avatar_palette_len()
65}
66
67pub fn initials(name: &str) -> String {
68 let words: Vec<&str> = name
69 .split(|character: char| !character.is_alphanumeric())
70 .filter(|word| !word.is_empty())
71 .collect();
72 let letters: Vec<char> = match words.as_slice() {
73 [] => return "?".to_owned(),
74 [single] => single.chars().take(2).collect(),
75 [first, .., last] => first.chars().take(1).chain(last.chars().take(1)).collect(),
76 };
77 letters.into_iter().flat_map(char::to_uppercase).collect()
78}
79
80pub fn first_name(name: &str) -> &str {
81 name.split_whitespace().next().unwrap_or(name)
82}
83
84pub fn badge_text(count: u32) -> String {
85 if count > BADGE_CAP {
86 format!("{BADGE_CAP}+")
87 } else {
88 count.to_string()
89 }
90}
91
92fn weekday_label(weekday: Weekday) -> &'static str {
93 match weekday {
94 Weekday::Mon => "Mon",
95 Weekday::Tue => "Tue",
96 Weekday::Wed => "Wed",
97 Weekday::Thu => "Thu",
98 Weekday::Fri => "Fri",
99 Weekday::Sat => "Sat",
100 Weekday::Sun => "Sun",
101 }
102}
103
104pub fn file_size_label(bytes: u64) -> String {
105 const KIB: f64 = 1024.;
106 let value = bytes as f64;
107 if value < KIB {
108 format!("{bytes} B")
109 } else if value < KIB * KIB {
110 format!("{:.0} KB", value / KIB)
111 } else {
112 format!("{:.1} MB", value / (KIB * KIB))
113 }
114}
115
116pub fn short_version(build_id: &str, package_version: &str) -> String {
117 let commit = build_id.split('-').next().unwrap_or(build_id);
118 format!("v{package_version} ({commit})")
119}
120
121pub fn list_time_label(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> String {
122 list_time_label_in(current_date_style(), time, today, offset)
123}
124
125pub fn list_time_label_in(
126 style: Option<DateStyle>,
127 time: DateTime<Utc>,
128 today: NaiveDate,
129 offset: FixedOffset,
130) -> String {
131 let local = time.with_timezone(&offset);
132 let day = local.date_naive();
133 let days_ago = (today - day).num_days();
134 if days_ago <= 0 {
135 local.format(style.map_or("%H:%M", |style| style.clock)).to_string()
136 } else if days_ago <= WEEKDAY_WINDOW_DAYS {
137 weekday_label(local.weekday()).to_owned()
138 } else {
139 local
140 .format(style.map_or("%b %-d", |style| style.day_month))
141 .to_string()
142 }
143}
144
145/// The last activity next to a channel name: the time today, else day and month, with the year once older.
146pub fn channel_time_label(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> String {
147 channel_time_label_in(current_date_style(), time, today, offset)
148}
149
150pub fn channel_time_label_in(
151 style: Option<DateStyle>,
152 time: DateTime<Utc>,
153 today: NaiveDate,
154 offset: FixedOffset,
155) -> String {
156 let local = time.with_timezone(&offset);
157 let pattern = if local.date_naive() >= today {
158 style.map_or("%H:%M", |style| style.clock)
159 } else if local.year() == today.year() {
160 style.map_or("%b %-d", |style| style.day_month)
161 } else {
162 style.map_or("%b %-d, %Y", |style| style.day_month_year)
163 };
164 local.format(pattern).to_string()
165}
166
167pub fn post_time_label(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> String {
168 post_time_label_in(current_date_style(), time, today, offset)
169}
170
171pub fn post_time_label_in(
172 style: Option<DateStyle>,
173 time: DateTime<Utc>,
174 today: NaiveDate,
175 offset: FixedOffset,
176) -> String {
177 let local = time.with_timezone(&offset);
178 let day = local.date_naive();
179 let days_ago = (today - day).num_days();
180 let clock = local.format(style.map_or("%H:%M", |style| style.clock));
181 let same_year = day.year() == today.year();
182 if days_ago <= 0 {
183 clock.to_string()
184 } else if days_ago == 1 {
185 format!("Yesterday {clock}")
186 } else if days_ago <= WEEKDAY_WINDOW_DAYS {
187 format!("{} {clock}", weekday_label(local.weekday()))
188 } else if let Some(style) = style {
189 let date = if same_year {
190 style.day_month
191 } else {
192 style.day_month_year
193 };
194 format!("{} {clock}", local.format(date))
195 } else if same_year {
196 format!("{} {clock}", local.format("%b %-d"))
197 } else {
198 format!("{} {clock}", local.format("%b %-d, %Y"))
199 }
200}
201
202pub fn day_label(day: NaiveDate, today: NaiveDate) -> String {
203 if day == today {
204 "Today".to_owned()
205 } else if today.pred_opt() == Some(day) {
206 "Yesterday".to_owned()
207 } else {
208 format!(
209 "{}, {}",
210 weekday_label(day.weekday()),
211 day.format("%b %-d, %Y")
212 )
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use chrono::TimeZone;
219
220 use super::*;
221
222 fn utc(day: u32, hour: u32) -> DateTime<Utc> {
223 Utc.with_ymd_and_hms(2026, 10, day, hour, 5, 0).unwrap()
224 }
225
226 fn today() -> NaiveDate {
227 NaiveDate::from_ymd_opt(2026, 10, 7).unwrap()
228 }
229
230 fn zero() -> FixedOffset {
231 FixedOffset::east_opt(0).unwrap()
232 }
233
234 #[test]
235 fn channel_times_show_the_clock_today_then_day_and_month_then_the_year() {
236 let style = Some(date_style("en-gb"));
237 let label = |time| channel_time_label_in(style, time, today(), zero());
238 assert_eq!(label(utc(7, 8)), "08:05");
239 assert_eq!(label(utc(1, 8)), "01/10");
240 assert_eq!(
241 label(Utc.with_ymd_and_hms(2025, 10, 23, 8, 0, 0).unwrap()),
242 "23/10/2025"
243 );
244 }
245
246 #[test]
247 fn palette_index_is_stable_and_in_range() {
248 assert_eq!(palette_index("user-1"), palette_index("user-1"));
249 for key in [
250 "a",
251 "b",
252 "demo-ada",
253 "",
254 "00000000-0000-0000-0000-000000000001",
255 ] {
256 assert!(palette_index(key) < theme::avatar_palette_len());
257 }
258 }
259
260 #[test]
261 fn palette_index_spreads_over_several_colors() {
262 let used: std::collections::HashSet<usize> = (0..40)
263 .map(|number| palette_index(&format!("user-{number}")))
264 .collect();
265 assert!(used.len() >= 4);
266 }
267
268 #[test]
269 fn initials_use_first_and_last_word() {
270 assert_eq!(initials("Mara Lindqvist"), "ML");
271 assert_eq!(initials("Ada"), "AD");
272 assert_eq!(initials("anna maria von Berg"), "AB");
273 assert_eq!(initials(" "), "?");
274 assert_eq!(initials("Release planning"), "RP");
275 }
276
277 #[test]
278 fn first_name_takes_the_first_word() {
279 assert_eq!(first_name("Priya Nair"), "Priya");
280 assert_eq!(first_name("Priya"), "Priya");
281 }
282
283 #[test]
284 fn file_sizes_use_binary_units() {
285 assert_eq!(file_size_label(900), "900 B");
286 assert_eq!(file_size_label(48_213), "47 KB");
287 assert_eq!(file_size_label(5 * 1024 * 1024 + 300_000), "5.3 MB");
288 }
289
290 #[test]
291 fn badge_caps_at_99_plus() {
292 assert_eq!(badge_text(1), "1");
293 assert_eq!(badge_text(99), "99");
294 assert_eq!(badge_text(100), "99+");
295 assert_eq!(badge_text(4000), "99+");
296 }
297
298 #[test]
299 fn list_time_is_clock_today_weekday_this_week_date_before() {
300 assert_eq!(list_time_label(utc(7, 13), today(), zero()), "13:05");
301 assert_eq!(list_time_label(utc(5, 13), today(), zero()), "Mon");
302 assert_eq!(list_time_label(utc(6, 9), today(), zero()), "Tue");
303 assert_eq!(list_time_label(utc(1, 13), today(), zero()), "Thu");
304 let september = Utc.with_ymd_and_hms(2026, 9, 30, 13, 0, 0).unwrap();
305 assert_eq!(list_time_label(september, today(), zero()), "Sep 30");
306 }
307
308 #[test]
309 fn list_time_respects_the_offset_for_the_day_boundary() {
310 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
311 assert_eq!(list_time_label(utc(6, 23), today(), plus_two), "01:05");
312 }
313
314 #[test]
315 fn short_version_keeps_the_commit_only() {
316 assert_eq!(
317 short_version("687e2dc-20261007T124355Z", "0.1.0"),
318 "v0.1.0 (687e2dc)"
319 );
320 assert_eq!(short_version("dev", "0.1.0"), "v0.1.0 (dev)");
321 }
322
323 #[test]
324 fn post_time_adds_the_day_when_not_today() {
325 assert_eq!(post_time_label(utc(7, 13), today(), zero()), "13:05");
326 assert_eq!(
327 post_time_label(utc(6, 9), today(), zero()),
328 "Yesterday 09:05"
329 );
330 assert_eq!(post_time_label(utc(5, 13), today(), zero()), "Mon 13:05");
331 let september = Utc.with_ymd_and_hms(2026, 9, 30, 8, 42, 0).unwrap();
332 assert_eq!(post_time_label(september, today(), zero()), "Sep 30 08:42");
333 let last_year = Utc.with_ymd_and_hms(2020, 5, 22, 8, 42, 0).unwrap();
334 assert_eq!(
335 post_time_label(last_year, today(), zero()),
336 "May 22, 2020 08:42"
337 );
338 }
339
340 #[test]
341 fn post_time_follows_the_display_language_like_teams() {
342 let september = Utc.with_ymd_and_hms(2026, 9, 24, 20, 54, 0).unwrap();
343 let label = |locale: &str| {
344 post_time_label_in(Some(date_style(locale)), september, today(), zero())
345 };
346 assert_eq!(label("en-GB"), "24/09 20:54");
347 assert_eq!(label("de-DE"), "24.9. 20:54");
348 assert_eq!(label("en-US"), "9/24 8:54 PM");
349 let last_year = Utc.with_ymd_and_hms(2020, 5, 2, 8, 42, 0).unwrap();
350 assert_eq!(
351 post_time_label_in(Some(date_style("en-GB")), last_year, today(), zero()),
352 "02/05/2020 08:42"
353 );
354 }
355
356 #[test]
357 fn list_time_follows_the_display_language_like_teams() {
358 let september = Utc.with_ymd_and_hms(2026, 9, 24, 20, 54, 0).unwrap();
359 let style = Some(date_style("en-GB"));
360 assert_eq!(list_time_label_in(style, september, today(), zero()), "24/09");
361 assert_eq!(list_time_label_in(style, utc(7, 13), today(), zero()), "13:05");
362 }
363
364 #[test]
365 fn day_labels() {
366 assert_eq!(day_label(today(), today()), "Today");
367 assert_eq!(day_label(today().pred_opt().unwrap(), today()), "Yesterday");
368 assert_eq!(
369 day_label(NaiveDate::from_ymd_opt(2026, 10, 1).unwrap(), today()),
370 "Thu, Oct 1, 2026"
371 );
372 }
373}