BlueGit

ict rusty-teams

Files

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

format.rs

format.rs 22.9 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/// Regions whose week starts on Sunday (CLDR first-day data for the common locales).
35const SUNDAY_FIRST_LOCALES: [&str; 13] = [
36 "en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in", "ja", "ko", "zh-tw", "he", "pt-br",
37 "es-mx", "zh-hk",
38];
39/// Arabic regions that start on Monday instead of Saturday.
40const ARABIC_MONDAY_LOCALES: [&str; 2] = ["ar-ma", "ar-tn"];
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct DateStyle {
44 day_month: &'static str,
45 day_month_year: &'static str,
46 clock: &'static str,
47 first_day: Weekday,
48}
49
50thread_local! {
51 static DATE_STYLE: Cell<Option<DateStyle>> = const { Cell::new(None) };
52}
53
54pub fn set_date_locale(locale: Option<&str>) {
55 DATE_STYLE.with(|style| style.set(locale.map(date_style)));
56}
57
58/// Teams desktop formats dates and times with the OS regional format, not the account language.
59pub fn os_regional_locale() -> Option<String> {
60 sys_locale::get_locale()
61 .as_deref()
62 .and_then(normalize_locale)
63}
64
65fn normalize_locale(raw: &str) -> Option<String> {
66 let tag = raw
67 .split(['.', '@'])
68 .next()
69 .unwrap_or_default()
70 .replace('_', "-");
71 (!tag.is_empty() && tag != "C" && tag != "POSIX").then_some(tag)
72}
73
74fn current_date_style() -> Option<DateStyle> {
75 DATE_STYLE.with(Cell::get)
76}
77
78/// First day of the week of the regional format; Monday when it is unknown.
79pub fn regional_first_day() -> Weekday {
80 current_date_style().map_or(Weekday::Mon, |style| style.first_day)
81}
82
83/// First day of the week for a locale tag such as `en-CH` (CLDR region data).
84pub fn first_day_for_locale(locale: &str) -> Weekday {
85 let locale = locale.to_ascii_lowercase().replace('_', "-");
86 let language = locale.split('-').next().unwrap_or_default().to_owned();
87 first_day_for(&locale, &language)
88}
89
90fn first_day_for(locale: &str, language: &str) -> Weekday {
91 if SUNDAY_FIRST_LOCALES.contains(&locale) || SUNDAY_FIRST_LOCALES.contains(&language) {
92 Weekday::Sun
93 } else if (language == "ar" && !ARABIC_MONDAY_LOCALES.contains(&locale)) || language == "fa" {
94 Weekday::Sat
95 } else {
96 Weekday::Mon
97 }
98}
99
100pub fn clock_format() -> &'static str {
101 current_date_style().map_or("%H:%M", |style| style.clock)
102}
103
104impl DateStyle {
105 fn month_first(&self) -> bool {
106 self.day_month.starts_with("%-m")
107 }
108
109 fn day_number(&self) -> &'static str {
110 if self.day_month.starts_with("%d") {
111 "%d"
112 } else {
113 "%-d"
114 }
115 }
116}
117
118pub fn calendar_day_number(date: NaiveDate) -> String {
119 date.format(current_date_style().map_or("%-d", |style| style.day_number()))
120 .to_string()
121}
122
123/// Month name in the app language (`calendar.month.mNN`), not chrono's English `%B`.
124pub fn month_name(date: NaiveDate) -> String {
125 crate::ui_locale::tr(&format!("calendar.month.m{:02}", date.month()))
126}
127
128/// "November 2026" / "November 2026" — month title of the month grid.
129pub fn month_year_label(date: NaiveDate) -> String {
130 format!("{} {}", month_name(date), date.year())
131}
132
133const WEEKDAY_KEYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum WeekdayWidth {
137 /// "Monday" / "Montag"
138 Full,
139 /// "Mon" / "Mo"
140 Short,
141 /// "M" / "M"
142 Letter,
143}
144
145/// Weekday name in the app language; chrono's `%A`/`%a` are always English.
146pub fn weekday_name(day: Weekday, width: WeekdayWidth) -> String {
147 let key = WEEKDAY_KEYS[day.num_days_from_monday() as usize];
148 match width {
149 WeekdayWidth::Full => crate::ui_locale::tr(&format!("calendar.weekday.{key}")),
150 WeekdayWidth::Short => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}")),
151 WeekdayWidth::Letter => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}"))
152 .chars()
153 .next()
154 .map(String::from)
155 .unwrap_or_default(),
156 }
157}
158
159pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
160 let style = current_date_style();
161 let day = |date: NaiveDate| {
162 date.format(style.map_or("%-d", |style| style.day_number()))
163 .to_string()
164 };
165 let (start_month, end_month) = (month_name(start), month_name(end));
166 if style.is_none_or(|style| style.month_first()) {
167 let to = format!("{end_month} {}, {}", day(end), end.year());
168 return if start == end {
169 to
170 } else if start.year() != end.year() {
171 format!("{start_month} {}, {} - {to}", day(start), start.year())
172 } else if start.month() != end.month() {
173 format!("{start_month} {} - {to}", day(start))
174 } else {
175 format!("{start_month} {}-{}, {}", day(start), day(end), end.year())
176 };
177 }
178 if style.is_some_and(|style| style.day_month.ends_with('.')) {
179 // German and other dotted styles: "16.–20. November 2026".
180 let to = format!("{}. {end_month} {}", day(end), end.year());
181 return if start == end {
182 to
183 } else if start.year() != end.year() {
184 format!("{}. {start_month} {} – {to}", day(start), start.year())
185 } else if start.month() != end.month() {
186 format!("{}. {start_month} – {to}", day(start))
187 } else {
188 format!("{}.–{to}", day(start))
189 };
190 }
191 let to = format!("{} {end_month}, {}", day(end), end.year());
192 if start == end {
193 to
194 } else if start.year() != end.year() {
195 format!("{} {start_month}, {} - {to}", day(start), start.year())
196 } else if start.month() != end.month() {
197 format!("{} {start_month} - {to}", day(start))
198 } else {
199 format!("{}-{to}", day(start))
200 }
201}
202
203/// Numeric day and month in the order of the account's display language, as `Intl.DateTimeFormat` does in Teams.
204pub fn date_style(locale: &str) -> DateStyle {
205 let locale = locale.to_ascii_lowercase();
206 let language = locale.split(['-', '_']).next().unwrap_or_default();
207 let twelve_hour = TWELVE_HOUR_LOCALES.contains(&locale.as_str());
208 let clock = match language {
209 _ if !twelve_hour => "%H:%M",
210 _ if locale == "en-au" || locale == "en-nz" || locale == "en-in" => "%-I:%M %P",
211 _ => "%-I:%M %p",
212 };
213 let (day_month, day_month_year) = match language {
214 _ if locale == "en-us" || locale == "en-ph" || locale == "en-ca" => {
215 ("%-m/%-d", "%-m/%-d/%Y")
216 }
217 "ja" | "zh" => ("%-m/%-d", "%Y/%-m/%-d"),
218 "nl" => ("%-d-%-m", "%-d-%-m-%Y"),
219 "sv" => ("%-d/%-m", "%Y-%m-%d"),
220 language if DOTTED_LOCALES.contains(&language) => ("%-d.%-m.", "%-d.%-m.%Y"),
221 language if PADDED_DOT_LOCALES.contains(&language) => ("%d.%m", "%d.%m.%Y"),
222 _ => ("%d/%m", "%d/%m/%Y"),
223 };
224 DateStyle {
225 day_month,
226 day_month_year,
227 clock,
228 first_day: first_day_for(&locale, language),
229 }
230}
231
232pub fn palette_index(key: &str) -> usize {
233 let mut hash: u32 = 0x811c_9dc5;
234 for byte in key.bytes() {
235 hash ^= u32::from(byte);
236 hash = hash.wrapping_mul(0x0100_0193);
237 }
238 hash as usize % theme::avatar_palette_len()
239}
240
241pub fn initials(name: &str) -> String {
242 let words: Vec<&str> = name
243 .split(|character: char| !character.is_alphanumeric())
244 .filter(|word| !word.is_empty())
245 .collect();
246 let letters: Vec<char> = match words.as_slice() {
247 [] => return "?".to_owned(),
248 [single] => single.chars().take(2).collect(),
249 [first, .., last] => first.chars().take(1).chain(last.chars().take(1)).collect(),
250 };
251 letters.into_iter().flat_map(char::to_uppercase).collect()
252}
253
254/// Teams letters a team tile from the first and last word, split at spaces and underscores, in their own case.
255pub fn team_initials(name: &str) -> String {
256 let words: Vec<&str> = name
257 .split([' ', '_'])
258 .filter(|word| word.chars().next().is_some_and(char::is_alphanumeric))
259 .collect();
260 match words.as_slice() {
261 [] => "?".to_owned(),
262 [single] => single.chars().take(1).collect(),
263 [first, .., last] => first.chars().take(1).chain(last.chars().take(1)).collect(),
264 }
265}
266
267pub fn first_name(name: &str) -> &str {
268 name.split_whitespace().next().unwrap_or(name)
269}
270
271pub fn badge_text(count: u32) -> String {
272 if count > BADGE_CAP {
273 format!("{BADGE_CAP}+")
274 } else {
275 count.to_string()
276 }
277}
278
279fn weekday_label(weekday: Weekday) -> &'static str {
280 match weekday {
281 Weekday::Mon => "Mon",
282 Weekday::Tue => "Tue",
283 Weekday::Wed => "Wed",
284 Weekday::Thu => "Thu",
285 Weekday::Fri => "Fri",
286 Weekday::Sat => "Sat",
287 Weekday::Sun => "Sun",
288 }
289}
290
291pub fn file_size_label(bytes: u64) -> String {
292 const KIB: f64 = 1024.;
293 let value = bytes as f64;
294 if value < KIB {
295 format!("{bytes} B")
296 } else if value < KIB * KIB {
297 format!("{:.0} KB", value / KIB)
298 } else {
299 format!("{:.1} MB", value / (KIB * KIB))
300 }
301}
302
303pub fn short_version(build_id: &str, package_version: &str) -> String {
304 let commit = build_id.split('-').next().unwrap_or(build_id);
305 format!("v{package_version} ({commit})")
306}
307
308pub fn list_time_label(time: DateTime<Utc>, today: NaiveDate, offset: impl Into<Zone>) -> String {
309 list_time_label_in(current_date_style(), time, today, offset)
310}
311
312pub fn list_time_label_in(
313 style: Option<DateStyle>,
314 time: DateTime<Utc>,
315 today: NaiveDate,
316 offset: impl Into<Zone>,
317) -> String {
318 let local = offset.into().at(time);
319 let day = local.date_naive();
320 let days_ago = (today - day).num_days();
321 if days_ago <= 0 {
322 local
323 .format(style.map_or("%H:%M", |style| style.clock))
324 .to_string()
325 } else if days_ago <= WEEKDAY_WINDOW_DAYS {
326 weekday_label(local.weekday()).to_owned()
327 } else {
328 local
329 .format(style.map_or("%b %-d", |style| style.day_month))
330 .to_string()
331 }
332}
333
334/// The last activity next to a channel name: the time today, else day and month, with the year once older.
335pub fn channel_time_label(
336 time: DateTime<Utc>,
337 today: NaiveDate,
338 offset: impl Into<Zone>,
339) -> String {
340 channel_time_label_in(current_date_style(), time, today, offset)
341}
342
343pub fn channel_time_label_in(
344 style: Option<DateStyle>,
345 time: DateTime<Utc>,
346 today: NaiveDate,
347 offset: impl Into<Zone>,
348) -> String {
349 let local = offset.into().at(time);
350 let pattern = if local.date_naive() >= today {
351 style.map_or("%H:%M", |style| style.clock)
352 } else if local.year() == today.year() {
353 style.map_or("%b %-d", |style| style.day_month)
354 } else {
355 style.map_or("%b %-d, %Y", |style| style.day_month_year)
356 };
357 local.format(pattern).to_string()
358}
359
360pub fn post_time_label(time: DateTime<Utc>, today: NaiveDate, offset: impl Into<Zone>) -> String {
361 post_time_label_in(current_date_style(), time, today, offset)
362}
363
364pub fn post_time_label_in(
365 style: Option<DateStyle>,
366 time: DateTime<Utc>,
367 today: NaiveDate,
368 offset: impl Into<Zone>,
369) -> String {
370 let local = offset.into().at(time);
371 let day = local.date_naive();
372 let days_ago = (today - day).num_days();
373 let clock = local.format(style.map_or("%H:%M", |style| style.clock));
374 let same_year = day.year() == today.year();
375 if days_ago <= 0 {
376 clock.to_string()
377 } else if days_ago == 1 {
378 format!("Yesterday {clock}")
379 } else if days_ago <= WEEKDAY_WINDOW_DAYS {
380 format!("{} {clock}", weekday_label(local.weekday()))
381 } else if let Some(style) = style {
382 let date = if same_year {
383 style.day_month
384 } else {
385 style.day_month_year
386 };
387 format!("{} {clock}", local.format(date))
388 } else if same_year {
389 format!("{} {clock}", local.format("%b %-d"))
390 } else {
391 format!("{} {clock}", local.format("%b %-d, %Y"))
392 }
393}
394
395pub fn day_label(day: NaiveDate, today: NaiveDate) -> String {
396 if day == today {
397 "Today".to_owned()
398 } else if today.pred_opt() == Some(day) {
399 "Yesterday".to_owned()
400 } else {
401 format!(
402 "{}, {}",
403 weekday_label(day.weekday()),
404 day.format("%b %-d, %Y")
405 )
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use chrono::TimeZone;
412
413 use super::*;
414
415 #[test]
416 fn the_first_day_of_week_follows_the_region() {
417 let first = |locale| {
418 set_date_locale(Some(locale));
419 regional_first_day()
420 };
421 assert_eq!(first("en-US"), Weekday::Sun);
422 assert_eq!(first("de-CH"), Weekday::Mon);
423 assert_eq!(first("en-GB"), Weekday::Mon);
424 assert_eq!(first("ar-SA"), Weekday::Sat);
425 assert_eq!(first("ar-MA"), Weekday::Mon);
426 assert_eq!(first("ja-JP"), Weekday::Sun);
427 assert_eq!(first_day_for_locale("en-CH"), Weekday::Mon);
428 assert_eq!(first_day_for_locale("en_US"), Weekday::Sun);
429 set_date_locale(None);
430 assert_eq!(regional_first_day(), Weekday::Mon);
431 }
432
433 #[test]
434 fn calendar_names_follow_the_app_language() {
435 let _guard = crate::ui_locale::locale_test_lock();
436 let date = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
437 rust_i18n::set_locale("de");
438 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Montag");
439 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Short), "Do");
440 assert_eq!(weekday_name(Weekday::Sun, WeekdayWidth::Letter), "S");
441 assert_eq!(month_year_label(date), "November 2026");
442 assert_eq!(
443 month_name(NaiveDate::from_ymd_opt(2026, 3, 1).unwrap()),
444 "März"
445 );
446 rust_i18n::set_locale("en");
447 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Monday");
448 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Letter), "T");
449 }
450
451 #[test]
452 fn calendar_range_reads_german_with_dots() {
453 let _guard = crate::ui_locale::locale_test_lock();
454 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
455 rust_i18n::set_locale("de");
456 set_date_locale(Some("de-CH"));
457 assert_eq!(
458 calendar_range_label(date(11, 16), date(11, 20)),
459 "16.–20. November 2026"
460 );
461 assert_eq!(
462 calendar_range_label(date(11, 30), date(12, 4)),
463 "30. November – 4. Dezember 2026"
464 );
465 assert_eq!(
466 calendar_range_label(date(11, 16), date(11, 16)),
467 "16. November 2026"
468 );
469 rust_i18n::set_locale("en");
470 set_date_locale(None);
471 }
472
473 #[test]
474 fn calendar_range_follows_the_account_locale() {
475 let _guard = crate::ui_locale::locale_test_lock();
476 rust_i18n::set_locale("en");
477 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
478 set_date_locale(Some("en-GB"));
479 assert_eq!(
480 calendar_range_label(date(11, 9), date(11, 15)),
481 "09-15 November, 2026"
482 );
483 assert_eq!(
484 calendar_range_label(date(11, 30), date(12, 4)),
485 "30 November - 04 December, 2026"
486 );
487 assert_eq!(calendar_day_number(date(11, 9)), "09");
488 set_date_locale(Some("en-US"));
489 assert_eq!(
490 calendar_range_label(date(11, 9), date(11, 13)),
491 "November 9-13, 2026"
492 );
493 assert_eq!(calendar_day_number(date(11, 9)), "9");
494 // Intl.DateTimeFormat in de-DE writes the day with a dot and no comma.
495 set_date_locale(Some("de-DE"));
496 assert_eq!(
497 calendar_range_label(date(11, 9), date(11, 9)),
498 "9. November 2026"
499 );
500 set_date_locale(None);
501 }
502
503 #[test]
504 fn team_tiles_letter_first_and_last_word_like_teams() {
505 assert_eq!(team_initials("e_IT-Support"), "eI");
506 assert_eq!(team_initials("e_ComponentLibrary"), "eC");
507 assert_eq!(team_initials("e_Human Resources"), "eR");
508 assert_eq!(team_initials("e_NLP / AI"), "eA");
509 assert_eq!(team_initials("Platform"), "P");
510 assert_eq!(team_initials(""), "?");
511 }
512
513 #[test]
514 fn os_locale_names_become_language_tags() {
515 assert_eq!(normalize_locale("en-GB").as_deref(), Some("en-GB"));
516 assert_eq!(normalize_locale("en_GB.UTF-8").as_deref(), Some("en-GB"));
517 assert_eq!(normalize_locale("de_DE@euro").as_deref(), Some("de-DE"));
518 assert_eq!(normalize_locale("C"), None);
519 assert_eq!(normalize_locale("POSIX"), None);
520 assert_eq!(normalize_locale(""), None);
521 }
522
523 #[test]
524 fn the_clock_follows_the_display_language() {
525 set_date_locale(Some("en-US"));
526 assert_eq!(clock_format(), "%-I:%M %p");
527 set_date_locale(Some("de-DE"));
528 assert_eq!(clock_format(), "%H:%M");
529 set_date_locale(None);
530 assert_eq!(clock_format(), "%H:%M");
531 }
532
533 fn utc(day: u32, hour: u32) -> DateTime<Utc> {
534 Utc.with_ymd_and_hms(2026, 10, day, hour, 5, 0).unwrap()
535 }
536
537 fn today() -> NaiveDate {
538 NaiveDate::from_ymd_opt(2026, 10, 7).unwrap()
539 }
540
541 fn zero() -> FixedOffset {
542 FixedOffset::east_opt(0).unwrap()
543 }
544
545 #[test]
546 fn channel_times_show_the_clock_today_then_day_and_month_then_the_year() {
547 let style = Some(date_style("en-gb"));
548 let label = |time| channel_time_label_in(style, time, today(), zero());
549 assert_eq!(label(utc(7, 8)), "08:05");
550 assert_eq!(label(utc(1, 8)), "01/10");
551 assert_eq!(
552 label(Utc.with_ymd_and_hms(2025, 10, 23, 8, 0, 0).unwrap()),
553 "23/10/2025"
554 );
555 }
556
557 #[test]
558 fn palette_index_is_stable_and_in_range() {
559 assert_eq!(palette_index("user-1"), palette_index("user-1"));
560 for key in [
561 "a",
562 "b",
563 "demo-ada",
564 "",
565 "00000000-0000-0000-0000-000000000001",
566 ] {
567 assert!(palette_index(key) < theme::avatar_palette_len());
568 }
569 }
570
571 #[test]
572 fn palette_index_spreads_over_several_colors() {
573 let used: std::collections::HashSet<usize> = (0..40)
574 .map(|number| palette_index(&format!("user-{number}")))
575 .collect();
576 assert!(used.len() >= 4);
577 }
578
579 #[test]
580 fn initials_use_first_and_last_word() {
581 assert_eq!(initials("Mara Lindqvist"), "ML");
582 assert_eq!(initials("Ada"), "AD");
583 assert_eq!(initials("anna maria von Berg"), "AB");
584 assert_eq!(initials(" "), "?");
585 assert_eq!(initials("Release planning"), "RP");
586 }
587
588 #[test]
589 fn first_name_takes_the_first_word() {
590 assert_eq!(first_name("Priya Nair"), "Priya");
591 assert_eq!(first_name("Priya"), "Priya");
592 }
593
594 #[test]
595 fn file_sizes_use_binary_units() {
596 assert_eq!(file_size_label(900), "900 B");
597 assert_eq!(file_size_label(48_213), "47 KB");
598 assert_eq!(file_size_label(5 * 1024 * 1024 + 300_000), "5.3 MB");
599 }
600
601 #[test]
602 fn badge_caps_at_99_plus() {
603 assert_eq!(badge_text(1), "1");
604 assert_eq!(badge_text(99), "99");
605 assert_eq!(badge_text(100), "99+");
606 assert_eq!(badge_text(4000), "99+");
607 }
608
609 #[test]
610 fn list_time_is_clock_today_weekday_this_week_date_before() {
611 assert_eq!(list_time_label(utc(7, 13), today(), zero()), "13:05");
612 assert_eq!(list_time_label(utc(5, 13), today(), zero()), "Mon");
613 assert_eq!(list_time_label(utc(6, 9), today(), zero()), "Tue");
614 assert_eq!(list_time_label(utc(1, 13), today(), zero()), "Thu");
615 let september = Utc.with_ymd_and_hms(2026, 9, 30, 13, 0, 0).unwrap();
616 assert_eq!(list_time_label(september, today(), zero()), "Sep 30");
617 }
618
619 #[test]
620 fn list_time_respects_the_offset_for_the_day_boundary() {
621 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
622 assert_eq!(list_time_label(utc(6, 23), today(), plus_two), "01:05");
623 }
624
625 #[test]
626 fn short_version_keeps_the_commit_only() {
627 assert_eq!(
628 short_version("687e2dc-20261007T124355Z", "0.1.0"),
629 "v0.1.0 (687e2dc)"
630 );
631 assert_eq!(short_version("dev", "0.1.0"), "v0.1.0 (dev)");
632 }
633
634 #[test]
635 fn post_time_adds_the_day_when_not_today() {
636 assert_eq!(post_time_label(utc(7, 13), today(), zero()), "13:05");
637 assert_eq!(
638 post_time_label(utc(6, 9), today(), zero()),
639 "Yesterday 09:05"
640 );
641 assert_eq!(post_time_label(utc(5, 13), today(), zero()), "Mon 13:05");
642 let september = Utc.with_ymd_and_hms(2026, 9, 30, 8, 42, 0).unwrap();
643 assert_eq!(post_time_label(september, today(), zero()), "Sep 30 08:42");
644 let last_year = Utc.with_ymd_and_hms(2020, 5, 22, 8, 42, 0).unwrap();
645 assert_eq!(
646 post_time_label(last_year, today(), zero()),
647 "May 22, 2020 08:42"
648 );
649 }
650
651 #[test]
652 fn post_time_follows_the_display_language_like_teams() {
653 let september = Utc.with_ymd_and_hms(2026, 9, 24, 20, 54, 0).unwrap();
654 let label =
655 |locale: &str| post_time_label_in(Some(date_style(locale)), september, today(), zero());
656 assert_eq!(label("en-GB"), "24/09 20:54");
657 assert_eq!(label("de-DE"), "24.9. 20:54");
658 assert_eq!(label("en-US"), "9/24 8:54 PM");
659 let last_year = Utc.with_ymd_and_hms(2020, 5, 2, 8, 42, 0).unwrap();
660 assert_eq!(
661 post_time_label_in(Some(date_style("en-GB")), last_year, today(), zero()),
662 "02/05/2020 08:42"
663 );
664 }
665
666 #[test]
667 fn list_time_follows_the_display_language_like_teams() {
668 let september = Utc.with_ymd_and_hms(2026, 9, 24, 20, 54, 0).unwrap();
669 let style = Some(date_style("en-GB"));
670 assert_eq!(
671 list_time_label_in(style, september, today(), zero()),
672 "24/09"
673 );
674 assert_eq!(
675 list_time_label_in(style, utc(7, 13), today(), zero()),
676 "13:05"
677 );
678 }
679
680 #[test]
681 fn day_labels() {
682 assert_eq!(day_label(today(), today()), "Today");
683 assert_eq!(day_label(today().pred_opt().unwrap(), today()), "Yesterday");
684 assert_eq!(
685 day_label(NaiveDate::from_ymd_opt(2026, 10, 1).unwrap(), today()),
686 "Thu, Oct 1, 2026"
687 );
688 }
689}