BlueGit

ict rusty-teams

Files

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

format.rs

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