BlueGit

ict rusty-teams

Files

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

format.rs

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