| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use app_base::status_choice::after; |
| 4 | pub use app_base::status_choice::{ |
| 5 | STATUS_CHOICES, STATUS_DURATIONS, StatusDuration, choice_label, end_of_day, end_of_week, |
| 6 | state_label, |
| 7 | }; |
| 8 | use chrono::{DateTime, Datelike, Duration, TimeZone, Utc}; |
| 9 | use gpui_kit::*; |
| 10 | use teams_core::{ |
| 11 | ForcedAvailability, ForcedKind, PresenceStatus, StatusNote, WorkLocation, WorkLocationKind, |
| 12 | WorkLocationSource, |
| 13 | }; |
| 14 | |
| 15 | use crate::app_state::{AppEvent, AppState}; |
| 16 | use crate::backend::Engine; |
| 17 | use crate::data::PresenceKind; |
| 18 | |
| 19 | pub const NOTE_LIMIT: usize = 280; |
| 20 | const WORK_LOCATION_FAILED: &str = "Work location couldn't be set. Try again."; |
| 21 | pub const NOTE_DURATIONS: [NoteDuration; 5] = [ |
| 22 | NoteDuration::Never, |
| 23 | NoteDuration::OneHour, |
| 24 | NoteDuration::FourHours, |
| 25 | NoteDuration::Today, |
| 26 | NoteDuration::ThisWeek, |
| 27 | ]; |
| 28 | |
| 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 30 | pub enum NoteDuration { |
| 31 | Never, |
| 32 | OneHour, |
| 33 | FourHours, |
| 34 | Today, |
| 35 | ThisWeek, |
| 36 | } |
| 37 | |
| 38 | impl NoteDuration { |
| 39 | pub const DEFAULT: NoteDuration = NoteDuration::Today; |
| 40 | |
| 41 | pub fn label(self) -> &'static str { |
| 42 | match self { |
| 43 | NoteDuration::Never => "Never", |
| 44 | NoteDuration::OneHour => "1 hour", |
| 45 | NoteDuration::FourHours => "4 hours", |
| 46 | NoteDuration::Today => "Today", |
| 47 | NoteDuration::ThisWeek => "This week", |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> Option<DateTime<Utc>> { |
| 52 | match self { |
| 53 | NoteDuration::Never => None, |
| 54 | NoteDuration::OneHour => Some(after(&now, Duration::hours(1))), |
| 55 | NoteDuration::FourHours => Some(after(&now, Duration::hours(4))), |
| 56 | NoteDuration::Today => Some(end_of_day(&now)), |
| 57 | NoteDuration::ThisWeek => Some(end_of_week(&now)), |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn presence_kind_for(kind: ForcedKind) -> PresenceKind { |
| 63 | match kind { |
| 64 | ForcedKind::Available => PresenceKind::Available, |
| 65 | ForcedKind::Busy => PresenceKind::Busy, |
| 66 | ForcedKind::DoNotDisturb => PresenceKind::DoNotDisturb, |
| 67 | ForcedKind::BeRightBack | ForcedKind::Away => PresenceKind::Away, |
| 68 | ForcedKind::Offline => PresenceKind::Offline, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub fn until_label<Zone: TimeZone>(expires_at: DateTime<Utc>, now: &DateTime<Zone>) -> String |
| 73 | where |
| 74 | Zone::Offset: std::fmt::Display, |
| 75 | { |
| 76 | let local = expires_at.with_timezone(&now.timezone()); |
| 77 | let clock = local.format(app_base::format::clock_format()).to_string(); |
| 78 | let time = if local.date_naive() == now.date_naive() { |
| 79 | clock |
| 80 | } else { |
| 81 | let weekday = |
| 82 | app_base::format::weekday_name(local.weekday(), app_base::format::WeekdayWidth::Short); |
| 83 | format!("{weekday} {clock}") |
| 84 | }; |
| 85 | app_base::ui_locale::tr_with("regional.until", &[("time", &time)]) |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 89 | pub struct StateSummary { |
| 90 | pub label: &'static str, |
| 91 | pub presence: PresenceKind, |
| 92 | pub until: Option<String>, |
| 93 | } |
| 94 | |
| 95 | pub fn state_summary<Zone: TimeZone>( |
| 96 | status: &PresenceStatus, |
| 97 | live: PresenceKind, |
| 98 | now: &DateTime<Zone>, |
| 99 | ) -> StateSummary |
| 100 | where |
| 101 | Zone::Offset: std::fmt::Display, |
| 102 | { |
| 103 | match status.forced { |
| 104 | Some(forced) => StateSummary { |
| 105 | label: state_label(forced.kind), |
| 106 | presence: presence_kind_for(forced.kind), |
| 107 | until: forced |
| 108 | .expires_at |
| 109 | .map(|expires_at| until_label(expires_at, now)), |
| 110 | }, |
| 111 | None => StateSummary { |
| 112 | label: match live.label() { |
| 113 | "" => "Set status", |
| 114 | label => label, |
| 115 | }, |
| 116 | presence: live, |
| 117 | until: None, |
| 118 | }, |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub fn duration_target(status: &PresenceStatus) -> Option<ForcedKind> { |
| 123 | status |
| 124 | .forced |
| 125 | .map(|forced| forced.kind) |
| 126 | .filter(|kind| *kind != ForcedKind::Available) |
| 127 | } |
| 128 | |
| 129 | pub fn with_forced(status: &PresenceStatus, forced: Option<ForcedAvailability>) -> PresenceStatus { |
| 130 | let availability = match forced { |
| 131 | Some(forced) => forced.kind.code().to_owned(), |
| 132 | None => status.availability.clone(), |
| 133 | }; |
| 134 | PresenceStatus { |
| 135 | availability, |
| 136 | forced, |
| 137 | ..status.clone() |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | pub fn with_note(status: &PresenceStatus, note: Option<StatusNote>) -> PresenceStatus { |
| 142 | PresenceStatus { |
| 143 | note, |
| 144 | ..status.clone() |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn work_location_label(location: Option<WorkLocation>) -> &'static str { |
| 149 | match location { |
| 150 | None => "Set work location", |
| 151 | Some(WorkLocation { |
| 152 | kind: WorkLocationKind::Office, |
| 153 | source: WorkLocationSource::Set, |
| 154 | }) => "In the office", |
| 155 | Some(WorkLocation { |
| 156 | kind: WorkLocationKind::Office, |
| 157 | source: WorkLocationSource::Scheduled, |
| 158 | }) => "Planned in the office", |
| 159 | Some(WorkLocation { |
| 160 | kind: WorkLocationKind::Office, |
| 161 | source: WorkLocationSource::Verified, |
| 162 | }) => "Checked in to the office", |
| 163 | Some(WorkLocation { |
| 164 | kind: WorkLocationKind::Remote, |
| 165 | source: WorkLocationSource::Scheduled, |
| 166 | }) => "Planned to work remotely", |
| 167 | Some(WorkLocation { |
| 168 | kind: WorkLocationKind::Remote, |
| 169 | .. |
| 170 | }) => "Working remotely", |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | pub fn with_work_location( |
| 175 | status: &PresenceStatus, |
| 176 | work_location: Option<WorkLocation>, |
| 177 | ) -> PresenceStatus { |
| 178 | PresenceStatus { |
| 179 | work_location, |
| 180 | ..status.clone() |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | pub fn clamp_note(text: &str) -> String { |
| 185 | text.chars().take(NOTE_LIMIT).collect() |
| 186 | } |
| 187 | |
| 188 | pub fn demo_status() -> PresenceStatus { |
| 189 | PresenceStatus { |
| 190 | availability: "Available".to_owned(), |
| 191 | ..PresenceStatus::default() |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | impl AppState { |
| 196 | pub fn own_presence_kind(&self) -> PresenceKind { |
| 197 | match &self.directory.me { |
| 198 | Some(me) => self.directory.presence_of(&me.user_id).kind(), |
| 199 | None => PresenceKind::Unknown, |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | pub fn set_status_menu_open(&mut self, open: bool, cx: &mut Context<Self>) { |
| 204 | if self.status_menu_open != open { |
| 205 | self.status_menu_open = open; |
| 206 | cx.notify(); |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | pub fn request_status_message(&mut self, cx: &mut Context<Self>) { |
| 211 | self.status_message_request = true; |
| 212 | cx.emit(AppEvent::StatusMessage); |
| 213 | cx.notify(); |
| 214 | } |
| 215 | |
| 216 | pub fn take_status_message_request(&mut self) -> bool { |
| 217 | std::mem::take(&mut self.status_message_request) |
| 218 | } |
| 219 | |
| 220 | pub fn refresh_own_status(&mut self, cx: &mut Context<Self>) { |
| 221 | let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else { |
| 222 | return; |
| 223 | }; |
| 224 | drop(crate::runtime::spawn(async move { |
| 225 | engine.refresh_own_status().await |
| 226 | })); |
| 227 | cx.notify(); |
| 228 | } |
| 229 | |
| 230 | pub fn apply_own_status(&mut self, status: PresenceStatus, cx: &mut Context<Self>) { |
| 231 | self.own_status = status; |
| 232 | cx.emit(AppEvent::Directory); |
| 233 | cx.notify(); |
| 234 | } |
| 235 | |
| 236 | pub fn set_own_availability( |
| 237 | &mut self, |
| 238 | forced: Option<ForcedAvailability>, |
| 239 | cx: &mut Context<Self>, |
| 240 | ) { |
| 241 | let Some(engine_or_demo) = self.own_status_engine(cx) else { |
| 242 | return; |
| 243 | }; |
| 244 | let previous_status = self.own_status.clone(); |
| 245 | let previous_presence = self.own_presence_kind(); |
| 246 | self.own_status = with_forced(&previous_status, forced); |
| 247 | if let Some(forced) = forced { |
| 248 | self.show_own_presence(presence_kind_for(forced.kind), cx); |
| 249 | } |
| 250 | let Some(engine) = engine_or_demo else { |
| 251 | return; |
| 252 | }; |
| 253 | self.run_chat_action( |
| 254 | "Status", |
| 255 | async move { engine.set_own_availability(forced).await }, |
| 256 | move |state, cx| { |
| 257 | state.own_status = previous_status; |
| 258 | state.show_own_presence(previous_presence, cx); |
| 259 | }, |
| 260 | |_, _| {}, |
| 261 | cx, |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | pub fn set_own_status_note(&mut self, note: Option<StatusNote>, cx: &mut Context<Self>) { |
| 266 | let Some(engine_or_demo) = self.own_status_engine(cx) else { |
| 267 | return; |
| 268 | }; |
| 269 | let previous_status = self.own_status.clone(); |
| 270 | self.own_status = with_note(&previous_status, note.clone()); |
| 271 | cx.emit(AppEvent::Directory); |
| 272 | cx.notify(); |
| 273 | let Some(engine) = engine_or_demo else { |
| 274 | return; |
| 275 | }; |
| 276 | self.run_chat_action( |
| 277 | "Status message", |
| 278 | async move { engine.set_own_status_note(note).await }, |
| 279 | move |state, cx| { |
| 280 | state.own_status = previous_status; |
| 281 | cx.emit(AppEvent::Directory); |
| 282 | cx.notify(); |
| 283 | }, |
| 284 | |_, _| {}, |
| 285 | cx, |
| 286 | ); |
| 287 | } |
| 288 | |
| 289 | pub fn set_own_work_location( |
| 290 | &mut self, |
| 291 | kind: Option<WorkLocationKind>, |
| 292 | cx: &mut Context<Self>, |
| 293 | ) { |
| 294 | let Some(engine_or_demo) = self.own_status_engine(cx) else { |
| 295 | return; |
| 296 | }; |
| 297 | let previous_status = self.own_status.clone(); |
| 298 | let optimistic = kind.map(|kind| WorkLocation { |
| 299 | kind, |
| 300 | source: WorkLocationSource::Set, |
| 301 | }); |
| 302 | self.own_status = with_work_location(&previous_status, optimistic); |
| 303 | cx.emit(AppEvent::Directory); |
| 304 | cx.notify(); |
| 305 | let Some(engine) = engine_or_demo else { |
| 306 | return; |
| 307 | }; |
| 308 | let location = kind.map(|kind| (kind, end_of_day(&chrono::Local::now()))); |
| 309 | let receiver = |
| 310 | crate::runtime::spawn(async move { engine.set_own_work_location(location).await }); |
| 311 | cx.spawn(async move |this, cx| { |
| 312 | let succeeded = matches!(receiver.await, Ok(Ok(()))); |
| 313 | this.update(cx, |state, cx| { |
| 314 | if succeeded { |
| 315 | return; |
| 316 | } |
| 317 | state.own_status = previous_status; |
| 318 | state.raise_notice(WORK_LOCATION_FAILED.to_owned(), None, cx); |
| 319 | }) |
| 320 | .ok(); |
| 321 | }) |
| 322 | .detach(); |
| 323 | } |
| 324 | |
| 325 | fn show_own_presence(&mut self, kind: PresenceKind, cx: &mut Context<Self>) { |
| 326 | if let Some(me) = self |
| 327 | .directory |
| 328 | .me |
| 329 | .clone() |
| 330 | .filter(|_| kind != PresenceKind::Unknown) |
| 331 | { |
| 332 | self.directory.set_presence(&me.user_id, kind); |
| 333 | } |
| 334 | cx.emit(AppEvent::Directory); |
| 335 | cx.notify(); |
| 336 | } |
| 337 | |
| 338 | fn own_status_engine(&mut self, cx: &mut Context<Self>) -> Option<Option<Arc<Engine>>> { |
| 339 | if self.mode.read_only { |
| 340 | self.raise_notice("Read-only mode: status not changed".to_owned(), None, cx); |
| 341 | return None; |
| 342 | } |
| 343 | match self.engine.clone() { |
| 344 | Some(engine) => Some(Some(engine)), |
| 345 | None if self.mode.demo => Some(None), |
| 346 | None => None, |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | #[cfg(test)] |
| 352 | mod tests { |
| 353 | use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc}; |
| 354 | use teams_core::{ |
| 355 | ForcedAvailability, ForcedKind, PresenceStatus, WorkLocation, WorkLocationKind, |
| 356 | WorkLocationSource, |
| 357 | }; |
| 358 | |
| 359 | use super::{ |
| 360 | NOTE_LIMIT, NoteDuration, STATUS_CHOICES, StateSummary, StatusDuration, choice_label, |
| 361 | clamp_note, duration_target, end_of_day, end_of_week, state_summary, until_label, |
| 362 | with_forced, work_location_label, |
| 363 | }; |
| 364 | use crate::data::PresenceKind; |
| 365 | |
| 366 | fn zone() -> FixedOffset { |
| 367 | FixedOffset::east_opt(2 * 3600).unwrap() |
| 368 | } |
| 369 | |
| 370 | fn local(day: u32, hour: u32, minute: u32) -> DateTime<FixedOffset> { |
| 371 | zone() |
| 372 | .with_ymd_and_hms(2026, 10, day, hour, minute, 0) |
| 373 | .unwrap() |
| 374 | } |
| 375 | |
| 376 | fn utc(day: u32, hour: u32, minute: u32, second: u32) -> DateTime<Utc> { |
| 377 | Utc.with_ymd_and_hms(2026, 10, day, hour, minute, second) |
| 378 | .unwrap() |
| 379 | } |
| 380 | |
| 381 | #[test] |
| 382 | fn relative_durations_add_to_now() { |
| 383 | let now = local(9, 14, 0); |
| 384 | assert_eq!(StatusDuration::HalfHour.expires_at(now), utc(9, 12, 30, 0)); |
| 385 | assert_eq!(StatusDuration::OneHour.expires_at(now), utc(9, 13, 0, 0)); |
| 386 | assert_eq!(StatusDuration::TwoHours.expires_at(now), utc(9, 14, 0, 0)); |
| 387 | assert_eq!( |
| 388 | NoteDuration::FourHours.expires_at(now), |
| 389 | Some(utc(9, 16, 0, 0)) |
| 390 | ); |
| 391 | assert_eq!( |
| 392 | NoteDuration::OneHour.expires_at(now), |
| 393 | Some(utc(9, 13, 0, 0)) |
| 394 | ); |
| 395 | assert_eq!(NoteDuration::Never.expires_at(now), None); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn today_ends_at_local_midnight() { |
| 400 | let expected = utc(9, 21, 59, 59) + Duration::milliseconds(999); |
| 401 | assert_eq!(StatusDuration::Today.expires_at(local(9, 14, 0)), expected); |
| 402 | assert_eq!( |
| 403 | NoteDuration::Today.expires_at(local(9, 0, 5)), |
| 404 | Some(expected) |
| 405 | ); |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn today_uses_the_local_date_not_the_utc_date() { |
| 410 | let now = local(10, 0, 30); |
| 411 | let expected = utc(10, 21, 59, 59) + Duration::milliseconds(999); |
| 412 | assert_eq!(end_of_day(&now), expected); |
| 413 | } |
| 414 | |
| 415 | #[test] |
| 416 | fn week_ends_saturday_night_with_sunday_as_first_day() { |
| 417 | let saturday = utc(10, 21, 59, 59) + Duration::milliseconds(999); |
| 418 | let friday = local(9, 14, 0); |
| 419 | assert_eq!(StatusDuration::ThisWeek.expires_at(friday), saturday); |
| 420 | assert_eq!(end_of_week(&local(10, 8, 0)), saturday); |
| 421 | assert_eq!(end_of_week(&local(4, 8, 0)), saturday); |
| 422 | let next_saturday = utc(17, 21, 59, 59) + Duration::milliseconds(999); |
| 423 | assert_eq!(end_of_week(&local(11, 8, 0)), next_saturday); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn until_label_shows_the_time_today_and_the_day_later() { |
| 428 | let now = local(9, 14, 0); |
| 429 | assert_eq!(until_label(utc(9, 13, 30, 0), &now), "until 15:30"); |
| 430 | assert_eq!(until_label(utc(10, 13, 30, 0), &now), "until Sat 15:30"); |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn forced_state_wins_over_the_live_presence_in_the_summary() { |
| 435 | let now = local(9, 14, 0); |
| 436 | let status = PresenceStatus { |
| 437 | forced: Some(ForcedAvailability { |
| 438 | kind: ForcedKind::DoNotDisturb, |
| 439 | expires_at: Some(utc(9, 13, 30, 0)), |
| 440 | }), |
| 441 | ..PresenceStatus::default() |
| 442 | }; |
| 443 | assert_eq!( |
| 444 | state_summary(&status, PresenceKind::Available, &now), |
| 445 | StateSummary { |
| 446 | label: "Do not disturb", |
| 447 | presence: PresenceKind::DoNotDisturb, |
| 448 | until: Some("until 15:30".into()), |
| 449 | } |
| 450 | ); |
| 451 | let automatic = state_summary(&PresenceStatus::default(), PresenceKind::Away, &now); |
| 452 | assert_eq!(automatic.label, "Away"); |
| 453 | assert_eq!(automatic.until, None); |
| 454 | let unknown = state_summary(&PresenceStatus::default(), PresenceKind::Unknown, &now); |
| 455 | assert_eq!(unknown.label, "Set status"); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn duration_needs_a_forced_state_other_than_available() { |
| 460 | let forced = |kind| PresenceStatus { |
| 461 | forced: Some(ForcedAvailability { |
| 462 | kind, |
| 463 | expires_at: None, |
| 464 | }), |
| 465 | ..PresenceStatus::default() |
| 466 | }; |
| 467 | assert_eq!(duration_target(&PresenceStatus::default()), None); |
| 468 | assert_eq!(duration_target(&forced(ForcedKind::Available)), None); |
| 469 | assert_eq!( |
| 470 | duration_target(&forced(ForcedKind::Busy)), |
| 471 | Some(ForcedKind::Busy) |
| 472 | ); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn optimistic_forced_state_sets_availability_and_reset_keeps_it() { |
| 477 | let busy = ForcedAvailability { |
| 478 | kind: ForcedKind::Busy, |
| 479 | expires_at: None, |
| 480 | }; |
| 481 | let status = with_forced(&PresenceStatus::default(), Some(busy)); |
| 482 | assert_eq!(status.availability, "Busy"); |
| 483 | assert_eq!(status.forced, Some(busy)); |
| 484 | let reset = with_forced(&status, None); |
| 485 | assert_eq!(reset.availability, "Busy"); |
| 486 | assert_eq!(reset.forced, None); |
| 487 | } |
| 488 | |
| 489 | #[test] |
| 490 | fn note_text_is_cut_at_the_limit_by_characters() { |
| 491 | let long = "ä".repeat(NOTE_LIMIT + 20); |
| 492 | assert_eq!(clamp_note(&long).chars().count(), NOTE_LIMIT); |
| 493 | assert_eq!(clamp_note("short"), "short"); |
| 494 | } |
| 495 | |
| 496 | #[test] |
| 497 | fn work_location_labels_follow_teams() { |
| 498 | let location = |kind, source| Some(WorkLocation { kind, source }); |
| 499 | assert_eq!(work_location_label(None), "Set work location"); |
| 500 | assert_eq!( |
| 501 | work_location_label(location(WorkLocationKind::Office, WorkLocationSource::Set)), |
| 502 | "In the office" |
| 503 | ); |
| 504 | assert_eq!( |
| 505 | work_location_label(location( |
| 506 | WorkLocationKind::Office, |
| 507 | WorkLocationSource::Scheduled |
| 508 | )), |
| 509 | "Planned in the office" |
| 510 | ); |
| 511 | assert_eq!( |
| 512 | work_location_label(location(WorkLocationKind::Remote, WorkLocationSource::Set)), |
| 513 | "Working remotely" |
| 514 | ); |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn labels_follow_the_teams_menu() { |
| 519 | let labels: Vec<&str> = STATUS_CHOICES |
| 520 | .iter() |
| 521 | .map(|kind| choice_label(*kind)) |
| 522 | .collect(); |
| 523 | assert_eq!( |
| 524 | labels, |
| 525 | [ |
| 526 | "Available", |
| 527 | "Busy", |
| 528 | "Do not disturb", |
| 529 | "Be right back", |
| 530 | "Appear away", |
| 531 | "Appear offline" |
| 532 | ] |
| 533 | ); |
| 534 | assert_eq!(NoteDuration::DEFAULT, NoteDuration::Today); |
| 535 | } |
| 536 | } |