| 1 | use std::time::Instant; |
| 2 | |
| 3 | use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs}; |
| 4 | use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday}; |
| 5 | use gpui_kit::Context; |
| 6 | |
| 7 | use super::agenda::demo_events; |
| 8 | use super::calendar::demo_anchor; |
| 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 | }; |
| 13 | use crate::app_state::AppState; |
| 14 | |
| 15 | pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar."; |
| 16 | |
| 17 | /// One calendar source that did not load for the visible range. |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub struct CalendarLoadFailure { |
| 20 | pub source: CalendarSource, |
| 21 | pub message: String, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, Default)] |
| 25 | pub struct CalendarWeek { |
| 26 | pub start: Option<NaiveDate>, |
| 27 | pub span: CalendarSpan, |
| 28 | pub events: Vec<CalendarEvent>, |
| 29 | pub loading: bool, |
| 30 | /// Sources that failed on the last load; cleared by the next load. |
| 31 | pub failures: Vec<CalendarLoadFailure>, |
| 32 | /// The calendar section is on screen (drives refresh on the poll interval). |
| 33 | pub visible: bool, |
| 34 | /// A load was asked for before the session existed; run it once it does. |
| 35 | pending: bool, |
| 36 | request: u64, |
| 37 | } |
| 38 | |
| 39 | impl CalendarWeek { |
| 40 | pub fn with_span(span: CalendarSpan) -> Self { |
| 41 | CalendarWeek { |
| 42 | span, |
| 43 | ..CalendarWeek::default() |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// True once when a skipped load should run now. |
| 48 | pub(crate) fn take_pending(&mut self) -> bool { |
| 49 | std::mem::take(&mut self.pending) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl AppState { |
| 54 | /// Week layout from the calendar settings and the regional format's first day. |
| 55 | pub fn calendar_layout(&self) -> WeekLayout { |
| 56 | self.calendar_prefs |
| 57 | .layout(app_base::format::regional_first_day()) |
| 58 | } |
| 59 | |
| 60 | pub fn calendar_start(&self) -> NaiveDate { |
| 61 | self.calendar_week |
| 62 | .start |
| 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()) |
| 84 | } |
| 85 | |
| 86 | pub fn open_calendar(&mut self, cx: &mut Context<Self>) { |
| 87 | self.calendar_week.visible = true; |
| 88 | self.calendar_week.start = Some(self.calendar_start()); |
| 89 | self.request_calendar_scroll_to_now(cx); |
| 90 | self.load_calendar_week(cx); |
| 91 | } |
| 92 | |
| 93 | /// The user left the calendar section; stop refreshing its range. |
| 94 | pub fn close_calendar(&mut self) { |
| 95 | self.calendar_week.visible = false; |
| 96 | } |
| 97 | |
| 98 | /// Reload the visible range after an agenda poll while the calendar is on screen. |
| 99 | pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) { |
| 100 | if self.calendar_week.visible && self.calendar_week.start.is_some() { |
| 101 | self.load_calendar_week(cx); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Retry from the inline notice after a source failed. |
| 106 | pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) { |
| 107 | self.load_calendar_week(cx); |
| 108 | } |
| 109 | |
| 110 | /// Run a grid load that was skipped because no session existed yet. |
| 111 | pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) { |
| 112 | if self.calendar_week.take_pending() { |
| 113 | self.load_calendar_week(cx); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) { |
| 118 | let span = self.calendar_week.span; |
| 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); |
| 122 | self.load_calendar_week(cx); |
| 123 | } |
| 124 | |
| 125 | pub fn calendar_to_today(&mut self, cx: &mut Context<Self>) { |
| 126 | self.calendar_week.start = None; |
| 127 | self.open_calendar(cx); |
| 128 | } |
| 129 | |
| 130 | /// Month the mini month shows: the user's own choice, else the visible range. |
| 131 | pub fn calendar_mini_month_shown(&self) -> NaiveDate { |
| 132 | self.calendar_mini_month.unwrap_or_else(|| { |
| 133 | let dates = self.calendar_dates(); |
| 134 | let middle = dates.get(dates.len() / 2).copied(); |
| 135 | super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start())) |
| 136 | }) |
| 137 | } |
| 138 | |
| 139 | pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) { |
| 140 | let month = self.calendar_mini_month_shown(); |
| 141 | let moved = if steps >= 0 { |
| 142 | month.checked_add_months(chrono::Months::new(steps.unsigned_abs())) |
| 143 | } else { |
| 144 | month.checked_sub_months(chrono::Months::new(steps.unsigned_abs())) |
| 145 | }; |
| 146 | self.calendar_mini_month = Some(moved.unwrap_or(month)); |
| 147 | cx.notify(); |
| 148 | } |
| 149 | |
| 150 | pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) { |
| 151 | if let Some(index) = self |
| 152 | .calendar_expanded_groups |
| 153 | .iter() |
| 154 | .position(|existing| existing == group) |
| 155 | { |
| 156 | self.calendar_expanded_groups.remove(index); |
| 157 | } else { |
| 158 | self.calendar_expanded_groups.push(group.to_owned()); |
| 159 | } |
| 160 | cx.notify(); |
| 161 | } |
| 162 | |
| 163 | pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) { |
| 164 | // Every navigation lands here: the mini month follows the grid again. |
| 165 | self.calendar_mini_month = None; |
| 166 | if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) { |
| 167 | return; |
| 168 | } |
| 169 | self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1); |
| 170 | cx.notify(); |
| 171 | } |
| 172 | |
| 173 | /// Span chosen from the view menu; remembered as the last used span. |
| 174 | pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) { |
| 175 | let today = Local::now().date_naive(); |
| 176 | let start = self.calendar_start(); |
| 177 | let anchor = if self.calendar_shows_today() { |
| 178 | today |
| 179 | } else { |
| 180 | start |
| 181 | }; |
| 182 | self.calendar_week.span = span; |
| 183 | self.calendar_week.start = Some(self.calendar_span_start(anchor)); |
| 184 | self.calendar_mini_month = None; |
| 185 | if self.calendar_prefs.last_span != span { |
| 186 | self.calendar_prefs.last_span = span; |
| 187 | save_calendar_prefs(&self.store, &self.calendar_prefs); |
| 188 | } |
| 189 | if crate::call::calendar_now::shows_hour_grid(span) { |
| 190 | self.request_calendar_scroll_to_now(cx); |
| 191 | } |
| 192 | self.load_calendar_week(cx); |
| 193 | } |
| 194 | |
| 195 | pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) { |
| 196 | self.calendar_week.start = Some(self.calendar_span_start(date)); |
| 197 | self.request_calendar_scroll_to_now(cx); |
| 198 | self.load_calendar_week(cx); |
| 199 | } |
| 200 | |
| 201 | pub fn show_calendar_day(&mut self, date: NaiveDate, cx: &mut Context<Self>) { |
| 202 | self.calendar_week.span = CalendarSpan::Day; |
| 203 | self.show_calendar_date(date, cx); |
| 204 | } |
| 205 | |
| 206 | pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) { |
| 207 | let start = self.calendar_start(); |
| 208 | let offset = Local::now().offset().fix(); |
| 209 | let (from, to) = dates_range(&self.calendar_dates(), offset); |
| 210 | if self.mode.demo { |
| 211 | let mut events = demo_events(demo_anchor()); |
| 212 | // Demo meetings sit Monday to Friday of the week the grid shows. |
| 213 | // The Monday inside the first shown week, whatever day the week starts on. |
| 214 | let dates = self.calendar_dates(); |
| 215 | let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start); |
| 216 | events.extend(demo_week(week_start(anchor, Weekday::Mon), offset)); |
| 217 | events.extend(self.demo_meetings.iter().cloned()); |
| 218 | events.retain(|event| event.end > from && event.start < to); |
| 219 | events.sort_by_key(|event| (event.start, event.end)); |
| 220 | self.calendar_week.events = events; |
| 221 | cx.notify(); |
| 222 | return; |
| 223 | } |
| 224 | // Grid load needs only the signed-in session, never the calling engine. |
| 225 | let Some(engine) = self.engine.clone() else { |
| 226 | self.calendar_week.pending = true; |
| 227 | return; |
| 228 | }; |
| 229 | self.calendar_week.request += 1; |
| 230 | let request = self.calendar_week.request; |
| 231 | self.calendar_week.loading = true; |
| 232 | cx.notify(); |
| 233 | let store = self.store.clone(); |
| 234 | let receiver = crate::runtime::spawn(async move { |
| 235 | let started = Instant::now(); |
| 236 | let accounts = store::load_calendar_accounts(&store); |
| 237 | let mut fetched_accounts = accounts.clone(); |
| 238 | let mut combined = Vec::new(); |
| 239 | let mut failures = Vec::new(); |
| 240 | let mut outlook_count = None; |
| 241 | if accounts.outlook_selected { |
| 242 | match Calendar::new(engine.remote().session()) |
| 243 | .calendar_view(from, to) |
| 244 | .await |
| 245 | { |
| 246 | Ok(events) => { |
| 247 | outlook_count = Some(events.len()); |
| 248 | combined.extend(events); |
| 249 | } |
| 250 | Err(error) => failures.push(CalendarLoadFailure { |
| 251 | source: CalendarSource::Outlook, |
| 252 | message: error.to_string(), |
| 253 | }), |
| 254 | } |
| 255 | } |
| 256 | let mut google_count = None; |
| 257 | if accounts.has_google() { |
| 258 | match crate::google_calendar_sync::fetch_google_events( |
| 259 | &mut fetched_accounts, |
| 260 | from, |
| 261 | to, |
| 262 | ) |
| 263 | .await |
| 264 | { |
| 265 | Ok(events) => { |
| 266 | // Keep only refreshed tokens: a toggle made meanwhile must survive. |
| 267 | let _ = store::merge_google_tokens(&store, &fetched_accounts); |
| 268 | google_count = Some(events.len()); |
| 269 | combined.extend(events); |
| 270 | } |
| 271 | Err(error) => failures.push(CalendarLoadFailure { |
| 272 | source: CalendarSource::Google, |
| 273 | message: error, |
| 274 | }), |
| 275 | } |
| 276 | } |
| 277 | let mut caldav_count = None; |
| 278 | if accounts.has_caldav() { |
| 279 | match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await |
| 280 | { |
| 281 | Ok((events, partial)) => { |
| 282 | let _ = store::merge_caldav_metadata(&store, &fetched_accounts); |
| 283 | caldav_count = Some(events.len()); |
| 284 | combined.extend(events); |
| 285 | for message in partial { |
| 286 | failures.push(CalendarLoadFailure { |
| 287 | source: CalendarSource::CalDav, |
| 288 | message, |
| 289 | }); |
| 290 | } |
| 291 | } |
| 292 | Err(error) => failures.push(CalendarLoadFailure { |
| 293 | source: CalendarSource::CalDav, |
| 294 | message: error, |
| 295 | }), |
| 296 | } |
| 297 | } |
| 298 | if accounts.has_ics() { |
| 299 | match crate::ics_sync::fetch_ics_events(&accounts, from, to).await { |
| 300 | Ok((events, partial)) => { |
| 301 | combined.extend(events); |
| 302 | for message in partial { |
| 303 | failures.push(CalendarLoadFailure { |
| 304 | source: CalendarSource::Ics, |
| 305 | message, |
| 306 | }); |
| 307 | } |
| 308 | } |
| 309 | Err(error) => failures.push(CalendarLoadFailure { |
| 310 | source: CalendarSource::Ics, |
| 311 | message: error, |
| 312 | }), |
| 313 | } |
| 314 | } |
| 315 | crate::diagnostics::record(load_summary( |
| 316 | from, |
| 317 | to, |
| 318 | outlook_count, |
| 319 | google_count, |
| 320 | caldav_count, |
| 321 | started.elapsed().as_millis(), |
| 322 | &failures, |
| 323 | )); |
| 324 | let home = home_calendar(&accounts); |
| 325 | (chatsvc::merge_calendar_events(combined, home), failures) |
| 326 | }); |
| 327 | cx.spawn(async move |this, cx| { |
| 328 | let loaded = receiver.await.unwrap_or_else(|_| { |
| 329 | ( |
| 330 | Vec::new(), |
| 331 | vec![CalendarLoadFailure { |
| 332 | source: CalendarSource::Outlook, |
| 333 | message: CALENDAR_LOAD_FAILURE.to_owned(), |
| 334 | }], |
| 335 | ) |
| 336 | }); |
| 337 | this.update(cx, |state, cx| { |
| 338 | if state.calendar_week.request != request { |
| 339 | return; |
| 340 | } |
| 341 | state.calendar_week.loading = false; |
| 342 | let (events, failures) = loaded; |
| 343 | let previous = std::mem::take(&mut state.calendar_week.events); |
| 344 | let mut events = keep_failed_sources(&previous, events, &failures); |
| 345 | retain_peek_details(&previous, &mut events); |
| 346 | state.calendar_week.events = events; |
| 347 | state.calendar_week.failures = failures; |
| 348 | cx.notify(); |
| 349 | }) |
| 350 | .ok(); |
| 351 | }) |
| 352 | .detach(); |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | /// A source that failed keeps its previous events on screen instead of blanking the week. |
| 357 | /// When the round already returned some events for that source (partial calendar failure), |
| 358 | /// previous events are left out so successful calendars are not duplicated. |
| 359 | pub(crate) fn keep_failed_sources( |
| 360 | previous: &[CalendarEvent], |
| 361 | mut events: Vec<CalendarEvent>, |
| 362 | failures: &[CalendarLoadFailure], |
| 363 | ) -> Vec<CalendarEvent> { |
| 364 | for failure in failures { |
| 365 | if events.iter().any(|event| event.source == failure.source) { |
| 366 | continue; |
| 367 | } |
| 368 | events.extend( |
| 369 | previous |
| 370 | .iter() |
| 371 | .filter(|event| event.source == failure.source) |
| 372 | .cloned(), |
| 373 | ); |
| 374 | } |
| 375 | events.sort_by_key(|event| (event.start, event.end)); |
| 376 | events |
| 377 | } |
| 378 | |
| 379 | /// One diagnostics line per grid load, so an empty week can be traced to its cause. |
| 380 | pub(crate) fn load_summary( |
| 381 | from: chrono::DateTime<chrono::Utc>, |
| 382 | to: chrono::DateTime<chrono::Utc>, |
| 383 | outlook: Option<usize>, |
| 384 | google: Option<usize>, |
| 385 | caldav: Option<usize>, |
| 386 | elapsed_ms: u128, |
| 387 | failures: &[CalendarLoadFailure], |
| 388 | ) -> String { |
| 389 | let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string()); |
| 390 | let mut line = format!( |
| 391 | "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms", |
| 392 | from.format("%Y-%m-%dT%H:%MZ"), |
| 393 | to.format("%Y-%m-%dT%H:%MZ"), |
| 394 | count(outlook), |
| 395 | count(google), |
| 396 | count(caldav), |
| 397 | ); |
| 398 | for failure in failures { |
| 399 | line.push_str(&format!( |
| 400 | "; {} failed: {}", |
| 401 | failure.source.label(), |
| 402 | failure.message.chars().take(160).collect::<String>() |
| 403 | )); |
| 404 | } |
| 405 | line |
| 406 | } |
| 407 | |
| 408 | fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> { |
| 409 | use store::CalendarProvider; |
| 410 | let source = match accounts.home.provider { |
| 411 | CalendarProvider::Outlook => CalendarSource::Outlook, |
| 412 | CalendarProvider::Google => CalendarSource::Google, |
| 413 | CalendarProvider::CalDav => CalendarSource::CalDav, |
| 414 | }; |
| 415 | Some(chatsvc::HomeCalendar { |
| 416 | source, |
| 417 | account_id: accounts.home.account_id.as_str(), |
| 418 | calendar_id: accounts.home.calendar_id.as_str(), |
| 419 | }) |
| 420 | } |
| 421 | |
| 422 | fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) { |
| 423 | for event in events { |
| 424 | let Some(old) = previous |
| 425 | .iter() |
| 426 | .find(|candidate| candidate.object_id == event.object_id) |
| 427 | else { |
| 428 | continue; |
| 429 | }; |
| 430 | if event.body_preview.is_none() { |
| 431 | event.body_preview = old.body_preview.clone(); |
| 432 | } |
| 433 | if event.body_html.is_none() { |
| 434 | event.body_html = old.body_html.clone(); |
| 435 | } |
| 436 | if event.attendees.is_empty() { |
| 437 | event.attendees = old.attendees.clone(); |
| 438 | } |
| 439 | if event.location.is_none() { |
| 440 | event.location = old.location.clone(); |
| 441 | } |
| 442 | if event.response_counts.is_none() { |
| 443 | event.response_counts = old.response_counts; |
| 444 | } |
| 445 | if event.series_master_id.is_none() { |
| 446 | event.series_master_id = old.series_master_id.clone(); |
| 447 | } |
| 448 | if event.reminders.is_empty() { |
| 449 | event.reminders = old.reminders.clone(); |
| 450 | } |
| 451 | if event.source_link.is_none() { |
| 452 | event.source_link = old.source_link.clone(); |
| 453 | } |
| 454 | if event.web_link.is_none() { |
| 455 | event.web_link = old.web_link.clone(); |
| 456 | } |
| 457 | if event.calendar_name.is_none() { |
| 458 | event.calendar_name = old.calendar_name.clone(); |
| 459 | } |
| 460 | if old.series { |
| 461 | event.series = true; |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs { |
| 467 | match response { |
| 468 | _ if subject.starts_with("Following: ") => ShowAs::Free, |
| 469 | ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative, |
| 470 | _ => ShowAs::Busy, |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> { |
| 475 | let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [ |
| 476 | ( |
| 477 | "Team standup", |
| 478 | "Mara Lindqvist", |
| 479 | 0, |
| 480 | 9 * 60 + 30, |
| 481 | 15, |
| 482 | ResponseType::Accepted, |
| 483 | ), |
| 484 | ( |
| 485 | "Release review", |
| 486 | "Jonas Ortega", |
| 487 | 0, |
| 488 | 11 * 60, |
| 489 | 60, |
| 490 | ResponseType::Organizer, |
| 491 | ), |
| 492 | ( |
| 493 | "Customer sync", |
| 494 | "Priya Nair", |
| 495 | 0, |
| 496 | 11 * 60 + 30, |
| 497 | 60, |
| 498 | ResponseType::NotResponded, |
| 499 | ), |
| 500 | ( |
| 501 | "Team standup", |
| 502 | "Mara Lindqvist", |
| 503 | 1, |
| 504 | 9 * 60 + 30, |
| 505 | 15, |
| 506 | ResponseType::Accepted, |
| 507 | ), |
| 508 | ( |
| 509 | "Architecture deep dive", |
| 510 | "Lena Brandt", |
| 511 | 2, |
| 512 | 14 * 60, |
| 513 | 90, |
| 514 | ResponseType::Tentative, |
| 515 | ), |
| 516 | ( |
| 517 | "1:1 Jonas", |
| 518 | "Jonas Ortega", |
| 519 | 3, |
| 520 | 10 * 60, |
| 521 | 30, |
| 522 | ResponseType::Accepted, |
| 523 | ), |
| 524 | ( |
| 525 | "Following: Design office hours", |
| 526 | "Lena Brandt", |
| 527 | 3, |
| 528 | 13 * 60, |
| 529 | 60, |
| 530 | ResponseType::Tentative, |
| 531 | ), |
| 532 | ( |
| 533 | "Sprint retro", |
| 534 | "Mara Lindqvist", |
| 535 | 4, |
| 536 | 15 * 60, |
| 537 | 60, |
| 538 | ResponseType::Accepted, |
| 539 | ), |
| 540 | ]; |
| 541 | slots |
| 542 | .iter() |
| 543 | .enumerate() |
| 544 | .map(|(index, (subject, organizer, day, minute, length, response))| { |
| 545 | let start = |
| 546 | local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute); |
| 547 | CalendarEvent { |
| 548 | object_id: format!("demo-week-{index}"), |
| 549 | subject: (*subject).to_owned(), |
| 550 | start, |
| 551 | end: start + Duration::minutes(*length), |
| 552 | all_day: false, |
| 553 | cancelled: false, |
| 554 | online: true, |
| 555 | join_url: Some(format!( |
| 556 | "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0" |
| 557 | )), |
| 558 | thread_id: None, |
| 559 | organizer_name: Some((*organizer).to_owned()), |
| 560 | organizer_address: None, |
| 561 | ical_uid: None, |
| 562 | show_as: demo_show_as(subject, *response), |
| 563 | dial_in: None, |
| 564 | response: *response, |
| 565 | ..Default::default() |
| 566 | } |
| 567 | }) |
| 568 | .collect() |
| 569 | } |
| 570 | |
| 571 | #[cfg(test)] |
| 572 | mod tests { |
| 573 | use std::sync::Arc; |
| 574 | |
| 575 | use chatsvc::{CalendarEvent, CalendarSource}; |
| 576 | use chrono::{Offset as _, TimeZone, Utc}; |
| 577 | use gpui_kit::{AppContext as _, TestAppContext}; |
| 578 | use store::Store; |
| 579 | |
| 580 | use super::{CalendarLoadFailure, keep_failed_sources, load_summary}; |
| 581 | use crate::app_state::{AppState, Mode}; |
| 582 | |
| 583 | fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent { |
| 584 | let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap(); |
| 585 | CalendarEvent { |
| 586 | object_id: id.into(), |
| 587 | subject: id.into(), |
| 588 | start, |
| 589 | end: start + chrono::Duration::minutes(30), |
| 590 | source, |
| 591 | ..Default::default() |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | #[gpui_kit::test] |
| 596 | fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) { |
| 597 | cx.update(gpui_kit::init); |
| 598 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 599 | let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default()))); |
| 600 | cx.update(|cx| { |
| 601 | app.update(cx, |state, cx| { |
| 602 | state.open_calendar(cx); |
| 603 | assert!(state.calendar_week.visible); |
| 604 | assert!(state.calendar_week.take_pending()); |
| 605 | assert!(!state.calendar_week.take_pending()); |
| 606 | }) |
| 607 | }); |
| 608 | } |
| 609 | |
| 610 | #[gpui_kit::test] |
| 611 | fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) { |
| 612 | cx.update(gpui_kit::init); |
| 613 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 614 | let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default()))); |
| 615 | cx.update(|cx| { |
| 616 | app.update(cx, |state, cx| { |
| 617 | state.open_calendar(cx); |
| 618 | state.calendar_week.take_pending(); |
| 619 | state.close_calendar(); |
| 620 | state.refresh_visible_calendar(cx); |
| 621 | assert!(!state.calendar_week.take_pending()); |
| 622 | state.open_calendar(cx); |
| 623 | state.calendar_week.take_pending(); |
| 624 | state.refresh_visible_calendar(cx); |
| 625 | assert!(state.calendar_week.take_pending()); |
| 626 | }) |
| 627 | }); |
| 628 | } |
| 629 | |
| 630 | #[gpui_kit::test] |
| 631 | fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) { |
| 632 | cx.update(gpui_kit::init); |
| 633 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 634 | let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default()))); |
| 635 | cx.update(|cx| { |
| 636 | app.update(cx, |state, cx| { |
| 637 | state.open_calendar(cx); |
| 638 | let opened = state.calendar_scroll_to_now; |
| 639 | state.shift_calendar_week(1, cx); |
| 640 | assert_ne!(state.calendar_scroll_to_now, opened); |
| 641 | let shifted = state.calendar_scroll_to_now; |
| 642 | state.show_calendar_date(chrono::Local::now().date_naive(), cx); |
| 643 | assert_ne!(state.calendar_scroll_to_now, shifted); |
| 644 | }) |
| 645 | }); |
| 646 | } |
| 647 | |
| 648 | #[gpui_kit::test] |
| 649 | fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) { |
| 650 | cx.update(gpui_kit::init); |
| 651 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 652 | let mode = Mode { |
| 653 | demo: true, |
| 654 | ..Mode::default() |
| 655 | }; |
| 656 | let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode))); |
| 657 | cx.update(|cx| { |
| 658 | app.update(cx, |state, cx| { |
| 659 | state.open_calendar(cx); |
| 660 | let dates = state.calendar_dates(); |
| 661 | let offset = chrono::Local::now().offset().fix(); |
| 662 | let days = |
| 663 | crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset); |
| 664 | let blocks: usize = days.iter().map(|day| day.blocks.len()).sum(); |
| 665 | assert!( |
| 666 | blocks >= 8, |
| 667 | "dates {dates:?}, events {}, blocks {blocks}", |
| 668 | state.calendar_week.events.len() |
| 669 | ); |
| 670 | }) |
| 671 | }); |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn a_failed_source_keeps_its_previous_events() { |
| 676 | let previous = vec![ |
| 677 | event("outlook-old", CalendarSource::Outlook, 9), |
| 678 | event("google-old", CalendarSource::Google, 10), |
| 679 | ]; |
| 680 | let fresh = vec![event("google-new", CalendarSource::Google, 8)]; |
| 681 | let failures = [CalendarLoadFailure { |
| 682 | source: CalendarSource::Outlook, |
| 683 | message: "HTTP 503".into(), |
| 684 | }]; |
| 685 | let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures) |
| 686 | .into_iter() |
| 687 | .map(|event| event.object_id) |
| 688 | .collect(); |
| 689 | assert_eq!(ids, ["google-new", "outlook-old"]); |
| 690 | let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[]) |
| 691 | .into_iter() |
| 692 | .map(|event| event.object_id) |
| 693 | .collect(); |
| 694 | assert_eq!(ids, ["google-new"]); |
| 695 | } |
| 696 | |
| 697 | #[test] |
| 698 | fn a_partial_source_failure_does_not_duplicate_fresh_events() { |
| 699 | let previous = vec![ |
| 700 | event("caldav-old-a", CalendarSource::CalDav, 9), |
| 701 | event("caldav-old-b", CalendarSource::CalDav, 10), |
| 702 | ]; |
| 703 | let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)]; |
| 704 | let failures = [CalendarLoadFailure { |
| 705 | source: CalendarSource::CalDav, |
| 706 | message: "CalDAV Work: timeout".into(), |
| 707 | }]; |
| 708 | let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures) |
| 709 | .into_iter() |
| 710 | .map(|event| event.object_id) |
| 711 | .collect(); |
| 712 | assert_eq!(ids, ["caldav-new"]); |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn the_load_summary_names_counts_and_failures() { |
| 717 | let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap(); |
| 718 | let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap(); |
| 719 | let failures = [CalendarLoadFailure { |
| 720 | source: CalendarSource::Google, |
| 721 | message: "client_secret is missing".into(), |
| 722 | }]; |
| 723 | assert_eq!( |
| 724 | load_summary(from, to, Some(3), None, None, 412, &failures), |
| 725 | "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \ |
| 726 | Google failed: client_secret is missing" |
| 727 | ); |
| 728 | } |
| 729 | } |