BlueGit

ict rusty-teams

Files

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

format.rs

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