BlueGit

ict rusty-teams

Files

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

format.rs

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