BlueGit

ict rusty-teams

Files

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

format.rs

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