BlueGit

ict rusty-teams

Files

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

format.rs

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