BlueGit

ict rusty-teams

feat(calendar): calendar preferences, mailbox work hours, week layout

- calendar.prefs meta: default view (Last used by default), last span,
  first-day override, time scale, weekend Work week, pane and group state
- work days and hours come from the Outlook mailbox
  (/me/mailboxSettings, MailboxSettings.ReadWrite) and are written back
  there; a failed write restores the previous value with a notice
- first day of week defaults to the regional format
- week_grid takes a WeekLayout: first day, work days (Work week shows
  only them, gaps allowed), next/this week on a day off; the grid draws
  a date list instead of start + count
- month names, weekday names and range labels follow the app language
- the span chosen from the view menu survives a restart; a day opened
  from a month cell does not change it

Deviation from 'save where Teams saves': first day of week and time
scale stay local, Teams keeps them in OWA options that Graph cannot
reach (decision note follows with the settings page).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Joachim Mild · pushed by metis

Authored 2026-11-15 · 2 weeks ago

Hash
04540699eb13bc7ac95fc5da7d34d853b6eb323b
Parent
51d4be66
15 files changed +1086 −159
crates/app-base/src/format.rs +109 −11
@@ -31,12 +31,20 @@ const WEEKDAY_WINDOW_DAYS: i64 = 6;
31 31 const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
32 32 const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
33 33 const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
34 /// Regions whose week starts on Sunday (CLDR first-day data for the common locales).
35 const 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.
40 const ARABIC_MONDAY_LOCALES: [&str; 2] = ["ar-ma", "ar-tn"];
34 41
35 42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36 43 pub struct DateStyle {
37 44 day_month: &'static str,
38 45 day_month_year: &'static str,
39 46 clock: &'static str,
47 first_day: Weekday,
40 48 }
41 49
42 50 thread_local! {
@@ -67,6 +75,21 @@ fn current_date_style() -> Option<DateStyle> {
67 75 DATE_STYLE.with(Cell::get)
68 76 }
69 77
78 /// First day of the week of the regional format; Monday when it is unknown.
79 pub fn regional_first_day() -> Weekday {
80 current_date_style().map_or(Weekday::Mon, |style| style.first_day)
81 }
82
83 fn first_day_for(locale: &str, language: &str) -> Weekday {
84 if SUNDAY_FIRST_LOCALES.contains(&locale) || SUNDAY_FIRST_LOCALES.contains(&language) {
85 Weekday::Sun
86 } else if (language == "ar" && !ARABIC_MONDAY_LOCALES.contains(&locale)) || language == "fa" {
87 Weekday::Sat
88 } else {
89 Weekday::Mon
90 }
91 }
92
70 93 pub fn clock_format() -> &'static str {
71 94 current_date_style().map_or("%H:%M", |style| style.clock)
72 95 }
@@ -90,32 +113,70 @@ pub fn calendar_day_number(date: NaiveDate) -> String {
90 113 .to_string()
91 114 }
92 115
116 /// Month name in the app language (`calendar.month.mNN`), not chrono's English `%B`.
117 pub fn month_name(date: NaiveDate) -> String {
118 crate::ui_locale::tr(&format!("calendar.month.m{:02}", date.month()))
119 }
120
121 /// "November 2026" / "November 2026" — month title of the month grid.
122 pub fn month_year_label(date: NaiveDate) -> String {
123 format!("{} {}", month_name(date), date.year())
124 }
125
126 const WEEKDAY_KEYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
127
128 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
129 pub enum WeekdayWidth {
130 /// "Monday" / "Montag"
131 Full,
132 /// "Mon" / "Mo"
133 Short,
134 /// "M" / "M"
135 Letter,
136 }
137
138 /// Weekday name in the app language; chrono's `%A`/`%a` are always English.
139 pub fn weekday_name(day: Weekday, width: WeekdayWidth) -> String {
140 let key = WEEKDAY_KEYS[day.num_days_from_monday() as usize];
141 match width {
142 WeekdayWidth::Full => crate::ui_locale::tr(&format!("calendar.weekday.{key}")),
143 WeekdayWidth::Short => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}")),
144 WeekdayWidth::Letter => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}"))
145 .chars()
146 .next()
147 .map(String::from)
148 .unwrap_or_default(),
149 }
150 }
151
93 152 pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
94 153 let style = current_date_style();
95 let day = style.map_or("%-d", |style| style.day_number());
154 let day = |date: NaiveDate| {
155 date.format(style.map_or("%-d", |style| style.day_number()))
156 .to_string()
157 };
158 let (start_month, end_month) = (month_name(start), month_name(end));
96 159 if style.is_none_or(|style| style.month_first()) {
97 let from = start.format(&format!("%B {day}")).to_string();
98 let to = end.format(&format!("%B {day}, %Y")).to_string();
160 let to = format!("{end_month} {}, {}", day(end), end.year());
99 161 return if start == end {
100 162 to
101 163 } else if start.year() != end.year() {
102 format!("{} - {to}", start.format(&format!("%B {day}, %Y")))
164 format!("{start_month} {}, {} - {to}", day(start), start.year())
103 165 } else if start.month() != end.month() {
104 format!("{from} - {to}")
166 format!("{start_month} {} - {to}", day(start))
105 167 } else {
106 format!("{from}-{}, {}", end.format(day), end.year())
168 format!("{start_month} {}-{}, {}", day(start), day(end), end.year())
107 169 };
108 170 }
109 let from = start.format(&format!("{day} %B")).to_string();
110 let to = end.format(&format!("{day} %B, %Y")).to_string();
171 let to = format!("{} {end_month}, {}", day(end), end.year());
111 172 if start == end {
112 173 to
113 174 } else if start.year() != end.year() {
114 format!("{} - {to}", start.format(&format!("{day} %B, %Y")))
175 format!("{} {start_month}, {} - {to}", day(start), start.year())
115 176 } else if start.month() != end.month() {
116 format!("{from} - {to}")
177 format!("{} {start_month} - {to}", day(start))
117 178 } else {
118 format!("{}-{to}", start.format(day))
179 format!("{}-{to}", day(start))
119 180 }
120 181 }
121 182
@@ -144,6 +205,7 @@ pub fn date_style(locale: &str) -> DateStyle {
144 205 day_month,
145 206 day_month_year,
146 207 clock,
208 first_day: first_day_for(&locale, language),
147 209 }
148 210 }
149 211
@@ -330,8 +392,44 @@ mod tests {
330 392
331 393 use super::*;
332 394
395 #[test]
396 fn the_first_day_of_week_follows_the_region() {
397 let first = |locale| {
398 set_date_locale(Some(locale));
399 regional_first_day()
400 };
401 assert_eq!(first("en-US"), Weekday::Sun);
402 assert_eq!(first("de-CH"), Weekday::Mon);
403 assert_eq!(first("en-GB"), Weekday::Mon);
404 assert_eq!(first("ar-SA"), Weekday::Sat);
405 assert_eq!(first("ar-MA"), Weekday::Mon);
406 assert_eq!(first("ja-JP"), Weekday::Sun);
407 set_date_locale(None);
408 assert_eq!(regional_first_day(), Weekday::Mon);
409 }
410
411 #[test]
412 fn calendar_names_follow_the_app_language() {
413 let _guard = crate::ui_locale::locale_test_lock();
414 let date = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
415 rust_i18n::set_locale("de");
416 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Montag");
417 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Short), "Do");
418 assert_eq!(weekday_name(Weekday::Sun, WeekdayWidth::Letter), "S");
419 assert_eq!(month_year_label(date), "November 2026");
420 assert_eq!(
421 month_name(NaiveDate::from_ymd_opt(2026, 3, 1).unwrap()),
422 "März"
423 );
424 rust_i18n::set_locale("en");
425 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Monday");
426 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Letter), "T");
427 }
428
333 429 #[test]
334 430 fn calendar_range_follows_the_account_locale() {
431 let _guard = crate::ui_locale::locale_test_lock();
432 rust_i18n::set_locale("en");
335 433 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
336 434 set_date_locale(Some("en-GB"));
337 435 assert_eq!(
@@ -31,12 +31,20 @@ const WEEKDAY_WINDOW_DAYS: i64 = 6;
31const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
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"];
32const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
33const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
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"];
34
41
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct DateStyle {
43pub struct DateStyle {
37 day_month: &'static str,
44 day_month: &'static str,
38 day_month_year: &'static str,
45 day_month_year: &'static str,
39 clock: &'static str,
46 clock: &'static str,
47 first_day: Weekday,
40}
48}
41
49
42thread_local! {
50thread_local! {
@@ -67,6 +75,21 @@ fn current_date_style() -> Option<DateStyle> {
67 DATE_STYLE.with(Cell::get)
75 DATE_STYLE.with(Cell::get)
68}
76}
69
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
83fn first_day_for(locale: &str, language: &str) -> Weekday {
84 if SUNDAY_FIRST_LOCALES.contains(&locale) || SUNDAY_FIRST_LOCALES.contains(&language) {
85 Weekday::Sun
86 } else if (language == "ar" && !ARABIC_MONDAY_LOCALES.contains(&locale)) || language == "fa" {
87 Weekday::Sat
88 } else {
89 Weekday::Mon
90 }
91}
92
70pub fn clock_format() -> &'static str {
93pub fn clock_format() -> &'static str {
71 current_date_style().map_or("%H:%M", |style| style.clock)
94 current_date_style().map_or("%H:%M", |style| style.clock)
72}
95}
@@ -90,32 +113,70 @@ pub fn calendar_day_number(date: NaiveDate) -> String {
90 .to_string()
113 .to_string()
91}
114}
92
115
116/// Month name in the app language (`calendar.month.mNN`), not chrono's English `%B`.
117pub fn month_name(date: NaiveDate) -> String {
118 crate::ui_locale::tr(&format!("calendar.month.m{:02}", date.month()))
119}
120
121/// "November 2026" / "November 2026" — month title of the month grid.
122pub fn month_year_label(date: NaiveDate) -> String {
123 format!("{} {}", month_name(date), date.year())
124}
125
126const WEEKDAY_KEYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum WeekdayWidth {
130 /// "Monday" / "Montag"
131 Full,
132 /// "Mon" / "Mo"
133 Short,
134 /// "M" / "M"
135 Letter,
136}
137
138/// Weekday name in the app language; chrono's `%A`/`%a` are always English.
139pub fn weekday_name(day: Weekday, width: WeekdayWidth) -> String {
140 let key = WEEKDAY_KEYS[day.num_days_from_monday() as usize];
141 match width {
142 WeekdayWidth::Full => crate::ui_locale::tr(&format!("calendar.weekday.{key}")),
143 WeekdayWidth::Short => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}")),
144 WeekdayWidth::Letter => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}"))
145 .chars()
146 .next()
147 .map(String::from)
148 .unwrap_or_default(),
149 }
150}
151
93pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
152pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
94 let style = current_date_style();
153 let style = current_date_style();
95 let day = style.map_or("%-d", |style| style.day_number());
154 let day = |date: NaiveDate| {
155 date.format(style.map_or("%-d", |style| style.day_number()))
156 .to_string()
157 };
158 let (start_month, end_month) = (month_name(start), month_name(end));
96 if style.is_none_or(|style| style.month_first()) {
159 if style.is_none_or(|style| style.month_first()) {
97 let from = start.format(&format!("%B {day}")).to_string();
160 let to = format!("{end_month} {}, {}", day(end), end.year());
98 let to = end.format(&format!("%B {day}, %Y")).to_string();
99 return if start == end {
161 return if start == end {
100 to
162 to
101 } else if start.year() != end.year() {
163 } else if start.year() != end.year() {
102 format!("{} - {to}", start.format(&format!("%B {day}, %Y")))
164 format!("{start_month} {}, {} - {to}", day(start), start.year())
103 } else if start.month() != end.month() {
165 } else if start.month() != end.month() {
104 format!("{from} - {to}")
166 format!("{start_month} {} - {to}", day(start))
105 } else {
167 } else {
106 format!("{from}-{}, {}", end.format(day), end.year())
168 format!("{start_month} {}-{}, {}", day(start), day(end), end.year())
107 };
169 };
108 }
170 }
109 let from = start.format(&format!("{day} %B")).to_string();
171 let to = format!("{} {end_month}, {}", day(end), end.year());
110 let to = end.format(&format!("{day} %B, %Y")).to_string();
111 if start == end {
172 if start == end {
112 to
173 to
113 } else if start.year() != end.year() {
174 } else if start.year() != end.year() {
114 format!("{} - {to}", start.format(&format!("{day} %B, %Y")))
175 format!("{} {start_month}, {} - {to}", day(start), start.year())
115 } else if start.month() != end.month() {
176 } else if start.month() != end.month() {
116 format!("{from} - {to}")
177 format!("{} {start_month} - {to}", day(start))
117 } else {
178 } else {
118 format!("{}-{to}", start.format(day))
179 format!("{}-{to}", day(start))
119 }
180 }
120}
181}
121
182
@@ -144,6 +205,7 @@ pub fn date_style(locale: &str) -> DateStyle {
144 day_month,
205 day_month,
145 day_month_year,
206 day_month_year,
146 clock,
207 clock,
208 first_day: first_day_for(&locale, language),
147 }
209 }
148}
210}
149
211
@@ -330,8 +392,44 @@ mod tests {
330
392
331 use super::*;
393 use super::*;
332
394
395 #[test]
396 fn the_first_day_of_week_follows_the_region() {
397 let first = |locale| {
398 set_date_locale(Some(locale));
399 regional_first_day()
400 };
401 assert_eq!(first("en-US"), Weekday::Sun);
402 assert_eq!(first("de-CH"), Weekday::Mon);
403 assert_eq!(first("en-GB"), Weekday::Mon);
404 assert_eq!(first("ar-SA"), Weekday::Sat);
405 assert_eq!(first("ar-MA"), Weekday::Mon);
406 assert_eq!(first("ja-JP"), Weekday::Sun);
407 set_date_locale(None);
408 assert_eq!(regional_first_day(), Weekday::Mon);
409 }
410
411 #[test]
412 fn calendar_names_follow_the_app_language() {
413 let _guard = crate::ui_locale::locale_test_lock();
414 let date = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
415 rust_i18n::set_locale("de");
416 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Montag");
417 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Short), "Do");
418 assert_eq!(weekday_name(Weekday::Sun, WeekdayWidth::Letter), "S");
419 assert_eq!(month_year_label(date), "November 2026");
420 assert_eq!(
421 month_name(NaiveDate::from_ymd_opt(2026, 3, 1).unwrap()),
422 "März"
423 );
424 rust_i18n::set_locale("en");
425 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Monday");
426 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Letter), "T");
427 }
428
333 #[test]
429 #[test]
334 fn calendar_range_follows_the_account_locale() {
430 fn calendar_range_follows_the_account_locale() {
431 let _guard = crate::ui_locale::locale_test_lock();
432 rust_i18n::set_locale("en");
335 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
433 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
336 set_date_locale(Some("en-GB"));
434 set_date_locale(Some("en-GB"));
337 assert_eq!(
435 assert_eq!(
crates/app-base/src/ui_locale.rs +7 −7
@@ -123,18 +123,18 @@ pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124 124 }
125 125
126 /// Serialises tests in this crate that read or set the global UI language.
126 127 #[cfg(test)]
127 mod tests {
128 use std::sync::{Mutex, MutexGuard};
128 pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
129 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130 LOCK.lock().unwrap_or_else(|error| error.into_inner())
131 }
129 132
133 #[cfg(test)]
134 mod tests {
130 135 use super::*;
131 136 use tempfile::tempdir;
132 137
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
136 }
137
138 138 #[test]
139 139 fn ui_locale_effective_prefers_explicit_english_and_german() {
140 140 let _guard = locale_test_lock();
@@ -123,18 +123,18 @@ pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124}
124}
125
125
126/// Serialises tests in this crate that read or set the global UI language.
126#[cfg(test)]
127#[cfg(test)]
127mod tests {
128pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
128 use std::sync::{Mutex, MutexGuard};
129 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130 LOCK.lock().unwrap_or_else(|error| error.into_inner())
131}
129
132
133#[cfg(test)]
134mod tests {
130 use super::*;
135 use super::*;
131 use tempfile::tempdir;
136 use tempfile::tempdir;
132
137
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
136 }
137
138 #[test]
138 #[test]
139 fn ui_locale_effective_prefers_explicit_english_and_german() {
139 fn ui_locale_effective_prefers_explicit_english_and_german() {
140 let _guard = locale_test_lock();
140 let _guard = locale_test_lock();
crates/app-call-model/src/calendar_prefs.rs added +262 −0
@@ -0,0 +1,262 @@
1 //! Local calendar preferences: default view, last span, week layout, time scale.
2 //!
3 //! Work days and hours belong to the Outlook mailbox (Teams and Outlook read them
4 //! there); the copy here is only a cache so the grid has them before the mailbox
5 //! answers and while offline.
6
7 use chrono::{NaiveTime, Weekday};
8 use serde::{Deserialize, Serialize};
9 use store::Store;
10
11 use crate::week_grid::{CalendarSpan, WeekLayout};
12
13 pub const CALENDAR_PREFS_KEY: &str = "calendar.prefs";
14
15 /// Groups in the calendar list are keyed by this id for Outlook.
16 pub const OUTLOOK_GROUP: &str = "outlook";
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
19 #[serde(rename_all = "snake_case")]
20 pub enum DefaultView {
21 #[default]
22 LastUsed,
23 Day,
24 WorkWeek,
25 Week,
26 Month,
27 }
28
29 impl DefaultView {
30 pub const ALL: [DefaultView; 5] = [
31 DefaultView::LastUsed,
32 DefaultView::Day,
33 DefaultView::WorkWeek,
34 DefaultView::Week,
35 DefaultView::Month,
36 ];
37
38 pub fn span(self) -> Option<CalendarSpan> {
39 match self {
40 DefaultView::LastUsed => None,
41 DefaultView::Day => Some(CalendarSpan::Day),
42 DefaultView::WorkWeek => Some(CalendarSpan::WorkWeek),
43 DefaultView::Week => Some(CalendarSpan::Week),
44 DefaultView::Month => Some(CalendarSpan::Month),
45 }
46 }
47 }
48
49 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50 #[serde(rename_all = "snake_case")]
51 pub enum TimeScale {
52 Min15,
53 /// Teams default.
54 #[default]
55 Min30,
56 Min60,
57 }
58
59 impl TimeScale {
60 pub const ALL: [TimeScale; 3] = [TimeScale::Min15, TimeScale::Min30, TimeScale::Min60];
61
62 pub fn minutes(self) -> u32 {
63 match self {
64 TimeScale::Min15 => 15,
65 TimeScale::Min30 => 30,
66 TimeScale::Min60 => 60,
67 }
68 }
69
70 /// Minor grid lines inside one hour.
71 pub fn steps_per_hour(self) -> u32 {
72 60 / self.minutes()
73 }
74 }
75
76 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
77 #[serde(rename_all = "snake_case")]
78 pub enum WeekendWorkWeek {
79 /// Outlook and Teams show the coming work week on a weekend.
80 #[default]
81 NextWeek,
82 ThisWeek,
83 }
84
85 /// Work days and hours as the mailbox stores them, in the mailbox's local time.
86 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87 pub struct WorkHours {
88 pub days: Vec<Weekday>,
89 pub start: NaiveTime,
90 pub end: NaiveTime,
91 }
92
93 impl Default for WorkHours {
94 fn default() -> Self {
95 WorkHours {
96 days: vec![
97 Weekday::Mon,
98 Weekday::Tue,
99 Weekday::Wed,
100 Weekday::Thu,
101 Weekday::Fri,
102 ],
103 start: NaiveTime::from_hms_opt(8, 0, 0).unwrap_or_default(),
104 end: NaiveTime::from_hms_opt(17, 0, 0).unwrap_or_default(),
105 }
106 }
107 }
108
109 impl WorkHours {
110 pub fn is_work_day(&self, day: Weekday) -> bool {
111 self.days.contains(&day)
112 }
113
114 /// Minutes after midnight where work time starts and ends.
115 pub fn minute_range(&self) -> (i64, i64) {
116 let minute = |time: NaiveTime| {
117 i64::from(chrono::Timelike::hour(&time)) * 60
118 + i64::from(chrono::Timelike::minute(&time))
119 };
120 (minute(self.start), minute(self.end))
121 }
122 }
123
124 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
125 #[serde(default)]
126 pub struct CalendarPrefs {
127 pub default_view: DefaultView,
128 pub last_span: CalendarSpan,
129 /// `None` follows the regional format.
130 pub first_day: Option<Weekday>,
131 pub time_scale: TimeScale,
132 pub weekend_work_week: WeekendWorkWeek,
133 pub pane_hidden: bool,
134 pub collapsed_groups: Vec<String>,
135 pub work_hours: WorkHours,
136 }
137
138 impl CalendarPrefs {
139 /// The span the calendar opens in.
140 pub fn initial_span(&self) -> CalendarSpan {
141 self.default_view.span().unwrap_or(self.last_span)
142 }
143
144 pub fn first_day_or(&self, regional: Weekday) -> Weekday {
145 self.first_day.unwrap_or(regional)
146 }
147
148 /// Week layout for the grid; `regional` is the regional format's first day.
149 pub fn layout(&self, regional: Weekday) -> WeekLayout {
150 WeekLayout {
151 first_day: self.first_day_or(regional),
152 work_days: self.work_hours.days.clone(),
153 weekend: self.weekend_work_week,
154 }
155 }
156
157 pub fn group_collapsed(&self, group: &str) -> bool {
158 self.collapsed_groups.iter().any(|id| id == group)
159 }
160
161 pub fn toggle_group(&mut self, group: &str) {
162 if self.group_collapsed(group) {
163 self.collapsed_groups.retain(|id| id != group);
164 } else {
165 self.collapsed_groups.push(group.to_owned());
166 }
167 }
168
169 pub fn from_json(text: &str) -> Self {
170 serde_json::from_str(text).unwrap_or_default()
171 }
172
173 pub fn to_json(&self) -> String {
174 serde_json::to_string(self).unwrap_or_default()
175 }
176 }
177
178 pub fn load_calendar_prefs(store: &Store) -> CalendarPrefs {
179 store
180 .meta(CALENDAR_PREFS_KEY)
181 .ok()
182 .flatten()
183 .map(|json| CalendarPrefs::from_json(&json))
184 .unwrap_or_default()
185 }
186
187 pub fn save_calendar_prefs(store: &Store, prefs: &CalendarPrefs) {
188 if let Err(error) = store.set_meta(CALENDAR_PREFS_KEY, &prefs.to_json()) {
189 log::warn!("calendar prefs not saved: {error}");
190 }
191 }
192
193 #[cfg(test)]
194 mod tests {
195 use super::*;
196
197 #[test]
198 fn defaults_keep_todays_behaviour() {
199 let prefs = CalendarPrefs::default();
200 assert_eq!(prefs.default_view, DefaultView::LastUsed);
201 assert_eq!(prefs.initial_span(), CalendarSpan::WorkWeek);
202 assert_eq!(prefs.time_scale.minutes(), 30);
203 assert_eq!(prefs.weekend_work_week, WeekendWorkWeek::NextWeek);
204 assert_eq!(prefs.work_hours.minute_range(), (8 * 60, 17 * 60));
205 assert!(!prefs.work_hours.is_work_day(Weekday::Sat));
206 }
207
208 #[test]
209 fn a_fixed_default_view_wins_over_the_last_span() {
210 let prefs = CalendarPrefs {
211 default_view: DefaultView::Week,
212 last_span: CalendarSpan::Month,
213 ..CalendarPrefs::default()
214 };
215 assert_eq!(prefs.initial_span(), CalendarSpan::Week);
216 let last_used = CalendarPrefs {
217 default_view: DefaultView::LastUsed,
218 ..prefs
219 };
220 assert_eq!(last_used.initial_span(), CalendarSpan::Month);
221 }
222
223 #[test]
224 fn prefs_round_trip_through_the_store() {
225 let store = Store::open_in_memory().unwrap();
226 let mut prefs = CalendarPrefs {
227 default_view: DefaultView::Month,
228 first_day: Some(Weekday::Sun),
229 time_scale: TimeScale::Min15,
230 pane_hidden: true,
231 ..CalendarPrefs::default()
232 };
233 prefs.toggle_group("g1");
234 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
235 save_calendar_prefs(&store, &prefs);
236 assert_eq!(load_calendar_prefs(&store), prefs);
237 }
238
239 #[test]
240 fn missing_fields_take_defaults_and_broken_json_resets() {
241 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
242 assert_eq!(partial.default_view, DefaultView::Month);
243 assert_eq!(partial.time_scale, TimeScale::Min30);
244 assert_eq!(
245 CalendarPrefs::from_json("{not json"),
246 CalendarPrefs::default()
247 );
248 assert_eq!(
249 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
250 CalendarPrefs::default()
251 );
252 }
253
254 #[test]
255 fn a_group_collapses_and_expands() {
256 let mut prefs = CalendarPrefs::default();
257 prefs.toggle_group(OUTLOOK_GROUP);
258 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
259 prefs.toggle_group(OUTLOOK_GROUP);
260 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
261 }
262 }
@@ -0,0 +1,262 @@
1//! Local calendar preferences: default view, last span, week layout, time scale.
2//!
3//! Work days and hours belong to the Outlook mailbox (Teams and Outlook read them
4//! there); the copy here is only a cache so the grid has them before the mailbox
5//! answers and while offline.
6
7use chrono::{NaiveTime, Weekday};
8use serde::{Deserialize, Serialize};
9use store::Store;
10
11use crate::week_grid::{CalendarSpan, WeekLayout};
12
13pub const CALENDAR_PREFS_KEY: &str = "calendar.prefs";
14
15/// Groups in the calendar list are keyed by this id for Outlook.
16pub const OUTLOOK_GROUP: &str = "outlook";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum DefaultView {
21 #[default]
22 LastUsed,
23 Day,
24 WorkWeek,
25 Week,
26 Month,
27}
28
29impl DefaultView {
30 pub const ALL: [DefaultView; 5] = [
31 DefaultView::LastUsed,
32 DefaultView::Day,
33 DefaultView::WorkWeek,
34 DefaultView::Week,
35 DefaultView::Month,
36 ];
37
38 pub fn span(self) -> Option<CalendarSpan> {
39 match self {
40 DefaultView::LastUsed => None,
41 DefaultView::Day => Some(CalendarSpan::Day),
42 DefaultView::WorkWeek => Some(CalendarSpan::WorkWeek),
43 DefaultView::Week => Some(CalendarSpan::Week),
44 DefaultView::Month => Some(CalendarSpan::Month),
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum TimeScale {
52 Min15,
53 /// Teams default.
54 #[default]
55 Min30,
56 Min60,
57}
58
59impl TimeScale {
60 pub const ALL: [TimeScale; 3] = [TimeScale::Min15, TimeScale::Min30, TimeScale::Min60];
61
62 pub fn minutes(self) -> u32 {
63 match self {
64 TimeScale::Min15 => 15,
65 TimeScale::Min30 => 30,
66 TimeScale::Min60 => 60,
67 }
68 }
69
70 /// Minor grid lines inside one hour.
71 pub fn steps_per_hour(self) -> u32 {
72 60 / self.minutes()
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum WeekendWorkWeek {
79 /// Outlook and Teams show the coming work week on a weekend.
80 #[default]
81 NextWeek,
82 ThisWeek,
83}
84
85/// Work days and hours as the mailbox stores them, in the mailbox's local time.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct WorkHours {
88 pub days: Vec<Weekday>,
89 pub start: NaiveTime,
90 pub end: NaiveTime,
91}
92
93impl Default for WorkHours {
94 fn default() -> Self {
95 WorkHours {
96 days: vec![
97 Weekday::Mon,
98 Weekday::Tue,
99 Weekday::Wed,
100 Weekday::Thu,
101 Weekday::Fri,
102 ],
103 start: NaiveTime::from_hms_opt(8, 0, 0).unwrap_or_default(),
104 end: NaiveTime::from_hms_opt(17, 0, 0).unwrap_or_default(),
105 }
106 }
107}
108
109impl WorkHours {
110 pub fn is_work_day(&self, day: Weekday) -> bool {
111 self.days.contains(&day)
112 }
113
114 /// Minutes after midnight where work time starts and ends.
115 pub fn minute_range(&self) -> (i64, i64) {
116 let minute = |time: NaiveTime| {
117 i64::from(chrono::Timelike::hour(&time)) * 60
118 + i64::from(chrono::Timelike::minute(&time))
119 };
120 (minute(self.start), minute(self.end))
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
125#[serde(default)]
126pub struct CalendarPrefs {
127 pub default_view: DefaultView,
128 pub last_span: CalendarSpan,
129 /// `None` follows the regional format.
130 pub first_day: Option<Weekday>,
131 pub time_scale: TimeScale,
132 pub weekend_work_week: WeekendWorkWeek,
133 pub pane_hidden: bool,
134 pub collapsed_groups: Vec<String>,
135 pub work_hours: WorkHours,
136}
137
138impl CalendarPrefs {
139 /// The span the calendar opens in.
140 pub fn initial_span(&self) -> CalendarSpan {
141 self.default_view.span().unwrap_or(self.last_span)
142 }
143
144 pub fn first_day_or(&self, regional: Weekday) -> Weekday {
145 self.first_day.unwrap_or(regional)
146 }
147
148 /// Week layout for the grid; `regional` is the regional format's first day.
149 pub fn layout(&self, regional: Weekday) -> WeekLayout {
150 WeekLayout {
151 first_day: self.first_day_or(regional),
152 work_days: self.work_hours.days.clone(),
153 weekend: self.weekend_work_week,
154 }
155 }
156
157 pub fn group_collapsed(&self, group: &str) -> bool {
158 self.collapsed_groups.iter().any(|id| id == group)
159 }
160
161 pub fn toggle_group(&mut self, group: &str) {
162 if self.group_collapsed(group) {
163 self.collapsed_groups.retain(|id| id != group);
164 } else {
165 self.collapsed_groups.push(group.to_owned());
166 }
167 }
168
169 pub fn from_json(text: &str) -> Self {
170 serde_json::from_str(text).unwrap_or_default()
171 }
172
173 pub fn to_json(&self) -> String {
174 serde_json::to_string(self).unwrap_or_default()
175 }
176}
177
178pub fn load_calendar_prefs(store: &Store) -> CalendarPrefs {
179 store
180 .meta(CALENDAR_PREFS_KEY)
181 .ok()
182 .flatten()
183 .map(|json| CalendarPrefs::from_json(&json))
184 .unwrap_or_default()
185}
186
187pub fn save_calendar_prefs(store: &Store, prefs: &CalendarPrefs) {
188 if let Err(error) = store.set_meta(CALENDAR_PREFS_KEY, &prefs.to_json()) {
189 log::warn!("calendar prefs not saved: {error}");
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn defaults_keep_todays_behaviour() {
199 let prefs = CalendarPrefs::default();
200 assert_eq!(prefs.default_view, DefaultView::LastUsed);
201 assert_eq!(prefs.initial_span(), CalendarSpan::WorkWeek);
202 assert_eq!(prefs.time_scale.minutes(), 30);
203 assert_eq!(prefs.weekend_work_week, WeekendWorkWeek::NextWeek);
204 assert_eq!(prefs.work_hours.minute_range(), (8 * 60, 17 * 60));
205 assert!(!prefs.work_hours.is_work_day(Weekday::Sat));
206 }
207
208 #[test]
209 fn a_fixed_default_view_wins_over_the_last_span() {
210 let prefs = CalendarPrefs {
211 default_view: DefaultView::Week,
212 last_span: CalendarSpan::Month,
213 ..CalendarPrefs::default()
214 };
215 assert_eq!(prefs.initial_span(), CalendarSpan::Week);
216 let last_used = CalendarPrefs {
217 default_view: DefaultView::LastUsed,
218 ..prefs
219 };
220 assert_eq!(last_used.initial_span(), CalendarSpan::Month);
221 }
222
223 #[test]
224 fn prefs_round_trip_through_the_store() {
225 let store = Store::open_in_memory().unwrap();
226 let mut prefs = CalendarPrefs {
227 default_view: DefaultView::Month,
228 first_day: Some(Weekday::Sun),
229 time_scale: TimeScale::Min15,
230 pane_hidden: true,
231 ..CalendarPrefs::default()
232 };
233 prefs.toggle_group("g1");
234 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
235 save_calendar_prefs(&store, &prefs);
236 assert_eq!(load_calendar_prefs(&store), prefs);
237 }
238
239 #[test]
240 fn missing_fields_take_defaults_and_broken_json_resets() {
241 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
242 assert_eq!(partial.default_view, DefaultView::Month);
243 assert_eq!(partial.time_scale, TimeScale::Min30);
244 assert_eq!(
245 CalendarPrefs::from_json("{not json"),
246 CalendarPrefs::default()
247 );
248 assert_eq!(
249 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
250 CalendarPrefs::default()
251 );
252 }
253
254 #[test]
255 fn a_group_collapses_and_expands() {
256 let mut prefs = CalendarPrefs::default();
257 prefs.toggle_group(OUTLOOK_GROUP);
258 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
259 prefs.toggle_group(OUTLOOK_GROUP);
260 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
261 }
262}
crates/app-call-model/src/lib.rs +1 −0
@@ -2,6 +2,7 @@ pub mod agenda;
2 2 pub mod background;
3 3 pub mod bubbles;
4 4 pub mod calendar_now;
5 pub mod calendar_prefs;
5 6 pub mod caption_style;
6 7 pub mod demo;
7 8 pub mod demo_scene;
@@ -2,6 +2,7 @@ pub mod agenda;
2pub mod background;
2pub mod background;
3pub mod bubbles;
3pub mod bubbles;
4pub mod calendar_now;
4pub mod calendar_now;
5pub mod calendar_prefs;
5pub mod caption_style;
6pub mod caption_style;
6pub mod demo;
7pub mod demo;
7pub mod demo_scene;
8pub mod demo_scene;
crates/app-call-model/src/week_grid.rs +241 −88
@@ -1,9 +1,10 @@
1 1 use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
3 pub use crate::calendar_prefs::WeekendWorkWeek;
2 4 use chrono::{
3 5 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4 6 };
5 7
6 pub const WORK_WEEK_DAYS: i64 = 5;
7 8 pub const MINUTES_PER_DAY: i64 = 24 * 60;
8 9 pub const MONTH_GRID_DAYS: i64 = 42;
9 10
@@ -23,11 +24,62 @@ pub struct WeekDay {
23 24 pub blocks: Vec<WeekBlock>,
24 25 }
25 26
26 pub fn week_start(date: NaiveDate) -> NaiveDate {
27 date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
27 /// How weeks are laid out: first day, work days, and what Work week shows on a day off.
28 #[derive(Debug, Clone, PartialEq, Eq)]
29 pub struct WeekLayout {
30 pub first_day: Weekday,
31 pub work_days: Vec<Weekday>,
32 pub weekend: WeekendWorkWeek,
33 }
34
35 impl Default for WeekLayout {
36 fn default() -> Self {
37 WeekLayout {
38 first_day: Weekday::Mon,
39 work_days: vec![
40 Weekday::Mon,
41 Weekday::Tue,
42 Weekday::Wed,
43 Weekday::Thu,
44 Weekday::Fri,
45 ],
46 weekend: WeekendWorkWeek::NextWeek,
47 }
48 }
49 }
50
51 impl WeekLayout {
52 pub fn is_work_day(&self, day: Weekday) -> bool {
53 self.work_days.contains(&day)
54 }
55
56 /// Work days, or Monday to Friday when none are set (an empty work week shows nothing).
57 fn effective_work_days(&self) -> Vec<Weekday> {
58 if self.work_days.is_empty() {
59 WeekLayout::default().work_days
60 } else {
61 self.work_days.clone()
62 }
63 }
64
65 /// The seven weekdays in order from the first day.
66 pub fn weekdays(&self) -> [Weekday; 7] {
67 let mut day = self.first_day;
68 std::array::from_fn(|_| {
69 let current = day;
70 day = day.succ();
71 current
72 })
73 }
74 }
75
76 pub fn week_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
77 let back = (7 + date.weekday().num_days_from_monday() - first_day.num_days_from_monday()) % 7;
78 date - Duration::days(i64::from(back))
28 79 }
29 80
30 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
82 #[serde(rename_all = "snake_case")]
31 83 pub enum CalendarSpan {
32 84 Day,
33 85 #[default]
@@ -44,34 +96,31 @@ impl CalendarSpan {
44 96 CalendarSpan::Month,
45 97 ];
46 98
47 pub fn label(self) -> &'static str {
99 /// Locale key of the span's name (`calendar.view.span_*`).
100 pub fn label_key(self) -> &'static str {
48 101 match self {
49 CalendarSpan::Day => "Day",
50 CalendarSpan::WorkWeek => "Work week",
51 CalendarSpan::Week => "Week",
52 CalendarSpan::Month => "Month",
102 CalendarSpan::Day => "calendar.view.span_day",
103 CalendarSpan::WorkWeek => "calendar.view.span_work_week",
104 CalendarSpan::Week => "calendar.view.span_week",
105 CalendarSpan::Month => "calendar.view.span_month",
53 106 }
54 107 }
55 108
56 pub fn days(self) -> i64 {
57 match self {
58 CalendarSpan::Day => 1,
59 CalendarSpan::WorkWeek => WORK_WEEK_DAYS,
60 CalendarSpan::Week => 7,
61 CalendarSpan::Month => MONTH_GRID_DAYS,
62 }
109 pub fn label(self) -> String {
110 app_base::ui_locale::tr(self.label_key())
63 111 }
64 112
65 pub fn start_for(self, date: NaiveDate) -> NaiveDate {
113 /// First date of the range that contains `date`.
114 pub fn start_for(self, date: NaiveDate, layout: &WeekLayout) -> NaiveDate {
66 115 match self {
67 116 CalendarSpan::Day => date,
68 CalendarSpan::WorkWeek => work_week_for(date),
69 CalendarSpan::Week => week_start(date),
70 CalendarSpan::Month => month_grid_start(date),
117 CalendarSpan::WorkWeek => work_week_for(date, layout),
118 CalendarSpan::Week => week_start(date, layout.first_day),
119 CalendarSpan::Month => month_grid_start(date, layout.first_day),
71 120 }
72 121 }
73 122
74 pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {
123 pub fn shifted(self, start: NaiveDate, steps: i32, layout: &WeekLayout) -> NaiveDate {
75 124 match self {
76 125 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
77 126 CalendarSpan::WorkWeek | CalendarSpan::Week => {
@@ -84,15 +133,37 @@ impl CalendarSpan {
84 133 } else {
85 134 month.checked_sub_months(Months::new(steps.unsigned_abs()))
86 135 };
87 month_grid_start(moved.unwrap_or(month))
136 month_grid_start(moved.unwrap_or(month), layout.first_day)
88 137 }
89 138 }
90 139 }
91 140
92 pub fn title(self, start: NaiveDate) -> String {
141 pub fn title(self, start: NaiveDate, layout: &WeekLayout) -> String {
93 142 match self {
94 CalendarSpan::Month => month_shown(start).format("%B %Y").to_string(),
95 _ => range_label(start, self.days()),
143 CalendarSpan::Month => app_base::format::month_year_label(month_shown(start)),
144 _ => {
145 let dates = visible_dates(self, start, layout);
146 let first = dates.first().copied().unwrap_or(start);
147 let last = dates.last().copied().unwrap_or(start);
148 app_base::format::calendar_range_label(first, last)
149 }
150 }
151 }
152 }
153
154 /// The dates a span draws, in column order. Work week keeps only work days.
155 pub fn visible_dates(span: CalendarSpan, start: NaiveDate, layout: &WeekLayout) -> Vec<NaiveDate> {
156 let run = |days: i64| (0..days).map(|day| start + Duration::days(day)).collect();
157 match span {
158 CalendarSpan::Day => vec![start],
159 CalendarSpan::Week => run(7),
160 CalendarSpan::Month => run(MONTH_GRID_DAYS),
161 CalendarSpan::WorkWeek => {
162 let work_days = layout.effective_work_days();
163 (0..7)
164 .map(|day| start + Duration::days(day))
165 .filter(|date| work_days.contains(&date.weekday()))
166 .collect()
96 167 }
97 168 }
98 169 }
@@ -101,8 +172,8 @@ pub fn first_of_month(date: NaiveDate) -> NaiveDate {
101 172 date.with_day(1).unwrap_or(date)
102 173 }
103 174
104 pub fn month_grid_start(date: NaiveDate) -> NaiveDate {
105 week_start(first_of_month(date))
175 pub fn month_grid_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
176 week_start(first_of_month(date), first_day)
106 177 }
107 178
108 179 /// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
@@ -110,11 +181,19 @@ pub fn month_shown(grid_start: NaiveDate) -> NaiveDate {
110 181 first_of_month(grid_start + Duration::weeks(1))
111 182 }
112 183
113 /// On a weekend the work week view shows the coming week, as Outlook does.
114 pub fn work_week_for(today: NaiveDate) -> NaiveDate {
115 match today.weekday() {
116 Weekday::Sat | Weekday::Sun => week_start(today) + Duration::weeks(1),
117 _ => week_start(today),
184 /// Start of the week Work week shows for `today`.
185 ///
186 /// On a day off with no work day left in this week, Outlook and Teams show the
187 /// coming week; `WeekendWorkWeek::ThisWeek` keeps the current one.
188 pub fn work_week_for(today: NaiveDate, layout: &WeekLayout) -> NaiveDate {
189 let week = week_start(today, layout.first_day);
190 let work_days = layout.effective_work_days();
191 let work_left = (0..7)
192 .map(|day| week + Duration::days(day))
193 .any(|date| date >= today && work_days.contains(&date.weekday()));
194 match layout.weekend {
195 WeekendWorkWeek::NextWeek if !work_left => week + Duration::weeks(1),
196 _ => week,
118 197 }
119 198 }
120 199
@@ -125,6 +204,16 @@ pub fn local_midnight(date: NaiveDate, offset: FixedOffset) -> DateTime<Utc> {
125 204 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
126 205 }
127 206
207 /// UTC range from the first date's midnight to the midnight after the last date.
208 pub fn dates_range(dates: &[NaiveDate], offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
209 let first = dates.first().copied().unwrap_or_default();
210 let last = dates.last().copied().unwrap_or(first);
211 (
212 local_midnight(first, offset),
213 local_midnight(last + Duration::days(1), offset),
214 )
215 }
216
128 217 pub fn week_range(
129 218 start: NaiveDate,
130 219 days: i64,
@@ -161,13 +250,12 @@ pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool
161 250
162 251 pub fn week_days(
163 252 events: &[CalendarEvent],
164 start: NaiveDate,
165 days: i64,
253 dates: &[NaiveDate],
166 254 offset: FixedOffset,
167 255 ) -> Vec<WeekDay> {
168 (0..days)
169 .map(|day| {
170 let date = start + Duration::days(day);
256 dates
257 .iter()
258 .map(|&date| {
171 259 let (day_start, day_end) = week_range(date, 1, offset);
172 260 let mut all_day = Vec::new();
173 261 let mut spans = Vec::new();
@@ -233,10 +321,6 @@ fn close_cluster(blocks: &mut [WeekBlock], lanes: usize) {
233 321 }
234 322 }
235 323
236 pub fn range_label(start: NaiveDate, days: i64) -> String {
237 app_base::format::calendar_range_label(start, start + Duration::days(days - 1))
238 }
239
240 324 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
241 325 pub enum EventLook {
242 326 Busy,
@@ -298,40 +382,113 @@ mod tests {
298 382 FixedOffset::east_opt(0).unwrap()
299 383 }
300 384
385 fn run(start: NaiveDate, days: i64) -> Vec<NaiveDate> {
386 (0..days).map(|day| start + Duration::days(day)).collect()
387 }
388
389 fn nov(day: u32) -> NaiveDate {
390 NaiveDate::from_ymd_opt(2026, 11, day).unwrap()
391 }
392
393 fn layout() -> WeekLayout {
394 WeekLayout::default()
395 }
396
397 fn sunday_first() -> WeekLayout {
398 WeekLayout {
399 first_day: Weekday::Sun,
400 ..WeekLayout::default()
401 }
402 }
403
301 404 #[test]
302 405 fn month_view_steps_whole_months_from_a_monday_grid() {
303 let date = |day| NaiveDate::from_ymd_opt(2026, 11, day).unwrap();
304 let start = CalendarSpan::Month.start_for(date(18));
406 let layout = layout();
407 let start = CalendarSpan::Month.start_for(nov(18), &layout);
305 408 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
306 assert_eq!(CalendarSpan::Month.title(start), "November 2026");
307 let next = CalendarSpan::Month.shifted(start, 1);
308 assert_eq!(next, NaiveDate::from_ymd_opt(2026, 11, 30).unwrap());
309 assert_eq!(CalendarSpan::Month.title(next), "December 2026");
310 let back = CalendarSpan::Month.shifted(start, -11);
311 assert_eq!(CalendarSpan::Month.title(back), "December 2025");
409 assert_eq!(month_shown(start), nov(1));
410 let next = CalendarSpan::Month.shifted(start, 1, &layout);
411 assert_eq!(next, nov(30));
412 let back = CalendarSpan::Month.shifted(start, -11, &layout);
312 413 assert_eq!(
313 CalendarSpan::Week.shifted(date(2), -1),
314 date(2) - Duration::weeks(1)
414 month_shown(back),
415 NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
416 );
417 assert_eq!(
418 CalendarSpan::Week.shifted(nov(2), -1, &layout),
419 nov(2) - Duration::weeks(1)
315 420 );
316 421 }
317 422
318 423 #[test]
319 fn the_week_starts_on_monday() {
320 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
424 fn a_sunday_first_week_and_month_start_on_sunday() {
425 let layout = sunday_first();
426 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(15));
427 assert_eq!(
428 visible_dates(CalendarSpan::Week, nov(15), &layout),
429 run(nov(15), 7)
430 );
431 assert_eq!(
432 CalendarSpan::Month.start_for(nov(18), &layout),
433 NaiveDate::from_ymd_opt(2026, 11, 1).unwrap()
434 );
435 assert_eq!(layout.weekdays()[0], Weekday::Sun);
436 assert_eq!(layout.weekdays()[6], Weekday::Sat);
437 }
438
439 #[test]
440 fn a_saturday_first_week_starts_on_saturday() {
441 let layout = WeekLayout {
442 first_day: Weekday::Sat,
443 ..WeekLayout::default()
444 };
445 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(14));
446 assert_eq!(week_start(nov(14), Weekday::Sat), nov(14));
447 }
448
449 #[test]
450 fn work_week_shows_only_the_work_days_even_with_gaps() {
451 let layout = WeekLayout {
452 work_days: vec![Weekday::Mon, Weekday::Tue, Weekday::Thu],
453 ..WeekLayout::default()
454 };
455 let start = CalendarSpan::WorkWeek.start_for(nov(18), &layout);
456 assert_eq!(
457 visible_dates(CalendarSpan::WorkWeek, start, &layout),
458 [nov(16), nov(17), nov(19)]
459 );
460 }
461
462 #[test]
463 fn on_sunday_work_week_shows_next_or_this_week() {
464 let next = layout();
465 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &next), nov(16));
466 let this = WeekLayout {
467 weekend: WeekendWorkWeek::ThisWeek,
468 ..WeekLayout::default()
469 };
470 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &this), nov(9));
471 // Sunday-first weeks still have work days ahead on Sunday.
321 472 assert_eq!(
322 week_start(sunday),
323 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
473 CalendarSpan::WorkWeek.start_for(nov(15), &sunday_first()),
474 nov(15)
324 475 );
325 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
326 476 assert_eq!(
327 work_week_for(sunday),
328 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
477 visible_dates(CalendarSpan::WorkWeek, nov(15), &sunday_first()),
478 run(nov(16), 5)
329 479 );
330 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
480 }
481
482 #[test]
483 fn the_week_starts_on_monday() {
484 let sunday = nov(15);
485 assert_eq!(week_start(sunday, Weekday::Mon), nov(9));
331 486 assert_eq!(
332 work_week_for(friday),
333 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
487 week_start(week_start(sunday, Weekday::Mon), Weekday::Mon),
488 nov(9)
334 489 );
490 assert_eq!(work_week_for(sunday, &layout()), nov(16));
491 assert_eq!(work_week_for(nov(13), &layout()), nov(9));
335 492 }
336 493
337 494 #[test]
@@ -343,7 +500,7 @@ mod tests {
343 500 event(13, 0, 30),
344 501 ];
345 502 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
346 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
503 let days = week_days(&events, &run(monday, 5), utc());
347 504 assert_eq!(days.len(), 5);
348 505 let lanes: Vec<(usize, usize, usize)> = days[0]
349 506 .blocks
@@ -363,7 +520,7 @@ mod tests {
363 520 all_day.all_day = true;
364 521 let late = event(23, 30, 60);
365 522 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
366 let days = week_days(&[declined, all_day, late], monday, 2, utc());
523 let days = week_days(&[declined, all_day, late], &run(monday, 2), utc());
367 524 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
368 525 assert_eq!(days[0].all_day, [1]);
369 526 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
@@ -381,7 +538,7 @@ mod tests {
381 538 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382 539 assert!(is_effective_all_day(&holiday, utc()));
383 540 assert!(!is_effective_all_day(&meeting, utc()));
384 let days = week_days(&[holiday, meeting], monday, 1, utc());
541 let days = week_days(&[holiday, meeting], &run(monday, 1), utc());
385 542 assert_eq!(days[0].all_day, [0]);
386 543 assert_eq!(days[0].blocks.len(), 1);
387 544 assert_eq!(days[0].blocks[0].event_index, 1);
@@ -393,7 +550,7 @@ mod tests {
393 550 let conference = event(0, 0, 4 * 24 * 60 - 1);
394 551 assert!(is_effective_all_day(&conference, utc()));
395 552 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396 let days = week_days(&[conference], monday, 5, utc());
553 let days = week_days(&[conference], &run(monday, 5), utc());
397 554 assert!(days.iter().all(|day| day.blocks.is_empty()));
398 555 assert_eq!(days[0].all_day, [0]);
399 556 assert_eq!(days[3].all_day, [0]);
@@ -401,36 +558,32 @@ mod tests {
401 558
402 559 #[test]
403 560 fn spans_start_and_step_like_teams() {
404 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
405 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
406 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
407 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
408 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
409 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
410 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
561 let layout = layout();
562 let (wednesday, monday) = (nov(11), nov(9));
563 assert_eq!(CalendarSpan::Day.start_for(wednesday, &layout), wednesday);
564 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday, &layout), monday);
565 assert_eq!(CalendarSpan::Week.start_for(wednesday, &layout), monday);
566 assert_eq!(CalendarSpan::Week.start_for(nov(15), &layout), monday);
411 567 assert_eq!(
412 CalendarSpan::Day.shifted(wednesday, 1),
568 CalendarSpan::Day.shifted(wednesday, 1, &layout),
413 569 wednesday + Duration::days(1)
414 570 );
415 assert_eq!(CalendarSpan::Week.days(), 7);
416 }
417
418 #[test]
419 fn labels_read_like_teams() {
420 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
421 assert_eq!(range_label(monday, 5), "November 30 - December 4, 2026");
422 assert_eq!(
423 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
424 "November 9-13, 2026"
425 );
571 assert_eq!(visible_dates(CalendarSpan::Week, monday, &layout).len(), 7);
426 572 assert_eq!(
427 range_label(NaiveDate::from_ymd_opt(2026, 12, 28).unwrap(), 7),
428 "December 28, 2026 - January 3, 2027"
573 visible_dates(CalendarSpan::WorkWeek, monday, &layout).len(),
574 5
429 575 );
430 576 assert_eq!(
431 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 1),
432 "November 9, 2026"
577 dates_range(&run(monday, 5), utc()),
578 (
579 local_midnight(monday, utc()),
580 local_midnight(nov(14), utc())
581 )
433 582 );
583 }
584
585 #[test]
586 fn labels_read_like_teams() {
434 587 assert_eq!(hour_label(0, true), "12 AM");
435 588 assert_eq!(hour_label(13, true), "1 PM");
436 589 assert_eq!(hour_label(13, false), "13");
@@ -1,9 +1,10 @@
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
3pub use crate::calendar_prefs::WeekendWorkWeek;
2use chrono::{
4use chrono::{
3 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
5 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4};
6};
5
7
6pub const WORK_WEEK_DAYS: i64 = 5;
7pub const MINUTES_PER_DAY: i64 = 24 * 60;
8pub const MINUTES_PER_DAY: i64 = 24 * 60;
8pub const MONTH_GRID_DAYS: i64 = 42;
9pub const MONTH_GRID_DAYS: i64 = 42;
9
10
@@ -23,11 +24,62 @@ pub struct WeekDay {
23 pub blocks: Vec<WeekBlock>,
24 pub blocks: Vec<WeekBlock>,
24}
25}
25
26
26pub fn week_start(date: NaiveDate) -> NaiveDate {
27/// How weeks are laid out: first day, work days, and what Work week shows on a day off.
27 date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct WeekLayout {
30 pub first_day: Weekday,
31 pub work_days: Vec<Weekday>,
32 pub weekend: WeekendWorkWeek,
33}
34
35impl Default for WeekLayout {
36 fn default() -> Self {
37 WeekLayout {
38 first_day: Weekday::Mon,
39 work_days: vec![
40 Weekday::Mon,
41 Weekday::Tue,
42 Weekday::Wed,
43 Weekday::Thu,
44 Weekday::Fri,
45 ],
46 weekend: WeekendWorkWeek::NextWeek,
47 }
48 }
49}
50
51impl WeekLayout {
52 pub fn is_work_day(&self, day: Weekday) -> bool {
53 self.work_days.contains(&day)
54 }
55
56 /// Work days, or Monday to Friday when none are set (an empty work week shows nothing).
57 fn effective_work_days(&self) -> Vec<Weekday> {
58 if self.work_days.is_empty() {
59 WeekLayout::default().work_days
60 } else {
61 self.work_days.clone()
62 }
63 }
64
65 /// The seven weekdays in order from the first day.
66 pub fn weekdays(&self) -> [Weekday; 7] {
67 let mut day = self.first_day;
68 std::array::from_fn(|_| {
69 let current = day;
70 day = day.succ();
71 current
72 })
73 }
74}
75
76pub fn week_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
77 let back = (7 + date.weekday().num_days_from_monday() - first_day.num_days_from_monday()) % 7;
78 date - Duration::days(i64::from(back))
28}
79}
29
80
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
82#[serde(rename_all = "snake_case")]
31pub enum CalendarSpan {
83pub enum CalendarSpan {
32 Day,
84 Day,
33 #[default]
85 #[default]
@@ -44,34 +96,31 @@ impl CalendarSpan {
44 CalendarSpan::Month,
96 CalendarSpan::Month,
45 ];
97 ];
46
98
47 pub fn label(self) -> &'static str {
99 /// Locale key of the span's name (`calendar.view.span_*`).
100 pub fn label_key(self) -> &'static str {
48 match self {
101 match self {
49 CalendarSpan::Day => "Day",
102 CalendarSpan::Day => "calendar.view.span_day",
50 CalendarSpan::WorkWeek => "Work week",
103 CalendarSpan::WorkWeek => "calendar.view.span_work_week",
51 CalendarSpan::Week => "Week",
104 CalendarSpan::Week => "calendar.view.span_week",
52 CalendarSpan::Month => "Month",
105 CalendarSpan::Month => "calendar.view.span_month",
53 }
106 }
54 }
107 }
55
108
56 pub fn days(self) -> i64 {
109 pub fn label(self) -> String {
57 match self {
110 app_base::ui_locale::tr(self.label_key())
58 CalendarSpan::Day => 1,
59 CalendarSpan::WorkWeek => WORK_WEEK_DAYS,
60 CalendarSpan::Week => 7,
61 CalendarSpan::Month => MONTH_GRID_DAYS,
62 }
63 }
111 }
64
112
65 pub fn start_for(self, date: NaiveDate) -> NaiveDate {
113 /// First date of the range that contains `date`.
114 pub fn start_for(self, date: NaiveDate, layout: &WeekLayout) -> NaiveDate {
66 match self {
115 match self {
67 CalendarSpan::Day => date,
116 CalendarSpan::Day => date,
68 CalendarSpan::WorkWeek => work_week_for(date),
117 CalendarSpan::WorkWeek => work_week_for(date, layout),
69 CalendarSpan::Week => week_start(date),
118 CalendarSpan::Week => week_start(date, layout.first_day),
70 CalendarSpan::Month => month_grid_start(date),
119 CalendarSpan::Month => month_grid_start(date, layout.first_day),
71 }
120 }
72 }
121 }
73
122
74 pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {
123 pub fn shifted(self, start: NaiveDate, steps: i32, layout: &WeekLayout) -> NaiveDate {
75 match self {
124 match self {
76 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
125 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
77 CalendarSpan::WorkWeek | CalendarSpan::Week => {
126 CalendarSpan::WorkWeek | CalendarSpan::Week => {
@@ -84,15 +133,37 @@ impl CalendarSpan {
84 } else {
133 } else {
85 month.checked_sub_months(Months::new(steps.unsigned_abs()))
134 month.checked_sub_months(Months::new(steps.unsigned_abs()))
86 };
135 };
87 month_grid_start(moved.unwrap_or(month))
136 month_grid_start(moved.unwrap_or(month), layout.first_day)
88 }
137 }
89 }
138 }
90 }
139 }
91
140
92 pub fn title(self, start: NaiveDate) -> String {
141 pub fn title(self, start: NaiveDate, layout: &WeekLayout) -> String {
93 match self {
142 match self {
94 CalendarSpan::Month => month_shown(start).format("%B %Y").to_string(),
143 CalendarSpan::Month => app_base::format::month_year_label(month_shown(start)),
95 _ => range_label(start, self.days()),
144 _ => {
145 let dates = visible_dates(self, start, layout);
146 let first = dates.first().copied().unwrap_or(start);
147 let last = dates.last().copied().unwrap_or(start);
148 app_base::format::calendar_range_label(first, last)
149 }
150 }
151 }
152}
153
154/// The dates a span draws, in column order. Work week keeps only work days.
155pub fn visible_dates(span: CalendarSpan, start: NaiveDate, layout: &WeekLayout) -> Vec<NaiveDate> {
156 let run = |days: i64| (0..days).map(|day| start + Duration::days(day)).collect();
157 match span {
158 CalendarSpan::Day => vec![start],
159 CalendarSpan::Week => run(7),
160 CalendarSpan::Month => run(MONTH_GRID_DAYS),
161 CalendarSpan::WorkWeek => {
162 let work_days = layout.effective_work_days();
163 (0..7)
164 .map(|day| start + Duration::days(day))
165 .filter(|date| work_days.contains(&date.weekday()))
166 .collect()
96 }
167 }
97 }
168 }
98}
169}
@@ -101,8 +172,8 @@ pub fn first_of_month(date: NaiveDate) -> NaiveDate {
101 date.with_day(1).unwrap_or(date)
172 date.with_day(1).unwrap_or(date)
102}
173}
103
174
104pub fn month_grid_start(date: NaiveDate) -> NaiveDate {
175pub fn month_grid_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
105 week_start(first_of_month(date))
176 week_start(first_of_month(date), first_day)
106}
177}
107
178
108/// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
179/// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
@@ -110,11 +181,19 @@ pub fn month_shown(grid_start: NaiveDate) -> NaiveDate {
110 first_of_month(grid_start + Duration::weeks(1))
181 first_of_month(grid_start + Duration::weeks(1))
111}
182}
112
183
113/// On a weekend the work week view shows the coming week, as Outlook does.
184/// Start of the week Work week shows for `today`.
114pub fn work_week_for(today: NaiveDate) -> NaiveDate {
185///
115 match today.weekday() {
186/// On a day off with no work day left in this week, Outlook and Teams show the
116 Weekday::Sat | Weekday::Sun => week_start(today) + Duration::weeks(1),
187/// coming week; `WeekendWorkWeek::ThisWeek` keeps the current one.
117 _ => week_start(today),
188pub fn work_week_for(today: NaiveDate, layout: &WeekLayout) -> NaiveDate {
189 let week = week_start(today, layout.first_day);
190 let work_days = layout.effective_work_days();
191 let work_left = (0..7)
192 .map(|day| week + Duration::days(day))
193 .any(|date| date >= today && work_days.contains(&date.weekday()));
194 match layout.weekend {
195 WeekendWorkWeek::NextWeek if !work_left => week + Duration::weeks(1),
196 _ => week,
118 }
197 }
119}
198}
120
199
@@ -125,6 +204,16 @@ pub fn local_midnight(date: NaiveDate, offset: FixedOffset) -> DateTime<Utc> {
125 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
204 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
126}
205}
127
206
207/// UTC range from the first date's midnight to the midnight after the last date.
208pub fn dates_range(dates: &[NaiveDate], offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
209 let first = dates.first().copied().unwrap_or_default();
210 let last = dates.last().copied().unwrap_or(first);
211 (
212 local_midnight(first, offset),
213 local_midnight(last + Duration::days(1), offset),
214 )
215}
216
128pub fn week_range(
217pub fn week_range(
129 start: NaiveDate,
218 start: NaiveDate,
130 days: i64,
219 days: i64,
@@ -161,13 +250,12 @@ pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool
161
250
162pub fn week_days(
251pub fn week_days(
163 events: &[CalendarEvent],
252 events: &[CalendarEvent],
164 start: NaiveDate,
253 dates: &[NaiveDate],
165 days: i64,
166 offset: FixedOffset,
254 offset: FixedOffset,
167) -> Vec<WeekDay> {
255) -> Vec<WeekDay> {
168 (0..days)
256 dates
169 .map(|day| {
257 .iter()
170 let date = start + Duration::days(day);
258 .map(|&date| {
171 let (day_start, day_end) = week_range(date, 1, offset);
259 let (day_start, day_end) = week_range(date, 1, offset);
172 let mut all_day = Vec::new();
260 let mut all_day = Vec::new();
173 let mut spans = Vec::new();
261 let mut spans = Vec::new();
@@ -233,10 +321,6 @@ fn close_cluster(blocks: &mut [WeekBlock], lanes: usize) {
233 }
321 }
234}
322}
235
323
236pub fn range_label(start: NaiveDate, days: i64) -> String {
237 app_base::format::calendar_range_label(start, start + Duration::days(days - 1))
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub enum EventLook {
325pub enum EventLook {
242 Busy,
326 Busy,
@@ -298,40 +382,113 @@ mod tests {
298 FixedOffset::east_opt(0).unwrap()
382 FixedOffset::east_opt(0).unwrap()
299 }
383 }
300
384
385 fn run(start: NaiveDate, days: i64) -> Vec<NaiveDate> {
386 (0..days).map(|day| start + Duration::days(day)).collect()
387 }
388
389 fn nov(day: u32) -> NaiveDate {
390 NaiveDate::from_ymd_opt(2026, 11, day).unwrap()
391 }
392
393 fn layout() -> WeekLayout {
394 WeekLayout::default()
395 }
396
397 fn sunday_first() -> WeekLayout {
398 WeekLayout {
399 first_day: Weekday::Sun,
400 ..WeekLayout::default()
401 }
402 }
403
301 #[test]
404 #[test]
302 fn month_view_steps_whole_months_from_a_monday_grid() {
405 fn month_view_steps_whole_months_from_a_monday_grid() {
303 let date = |day| NaiveDate::from_ymd_opt(2026, 11, day).unwrap();
406 let layout = layout();
304 let start = CalendarSpan::Month.start_for(date(18));
407 let start = CalendarSpan::Month.start_for(nov(18), &layout);
305 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
408 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
306 assert_eq!(CalendarSpan::Month.title(start), "November 2026");
409 assert_eq!(month_shown(start), nov(1));
307 let next = CalendarSpan::Month.shifted(start, 1);
410 let next = CalendarSpan::Month.shifted(start, 1, &layout);
308 assert_eq!(next, NaiveDate::from_ymd_opt(2026, 11, 30).unwrap());
411 assert_eq!(next, nov(30));
309 assert_eq!(CalendarSpan::Month.title(next), "December 2026");
412 let back = CalendarSpan::Month.shifted(start, -11, &layout);
310 let back = CalendarSpan::Month.shifted(start, -11);
311 assert_eq!(CalendarSpan::Month.title(back), "December 2025");
312 assert_eq!(
413 assert_eq!(
313 CalendarSpan::Week.shifted(date(2), -1),
414 month_shown(back),
314 date(2) - Duration::weeks(1)
415 NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
416 );
417 assert_eq!(
418 CalendarSpan::Week.shifted(nov(2), -1, &layout),
419 nov(2) - Duration::weeks(1)
315 );
420 );
316 }
421 }
317
422
318 #[test]
423 #[test]
319 fn the_week_starts_on_monday() {
424 fn a_sunday_first_week_and_month_start_on_sunday() {
320 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
425 let layout = sunday_first();
426 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(15));
427 assert_eq!(
428 visible_dates(CalendarSpan::Week, nov(15), &layout),
429 run(nov(15), 7)
430 );
431 assert_eq!(
432 CalendarSpan::Month.start_for(nov(18), &layout),
433 NaiveDate::from_ymd_opt(2026, 11, 1).unwrap()
434 );
435 assert_eq!(layout.weekdays()[0], Weekday::Sun);
436 assert_eq!(layout.weekdays()[6], Weekday::Sat);
437 }
438
439 #[test]
440 fn a_saturday_first_week_starts_on_saturday() {
441 let layout = WeekLayout {
442 first_day: Weekday::Sat,
443 ..WeekLayout::default()
444 };
445 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(14));
446 assert_eq!(week_start(nov(14), Weekday::Sat), nov(14));
447 }
448
449 #[test]
450 fn work_week_shows_only_the_work_days_even_with_gaps() {
451 let layout = WeekLayout {
452 work_days: vec![Weekday::Mon, Weekday::Tue, Weekday::Thu],
453 ..WeekLayout::default()
454 };
455 let start = CalendarSpan::WorkWeek.start_for(nov(18), &layout);
456 assert_eq!(
457 visible_dates(CalendarSpan::WorkWeek, start, &layout),
458 [nov(16), nov(17), nov(19)]
459 );
460 }
461
462 #[test]
463 fn on_sunday_work_week_shows_next_or_this_week() {
464 let next = layout();
465 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &next), nov(16));
466 let this = WeekLayout {
467 weekend: WeekendWorkWeek::ThisWeek,
468 ..WeekLayout::default()
469 };
470 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &this), nov(9));
471 // Sunday-first weeks still have work days ahead on Sunday.
321 assert_eq!(
472 assert_eq!(
322 week_start(sunday),
473 CalendarSpan::WorkWeek.start_for(nov(15), &sunday_first()),
323 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
474 nov(15)
324 );
475 );
325 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
326 assert_eq!(
476 assert_eq!(
327 work_week_for(sunday),
477 visible_dates(CalendarSpan::WorkWeek, nov(15), &sunday_first()),
328 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
478 run(nov(16), 5)
329 );
479 );
330 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
480 }
481
482 #[test]
483 fn the_week_starts_on_monday() {
484 let sunday = nov(15);
485 assert_eq!(week_start(sunday, Weekday::Mon), nov(9));
331 assert_eq!(
486 assert_eq!(
332 work_week_for(friday),
487 week_start(week_start(sunday, Weekday::Mon), Weekday::Mon),
333 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
488 nov(9)
334 );
489 );
490 assert_eq!(work_week_for(sunday, &layout()), nov(16));
491 assert_eq!(work_week_for(nov(13), &layout()), nov(9));
335 }
492 }
336
493
337 #[test]
494 #[test]
@@ -343,7 +500,7 @@ mod tests {
343 event(13, 0, 30),
500 event(13, 0, 30),
344 ];
501 ];
345 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
502 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
346 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
503 let days = week_days(&events, &run(monday, 5), utc());
347 assert_eq!(days.len(), 5);
504 assert_eq!(days.len(), 5);
348 let lanes: Vec<(usize, usize, usize)> = days[0]
505 let lanes: Vec<(usize, usize, usize)> = days[0]
349 .blocks
506 .blocks
@@ -363,7 +520,7 @@ mod tests {
363 all_day.all_day = true;
520 all_day.all_day = true;
364 let late = event(23, 30, 60);
521 let late = event(23, 30, 60);
365 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
522 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
366 let days = week_days(&[declined, all_day, late], monday, 2, utc());
523 let days = week_days(&[declined, all_day, late], &run(monday, 2), utc());
367 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
524 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
368 assert_eq!(days[0].all_day, [1]);
525 assert_eq!(days[0].all_day, [1]);
369 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
526 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
@@ -381,7 +538,7 @@ mod tests {
381 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
538 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382 assert!(is_effective_all_day(&holiday, utc()));
539 assert!(is_effective_all_day(&holiday, utc()));
383 assert!(!is_effective_all_day(&meeting, utc()));
540 assert!(!is_effective_all_day(&meeting, utc()));
384 let days = week_days(&[holiday, meeting], monday, 1, utc());
541 let days = week_days(&[holiday, meeting], &run(monday, 1), utc());
385 assert_eq!(days[0].all_day, [0]);
542 assert_eq!(days[0].all_day, [0]);
386 assert_eq!(days[0].blocks.len(), 1);
543 assert_eq!(days[0].blocks.len(), 1);
387 assert_eq!(days[0].blocks[0].event_index, 1);
544 assert_eq!(days[0].blocks[0].event_index, 1);
@@ -393,7 +550,7 @@ mod tests {
393 let conference = event(0, 0, 4 * 24 * 60 - 1);
550 let conference = event(0, 0, 4 * 24 * 60 - 1);
394 assert!(is_effective_all_day(&conference, utc()));
551 assert!(is_effective_all_day(&conference, utc()));
395 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
552 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396 let days = week_days(&[conference], monday, 5, utc());
553 let days = week_days(&[conference], &run(monday, 5), utc());
397 assert!(days.iter().all(|day| day.blocks.is_empty()));
554 assert!(days.iter().all(|day| day.blocks.is_empty()));
398 assert_eq!(days[0].all_day, [0]);
555 assert_eq!(days[0].all_day, [0]);
399 assert_eq!(days[3].all_day, [0]);
556 assert_eq!(days[3].all_day, [0]);
@@ -401,36 +558,32 @@ mod tests {
401
558
402 #[test]
559 #[test]
403 fn spans_start_and_step_like_teams() {
560 fn spans_start_and_step_like_teams() {
404 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
561 let layout = layout();
405 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
562 let (wednesday, monday) = (nov(11), nov(9));
406 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
563 assert_eq!(CalendarSpan::Day.start_for(wednesday, &layout), wednesday);
407 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
564 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday, &layout), monday);
408 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
565 assert_eq!(CalendarSpan::Week.start_for(wednesday, &layout), monday);
409 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
566 assert_eq!(CalendarSpan::Week.start_for(nov(15), &layout), monday);
410 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
411 assert_eq!(
567 assert_eq!(
412 CalendarSpan::Day.shifted(wednesday, 1),
568 CalendarSpan::Day.shifted(wednesday, 1, &layout),
413 wednesday + Duration::days(1)
569 wednesday + Duration::days(1)
414 );
570 );
415 assert_eq!(CalendarSpan::Week.days(), 7);
571 assert_eq!(visible_dates(CalendarSpan::Week, monday, &layout).len(), 7);
416 }
417
418 #[test]
419 fn labels_read_like_teams() {
420 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
421 assert_eq!(range_label(monday, 5), "November 30 - December 4, 2026");
422 assert_eq!(
423 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
424 "November 9-13, 2026"
425 );
426 assert_eq!(
572 assert_eq!(
427 range_label(NaiveDate::from_ymd_opt(2026, 12, 28).unwrap(), 7),
573 visible_dates(CalendarSpan::WorkWeek, monday, &layout).len(),
428 "December 28, 2026 - January 3, 2027"
574 5
429 );
575 );
430 assert_eq!(
576 assert_eq!(
431 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 1),
577 dates_range(&run(monday, 5), utc()),
432 "November 9, 2026"
578 (
579 local_midnight(monday, utc()),
580 local_midnight(nov(14), utc())
581 )
433 );
582 );
583 }
584
585 #[test]
586 fn labels_read_like_teams() {
434 assert_eq!(hour_label(0, true), "12 AM");
587 assert_eq!(hour_label(0, true), "12 AM");
435 assert_eq!(hour_label(13, true), "1 PM");
588 assert_eq!(hour_label(13, true), "1 PM");
436 assert_eq!(hour_label(13, false), "13");
589 assert_eq!(hour_label(13, false), "13");
crates/app-state/src/app_state.rs +10 −1
@@ -211,6 +211,9 @@ pub struct AppState {
211 211 pub meeting_toasts: crate::call::MeetingToasts,
212 212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 213 pub calendar_week: crate::call::week::CalendarWeek,
214 pub calendar_prefs: crate::call::calendar_prefs::CalendarPrefs,
215 /// Mailbox time zone name, written back unchanged with the work hours.
216 pub mailbox_time_zone: Option<String>,
214 217 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
215 218 pub calendar_scroll_to_now: u64,
216 219 pub call_backgrounds: crate::call::BackgroundLibrary,
@@ -275,6 +278,7 @@ impl AppState {
275 278 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
276 279 let actions_on_right_click =
277 280 crate::chat_settings_actions::stored_actions_on_right_click(&store);
281 let calendar_prefs = crate::call::calendar_prefs::load_calendar_prefs(&store);
278 282 let mut state = AppState {
279 283 store,
280 284 engine: None,
@@ -375,7 +379,11 @@ impl AppState {
375 379 rsvp_send_response: true,
376 380 meeting_toasts: crate::call::MeetingToasts::default(),
377 381 demo_meetings: Vec::new(),
378 calendar_week: crate::call::week::CalendarWeek::default(),
382 calendar_week: crate::call::week::CalendarWeek::with_span(
383 calendar_prefs.initial_span(),
384 ),
385 calendar_prefs,
386 mailbox_time_zone: None,
379 387 calendar_scroll_to_now: 0,
380 388 call_backgrounds: if mode.demo {
381 389 crate::call::demo_library()
@@ -1178,6 +1186,7 @@ impl AppState {
1178 1186 crate::agent_api::engine_ready(engine.clone(), cx);
1179 1187 self.engine = Some(engine);
1180 1188 self.run_pending_calendar_load(cx);
1189 self.load_work_hours(cx);
1181 1190 self.resend_outbox(cx);
1182 1191 self.refresh_scheduled(cx);
1183 1192 self.refresh_translation_settings(cx);
@@ -211,6 +211,9 @@ pub struct AppState {
211 pub meeting_toasts: crate::call::MeetingToasts,
211 pub meeting_toasts: crate::call::MeetingToasts,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 pub calendar_week: crate::call::week::CalendarWeek,
213 pub calendar_week: crate::call::week::CalendarWeek,
214 pub calendar_prefs: crate::call::calendar_prefs::CalendarPrefs,
215 /// Mailbox time zone name, written back unchanged with the work hours.
216 pub mailbox_time_zone: Option<String>,
214 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
217 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
215 pub calendar_scroll_to_now: u64,
218 pub calendar_scroll_to_now: u64,
216 pub call_backgrounds: crate::call::BackgroundLibrary,
219 pub call_backgrounds: crate::call::BackgroundLibrary,
@@ -275,6 +278,7 @@ impl AppState {
275 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
278 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
276 let actions_on_right_click =
279 let actions_on_right_click =
277 crate::chat_settings_actions::stored_actions_on_right_click(&store);
280 crate::chat_settings_actions::stored_actions_on_right_click(&store);
281 let calendar_prefs = crate::call::calendar_prefs::load_calendar_prefs(&store);
278 let mut state = AppState {
282 let mut state = AppState {
279 store,
283 store,
280 engine: None,
284 engine: None,
@@ -375,7 +379,11 @@ impl AppState {
375 rsvp_send_response: true,
379 rsvp_send_response: true,
376 meeting_toasts: crate::call::MeetingToasts::default(),
380 meeting_toasts: crate::call::MeetingToasts::default(),
377 demo_meetings: Vec::new(),
381 demo_meetings: Vec::new(),
378 calendar_week: crate::call::week::CalendarWeek::default(),
382 calendar_week: crate::call::week::CalendarWeek::with_span(
383 calendar_prefs.initial_span(),
384 ),
385 calendar_prefs,
386 mailbox_time_zone: None,
379 calendar_scroll_to_now: 0,
387 calendar_scroll_to_now: 0,
380 call_backgrounds: if mode.demo {
388 call_backgrounds: if mode.demo {
381 crate::call::demo_library()
389 crate::call::demo_library()
@@ -1178,6 +1186,7 @@ impl AppState {
1178 crate::agent_api::engine_ready(engine.clone(), cx);
1186 crate::agent_api::engine_ready(engine.clone(), cx);
1179 self.engine = Some(engine);
1187 self.engine = Some(engine);
1180 self.run_pending_calendar_load(cx);
1188 self.run_pending_calendar_load(cx);
1189 self.load_work_hours(cx);
1181 self.resend_outbox(cx);
1190 self.resend_outbox(cx);
1182 self.refresh_scheduled(cx);
1191 self.refresh_scheduled(cx);
1183 self.refresh_translation_settings(cx);
1192 self.refresh_translation_settings(cx);
crates/app-state/src/call/calendar_settings.rs added +169 −0
@@ -0,0 +1,169 @@
1 //! Calendar view settings on `AppState`: local preferences plus the mailbox work hours.
2
3 use app_base::ui_locale::tr;
4 use gpui_kit::Context;
5 use graph::MailboxWorkingHours;
6
7 use super::calendar_prefs::{CalendarPrefs, WorkHours, save_calendar_prefs};
8 use crate::app_state::AppState;
9
10 impl AppState {
11 /// Change local calendar preferences, save them and redraw the visible range.
12 pub fn update_calendar_prefs(
13 &mut self,
14 change: impl FnOnce(&mut CalendarPrefs),
15 cx: &mut Context<Self>,
16 ) {
17 let anchor = self.calendar_week.start;
18 change(&mut self.calendar_prefs);
19 save_calendar_prefs(&self.store, &self.calendar_prefs);
20 if let Some(anchor) = anchor {
21 // Week start or work days may have moved: re-anchor on the same date.
22 self.calendar_week.start = Some(self.calendar_span_start(anchor));
23 self.request_calendar_scroll_to_now(cx);
24 self.load_calendar_week(cx);
25 }
26 cx.notify();
27 }
28
29 /// Read the mailbox work hours once the session is there and cache them.
30 pub(crate) fn load_work_hours(&mut self, cx: &mut Context<Self>) {
31 if self.mode.demo {
32 return;
33 }
34 let Some(engine) = self.engine.clone() else {
35 return;
36 };
37 let receiver = crate::runtime::spawn(async move { engine.remote().working_hours().await });
38 cx.spawn(async move |this, cx| {
39 let Ok(result) = receiver.await else {
40 return;
41 };
42 this.update(cx, |state, cx| match result {
43 Ok(mailbox) => {
44 state.mailbox_time_zone = mailbox.time_zone.clone();
45 let hours = work_hours_from(&mailbox);
46 if hours != state.calendar_prefs.work_hours {
47 state.update_calendar_prefs(|prefs| prefs.work_hours = hours, cx);
48 }
49 }
50 Err(error) => crate::diagnostics::record(format!(
51 "calendar: mailbox work hours not read: {error}"
52 )),
53 })
54 .ok();
55 })
56 .detach();
57 }
58
59 /// Save work days and hours to the mailbox; on failure the previous value returns.
60 pub fn set_work_hours(&mut self, hours: WorkHours, cx: &mut Context<Self>) {
61 let previous = self.calendar_prefs.work_hours.clone();
62 if previous == hours {
63 return;
64 }
65 let wanted = hours.clone();
66 self.update_calendar_prefs(|prefs| prefs.work_hours = wanted, cx);
67 if self.mode.demo {
68 return;
69 }
70 let Some(engine) = self.engine.clone() else {
71 self.revert_work_hours(previous, "no session".to_owned(), cx);
72 return;
73 };
74 let mailbox = MailboxWorkingHours {
75 days: hours.days,
76 start: hours.start,
77 end: hours.end,
78 time_zone: self.mailbox_time_zone.clone(),
79 };
80 let receiver =
81 crate::runtime::spawn(async move { engine.remote().set_working_hours(&mailbox).await });
82 cx.spawn(async move |this, cx| {
83 let result = receiver
84 .await
85 .unwrap_or_else(|_| Err(graph::Error::Decode("mailbox task cancelled".into())));
86 this.update(cx, |state, cx| {
87 if let Err(error) = result {
88 state.revert_work_hours(previous, error.to_string(), cx);
89 }
90 })
91 .ok();
92 })
93 .detach();
94 }
95
96 fn revert_work_hours(&mut self, previous: WorkHours, error: String, cx: &mut Context<Self>) {
97 crate::diagnostics::record(format!("calendar: mailbox work hours not saved: {error}"));
98 self.update_calendar_prefs(|prefs| prefs.work_hours = previous, cx);
99 self.raise_notice(tr("settings.calendar.work_hours_not_saved"), None, cx);
100 }
101 }
102
103 fn work_hours_from(mailbox: &MailboxWorkingHours) -> WorkHours {
104 WorkHours {
105 days: mailbox.days.clone(),
106 start: mailbox.start,
107 end: mailbox.end,
108 }
109 }
110
111 #[cfg(test)]
112 mod tests {
113 use std::sync::Arc;
114
115 use chrono::Weekday;
116 use gpui_kit::{AppContext as _, TestAppContext};
117 use store::Store;
118
119 use crate::app_state::{AppState, Mode};
120 use crate::call::calendar_prefs::{DefaultView, WorkHours, load_calendar_prefs};
121 use crate::call::week_grid::CalendarSpan;
122
123 #[gpui_kit::test]
124 fn the_chosen_span_survives_a_restart(cx: &mut TestAppContext) {
125 cx.update(gpui_kit::init);
126 let store = Arc::new(Store::open_in_memory().unwrap());
127 let first = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
128 cx.update(|cx| {
129 first.update(cx, |state, cx| {
130 assert_eq!(state.calendar_week.span, CalendarSpan::WorkWeek);
131 state.set_calendar_span(CalendarSpan::Month, cx);
132 // A day opened from a month cell is temporary navigation.
133 let today = chrono::Local::now().date_naive();
134 state.show_calendar_day(today, cx);
135 })
136 });
137 let second = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
138 cx.update(|cx| {
139 second.update(cx, |state, cx| {
140 assert_eq!(state.calendar_week.span, CalendarSpan::Month);
141 state.update_calendar_prefs(|prefs| prefs.default_view = DefaultView::Week, cx);
142 state.set_calendar_span(CalendarSpan::Day, cx);
143 })
144 });
145 let third = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
146 cx.update(|cx| {
147 third.update(cx, |state, _| {
148 assert_eq!(state.calendar_week.span, CalendarSpan::Week)
149 })
150 });
151 }
152
153 #[gpui_kit::test]
154 fn work_hours_fall_back_when_the_mailbox_cannot_be_written(cx: &mut TestAppContext) {
155 cx.update(gpui_kit::init);
156 let store = Arc::new(Store::open_in_memory().unwrap());
157 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
158 cx.update(|cx| {
159 app.update(cx, |state, cx| {
160 let mut hours = WorkHours::default();
161 hours.days.retain(|day| *day != Weekday::Fri);
162 state.set_work_hours(hours, cx);
163 assert_eq!(state.calendar_prefs.work_hours, WorkHours::default());
164 assert!(state.notice.is_some());
165 })
166 });
167 assert_eq!(load_calendar_prefs(&store).work_hours, WorkHours::default());
168 }
169 }
@@ -0,0 +1,169 @@
1//! Calendar view settings on `AppState`: local preferences plus the mailbox work hours.
2
3use app_base::ui_locale::tr;
4use gpui_kit::Context;
5use graph::MailboxWorkingHours;
6
7use super::calendar_prefs::{CalendarPrefs, WorkHours, save_calendar_prefs};
8use crate::app_state::AppState;
9
10impl AppState {
11 /// Change local calendar preferences, save them and redraw the visible range.
12 pub fn update_calendar_prefs(
13 &mut self,
14 change: impl FnOnce(&mut CalendarPrefs),
15 cx: &mut Context<Self>,
16 ) {
17 let anchor = self.calendar_week.start;
18 change(&mut self.calendar_prefs);
19 save_calendar_prefs(&self.store, &self.calendar_prefs);
20 if let Some(anchor) = anchor {
21 // Week start or work days may have moved: re-anchor on the same date.
22 self.calendar_week.start = Some(self.calendar_span_start(anchor));
23 self.request_calendar_scroll_to_now(cx);
24 self.load_calendar_week(cx);
25 }
26 cx.notify();
27 }
28
29 /// Read the mailbox work hours once the session is there and cache them.
30 pub(crate) fn load_work_hours(&mut self, cx: &mut Context<Self>) {
31 if self.mode.demo {
32 return;
33 }
34 let Some(engine) = self.engine.clone() else {
35 return;
36 };
37 let receiver = crate::runtime::spawn(async move { engine.remote().working_hours().await });
38 cx.spawn(async move |this, cx| {
39 let Ok(result) = receiver.await else {
40 return;
41 };
42 this.update(cx, |state, cx| match result {
43 Ok(mailbox) => {
44 state.mailbox_time_zone = mailbox.time_zone.clone();
45 let hours = work_hours_from(&mailbox);
46 if hours != state.calendar_prefs.work_hours {
47 state.update_calendar_prefs(|prefs| prefs.work_hours = hours, cx);
48 }
49 }
50 Err(error) => crate::diagnostics::record(format!(
51 "calendar: mailbox work hours not read: {error}"
52 )),
53 })
54 .ok();
55 })
56 .detach();
57 }
58
59 /// Save work days and hours to the mailbox; on failure the previous value returns.
60 pub fn set_work_hours(&mut self, hours: WorkHours, cx: &mut Context<Self>) {
61 let previous = self.calendar_prefs.work_hours.clone();
62 if previous == hours {
63 return;
64 }
65 let wanted = hours.clone();
66 self.update_calendar_prefs(|prefs| prefs.work_hours = wanted, cx);
67 if self.mode.demo {
68 return;
69 }
70 let Some(engine) = self.engine.clone() else {
71 self.revert_work_hours(previous, "no session".to_owned(), cx);
72 return;
73 };
74 let mailbox = MailboxWorkingHours {
75 days: hours.days,
76 start: hours.start,
77 end: hours.end,
78 time_zone: self.mailbox_time_zone.clone(),
79 };
80 let receiver =
81 crate::runtime::spawn(async move { engine.remote().set_working_hours(&mailbox).await });
82 cx.spawn(async move |this, cx| {
83 let result = receiver
84 .await
85 .unwrap_or_else(|_| Err(graph::Error::Decode("mailbox task cancelled".into())));
86 this.update(cx, |state, cx| {
87 if let Err(error) = result {
88 state.revert_work_hours(previous, error.to_string(), cx);
89 }
90 })
91 .ok();
92 })
93 .detach();
94 }
95
96 fn revert_work_hours(&mut self, previous: WorkHours, error: String, cx: &mut Context<Self>) {
97 crate::diagnostics::record(format!("calendar: mailbox work hours not saved: {error}"));
98 self.update_calendar_prefs(|prefs| prefs.work_hours = previous, cx);
99 self.raise_notice(tr("settings.calendar.work_hours_not_saved"), None, cx);
100 }
101}
102
103fn work_hours_from(mailbox: &MailboxWorkingHours) -> WorkHours {
104 WorkHours {
105 days: mailbox.days.clone(),
106 start: mailbox.start,
107 end: mailbox.end,
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use std::sync::Arc;
114
115 use chrono::Weekday;
116 use gpui_kit::{AppContext as _, TestAppContext};
117 use store::Store;
118
119 use crate::app_state::{AppState, Mode};
120 use crate::call::calendar_prefs::{DefaultView, WorkHours, load_calendar_prefs};
121 use crate::call::week_grid::CalendarSpan;
122
123 #[gpui_kit::test]
124 fn the_chosen_span_survives_a_restart(cx: &mut TestAppContext) {
125 cx.update(gpui_kit::init);
126 let store = Arc::new(Store::open_in_memory().unwrap());
127 let first = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
128 cx.update(|cx| {
129 first.update(cx, |state, cx| {
130 assert_eq!(state.calendar_week.span, CalendarSpan::WorkWeek);
131 state.set_calendar_span(CalendarSpan::Month, cx);
132 // A day opened from a month cell is temporary navigation.
133 let today = chrono::Local::now().date_naive();
134 state.show_calendar_day(today, cx);
135 })
136 });
137 let second = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
138 cx.update(|cx| {
139 second.update(cx, |state, cx| {
140 assert_eq!(state.calendar_week.span, CalendarSpan::Month);
141 state.update_calendar_prefs(|prefs| prefs.default_view = DefaultView::Week, cx);
142 state.set_calendar_span(CalendarSpan::Day, cx);
143 })
144 });
145 let third = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
146 cx.update(|cx| {
147 third.update(cx, |state, _| {
148 assert_eq!(state.calendar_week.span, CalendarSpan::Week)
149 })
150 });
151 }
152
153 #[gpui_kit::test]
154 fn work_hours_fall_back_when_the_mailbox_cannot_be_written(cx: &mut TestAppContext) {
155 cx.update(gpui_kit::init);
156 let store = Arc::new(Store::open_in_memory().unwrap());
157 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
158 cx.update(|cx| {
159 app.update(cx, |state, cx| {
160 let mut hours = WorkHours::default();
161 hours.days.retain(|day| *day != Weekday::Fri);
162 state.set_work_hours(hours, cx);
163 assert_eq!(state.calendar_prefs.work_hours, WorkHours::default());
164 assert!(state.notice.is_some());
165 })
166 });
167 assert_eq!(load_calendar_prefs(&store).work_hours, WorkHours::default());
168 }
169}
crates/app-state/src/call/mod.rs +5 −3
@@ -1,5 +1,6 @@
1 1 pub mod actions;
2 2 pub mod calendar;
3 pub mod calendar_settings;
3 4 pub mod consult;
4 5 pub mod end_actions;
5 6 pub mod features;
@@ -24,9 +25,10 @@ pub mod view_actions;
24 25 pub mod week;
25 26
26 27 pub use app_call_model::{
27 agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,
28 media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,
29 ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
28 agenda, background, bubbles, calendar_now, calendar_prefs, caption_style, demo, end_screen,
29 fullscreen, health, media, mic, model, options_dialog, people, preview, record_rights,
30 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
31 week_grid,
30 32 };
31 33
32 34 pub use actions::{
@@ -1,5 +1,6 @@
1pub mod actions;
1pub mod actions;
2pub mod calendar;
2pub mod calendar;
3pub mod calendar_settings;
3pub mod consult;
4pub mod consult;
4pub mod end_actions;
5pub mod end_actions;
5pub mod features;
6pub mod features;
@@ -24,9 +25,10 @@ pub mod view_actions;
24pub mod week;
25pub mod week;
25
26
26pub use app_call_model::{
27pub use app_call_model::{
27 agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,
28 agenda, background, bubbles, calendar_now, calendar_prefs, caption_style, demo, end_screen,
28 media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,
29 fullscreen, health, media, mic, model, options_dialog, people, preview, record_rights,
29 ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
30 recording_menu, report, ring, share_view, stage_layout, stage_split, transcript, view_settings,
31 week_grid,
30};
32};
31
33
32pub use actions::{
34pub use actions::{
crates/app-state/src/call/week.rs +57 −10
@@ -1,12 +1,15 @@
1 1 use std::time::Instant;
2 2
3 3 use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4 use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
4 use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
5 5 use gpui_kit::Context;
6 6
7 7 use super::agenda::demo_events;
8 8 use super::calendar::demo_anchor;
9 use super::week_grid::{CalendarSpan, local_midnight, week_range, week_start};
9 use super::calendar_prefs::save_calendar_prefs;
10 use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12 };
10 13 use crate::app_state::AppState;
11 14
12 15 pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
@@ -34,6 +37,13 @@ pub struct CalendarWeek {
34 37 }
35 38
36 39 impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
37 47 /// True once when a skipped load should run now.
38 48 pub(crate) fn take_pending(&mut self) -> bool {
39 49 std::mem::take(&mut self.pending)
@@ -41,10 +51,36 @@ impl CalendarWeek {
41 51 }
42 52
43 53 impl AppState {
54 /// Week layout from the calendar settings and the regional first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs
57 .layout(app_base::format::regional_first_day())
58 }
59
44 60 pub fn calendar_start(&self) -> NaiveDate {
45 61 self.calendar_week
46 62 .start
47 .unwrap_or_else(|| self.calendar_week.span.start_for(Local::now().date_naive()))
63 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
64 }
65
66 /// Start of the visible span's range that contains `date`.
67 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
68 self.calendar_week
69 .span
70 .start_for(date, &self.calendar_layout())
71 }
72
73 /// The dates the grid draws, in column order.
74 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
75 visible_dates(
76 self.calendar_week.span,
77 self.calendar_start(),
78 &self.calendar_layout(),
79 )
80 }
81
82 pub fn calendar_shows_today(&self) -> bool {
83 self.calendar_dates().contains(&Local::now().date_naive())
48 84 }
49 85
50 86 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
@@ -80,7 +116,9 @@ impl AppState {
80 116
81 117 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
82 118 let span = self.calendar_week.span;
83 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
119 let layout = self.calendar_layout();
120 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
121 self.request_calendar_scroll_to_now(cx);
84 122 self.load_calendar_week(cx);
85 123 }
86 124
@@ -97,13 +135,21 @@ impl AppState {
97 135 cx.notify();
98 136 }
99 137
138 /// Span chosen from the view menu; remembered as the last used span.
100 139 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
101 140 let today = Local::now().date_naive();
102 141 let start = self.calendar_start();
103 let shown =
104 start <= today && today < start + Duration::days(self.calendar_week.span.days());
142 let anchor = if self.calendar_shows_today() {
143 today
144 } else {
145 start
146 };
105 147 self.calendar_week.span = span;
106 self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));
148 self.calendar_week.start = Some(self.calendar_span_start(anchor));
149 if self.calendar_prefs.last_span != span {
150 self.calendar_prefs.last_span = span;
151 save_calendar_prefs(&self.store, &self.calendar_prefs);
152 }
107 153 if crate::call::calendar_now::shows_hour_grid(span) {
108 154 self.request_calendar_scroll_to_now(cx);
109 155 }
@@ -111,7 +157,8 @@ impl AppState {
111 157 }
112 158
113 159 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
114 self.calendar_week.start = Some(self.calendar_week.span.start_for(date));
160 self.calendar_week.start = Some(self.calendar_span_start(date));
161 self.request_calendar_scroll_to_now(cx);
115 162 self.load_calendar_week(cx);
116 163 }
117 164
@@ -123,10 +170,10 @@ impl AppState {
123 170 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
124 171 let start = self.calendar_start();
125 172 let offset = Local::now().offset().fix();
126 let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
173 let (from, to) = dates_range(&self.calendar_dates(), offset);
127 174 if self.mode.demo {
128 175 let mut events = demo_events(demo_anchor());
129 events.extend(demo_week(week_start(start), offset));
176 events.extend(demo_week(week_start(start, Weekday::Mon), offset));
130 177 events.extend(self.demo_meetings.iter().cloned());
131 178 events.retain(|event| event.end > from && event.start < to);
132 179 events.sort_by_key(|event| (event.start, event.end));
@@ -1,12 +1,15 @@
1use std::time::Instant;
1use std::time::Instant;
2
2
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
5use gpui_kit::Context;
5use gpui_kit::Context;
6
6
7use super::agenda::demo_events;
7use super::agenda::demo_events;
8use super::calendar::demo_anchor;
8use super::calendar::demo_anchor;
9use super::week_grid::{CalendarSpan, local_midnight, week_range, week_start};
9use super::calendar_prefs::save_calendar_prefs;
10use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12};
10use crate::app_state::AppState;
13use crate::app_state::AppState;
11
14
12pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
15pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
@@ -34,6 +37,13 @@ pub struct CalendarWeek {
34}
37}
35
38
36impl CalendarWeek {
39impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
37 /// True once when a skipped load should run now.
47 /// True once when a skipped load should run now.
38 pub(crate) fn take_pending(&mut self) -> bool {
48 pub(crate) fn take_pending(&mut self) -> bool {
39 std::mem::take(&mut self.pending)
49 std::mem::take(&mut self.pending)
@@ -41,10 +51,36 @@ impl CalendarWeek {
41}
51}
42
52
43impl AppState {
53impl AppState {
54 /// Week layout from the calendar settings and the regional first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs
57 .layout(app_base::format::regional_first_day())
58 }
59
44 pub fn calendar_start(&self) -> NaiveDate {
60 pub fn calendar_start(&self) -> NaiveDate {
45 self.calendar_week
61 self.calendar_week
46 .start
62 .start
47 .unwrap_or_else(|| self.calendar_week.span.start_for(Local::now().date_naive()))
63 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
64 }
65
66 /// Start of the visible span's range that contains `date`.
67 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
68 self.calendar_week
69 .span
70 .start_for(date, &self.calendar_layout())
71 }
72
73 /// The dates the grid draws, in column order.
74 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
75 visible_dates(
76 self.calendar_week.span,
77 self.calendar_start(),
78 &self.calendar_layout(),
79 )
80 }
81
82 pub fn calendar_shows_today(&self) -> bool {
83 self.calendar_dates().contains(&Local::now().date_naive())
48 }
84 }
49
85
50 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
86 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
@@ -80,7 +116,9 @@ impl AppState {
80
116
81 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
117 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
82 let span = self.calendar_week.span;
118 let span = self.calendar_week.span;
83 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
119 let layout = self.calendar_layout();
120 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
121 self.request_calendar_scroll_to_now(cx);
84 self.load_calendar_week(cx);
122 self.load_calendar_week(cx);
85 }
123 }
86
124
@@ -97,13 +135,21 @@ impl AppState {
97 cx.notify();
135 cx.notify();
98 }
136 }
99
137
138 /// Span chosen from the view menu; remembered as the last used span.
100 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
139 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
101 let today = Local::now().date_naive();
140 let today = Local::now().date_naive();
102 let start = self.calendar_start();
141 let start = self.calendar_start();
103 let shown =
142 let anchor = if self.calendar_shows_today() {
104 start <= today && today < start + Duration::days(self.calendar_week.span.days());
143 today
144 } else {
145 start
146 };
105 self.calendar_week.span = span;
147 self.calendar_week.span = span;
106 self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));
148 self.calendar_week.start = Some(self.calendar_span_start(anchor));
149 if self.calendar_prefs.last_span != span {
150 self.calendar_prefs.last_span = span;
151 save_calendar_prefs(&self.store, &self.calendar_prefs);
152 }
107 if crate::call::calendar_now::shows_hour_grid(span) {
153 if crate::call::calendar_now::shows_hour_grid(span) {
108 self.request_calendar_scroll_to_now(cx);
154 self.request_calendar_scroll_to_now(cx);
109 }
155 }
@@ -111,7 +157,8 @@ impl AppState {
111 }
157 }
112
158
113 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
159 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
114 self.calendar_week.start = Some(self.calendar_week.span.start_for(date));
160 self.calendar_week.start = Some(self.calendar_span_start(date));
161 self.request_calendar_scroll_to_now(cx);
115 self.load_calendar_week(cx);
162 self.load_calendar_week(cx);
116 }
163 }
117
164
@@ -123,10 +170,10 @@ impl AppState {
123 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
170 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
124 let start = self.calendar_start();
171 let start = self.calendar_start();
125 let offset = Local::now().offset().fix();
172 let offset = Local::now().offset().fix();
126 let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
173 let (from, to) = dates_range(&self.calendar_dates(), offset);
127 if self.mode.demo {
174 if self.mode.demo {
128 let mut events = demo_events(demo_anchor());
175 let mut events = demo_events(demo_anchor());
129 events.extend(demo_week(week_start(start), offset));
176 events.extend(demo_week(week_start(start, Weekday::Mon), offset));
130 events.extend(self.demo_meetings.iter().cloned());
177 events.extend(self.demo_meetings.iter().cloned());
131 events.retain(|event| event.end > from && event.start < to);
178 events.retain(|event| event.end > from && event.start < to);
132 events.sort_by_key(|event| (event.start, event.end));
179 events.sort_by_key(|event| (event.start, event.end));
crates/app/src/views/calendar_date_picker.rs +35 −24
@@ -1,7 +1,7 @@
1 1 use std::cell::RefCell;
2 2 use std::rc::Rc;
3 3
4 use chrono::{Datelike, Duration, Local, Months, NaiveDate};
4 use chrono::{Datelike, Duration, Local, Months, NaiveDate, Weekday};
5 5 use gpui_kit::assets::IconName;
6 6 use gpui_kit::component::Sizable as _;
7 7 use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -15,31 +15,30 @@ use crate::call::week_grid::{MONTH_GRID_DAYS, first_of_month, month_grid_start};
15 15 use crate::theme;
16 16
17 17 pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
18 const WEEKDAY_LETTERS: [&str; 7] = ["M", "T", "W", "T", "F", "S", "S"];
19 18 const CELL_SIZE: f32 = 32.;
20 19 const PICKER_PADDING: f32 = 12.;
21 20
22 21 pub struct DatePicker {
23 22 app: Entity<AppState>,
24 23 month: NaiveDate,
25 shown_start: NaiveDate,
26 shown_days: i64,
24 shown: Vec<NaiveDate>,
25 first_day: Weekday,
27 26 popover: WeakEntity<PopoverState>,
28 27 }
29 28
30 29 impl DatePicker {
31 30 fn new(
32 31 app: Entity<AppState>,
33 shown_start: NaiveDate,
34 shown_days: i64,
32 shown: Vec<NaiveDate>,
33 first_day: Weekday,
35 34 month: NaiveDate,
36 35 popover: WeakEntity<PopoverState>,
37 36 ) -> Self {
38 37 DatePicker {
39 38 app,
40 39 month: first_of_month(month),
41 shown_start,
42 shown_days,
40 shown,
41 first_day,
43 42 popover,
44 43 }
45 44 }
@@ -64,8 +63,7 @@ impl DatePicker {
64 63
65 64 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 65 let in_month = date.month() == self.month.month();
67 let shown =
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
66 let shown = self.shown.contains(&date);
69 67 let is_today = date == today;
70 68 div()
71 69 .id(SharedString::from(format!("date-picker-{date}")))
@@ -96,7 +94,7 @@ impl DatePicker {
96 94 impl Render for DatePicker {
97 95 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
98 96 let today = Local::now().date_naive();
99 let start = month_grid_start(self.month);
97 let start = month_grid_start(self.month, self.first_day);
100 98 let days: Vec<NaiveDate> = (0..MONTH_GRID_DAYS)
101 99 .map(|offset| start + Duration::days(offset))
102 100 .collect();
@@ -151,25 +149,37 @@ impl Render for DatePicker {
151 149 ),
152 150 ),
153 151 )
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
155 div()
156 .size(px(CELL_SIZE))
157 .flex()
158 .items_center()
159 .justify_center()
160 .text_size(px(11.))
161 .text_color(theme::text_muted())
162 .child(*letter)
163 })))
152 .child(
153 h_flex().children(weekday_letters(self.first_day).map(|letter| {
154 div()
155 .size(px(CELL_SIZE))
156 .flex()
157 .items_center()
158 .justify_center()
159 .text_size(px(11.))
160 .text_color(theme::text_muted())
161 .child(letter)
162 })),
163 )
164 164 .children(weeks)
165 165 }
166 166 }
167 167
168 /// Weekday initials in column order from the first day, in the app language.
169 fn weekday_letters(first_day: Weekday) -> [String; 7] {
170 let mut day = first_day;
171 std::array::from_fn(|_| {
172 let letter = app_base::format::weekday_name(day, app_base::format::WeekdayWidth::Letter);
173 day = day.succ();
174 letter
175 })
176 }
177
168 178 pub fn date_picker_button(
169 179 app: &Entity<AppState>,
170 180 title: String,
171 shown_start: NaiveDate,
172 shown_days: i64,
181 shown: Vec<NaiveDate>,
182 first_day: Weekday,
173 183 month: NaiveDate,
174 184 ) -> AnyElement {
175 185 let app = app.clone();
@@ -196,7 +206,8 @@ pub fn date_picker_button(
196 206 }
197 207 let popover = cx.entity().downgrade();
198 208 let app = app.clone();
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
209 let created =
210 cx.new(|_| DatePicker::new(app, shown.clone(), first_day, month, popover));
200 211 *picker.borrow_mut() = Some(created.clone());
201 212 created
202 213 })
@@ -1,7 +1,7 @@
1use std::cell::RefCell;
1use std::cell::RefCell;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use chrono::{Datelike, Duration, Local, Months, NaiveDate};
4use chrono::{Datelike, Duration, Local, Months, NaiveDate, Weekday};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::Sizable as _;
6use gpui_kit::component::Sizable as _;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -15,31 +15,30 @@ use crate::call::week_grid::{MONTH_GRID_DAYS, first_of_month, month_grid_start};
15use crate::theme;
15use crate::theme;
16
16
17pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
17pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
18const WEEKDAY_LETTERS: [&str; 7] = ["M", "T", "W", "T", "F", "S", "S"];
19const CELL_SIZE: f32 = 32.;
18const CELL_SIZE: f32 = 32.;
20const PICKER_PADDING: f32 = 12.;
19const PICKER_PADDING: f32 = 12.;
21
20
22pub struct DatePicker {
21pub struct DatePicker {
23 app: Entity<AppState>,
22 app: Entity<AppState>,
24 month: NaiveDate,
23 month: NaiveDate,
25 shown_start: NaiveDate,
24 shown: Vec<NaiveDate>,
26 shown_days: i64,
25 first_day: Weekday,
27 popover: WeakEntity<PopoverState>,
26 popover: WeakEntity<PopoverState>,
28}
27}
29
28
30impl DatePicker {
29impl DatePicker {
31 fn new(
30 fn new(
32 app: Entity<AppState>,
31 app: Entity<AppState>,
33 shown_start: NaiveDate,
32 shown: Vec<NaiveDate>,
34 shown_days: i64,
33 first_day: Weekday,
35 month: NaiveDate,
34 month: NaiveDate,
36 popover: WeakEntity<PopoverState>,
35 popover: WeakEntity<PopoverState>,
37 ) -> Self {
36 ) -> Self {
38 DatePicker {
37 DatePicker {
39 app,
38 app,
40 month: first_of_month(month),
39 month: first_of_month(month),
41 shown_start,
40 shown,
42 shown_days,
41 first_day,
43 popover,
42 popover,
44 }
43 }
45 }
44 }
@@ -64,8 +63,7 @@ impl DatePicker {
64
63
65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
64 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 let in_month = date.month() == self.month.month();
65 let in_month = date.month() == self.month.month();
67 let shown =
66 let shown = self.shown.contains(&date);
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
69 let is_today = date == today;
67 let is_today = date == today;
70 div()
68 div()
71 .id(SharedString::from(format!("date-picker-{date}")))
69 .id(SharedString::from(format!("date-picker-{date}")))
@@ -96,7 +94,7 @@ impl DatePicker {
96impl Render for DatePicker {
94impl Render for DatePicker {
97 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
95 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
98 let today = Local::now().date_naive();
96 let today = Local::now().date_naive();
99 let start = month_grid_start(self.month);
97 let start = month_grid_start(self.month, self.first_day);
100 let days: Vec<NaiveDate> = (0..MONTH_GRID_DAYS)
98 let days: Vec<NaiveDate> = (0..MONTH_GRID_DAYS)
101 .map(|offset| start + Duration::days(offset))
99 .map(|offset| start + Duration::days(offset))
102 .collect();
100 .collect();
@@ -151,25 +149,37 @@ impl Render for DatePicker {
151 ),
149 ),
152 ),
150 ),
153 )
151 )
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
152 .child(
155 div()
153 h_flex().children(weekday_letters(self.first_day).map(|letter| {
156 .size(px(CELL_SIZE))
154 div()
157 .flex()
155 .size(px(CELL_SIZE))
158 .items_center()
156 .flex()
159 .justify_center()
157 .items_center()
160 .text_size(px(11.))
158 .justify_center()
161 .text_color(theme::text_muted())
159 .text_size(px(11.))
162 .child(*letter)
160 .text_color(theme::text_muted())
163 })))
161 .child(letter)
162 })),
163 )
164 .children(weeks)
164 .children(weeks)
165 }
165 }
166}
166}
167
167
168/// Weekday initials in column order from the first day, in the app language.
169fn weekday_letters(first_day: Weekday) -> [String; 7] {
170 let mut day = first_day;
171 std::array::from_fn(|_| {
172 let letter = app_base::format::weekday_name(day, app_base::format::WeekdayWidth::Letter);
173 day = day.succ();
174 letter
175 })
176}
177
168pub fn date_picker_button(
178pub fn date_picker_button(
169 app: &Entity<AppState>,
179 app: &Entity<AppState>,
170 title: String,
180 title: String,
171 shown_start: NaiveDate,
181 shown: Vec<NaiveDate>,
172 shown_days: i64,
182 first_day: Weekday,
173 month: NaiveDate,
183 month: NaiveDate,
174) -> AnyElement {
184) -> AnyElement {
175 let app = app.clone();
185 let app = app.clone();
@@ -196,7 +206,8 @@ pub fn date_picker_button(
196 }
206 }
197 let popover = cx.entity().downgrade();
207 let popover = cx.entity().downgrade();
198 let app = app.clone();
208 let app = app.clone();
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
209 let created =
210 cx.new(|_| DatePicker::new(app, shown.clone(), first_day, month, popover));
200 *picker.borrow_mut() = Some(created.clone());
211 *picker.borrow_mut() = Some(created.clone());
201 created
212 created
202 })
213 })
crates/app/src/views/calendar_month.rs +5 −4
@@ -1,6 +1,7 @@
1 1 use app_base::format::clock_format;
2 use app_base::format::{WeekdayWidth, weekday_name};
2 3 use chatsvc::CalendarEvent;
3 use chrono::{Datelike, FixedOffset, NaiveDate};
4 use chrono::{Datelike, FixedOffset, NaiveDate, Weekday};
4 5 use gpui_kit::component::{h_flex, v_flex};
5 6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
@@ -10,7 +11,6 @@ use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10 11 use crate::theme;
11 12
12 13 pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13 const WEEKDAY_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
14 14 const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
15 15 const VISIBLE_EVENTS: usize = 3;
16 16 const DAY_NUMBER_SIZE: f32 = 24.;
@@ -168,6 +168,7 @@ pub fn month_grid(
168 168 events: &[CalendarEvent],
169 169 today: NaiveDate,
170 170 offset: FixedOffset,
171 weekdays: [Weekday; 7],
171 172 ) -> Div {
172 173 let shown_month = month_shown(start);
173 174 let mut rows = v_flex().flex_1().min_h_0().w_full();
@@ -191,13 +192,13 @@ pub fn month_grid(
191 192 .h(px(WEEKDAY_HEADER_HEIGHT))
192 193 .flex_none()
193 194 .w_full()
194 .children(WEEKDAY_NAMES.iter().map(|name| {
195 .children(weekdays.iter().map(|day| {
195 196 div()
196 197 .flex_1()
197 198 .px(px(10.))
198 199 .text_size(px(12.))
199 200 .text_color(theme::text_muted())
200 .child(*name)
201 .child(weekday_name(*day, WeekdayWidth::Short))
201 202 })),
202 203 )
203 204 .child(rows)
@@ -1,6 +1,7 @@
1use app_base::format::clock_format;
1use app_base::format::clock_format;
2use app_base::format::{WeekdayWidth, weekday_name};
2use chatsvc::CalendarEvent;
3use chatsvc::CalendarEvent;
3use chrono::{Datelike, FixedOffset, NaiveDate};
4use chrono::{Datelike, FixedOffset, NaiveDate, Weekday};
4use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
@@ -10,7 +11,6 @@ use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10use crate::theme;
11use crate::theme;
11
12
12pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13const WEEKDAY_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
14const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
14const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
15const VISIBLE_EVENTS: usize = 3;
15const VISIBLE_EVENTS: usize = 3;
16const DAY_NUMBER_SIZE: f32 = 24.;
16const DAY_NUMBER_SIZE: f32 = 24.;
@@ -168,6 +168,7 @@ pub fn month_grid(
168 events: &[CalendarEvent],
168 events: &[CalendarEvent],
169 today: NaiveDate,
169 today: NaiveDate,
170 offset: FixedOffset,
170 offset: FixedOffset,
171 weekdays: [Weekday; 7],
171) -> Div {
172) -> Div {
172 let shown_month = month_shown(start);
173 let shown_month = month_shown(start);
173 let mut rows = v_flex().flex_1().min_h_0().w_full();
174 let mut rows = v_flex().flex_1().min_h_0().w_full();
@@ -191,13 +192,13 @@ pub fn month_grid(
191 .h(px(WEEKDAY_HEADER_HEIGHT))
192 .h(px(WEEKDAY_HEADER_HEIGHT))
192 .flex_none()
193 .flex_none()
193 .w_full()
194 .w_full()
194 .children(WEEKDAY_NAMES.iter().map(|name| {
195 .children(weekdays.iter().map(|day| {
195 div()
196 div()
196 .flex_1()
197 .flex_1()
197 .px(px(10.))
198 .px(px(10.))
198 .text_size(px(12.))
199 .text_size(px(12.))
199 .text_color(theme::text_muted())
200 .text_color(theme::text_muted())
200 .child(*name)
201 .child(weekday_name(*day, WeekdayWidth::Short))
201 })),
202 })),
202 )
203 )
203 .child(rows)
204 .child(rows)
crates/app/src/views/calendar_view.rs +19 −11
@@ -27,7 +27,8 @@ use crate::call::calendar_now::{
27 27 };
28 28 use crate::call::week::CalendarLoadFailure;
29 29 use crate::call::week_grid::{
30 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 CalendarSpan, EventLook, WeekBlock, WeekDay, WeekLayout, event_look, hour_label, month_shown,
31 week_days,
31 32 };
32 33 use crate::i18n::tr;
33 34 use crate::theme;
@@ -105,10 +106,7 @@ impl CalendarView {
105 106 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
106 107 let (scroll_to_now, span, today_visible) = {
107 108 let state = self.state.read(cx);
108 let start = state.calendar_start();
109 let today = Local::now().date_naive();
110 let today_visible = start <= today
111 && today < start + chrono::Duration::days(state.calendar_week.span.days());
109 let today_visible = state.calendar_shows_today();
112 110 (
113 111 state.calendar_scroll_to_now,
114 112 state.calendar_week.span,
@@ -181,7 +179,14 @@ impl CalendarView {
181 179 cx.notify();
182 180 }
183 181
184 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
182 fn header(
183 &self,
184 start: NaiveDate,
185 span: CalendarSpan,
186 dates: &[NaiveDate],
187 layout: &WeekLayout,
188 compact: bool,
189 ) -> impl IntoElement {
185 190 let span_state = self.state.clone();
186 191 let label = |text: &'static str| (!compact).then_some(text);
187 192 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
@@ -242,9 +247,9 @@ impl CalendarView {
242 247 )
243 248 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
244 249 &self.state,
245 span.title(start),
246 start,
247 span.days(),
250 span.title(start, layout),
251 dates.to_vec(),
252 layout.first_day,
248 253 if span == CalendarSpan::Month {
249 254 month_shown(start)
250 255 } else {
@@ -815,7 +820,9 @@ impl Render for CalendarView {
815 820 let loading = state.calendar_week.loading && events.is_empty();
816 821 let offset = Local::now().offset().fix();
817 822 let span = state.calendar_week.span;
818 let days = week_days(&events, start, span.days(), offset);
823 let layout = state.calendar_layout();
824 let dates = state.calendar_dates();
825 let days = week_days(&events, &dates, offset);
819 826 let today = Local::now().date_naive();
820 827 let now = Utc::now();
821 828 let show_picker = !compact;
@@ -836,7 +843,7 @@ impl Render for CalendarView {
836 843 .flex_1()
837 844 .min_w_0()
838 845 .h_full()
839 .child(self.header(start, span, compact))
846 .child(self.header(start, span, &dates, &layout, compact))
840 847 .children(load_notices(&self.state, &failures, loading))
841 848 .children(meeting_proposal_cards(cx))
842 849 .map(|calendar| {
@@ -848,6 +855,7 @@ impl Render for CalendarView {
848 855 &events,
849 856 today,
850 857 offset,
858 layout.weekdays(),
851 859 ))
852 860 } else {
853 861 calendar
@@ -27,7 +27,8 @@ use crate::call::calendar_now::{
27};
27};
28use crate::call::week::CalendarLoadFailure;
28use crate::call::week::CalendarLoadFailure;
29use crate::call::week_grid::{
29use crate::call::week_grid::{
30 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 CalendarSpan, EventLook, WeekBlock, WeekDay, WeekLayout, event_look, hour_label, month_shown,
31 week_days,
31};
32};
32use crate::i18n::tr;
33use crate::i18n::tr;
33use crate::theme;
34use crate::theme;
@@ -105,10 +106,7 @@ impl CalendarView {
105 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
106 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
106 let (scroll_to_now, span, today_visible) = {
107 let (scroll_to_now, span, today_visible) = {
107 let state = self.state.read(cx);
108 let state = self.state.read(cx);
108 let start = state.calendar_start();
109 let today_visible = state.calendar_shows_today();
109 let today = Local::now().date_naive();
110 let today_visible = start <= today
111 && today < start + chrono::Duration::days(state.calendar_week.span.days());
112 (
110 (
113 state.calendar_scroll_to_now,
111 state.calendar_scroll_to_now,
114 state.calendar_week.span,
112 state.calendar_week.span,
@@ -181,7 +179,14 @@ impl CalendarView {
181 cx.notify();
179 cx.notify();
182 }
180 }
183
181
184 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
182 fn header(
183 &self,
184 start: NaiveDate,
185 span: CalendarSpan,
186 dates: &[NaiveDate],
187 layout: &WeekLayout,
188 compact: bool,
189 ) -> impl IntoElement {
185 let span_state = self.state.clone();
190 let span_state = self.state.clone();
186 let label = |text: &'static str| (!compact).then_some(text);
191 let label = |text: &'static str| (!compact).then_some(text);
187 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
192 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
@@ -242,9 +247,9 @@ impl CalendarView {
242 )
247 )
243 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
248 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
244 &self.state,
249 &self.state,
245 span.title(start),
250 span.title(start, layout),
246 start,
251 dates.to_vec(),
247 span.days(),
252 layout.first_day,
248 if span == CalendarSpan::Month {
253 if span == CalendarSpan::Month {
249 month_shown(start)
254 month_shown(start)
250 } else {
255 } else {
@@ -815,7 +820,9 @@ impl Render for CalendarView {
815 let loading = state.calendar_week.loading && events.is_empty();
820 let loading = state.calendar_week.loading && events.is_empty();
816 let offset = Local::now().offset().fix();
821 let offset = Local::now().offset().fix();
817 let span = state.calendar_week.span;
822 let span = state.calendar_week.span;
818 let days = week_days(&events, start, span.days(), offset);
823 let layout = state.calendar_layout();
824 let dates = state.calendar_dates();
825 let days = week_days(&events, &dates, offset);
819 let today = Local::now().date_naive();
826 let today = Local::now().date_naive();
820 let now = Utc::now();
827 let now = Utc::now();
821 let show_picker = !compact;
828 let show_picker = !compact;
@@ -836,7 +843,7 @@ impl Render for CalendarView {
836 .flex_1()
843 .flex_1()
837 .min_w_0()
844 .min_w_0()
838 .h_full()
845 .h_full()
839 .child(self.header(start, span, compact))
846 .child(self.header(start, span, &dates, &layout, compact))
840 .children(load_notices(&self.state, &failures, loading))
847 .children(load_notices(&self.state, &failures, loading))
841 .children(meeting_proposal_cards(cx))
848 .children(meeting_proposal_cards(cx))
842 .map(|calendar| {
849 .map(|calendar| {
@@ -848,6 +855,7 @@ impl Render for CalendarView {
848 &events,
855 &events,
849 today,
856 today,
850 offset,
857 offset,
858 layout.weekdays(),
851 ))
859 ))
852 } else {
860 } else {
853 calendar
861 calendar
crates/graph/src/lib.rs +2 −0
@@ -4,6 +4,7 @@ mod content;
4 4 mod error;
5 5 mod files;
6 6 mod library;
7 mod mailbox;
7 8 mod models;
8 9 mod outgoing;
9 10 mod page;
@@ -23,6 +24,7 @@ pub use files::{
23 24 percent_done, share_id,
24 25 };
25 26 pub use library::DriveEntry;
27 pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
26 28 pub use models::{
27 29 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
28 30 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
@@ -4,6 +4,7 @@ mod content;
4mod error;
4mod error;
5mod files;
5mod files;
6mod library;
6mod library;
7mod mailbox;
7mod models;
8mod models;
8mod outgoing;
9mod outgoing;
9mod page;
10mod page;
@@ -23,6 +24,7 @@ pub use files::{
23 percent_done, share_id,
24 percent_done, share_id,
24};
25};
25pub use library::DriveEntry;
26pub use library::DriveEntry;
27pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
26pub use models::{
28pub use models::{
27 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
29 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
28 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
30 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
crates/graph/src/mailbox.rs added +160 −0
@@ -0,0 +1,160 @@
1 //! Outlook mailbox working hours (`/me/mailboxSettings`), the setting Teams and
2 //! Outlook read for work days and hours.
3 //!
4 //! `MailboxSettings.Read` is not granted to the Teams client; `ReadWrite` is.
5
6 use chrono::{NaiveTime, Weekday};
7 use serde_json::{Value, json};
8 use session::{Method, Scope};
9
10 use crate::client::Graph;
11 use crate::error::{Error, Result};
12 use crate::urls;
13
14 const MAILBOX_SCOPE: &str = "MailboxSettings.ReadWrite";
15 const TIME_FORMAT: &str = "%H:%M:%S%.f";
16
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct MailboxWorkingHours {
19 pub days: Vec<Weekday>,
20 pub start: NaiveTime,
21 pub end: NaiveTime,
22 /// Windows or IANA name as the mailbox stores it; written back unchanged.
23 pub time_zone: Option<String>,
24 }
25
26 impl Graph {
27 pub async fn working_hours(&self) -> Result<MailboxWorkingHours> {
28 let url = urls::mailbox_settings();
29 let body = self.get(&url, &Scope::graph(MAILBOX_SCOPE)).await?;
30 parse_working_hours(&body)
31 .ok_or_else(|| Error::from(session::Error::api(200, &url, body.clone())))
32 }
33
34 pub async fn set_working_hours(&self, hours: &MailboxWorkingHours) -> Result<()> {
35 self.session()
36 .request(
37 Method::Patch,
38 &urls::mailbox_settings(),
39 &Scope::graph(MAILBOX_SCOPE),
40 Some(working_hours_body(hours)),
41 )
42 .await?;
43 Ok(())
44 }
45 }
46
47 pub fn parse_working_hours(body: &Value) -> Option<MailboxWorkingHours> {
48 let hours = body.get("workingHours")?;
49 let days = hours
50 .get("daysOfWeek")?
51 .as_array()?
52 .iter()
53 .filter_map(Value::as_str)
54 .filter_map(|day| day.parse::<Weekday>().ok())
55 .collect();
56 let time = |key: &str| {
57 let text = hours.get(key)?.as_str()?;
58 NaiveTime::parse_from_str(text, TIME_FORMAT)
59 .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M"))
60 .ok()
61 };
62 Some(MailboxWorkingHours {
63 days,
64 start: time("startTime")?,
65 end: time("endTime")?,
66 time_zone: hours
67 .pointer("/timeZone/name")
68 .and_then(Value::as_str)
69 .map(str::to_owned),
70 })
71 }
72
73 pub fn working_hours_body(hours: &MailboxWorkingHours) -> Value {
74 let mut working = json!({
75 "daysOfWeek": hours.days.iter().map(|day| day_name(*day)).collect::<Vec<_>>(),
76 "startTime": graph_time(hours.start),
77 "endTime": graph_time(hours.end),
78 });
79 if let Some(name) = &hours.time_zone {
80 working["timeZone"] = json!({ "name": name });
81 }
82 json!({ "workingHours": working })
83 }
84
85 /// Graph writes seven fraction digits; working hours never carry fractions.
86 fn graph_time(time: NaiveTime) -> String {
87 format!("{}.0000000", time.format("%H:%M:%S"))
88 }
89
90 fn day_name(day: Weekday) -> &'static str {
91 match day {
92 Weekday::Mon => "monday",
93 Weekday::Tue => "tuesday",
94 Weekday::Wed => "wednesday",
95 Weekday::Thu => "thursday",
96 Weekday::Fri => "friday",
97 Weekday::Sat => "saturday",
98 Weekday::Sun => "sunday",
99 }
100 }
101
102 #[cfg(test)]
103 mod tests {
104 use super::*;
105
106 fn captured() -> Value {
107 // Shape of GET /me/mailboxSettings as returned on 2026-11-15.
108 json!({
109 "timeFormat": "HH:mm",
110 "dateFormat": "d MMM yyyy",
111 "workingHours": {
112 "daysOfWeek": ["monday", "tuesday", "wednesday", "thursday", "friday"],
113 "startTime": "08:00:00.0000000",
114 "endTime": "17:00:00.0000000",
115 "timeZone": {"name": "W. Europe Standard Time"}
116 }
117 })
118 }
119
120 #[test]
121 fn mailbox_working_hours_parse() {
122 let hours = parse_working_hours(&captured()).unwrap();
123 assert_eq!(
124 hours.days,
125 [
126 Weekday::Mon,
127 Weekday::Tue,
128 Weekday::Wed,
129 Weekday::Thu,
130 Weekday::Fri
131 ]
132 );
133 assert_eq!(hours.start, NaiveTime::from_hms_opt(8, 0, 0).unwrap());
134 assert_eq!(hours.end, NaiveTime::from_hms_opt(17, 0, 0).unwrap());
135 assert_eq!(hours.time_zone.as_deref(), Some("W. Europe Standard Time"));
136 }
137
138 #[test]
139 fn mailbox_working_hours_body_round_trips() {
140 let mut hours = parse_working_hours(&captured()).unwrap();
141 hours.days.retain(|day| *day != Weekday::Fri);
142 hours.start = NaiveTime::from_hms_opt(7, 30, 0).unwrap();
143 let body = working_hours_body(&hours);
144 assert_eq!(
145 body["workingHours"]["daysOfWeek"],
146 json!(["monday", "tuesday", "wednesday", "thursday"])
147 );
148 assert_eq!(body["workingHours"]["startTime"], "07:30:00.0000000");
149 assert_eq!(
150 body["workingHours"]["timeZone"]["name"],
151 "W. Europe Standard Time"
152 );
153 assert_eq!(parse_working_hours(&body).unwrap(), hours);
154 }
155
156 #[test]
157 fn mailbox_without_working_hours_is_none() {
158 assert!(parse_working_hours(&json!({"timeFormat": "HH:mm"})).is_none());
159 }
160 }
@@ -0,0 +1,160 @@
1//! Outlook mailbox working hours (`/me/mailboxSettings`), the setting Teams and
2//! Outlook read for work days and hours.
3//!
4//! `MailboxSettings.Read` is not granted to the Teams client; `ReadWrite` is.
5
6use chrono::{NaiveTime, Weekday};
7use serde_json::{Value, json};
8use session::{Method, Scope};
9
10use crate::client::Graph;
11use crate::error::{Error, Result};
12use crate::urls;
13
14const MAILBOX_SCOPE: &str = "MailboxSettings.ReadWrite";
15const TIME_FORMAT: &str = "%H:%M:%S%.f";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MailboxWorkingHours {
19 pub days: Vec<Weekday>,
20 pub start: NaiveTime,
21 pub end: NaiveTime,
22 /// Windows or IANA name as the mailbox stores it; written back unchanged.
23 pub time_zone: Option<String>,
24}
25
26impl Graph {
27 pub async fn working_hours(&self) -> Result<MailboxWorkingHours> {
28 let url = urls::mailbox_settings();
29 let body = self.get(&url, &Scope::graph(MAILBOX_SCOPE)).await?;
30 parse_working_hours(&body)
31 .ok_or_else(|| Error::from(session::Error::api(200, &url, body.clone())))
32 }
33
34 pub async fn set_working_hours(&self, hours: &MailboxWorkingHours) -> Result<()> {
35 self.session()
36 .request(
37 Method::Patch,
38 &urls::mailbox_settings(),
39 &Scope::graph(MAILBOX_SCOPE),
40 Some(working_hours_body(hours)),
41 )
42 .await?;
43 Ok(())
44 }
45}
46
47pub fn parse_working_hours(body: &Value) -> Option<MailboxWorkingHours> {
48 let hours = body.get("workingHours")?;
49 let days = hours
50 .get("daysOfWeek")?
51 .as_array()?
52 .iter()
53 .filter_map(Value::as_str)
54 .filter_map(|day| day.parse::<Weekday>().ok())
55 .collect();
56 let time = |key: &str| {
57 let text = hours.get(key)?.as_str()?;
58 NaiveTime::parse_from_str(text, TIME_FORMAT)
59 .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M"))
60 .ok()
61 };
62 Some(MailboxWorkingHours {
63 days,
64 start: time("startTime")?,
65 end: time("endTime")?,
66 time_zone: hours
67 .pointer("/timeZone/name")
68 .and_then(Value::as_str)
69 .map(str::to_owned),
70 })
71}
72
73pub fn working_hours_body(hours: &MailboxWorkingHours) -> Value {
74 let mut working = json!({
75 "daysOfWeek": hours.days.iter().map(|day| day_name(*day)).collect::<Vec<_>>(),
76 "startTime": graph_time(hours.start),
77 "endTime": graph_time(hours.end),
78 });
79 if let Some(name) = &hours.time_zone {
80 working["timeZone"] = json!({ "name": name });
81 }
82 json!({ "workingHours": working })
83}
84
85/// Graph writes seven fraction digits; working hours never carry fractions.
86fn graph_time(time: NaiveTime) -> String {
87 format!("{}.0000000", time.format("%H:%M:%S"))
88}
89
90fn day_name(day: Weekday) -> &'static str {
91 match day {
92 Weekday::Mon => "monday",
93 Weekday::Tue => "tuesday",
94 Weekday::Wed => "wednesday",
95 Weekday::Thu => "thursday",
96 Weekday::Fri => "friday",
97 Weekday::Sat => "saturday",
98 Weekday::Sun => "sunday",
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 fn captured() -> Value {
107 // Shape of GET /me/mailboxSettings as returned on 2026-11-15.
108 json!({
109 "timeFormat": "HH:mm",
110 "dateFormat": "d MMM yyyy",
111 "workingHours": {
112 "daysOfWeek": ["monday", "tuesday", "wednesday", "thursday", "friday"],
113 "startTime": "08:00:00.0000000",
114 "endTime": "17:00:00.0000000",
115 "timeZone": {"name": "W. Europe Standard Time"}
116 }
117 })
118 }
119
120 #[test]
121 fn mailbox_working_hours_parse() {
122 let hours = parse_working_hours(&captured()).unwrap();
123 assert_eq!(
124 hours.days,
125 [
126 Weekday::Mon,
127 Weekday::Tue,
128 Weekday::Wed,
129 Weekday::Thu,
130 Weekday::Fri
131 ]
132 );
133 assert_eq!(hours.start, NaiveTime::from_hms_opt(8, 0, 0).unwrap());
134 assert_eq!(hours.end, NaiveTime::from_hms_opt(17, 0, 0).unwrap());
135 assert_eq!(hours.time_zone.as_deref(), Some("W. Europe Standard Time"));
136 }
137
138 #[test]
139 fn mailbox_working_hours_body_round_trips() {
140 let mut hours = parse_working_hours(&captured()).unwrap();
141 hours.days.retain(|day| *day != Weekday::Fri);
142 hours.start = NaiveTime::from_hms_opt(7, 30, 0).unwrap();
143 let body = working_hours_body(&hours);
144 assert_eq!(
145 body["workingHours"]["daysOfWeek"],
146 json!(["monday", "tuesday", "wednesday", "thursday"])
147 );
148 assert_eq!(body["workingHours"]["startTime"], "07:30:00.0000000");
149 assert_eq!(
150 body["workingHours"]["timeZone"]["name"],
151 "W. Europe Standard Time"
152 );
153 assert_eq!(parse_working_hours(&body).unwrap(), hours);
154 }
155
156 #[test]
157 fn mailbox_without_working_hours_is_none() {
158 assert!(parse_working_hours(&json!({"timeFormat": "HH:mm"})).is_none());
159 }
160}
crates/graph/src/urls.rs +4 −0
@@ -62,6 +62,10 @@ pub fn user_direct_reports(user_id: &str) -> String {
62 62 )
63 63 }
64 64
65 pub fn mailbox_settings() -> String {
66 format!("{GRAPH}/v1.0/me/mailboxSettings")
67 }
68
65 69 pub fn get_schedule() -> String {
66 70 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67 71 }
@@ -62,6 +62,10 @@ pub fn user_direct_reports(user_id: &str) -> String {
62 )
62 )
63}
63}
64
64
65pub fn mailbox_settings() -> String {
66 format!("{GRAPH}/v1.0/me/mailboxSettings")
67}
68
65pub fn get_schedule() -> String {
69pub fn get_schedule() -> String {
66 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
70 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67}
71}