| 1 | //! Regional format on `AppState`: the saved choice and the date style every label reads. |
| 2 | |
| 3 | use app_base::regional::{self, FormatSources, RegionalPrefs, SystemFormat}; |
| 4 | use gpui_kit::Context; |
| 5 | use store::Store; |
| 6 | |
| 7 | use crate::app_state::AppState; |
| 8 | use crate::call::calendar_prefs::{CALENDAR_PREFS_KEY, CalendarPrefs}; |
| 9 | use crate::format::{self, DateStyle}; |
| 10 | |
| 11 | /// The saved choice. Before the first save, a first day set in the calendar settings carries over. |
| 12 | pub(crate) fn load_regional_prefs(store: &Store) -> RegionalPrefs { |
| 13 | if let Some(prefs) = regional::load(store) { |
| 14 | return prefs; |
| 15 | } |
| 16 | let first_day = store |
| 17 | .meta(CALENDAR_PREFS_KEY) |
| 18 | .ok() |
| 19 | .flatten() |
| 20 | .as_deref() |
| 21 | .and_then(CalendarPrefs::legacy_first_day); |
| 22 | let prefs = RegionalPrefs { |
| 23 | first_day, |
| 24 | ..RegionalPrefs::default() |
| 25 | }; |
| 26 | if first_day.is_some() { |
| 27 | regional::save(store, &prefs); |
| 28 | } |
| 29 | prefs |
| 30 | } |
| 31 | |
| 32 | impl AppState { |
| 33 | /// The style `prefs` resolve to with the OS, account and mailbox as they are now. |
| 34 | pub fn regional_style(&self, prefs: &RegionalPrefs, system: &SystemFormat) -> DateStyle { |
| 35 | let display_locale = self |
| 36 | .translation |
| 37 | .settings |
| 38 | .as_ref() |
| 39 | .and_then(|settings| settings.display_locale.as_deref()); |
| 40 | regional::resolve( |
| 41 | prefs, |
| 42 | FormatSources { |
| 43 | system, |
| 44 | display_locale, |
| 45 | mailbox_locale: self.calendar_prefs.mailbox_locale.as_deref(), |
| 46 | }, |
| 47 | ) |
| 48 | } |
| 49 | |
| 50 | /// Set the date style that labels read; call after any of its sources changed. |
| 51 | pub fn apply_regional_format(&self) { |
| 52 | let style = self.regional_style(&self.regional_prefs, &SystemFormat::read()); |
| 53 | format::set_date_style(Some(style)); |
| 54 | } |
| 55 | |
| 56 | pub fn set_regional_prefs(&mut self, prefs: RegionalPrefs, cx: &mut Context<Self>) { |
| 57 | if prefs == self.regional_prefs { |
| 58 | return; |
| 59 | } |
| 60 | self.regional_prefs = prefs; |
| 61 | regional::save(&self.store, &prefs); |
| 62 | self.apply_regional_format(); |
| 63 | self.reanchor_calendar(cx); |
| 64 | cx.notify(); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | #[cfg(test)] |
| 69 | mod tests { |
| 70 | use chrono::Weekday; |
| 71 | |
| 72 | use super::*; |
| 73 | |
| 74 | #[test] |
| 75 | fn the_calendar_first_day_carries_over_once() { |
| 76 | let store = Store::open_in_memory().unwrap(); |
| 77 | store |
| 78 | .set_meta(CALENDAR_PREFS_KEY, r#"{"first_day":"Sat"}"#) |
| 79 | .unwrap(); |
| 80 | assert_eq!(load_regional_prefs(&store).first_day, Some(Weekday::Sat)); |
| 81 | store.set_meta(CALENDAR_PREFS_KEY, "{}").unwrap(); |
| 82 | assert_eq!(load_regional_prefs(&store).first_day, Some(Weekday::Sat)); |
| 83 | } |
| 84 | } |