BlueGit

ict rusty-teams

Files

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

format.rs

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