BlueGit

ict rusty-teams

feat(calendar): Teams-like event peek with Google fields

Replace the labeled event dialog with a peek: full scrollable agenda,
enlarge to a Tracking panel, RSVP with optional Outlook comment, and
Google calendar name, reminders, source link, and Open in Google Calendar.

metis Joachim Mild · pushed by metis

Authored 2026-11-13 · 2 weeks ago

Hash
9fa73c38527fb485fc8376327cdb5995317c5360
Parent
fad12088
20 files changed +2800 −227
crates/app-base/locales/app.yml +197 −14
@@ -8,7 +8,7 @@ common:
8 8 de: Speichern
9 9 close:
10 10 en: Close
11 de: Schließen
11 de: Schliessen
12 12 delete:
13 13 en: Delete
14 14 de: Löschen
@@ -146,6 +146,85 @@ settings:
146 146 sound:
147 147 en: SOUND
148 148 de: TON
149 calendar:
150 section_google:
151 en: GOOGLE
152 de: GOOGLE
153 section_home:
154 en: HOME CALENDAR
155 de: HAUPTKALENDER
156 section_write:
157 en: ALSO WRITE TO
158 de: AUCH SCHREIBEN NACH
159 google_title:
160 en: Google Calendar
161 de: Google Kalender
162 connect_button:
163 en: Connect Google
164 de: Google verbinden
165 connect_hint:
166 en: Opens a browser for sign-in. If Google says the app is not verified, choose Advanced, then continue.
167 de: Öffnet einen Browser zur Anmeldung. Meldet Google, die App sei nicht verifiziert, wählen Sie Advanced und dann Weiter.
168 finish_in_browser:
169 en: Finish sign-in in your browser.
170 de: Schliessen Sie die Anmeldung im Browser ab.
171 open_browser_again:
172 en: Open browser again
173 de: Browser erneut öffnen
174 copy_link:
175 en: Copy link
176 de: Link kopieren
177 connected_detail:
178 en: Connected accounts appear below. Disconnect removes tokens from this device.
179 de: Verbundene Konten erscheinen unten. Trennen entfernt die Tokens von diesem Gerät.
180 google_account:
181 en: Google account
182 de: Google-Konto
183 disconnect:
184 en: Disconnect
185 de: Trennen
186 primary:
187 en: Primary calendar
188 de: Hauptkalender
189 show_in_grid:
190 en: Show in calendar grid
191 de: Im Kalendergitter anzeigen
192 also_write_to:
193 en: Also write new meetings to %{name}
194 de: Neue Besprechungen auch nach %{name} schreiben
195 outlook_mailbox:
196 en: Outlook (Microsoft mailbox)
197 de: Outlook (Microsoft-Postfach)
198 dual_write_when_google_home:
199 en: Dual-write when home is Google
200 de: Zusätzlich schreiben, wenn der Hauptkalender Google ist
201 outlook_home_detail:
202 en: Default when no Google home is chosen
203 de: Standard, wenn kein Google-Hauptkalender gewählt ist
204 no_extra_targets:
205 en: No extra write targets
206 de: Keine weiteren Schreibziele
207 connect_then_dual_write:
208 en: Connect Google, then enable dual-write on a calendar above.
209 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
210 google_label:
211 en: Google
212 de: Google
213 not_in_build:
214 en: Google Calendar is not included in this build.
215 de: Google Kalender ist in diesem Build nicht enthalten.
216 sign_in_start_failed:
217 en: Could not start Google sign-in.
218 de: Google-Anmeldung konnte nicht gestartet werden.
219 sign_in_cancelled:
220 en: Google sign-in was cancelled.
221 de: Google-Anmeldung wurde abgebrochen.
222 connected:
223 en: Google Calendar connected (%{email}).
224 de: Google Kalender verbunden (%{email}).
225 picker_connect_hint:
226 en: Connect Google in Settings › Calendar
227 de: Google in Einstellungen › Kalender verbinden
149 228 general:
150 229 auto_start:
151 230 en: Auto-start Teams
@@ -155,10 +234,19 @@ settings:
155 234 de: Anwendung im Hintergrund starten
156 235 close_to_tray:
157 236 en: On close, keep the application running
158 de: Beim Schließen Anwendung weiterlaufen lassen
237 de: Beim Schliessen Anwendung weiterlaufen lassen
159 238 close_to_tray_detail:
160 239 en: The title bar X hides the window to the tray
161 240 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
241 external_browser:
242 en: Open links and Google sign-in with
243 de: Links und Google-Anmeldung öffnen mit
244 external_browser_detail:
245 en: Does not change the Teams session browser (Chrome/Chromium is required for that).
246 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt Chrome/Chromium nötig).
247 external_browser_system:
248 en: System default
249 de: Systemstandard
162 250 up_arrow:
163 251 en: Up arrow key behaviour in compose box
164 252 de: Verhalten der Aufwärtspfeil-Taste im Eingabefeld
@@ -189,15 +277,6 @@ settings:
189 277 never_translate:
190 278 en: Never translate messages in these languages
191 279 de: Nachrichten in diesen Sprachen nie übersetzen
192 external_browser:
193 en: Open links and Google sign-in with
194 de: Links und Google-Anmeldung öffnen mit
195 external_browser_detail:
196 en: Does not change the Teams session browser (Chrome/Chromium is required for that).
197 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt Chrome/Chromium nötig).
198 external_browser_system:
199 en: System default
200 de: Systemstandard
201 280 notifications:
202 281 flash_taskbar:
203 282 en: Flash taskbar when notifications are received
@@ -655,7 +734,7 @@ calls:
655 734 de: Chat öffnen
656 735 close_chat:
657 736 en: Close the chat
658 de: Chat schließen
737 de: Chat schliessen
659 738 share_entire_screen:
660 739 en: Share entire screen
661 740 de: Gesamten Bildschirm freigeben
@@ -869,6 +948,110 @@ calls:
869 948 teams_link_added:
870 949 en: Teams meeting link is added
871 950 de: Teams-Besprechungslink wird hinzugefügt
951 calendar:
952 peek:
953 all_day:
954 en: All day
955 de: Ganztägig
956 teams_meeting:
957 en: Microsoft Teams meeting
958 de: Microsoft Teams-Besprechung
959 google_meet:
960 en: Google Meet
961 de: Google Meet
962 series:
963 en: Series
964 de: Serie
965 invited_you:
966 en: "%{name} invited you."
967 de: "%{name} hat dich eingeladen."
968 accepted:
969 en: Accepted
970 de: Angenommen
971 declined:
972 en: Declined
973 de: Abgelehnt
974 tentative:
975 en: Tentative
976 de: Mit Vorbehalt
977 no_response:
978 en: Didn't respond
979 de: Keine Antwort
980 email_organizer:
981 en: Email organizer
982 de: E-Mail an den Organisator
983 message_placeholder:
984 en: Add a message (optional)
985 de: Nachricht hinzufügen (optional)
986 accept:
987 en: Accept
988 de: Annehmen
989 decline:
990 en: Decline
991 de: Ablehnen
992 tentative_action:
993 en: Tentative
994 de: Mit Vorbehalt
995 this_occurrence:
996 en: This occurrence
997 de: Nur dieser Termin
998 entire_series:
999 en: Entire series
1000 de: Ganze Serie
1001 join_link:
1002 en: Join link
1003 de: Beitrittslink
1004 tracking:
1005 en: Tracking
1006 de: Nachverfolgung
1007 organizer:
1008 en: Organizer
1009 de: Organisator
1010 required:
1011 en: Required
1012 de: Erforderlich
1013 optional:
1014 en: Optional
1015 de: Optional
1016 attendees_unknown:
1017 en: Attendee list not available.
1018 de: Teilnehmerliste nicht verfügbar.
1019 when_starts:
1020 en: When the event starts
1021 de: Zum Beginn des Termins
1022 minute_before:
1023 en: "%{count} minute before"
1024 de: "%{count} Minute vorher"
1025 minutes_before:
1026 en: "%{count} minutes before"
1027 de: "%{count} Minuten vorher"
1028 hour_before:
1029 en: "%{count} hour before"
1030 de: "%{count} Stunde vorher"
1031 hours_before:
1032 en: "%{count} hours before"
1033 de: "%{count} Stunden vorher"
1034 day_before:
1035 en: "%{count} day before"
1036 de: "%{count} Tag vorher"
1037 days_before:
1038 en: "%{count} days before"
1039 de: "%{count} Tage vorher"
1040 view_source:
1041 en: View source
1042 de: Quelle anzeigen
1043 open_in_google:
1044 en: Open in Google Calendar
1045 de: In Google Kalender öffnen
1046 email_guests:
1047 en: Email guests
1048 de: Gäste per E-Mail
1049 canceled_prefix:
1050 en: "Canceled: "
1051 de: "Abgesagt: "
1052 no_title:
1053 en: (No title)
1054 de: (Kein Titel)
872 1055 agents:
873 1056 start:
874 1057 new_session:
@@ -1156,7 +1339,7 @@ sidebar:
1156 1339 de: Aus
1157 1340 include_thread_replies:
1158 1341 en: Include thread replies
1159 de: Thread-Antworten einschließen
1342 de: Thread-Antworten einschliessen
1160 1343 filter:
1161 1344 placeholder:
1162 1345 en: Filter by person or chat name
@@ -1178,7 +1361,7 @@ sidebar:
1178 1361 de: Filterfeld anzeigen
1179 1362 close_box:
1180 1363 en: Close filter text box
1181 de: Filterfeld schließen
1364 de: Filterfeld schliessen
1182 1365 show_shortcut:
1183 1366 en: "%{label} (Ctrl+Shift+F)"
1184 1367 de: "%{label} (Strg+Umschalt+F)"
@@ -8,7 +8,7 @@ common:
8 de: Speichern
8 de: Speichern
9 close:
9 close:
10 en: Close
10 en: Close
11 de: Schließen
11 de: Schliessen
12 delete:
12 delete:
13 en: Delete
13 en: Delete
14 de: Löschen
14 de: Löschen
@@ -146,6 +146,85 @@ settings:
146 sound:
146 sound:
147 en: SOUND
147 en: SOUND
148 de: TON
148 de: TON
149 calendar:
150 section_google:
151 en: GOOGLE
152 de: GOOGLE
153 section_home:
154 en: HOME CALENDAR
155 de: HAUPTKALENDER
156 section_write:
157 en: ALSO WRITE TO
158 de: AUCH SCHREIBEN NACH
159 google_title:
160 en: Google Calendar
161 de: Google Kalender
162 connect_button:
163 en: Connect Google
164 de: Google verbinden
165 connect_hint:
166 en: Opens a browser for sign-in. If Google says the app is not verified, choose Advanced, then continue.
167 de: Öffnet einen Browser zur Anmeldung. Meldet Google, die App sei nicht verifiziert, wählen Sie Advanced und dann Weiter.
168 finish_in_browser:
169 en: Finish sign-in in your browser.
170 de: Schliessen Sie die Anmeldung im Browser ab.
171 open_browser_again:
172 en: Open browser again
173 de: Browser erneut öffnen
174 copy_link:
175 en: Copy link
176 de: Link kopieren
177 connected_detail:
178 en: Connected accounts appear below. Disconnect removes tokens from this device.
179 de: Verbundene Konten erscheinen unten. Trennen entfernt die Tokens von diesem Gerät.
180 google_account:
181 en: Google account
182 de: Google-Konto
183 disconnect:
184 en: Disconnect
185 de: Trennen
186 primary:
187 en: Primary calendar
188 de: Hauptkalender
189 show_in_grid:
190 en: Show in calendar grid
191 de: Im Kalendergitter anzeigen
192 also_write_to:
193 en: Also write new meetings to %{name}
194 de: Neue Besprechungen auch nach %{name} schreiben
195 outlook_mailbox:
196 en: Outlook (Microsoft mailbox)
197 de: Outlook (Microsoft-Postfach)
198 dual_write_when_google_home:
199 en: Dual-write when home is Google
200 de: Zusätzlich schreiben, wenn der Hauptkalender Google ist
201 outlook_home_detail:
202 en: Default when no Google home is chosen
203 de: Standard, wenn kein Google-Hauptkalender gewählt ist
204 no_extra_targets:
205 en: No extra write targets
206 de: Keine weiteren Schreibziele
207 connect_then_dual_write:
208 en: Connect Google, then enable dual-write on a calendar above.
209 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
210 google_label:
211 en: Google
212 de: Google
213 not_in_build:
214 en: Google Calendar is not included in this build.
215 de: Google Kalender ist in diesem Build nicht enthalten.
216 sign_in_start_failed:
217 en: Could not start Google sign-in.
218 de: Google-Anmeldung konnte nicht gestartet werden.
219 sign_in_cancelled:
220 en: Google sign-in was cancelled.
221 de: Google-Anmeldung wurde abgebrochen.
222 connected:
223 en: Google Calendar connected (%{email}).
224 de: Google Kalender verbunden (%{email}).
225 picker_connect_hint:
226 en: Connect Google in Settings › Calendar
227 de: Google in Einstellungen › Kalender verbinden
149 general:
228 general:
150 auto_start:
229 auto_start:
151 en: Auto-start Teams
230 en: Auto-start Teams
@@ -155,10 +234,19 @@ settings:
155 de: Anwendung im Hintergrund starten
234 de: Anwendung im Hintergrund starten
156 close_to_tray:
235 close_to_tray:
157 en: On close, keep the application running
236 en: On close, keep the application running
158 de: Beim Schließen Anwendung weiterlaufen lassen
237 de: Beim Schliessen Anwendung weiterlaufen lassen
159 close_to_tray_detail:
238 close_to_tray_detail:
160 en: The title bar X hides the window to the tray
239 en: The title bar X hides the window to the tray
161 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
240 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
241 external_browser:
242 en: Open links and Google sign-in with
243 de: Links und Google-Anmeldung öffnen mit
244 external_browser_detail:
245 en: Does not change the Teams session browser (Chrome/Chromium is required for that).
246 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt Chrome/Chromium nötig).
247 external_browser_system:
248 en: System default
249 de: Systemstandard
162 up_arrow:
250 up_arrow:
163 en: Up arrow key behaviour in compose box
251 en: Up arrow key behaviour in compose box
164 de: Verhalten der Aufwärtspfeil-Taste im Eingabefeld
252 de: Verhalten der Aufwärtspfeil-Taste im Eingabefeld
@@ -189,15 +277,6 @@ settings:
189 never_translate:
277 never_translate:
190 en: Never translate messages in these languages
278 en: Never translate messages in these languages
191 de: Nachrichten in diesen Sprachen nie übersetzen
279 de: Nachrichten in diesen Sprachen nie übersetzen
192 external_browser:
193 en: Open links and Google sign-in with
194 de: Links und Google-Anmeldung öffnen mit
195 external_browser_detail:
196 en: Does not change the Teams session browser (Chrome/Chromium is required for that).
197 de: Ändert nicht den Browser der Teams-Sitzung (dafür bleibt Chrome/Chromium nötig).
198 external_browser_system:
199 en: System default
200 de: Systemstandard
201 notifications:
280 notifications:
202 flash_taskbar:
281 flash_taskbar:
203 en: Flash taskbar when notifications are received
282 en: Flash taskbar when notifications are received
@@ -655,7 +734,7 @@ calls:
655 de: Chat öffnen
734 de: Chat öffnen
656 close_chat:
735 close_chat:
657 en: Close the chat
736 en: Close the chat
658 de: Chat schließen
737 de: Chat schliessen
659 share_entire_screen:
738 share_entire_screen:
660 en: Share entire screen
739 en: Share entire screen
661 de: Gesamten Bildschirm freigeben
740 de: Gesamten Bildschirm freigeben
@@ -869,6 +948,110 @@ calls:
869 teams_link_added:
948 teams_link_added:
870 en: Teams meeting link is added
949 en: Teams meeting link is added
871 de: Teams-Besprechungslink wird hinzugefügt
950 de: Teams-Besprechungslink wird hinzugefügt
951calendar:
952 peek:
953 all_day:
954 en: All day
955 de: Ganztägig
956 teams_meeting:
957 en: Microsoft Teams meeting
958 de: Microsoft Teams-Besprechung
959 google_meet:
960 en: Google Meet
961 de: Google Meet
962 series:
963 en: Series
964 de: Serie
965 invited_you:
966 en: "%{name} invited you."
967 de: "%{name} hat dich eingeladen."
968 accepted:
969 en: Accepted
970 de: Angenommen
971 declined:
972 en: Declined
973 de: Abgelehnt
974 tentative:
975 en: Tentative
976 de: Mit Vorbehalt
977 no_response:
978 en: Didn't respond
979 de: Keine Antwort
980 email_organizer:
981 en: Email organizer
982 de: E-Mail an den Organisator
983 message_placeholder:
984 en: Add a message (optional)
985 de: Nachricht hinzufügen (optional)
986 accept:
987 en: Accept
988 de: Annehmen
989 decline:
990 en: Decline
991 de: Ablehnen
992 tentative_action:
993 en: Tentative
994 de: Mit Vorbehalt
995 this_occurrence:
996 en: This occurrence
997 de: Nur dieser Termin
998 entire_series:
999 en: Entire series
1000 de: Ganze Serie
1001 join_link:
1002 en: Join link
1003 de: Beitrittslink
1004 tracking:
1005 en: Tracking
1006 de: Nachverfolgung
1007 organizer:
1008 en: Organizer
1009 de: Organisator
1010 required:
1011 en: Required
1012 de: Erforderlich
1013 optional:
1014 en: Optional
1015 de: Optional
1016 attendees_unknown:
1017 en: Attendee list not available.
1018 de: Teilnehmerliste nicht verfügbar.
1019 when_starts:
1020 en: When the event starts
1021 de: Zum Beginn des Termins
1022 minute_before:
1023 en: "%{count} minute before"
1024 de: "%{count} Minute vorher"
1025 minutes_before:
1026 en: "%{count} minutes before"
1027 de: "%{count} Minuten vorher"
1028 hour_before:
1029 en: "%{count} hour before"
1030 de: "%{count} Stunde vorher"
1031 hours_before:
1032 en: "%{count} hours before"
1033 de: "%{count} Stunden vorher"
1034 day_before:
1035 en: "%{count} day before"
1036 de: "%{count} Tag vorher"
1037 days_before:
1038 en: "%{count} days before"
1039 de: "%{count} Tage vorher"
1040 view_source:
1041 en: View source
1042 de: Quelle anzeigen
1043 open_in_google:
1044 en: Open in Google Calendar
1045 de: In Google Kalender öffnen
1046 email_guests:
1047 en: Email guests
1048 de: Gäste per E-Mail
1049 canceled_prefix:
1050 en: "Canceled: "
1051 de: "Abgesagt: "
1052 no_title:
1053 en: (No title)
1054 de: (Kein Titel)
872agents:
1055agents:
873 start:
1056 start:
874 new_session:
1057 new_session:
@@ -1156,7 +1339,7 @@ sidebar:
1156 de: Aus
1339 de: Aus
1157 include_thread_replies:
1340 include_thread_replies:
1158 en: Include thread replies
1341 en: Include thread replies
1159 de: Thread-Antworten einschließen
1342 de: Thread-Antworten einschliessen
1160 filter:
1343 filter:
1161 placeholder:
1344 placeholder:
1162 en: Filter by person or chat name
1345 en: Filter by person or chat name
@@ -1178,7 +1361,7 @@ sidebar:
1178 de: Filterfeld anzeigen
1361 de: Filterfeld anzeigen
1179 close_box:
1362 close_box:
1180 en: Close filter text box
1363 en: Close filter text box
1181 de: Filterfeld schließen
1364 de: Filterfeld schliessen
1182 show_shortcut:
1365 show_shortcut:
1183 en: "%{label} (Ctrl+Shift+F)"
1366 en: "%{label} (Ctrl+Shift+F)"
1184 de: "%{label} (Strg+Umschalt+F)"
1367 de: "%{label} (Strg+Umschalt+F)"
crates/app-state/src/app_state.rs +6 −0
@@ -92,6 +92,7 @@ pub enum AppEvent {
92 92 ForwardSelection,
93 93 ImageViewer,
94 94 StatusMessage,
95 CalendarEventPeek,
95 96 Settings(crate::settings_section::SettingsSection),
96 97 Profile,
97 98 Call,
@@ -158,6 +159,7 @@ pub struct AppState {
158 159 pub saved: SavedSet,
159 160 pub call_history: Vec<teams_core::CallLogEntry>,
160 161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
161 163 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
162 164 pub calls_list: crate::call::CallsList,
163 165 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
@@ -208,6 +210,8 @@ pub struct AppState {
208 210 pub rsvp_send_response: bool,
209 211 pub meeting_toasts: crate::call::MeetingToasts,
210 212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 /// Google week-load failure already surfaced as a notice this session.
214 pub google_sync_notice_shown: bool,
211 215 pub calendar_week: crate::call::week::CalendarWeek,
212 216 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
213 217 pub calendar_scroll_to_now: u64,
@@ -322,6 +326,7 @@ impl AppState {
322 326 saved: SavedSet::default(),
323 327 call_history: Vec::new(),
324 328 calendar_events: Vec::new(),
329 calendar_event_peek_request: None,
325 330 calendar_nudge: None,
326 331 calls_list: crate::call::CallsList::default(),
327 332 speed_dial,
@@ -372,6 +377,7 @@ impl AppState {
372 377 rsvp_send_response: true,
373 378 meeting_toasts: crate::call::MeetingToasts::default(),
374 379 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
375 381 calendar_week: crate::call::week::CalendarWeek::default(),
376 382 calendar_scroll_to_now: 0,
377 383 call_backgrounds: if mode.demo {
@@ -92,6 +92,7 @@ pub enum AppEvent {
92 ForwardSelection,
92 ForwardSelection,
93 ImageViewer,
93 ImageViewer,
94 StatusMessage,
94 StatusMessage,
95 CalendarEventPeek,
95 Settings(crate::settings_section::SettingsSection),
96 Settings(crate::settings_section::SettingsSection),
96 Profile,
97 Profile,
97 Call,
98 Call,
@@ -158,6 +159,7 @@ pub struct AppState {
158 pub saved: SavedSet,
159 pub saved: SavedSet,
159 pub call_history: Vec<teams_core::CallLogEntry>,
160 pub call_history: Vec<teams_core::CallLogEntry>,
160 pub calendar_events: Vec<chatsvc::CalendarEvent>,
161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
161 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
163 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
162 pub calls_list: crate::call::CallsList,
164 pub calls_list: crate::call::CallsList,
163 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
165 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
@@ -208,6 +210,8 @@ pub struct AppState {
208 pub rsvp_send_response: bool,
210 pub rsvp_send_response: bool,
209 pub meeting_toasts: crate::call::MeetingToasts,
211 pub meeting_toasts: crate::call::MeetingToasts,
210 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
213 /// Google week-load failure already surfaced as a notice this session.
214 pub google_sync_notice_shown: bool,
211 pub calendar_week: crate::call::week::CalendarWeek,
215 pub calendar_week: crate::call::week::CalendarWeek,
212 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
216 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
213 pub calendar_scroll_to_now: u64,
217 pub calendar_scroll_to_now: u64,
@@ -322,6 +326,7 @@ impl AppState {
322 saved: SavedSet::default(),
326 saved: SavedSet::default(),
323 call_history: Vec::new(),
327 call_history: Vec::new(),
324 calendar_events: Vec::new(),
328 calendar_events: Vec::new(),
329 calendar_event_peek_request: None,
325 calendar_nudge: None,
330 calendar_nudge: None,
326 calls_list: crate::call::CallsList::default(),
331 calls_list: crate::call::CallsList::default(),
327 speed_dial,
332 speed_dial,
@@ -372,6 +377,7 @@ impl AppState {
372 rsvp_send_response: true,
377 rsvp_send_response: true,
373 meeting_toasts: crate::call::MeetingToasts::default(),
378 meeting_toasts: crate::call::MeetingToasts::default(),
374 demo_meetings: Vec::new(),
379 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
375 calendar_week: crate::call::week::CalendarWeek::default(),
381 calendar_week: crate::call::week::CalendarWeek::default(),
376 calendar_scroll_to_now: 0,
382 calendar_scroll_to_now: 0,
377 call_backgrounds: if mode.demo {
383 call_backgrounds: if mode.demo {
crates/app-state/src/backend.rs +9 −5
@@ -505,11 +505,15 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 505 }
506 506 }
507 507 }
508 if let Ok(google_events) =
509 crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await
510 {
511 let _ = store::save_calendar_accounts(&store, &accounts);
512 combined.extend(google_events);
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 Ok(google_events) => {
510 let _ = store::save_calendar_accounts(&store, &accounts);
511 combined.extend(google_events);
512 }
513 Err(error) => crate::diagnostics::record(format!(
514 "calls: google calendar not loaded: {}",
515 shorten(&error)
516 )),
513 517 }
514 518 if combined.is_empty() && outlook_failed && !accounts.has_google() {
515 519 continue;
@@ -505,11 +505,15 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 }
505 }
506 }
506 }
507 }
507 }
508 if let Ok(google_events) =
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await
509 Ok(google_events) => {
510 {
510 let _ = store::save_calendar_accounts(&store, &accounts);
511 let _ = store::save_calendar_accounts(&store, &accounts);
511 combined.extend(google_events);
512 combined.extend(google_events);
512 }
513 Err(error) => crate::diagnostics::record(format!(
514 "calls: google calendar not loaded: {}",
515 shorten(&error)
516 )),
513 }
517 }
514 if combined.is_empty() && outlook_failed && !accounts.has_google() {
518 if combined.is_empty() && outlook_failed && !accounts.has_google() {
515 continue;
519 continue;
crates/app-state/src/call/launcher.rs +18 −1
@@ -241,6 +241,7 @@ impl CallLauncher {
241 241 ical_uid: Option<&str>,
242 242 reply: chatsvc::Reply,
243 243 send_response: bool,
244 comment: &str,
244 245 ) -> Result<(), String> {
245 246 let session = self
246 247 .ready_engine()
@@ -248,7 +249,23 @@ impl CallLauncher {
248 249 .ok_or_else(|| NOT_READY.to_owned())?
249 250 .session();
250 251 chatsvc::Calendar::new(&session)
251 .respond(event_id, ical_uid, reply, send_response)
252 .respond(event_id, ical_uid, reply, send_response, comment)
253 .await
254 .map_err(|error| error.to_string())
255 }
256
257 pub async fn calendar_event_details(
258 &self,
259 event_id: &str,
260 ical_uid: Option<&str>,
261 ) -> Result<serde_json::Value, String> {
262 let session = self
263 .ready_engine()
264 .await
265 .ok_or_else(|| NOT_READY.to_owned())?
266 .session();
267 chatsvc::Calendar::new(&session)
268 .event_details(event_id, ical_uid)
252 269 .await
253 270 .map_err(|error| error.to_string())
254 271 }
@@ -241,6 +241,7 @@ impl CallLauncher {
241 ical_uid: Option<&str>,
241 ical_uid: Option<&str>,
242 reply: chatsvc::Reply,
242 reply: chatsvc::Reply,
243 send_response: bool,
243 send_response: bool,
244 comment: &str,
244 ) -> Result<(), String> {
245 ) -> Result<(), String> {
245 let session = self
246 let session = self
246 .ready_engine()
247 .ready_engine()
@@ -248,7 +249,23 @@ impl CallLauncher {
248 .ok_or_else(|| NOT_READY.to_owned())?
249 .ok_or_else(|| NOT_READY.to_owned())?
249 .session();
250 .session();
250 chatsvc::Calendar::new(&session)
251 chatsvc::Calendar::new(&session)
251 .respond(event_id, ical_uid, reply, send_response)
252 .respond(event_id, ical_uid, reply, send_response, comment)
253 .await
254 .map_err(|error| error.to_string())
255 }
256
257 pub async fn calendar_event_details(
258 &self,
259 event_id: &str,
260 ical_uid: Option<&str>,
261 ) -> Result<serde_json::Value, String> {
262 let session = self
263 .ready_engine()
264 .await
265 .ok_or_else(|| NOT_READY.to_owned())?
266 .session();
267 chatsvc::Calendar::new(&session)
268 .event_details(event_id, ical_uid)
252 .await
269 .await
253 .map_err(|error| error.to_string())
270 .map_err(|error| error.to_string())
254 }
271 }
crates/app-state/src/call/schedule.rs +166 −2
@@ -334,7 +334,164 @@ impl AppState {
334 334 .detach();
335 335 }
336 336
337 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
337 pub fn request_calendar_event_peek(
338 &mut self,
339 event: CalendarEvent,
340 cx: &mut Context<Self>,
341 ) {
342 self.calendar_event_peek_request = Some(event);
343 cx.emit(crate::app_state::AppEvent::CalendarEventPeek);
344 cx.notify();
345 }
346
347 pub fn take_calendar_event_peek_request(&mut self) -> Option<CalendarEvent> {
348 self.calendar_event_peek_request.take()
349 }
350
351 pub fn needs_event_details(event: &CalendarEvent) -> bool {
352 event.source == chatsvc::CalendarSource::Outlook
353 && (event.location.is_none()
354 || event.body_html.is_none()
355 || event.attendees.is_empty()
356 || event.response_counts.is_none()
357 || (event.series && event.series_master_id.is_none()))
358 }
359
360 pub fn apply_calendar_event_details(
361 &mut self,
362 event_key: &str,
363 details: &serde_json::Value,
364 cx: &mut Context<Self>,
365 ) {
366 for event in self
367 .calendar_week
368 .events
369 .iter_mut()
370 .chain(self.calendar_events.iter_mut())
371 {
372 if event.object_id == event_key {
373 chatsvc::apply_event_details(event, details);
374 }
375 }
376 cx.notify();
377 }
378
379 pub fn enrich_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {
380 let Some(event) = self
381 .calendar_events
382 .iter()
383 .chain(&self.calendar_week.events)
384 .find(|event| event.object_id == event_key)
385 .cloned()
386 else {
387 return;
388 };
389 if !Self::needs_event_details(&event) {
390 return;
391 }
392 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
393 let Some(launcher) = launcher else {
394 return;
395 };
396 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
397 let fetched = runtime::spawn({
398 let event_id = event_id.clone();
399 async move {
400 launcher
401 .calendar_event_details(&event_id, ical_uid.as_deref())
402 .await
403 }
404 });
405 cx.spawn(async move |this, cx| {
406 let details = match fetched.await {
407 Ok(Ok(details)) => details,
408 Ok(Err(error)) => {
409 crate::diagnostics::record(format!(
410 "calendar peek: details failed for {event_id}: {error}"
411 ));
412 return;
413 }
414 Err(_) => {
415 crate::diagnostics::record(format!(
416 "calendar peek: details task join failed for {event_id}"
417 ));
418 return;
419 }
420 };
421 let preview_chars = details
422 .get("bodyPreview")
423 .and_then(|value| value.as_str())
424 .map(str::len)
425 .or_else(|| {
426 details
427 .pointer("/body/content")
428 .and_then(|value| value.as_str())
429 .map(str::len)
430 })
431 .or_else(|| {
432 details
433 .get("bodyContent")
434 .and_then(|value| value.as_str())
435 .map(str::len)
436 })
437 .unwrap_or(0);
438 crate::diagnostics::record(format!(
439 "calendar peek: details ok for {event_id}, preview_chars={preview_chars}"
440 ));
441 this.update(cx, |state, cx| {
442 state.apply_calendar_event_details(&event_id, &details, cx);
443 })
444 .ok();
445 // Series occurrences often ship empty body/bodyPreview; pull the master agenda.
446 let master_id = this
447 .update(cx, |state, _| {
448 state
449 .calendar_week
450 .events
451 .iter()
452 .chain(state.calendar_events.iter())
453 .find(|event| event.object_id == event_id)
454 .and_then(|event| {
455 event
456 .body_html
457 .is_none()
458 .then(|| event.series_master_id.clone())
459 .flatten()
460 })
461 })
462 .ok()
463 .flatten();
464 let Some(master_id) = master_id else {
465 return;
466 };
467 let Some(launcher) = this
468 .update(cx, |state, _| state.call_launcher.clone())
469 .ok()
470 .flatten()
471 else {
472 return;
473 };
474 let master = runtime::spawn(async move {
475 launcher.calendar_event_details(&master_id, None).await
476 });
477 let Ok(Ok(master_details)) = master.await else {
478 return;
479 };
480 this.update(cx, |state, cx| {
481 state.apply_calendar_event_details(&event_id, &master_details, cx);
482 })
483 .ok();
484 })
485 .detach();
486 }
487
488 pub fn respond_to_event(
489 &mut self,
490 event_key: &str,
491 reply: Reply,
492 comment: &str,
493 cx: &mut Context<Self>,
494 ) {
338 495 if self.mode.read_only {
339 496 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
340 497 return;
@@ -359,6 +516,7 @@ impl AppState {
359 516 return;
360 517 };
361 518 let send_response = self.rsvp_send_response;
519 let comment = comment.to_owned();
362 520 let store = self.store.clone();
363 521 let answered = runtime::spawn({
364 522 let event_id = event_id.clone();
@@ -366,7 +524,13 @@ impl AppState {
366 524 match source {
367 525 chatsvc::CalendarSource::Outlook => {
368 526 launcher
369 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
527 .respond_to_event(
528 &event_id,
529 ical_uid.as_deref(),
530 reply,
531 send_response,
532 &comment,
533 )
370 534 .await
371 535 }
372 536 chatsvc::CalendarSource::Google => {
@@ -334,7 +334,164 @@ impl AppState {
334 .detach();
334 .detach();
335 }
335 }
336
336
337 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
337 pub fn request_calendar_event_peek(
338 &mut self,
339 event: CalendarEvent,
340 cx: &mut Context<Self>,
341 ) {
342 self.calendar_event_peek_request = Some(event);
343 cx.emit(crate::app_state::AppEvent::CalendarEventPeek);
344 cx.notify();
345 }
346
347 pub fn take_calendar_event_peek_request(&mut self) -> Option<CalendarEvent> {
348 self.calendar_event_peek_request.take()
349 }
350
351 pub fn needs_event_details(event: &CalendarEvent) -> bool {
352 event.source == chatsvc::CalendarSource::Outlook
353 && (event.location.is_none()
354 || event.body_html.is_none()
355 || event.attendees.is_empty()
356 || event.response_counts.is_none()
357 || (event.series && event.series_master_id.is_none()))
358 }
359
360 pub fn apply_calendar_event_details(
361 &mut self,
362 event_key: &str,
363 details: &serde_json::Value,
364 cx: &mut Context<Self>,
365 ) {
366 for event in self
367 .calendar_week
368 .events
369 .iter_mut()
370 .chain(self.calendar_events.iter_mut())
371 {
372 if event.object_id == event_key {
373 chatsvc::apply_event_details(event, details);
374 }
375 }
376 cx.notify();
377 }
378
379 pub fn enrich_calendar_event(&mut self, event_key: &str, cx: &mut Context<Self>) {
380 let Some(event) = self
381 .calendar_events
382 .iter()
383 .chain(&self.calendar_week.events)
384 .find(|event| event.object_id == event_key)
385 .cloned()
386 else {
387 return;
388 };
389 if !Self::needs_event_details(&event) {
390 return;
391 }
392 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
393 let Some(launcher) = launcher else {
394 return;
395 };
396 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
397 let fetched = runtime::spawn({
398 let event_id = event_id.clone();
399 async move {
400 launcher
401 .calendar_event_details(&event_id, ical_uid.as_deref())
402 .await
403 }
404 });
405 cx.spawn(async move |this, cx| {
406 let details = match fetched.await {
407 Ok(Ok(details)) => details,
408 Ok(Err(error)) => {
409 crate::diagnostics::record(format!(
410 "calendar peek: details failed for {event_id}: {error}"
411 ));
412 return;
413 }
414 Err(_) => {
415 crate::diagnostics::record(format!(
416 "calendar peek: details task join failed for {event_id}"
417 ));
418 return;
419 }
420 };
421 let preview_chars = details
422 .get("bodyPreview")
423 .and_then(|value| value.as_str())
424 .map(str::len)
425 .or_else(|| {
426 details
427 .pointer("/body/content")
428 .and_then(|value| value.as_str())
429 .map(str::len)
430 })
431 .or_else(|| {
432 details
433 .get("bodyContent")
434 .and_then(|value| value.as_str())
435 .map(str::len)
436 })
437 .unwrap_or(0);
438 crate::diagnostics::record(format!(
439 "calendar peek: details ok for {event_id}, preview_chars={preview_chars}"
440 ));
441 this.update(cx, |state, cx| {
442 state.apply_calendar_event_details(&event_id, &details, cx);
443 })
444 .ok();
445 // Series occurrences often ship empty body/bodyPreview; pull the master agenda.
446 let master_id = this
447 .update(cx, |state, _| {
448 state
449 .calendar_week
450 .events
451 .iter()
452 .chain(state.calendar_events.iter())
453 .find(|event| event.object_id == event_id)
454 .and_then(|event| {
455 event
456 .body_html
457 .is_none()
458 .then(|| event.series_master_id.clone())
459 .flatten()
460 })
461 })
462 .ok()
463 .flatten();
464 let Some(master_id) = master_id else {
465 return;
466 };
467 let Some(launcher) = this
468 .update(cx, |state, _| state.call_launcher.clone())
469 .ok()
470 .flatten()
471 else {
472 return;
473 };
474 let master = runtime::spawn(async move {
475 launcher.calendar_event_details(&master_id, None).await
476 });
477 let Ok(Ok(master_details)) = master.await else {
478 return;
479 };
480 this.update(cx, |state, cx| {
481 state.apply_calendar_event_details(&event_id, &master_details, cx);
482 })
483 .ok();
484 })
485 .detach();
486 }
487
488 pub fn respond_to_event(
489 &mut self,
490 event_key: &str,
491 reply: Reply,
492 comment: &str,
493 cx: &mut Context<Self>,
494 ) {
338 if self.mode.read_only {
495 if self.mode.read_only {
339 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
496 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
340 return;
497 return;
@@ -359,6 +516,7 @@ impl AppState {
359 return;
516 return;
360 };
517 };
361 let send_response = self.rsvp_send_response;
518 let send_response = self.rsvp_send_response;
519 let comment = comment.to_owned();
362 let store = self.store.clone();
520 let store = self.store.clone();
363 let answered = runtime::spawn({
521 let answered = runtime::spawn({
364 let event_id = event_id.clone();
522 let event_id = event_id.clone();
@@ -366,7 +524,13 @@ impl AppState {
366 match source {
524 match source {
367 chatsvc::CalendarSource::Outlook => {
525 chatsvc::CalendarSource::Outlook => {
368 launcher
526 launcher
369 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
527 .respond_to_event(
528 &event_id,
529 ical_uid.as_deref(),
530 reply,
531 send_response,
532 &comment,
533 )
370 .await
534 .await
371 }
535 }
372 chatsvc::CalendarSource::Google => {
536 chatsvc::CalendarSource::Google => {
crates/app-state/src/call/week.rs +65 −5
@@ -110,19 +110,23 @@ impl AppState {
110 110 }
111 111 }
112 112 }
113 let mut google_error = None;
113 114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
114 115 Ok(events) => {
115 116 let _ = store::save_calendar_accounts(&store, &accounts);
116 117 combined.extend(events);
117 118 }
118 Err(error) => crate::diagnostics::record(format!(
119 "calls: google calendar week not loaded: {error}"
120 )),
119 Err(error) => {
120 crate::diagnostics::record(format!(
121 "calls: google calendar week not loaded: {error}"
122 ));
123 google_error = Some(error);
124 }
121 125 }
122 126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
123 127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
124 128 }
125 Ok(chatsvc::merge_calendar_events(combined))
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
126 130 });
127 131 cx.spawn(async move |this, cx| {
128 132 let loaded = receiver
@@ -134,7 +138,19 @@ impl AppState {
134 138 }
135 139 state.calendar_week.loading = false;
136 140 match loaded {
137 Ok(events) => state.calendar_week.events = events,
141 Ok((events, google_error)) => {
142 // Keep detail enrichment (agenda/location/RSVP counts) across week reloads.
143 let previous = std::mem::take(&mut state.calendar_week.events);
144 let mut events = events;
145 retain_peek_details(&previous, &mut events);
146 state.calendar_week.events = events;
147 if let Some(error) = google_error {
148 if !state.google_sync_notice_shown {
149 state.google_sync_notice_shown = true;
150 state.raise_notice(error, None, cx);
151 }
152 }
153 }
138 154 Err(notice) => state.raise_notice(notice, None, cx),
139 155 }
140 156 cx.notify();
@@ -145,6 +161,50 @@ impl AppState {
145 161 }
146 162 }
147 163
164 fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 for event in events {
166 let Some(old) = previous
167 .iter()
168 .find(|candidate| candidate.object_id == event.object_id)
169 else {
170 continue;
171 };
172 if event.body_preview.is_none() {
173 event.body_preview = old.body_preview.clone();
174 }
175 if event.body_html.is_none() {
176 event.body_html = old.body_html.clone();
177 }
178 if event.attendees.is_empty() {
179 event.attendees = old.attendees.clone();
180 }
181 if event.location.is_none() {
182 event.location = old.location.clone();
183 }
184 if event.response_counts.is_none() {
185 event.response_counts = old.response_counts;
186 }
187 if event.series_master_id.is_none() {
188 event.series_master_id = old.series_master_id.clone();
189 }
190 if event.reminders.is_empty() {
191 event.reminders = old.reminders.clone();
192 }
193 if event.source_link.is_none() {
194 event.source_link = old.source_link.clone();
195 }
196 if event.web_link.is_none() {
197 event.web_link = old.web_link.clone();
198 }
199 if event.calendar_name.is_none() {
200 event.calendar_name = old.calendar_name.clone();
201 }
202 if old.series {
203 event.series = true;
204 }
205 }
206 }
207
148 208 fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
149 209 match response {
150 210 _ if subject.starts_with("Following: ") => ShowAs::Free,
@@ -110,19 +110,23 @@ impl AppState {
110 }
110 }
111 }
111 }
112 }
112 }
113 let mut google_error = None;
113 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
114 Ok(events) => {
115 Ok(events) => {
115 let _ = store::save_calendar_accounts(&store, &accounts);
116 let _ = store::save_calendar_accounts(&store, &accounts);
116 combined.extend(events);
117 combined.extend(events);
117 }
118 }
118 Err(error) => crate::diagnostics::record(format!(
119 Err(error) => {
119 "calls: google calendar week not loaded: {error}"
120 crate::diagnostics::record(format!(
120 )),
121 "calls: google calendar week not loaded: {error}"
122 ));
123 google_error = Some(error);
124 }
121 }
125 }
122 if combined.is_empty() && outlook_failed && !accounts.has_google() {
126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
123 return Err(CALENDAR_LOAD_FAILURE.to_owned());
127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
124 }
128 }
125 Ok(chatsvc::merge_calendar_events(combined))
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
126 });
130 });
127 cx.spawn(async move |this, cx| {
131 cx.spawn(async move |this, cx| {
128 let loaded = receiver
132 let loaded = receiver
@@ -134,7 +138,19 @@ impl AppState {
134 }
138 }
135 state.calendar_week.loading = false;
139 state.calendar_week.loading = false;
136 match loaded {
140 match loaded {
137 Ok(events) => state.calendar_week.events = events,
141 Ok((events, google_error)) => {
142 // Keep detail enrichment (agenda/location/RSVP counts) across week reloads.
143 let previous = std::mem::take(&mut state.calendar_week.events);
144 let mut events = events;
145 retain_peek_details(&previous, &mut events);
146 state.calendar_week.events = events;
147 if let Some(error) = google_error {
148 if !state.google_sync_notice_shown {
149 state.google_sync_notice_shown = true;
150 state.raise_notice(error, None, cx);
151 }
152 }
153 }
138 Err(notice) => state.raise_notice(notice, None, cx),
154 Err(notice) => state.raise_notice(notice, None, cx),
139 }
155 }
140 cx.notify();
156 cx.notify();
@@ -145,6 +161,50 @@ impl AppState {
145 }
161 }
146}
162}
147
163
164fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 for event in events {
166 let Some(old) = previous
167 .iter()
168 .find(|candidate| candidate.object_id == event.object_id)
169 else {
170 continue;
171 };
172 if event.body_preview.is_none() {
173 event.body_preview = old.body_preview.clone();
174 }
175 if event.body_html.is_none() {
176 event.body_html = old.body_html.clone();
177 }
178 if event.attendees.is_empty() {
179 event.attendees = old.attendees.clone();
180 }
181 if event.location.is_none() {
182 event.location = old.location.clone();
183 }
184 if event.response_counts.is_none() {
185 event.response_counts = old.response_counts;
186 }
187 if event.series_master_id.is_none() {
188 event.series_master_id = old.series_master_id.clone();
189 }
190 if event.reminders.is_empty() {
191 event.reminders = old.reminders.clone();
192 }
193 if event.source_link.is_none() {
194 event.source_link = old.source_link.clone();
195 }
196 if event.web_link.is_none() {
197 event.web_link = old.web_link.clone();
198 }
199 if event.calendar_name.is_none() {
200 event.calendar_name = old.calendar_name.clone();
201 }
202 if old.series {
203 event.series = true;
204 }
205 }
206}
207
148fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
208fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
149 match response {
209 match response {
150 _ if subject.starts_with("Following: ") => ShowAs::Free,
210 _ if subject.starts_with("Following: ") => ShowAs::Free,
crates/app-state/src/google_calendar_sync.rs +10 −5
@@ -13,6 +13,10 @@ pub async fn fetch_google_events(
13 13 end: DateTime<Utc>,
14 14 ) -> Result<Vec<CalendarEvent>, String> {
15 15 let Some(oauth) = client_id_from_env() else {
16 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 if accounts.has_google() {
18 return Err(missing_client_id());
19 }
16 20 return Ok(Vec::new());
17 21 };
18 22 let mut all = Vec::new();
@@ -23,24 +27,25 @@ pub async fn fetch_google_events(
23 27 let account = &accounts.google_accounts[index];
24 28 let access = account.tokens.access_token.clone();
25 29 let account_id = account.id.clone();
26 let calendars: Vec<_> = account
30 let calendars: Vec<(String, String)> = account
27 31 .calendars
28 32 .iter()
29 33 .filter(|calendar| calendar.selected)
30 .map(|calendar| calendar.id.clone())
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
31 35 .collect();
32 36 let calendars = if calendars.is_empty() {
33 vec!["primary".to_owned()]
37 vec![("primary".to_owned(), "Primary".to_owned())]
34 38 } else {
35 39 calendars
36 40 };
37 41 let client = GoogleCalendar::new(access);
38 for calendar_id in calendars {
42 for (calendar_id, calendar_name) in calendars {
39 43 match client.events(&calendar_id, start, end).await {
40 44 Ok(mut events) => {
41 45 for event in &mut events {
42 46 event.account_id = Some(account_id.clone());
43 47 event.calendar_id = Some(calendar_id.clone());
48 event.calendar_name = Some(calendar_name.clone());
44 49 }
45 50 all.extend(events);
46 51 }
@@ -161,5 +166,5 @@ async fn ensure_access_token(
161 166 }
162 167
163 168 fn missing_client_id() -> String {
164 "Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()
169 app_base::ui_locale::tr("settings.calendar.not_in_build")
165 170 }
@@ -13,6 +13,10 @@ pub async fn fetch_google_events(
13 end: DateTime<Utc>,
13 end: DateTime<Utc>,
14) -> Result<Vec<CalendarEvent>, String> {
14) -> Result<Vec<CalendarEvent>, String> {
15 let Some(oauth) = client_id_from_env() else {
15 let Some(oauth) = client_id_from_env() else {
16 // Connected accounts but no client id compiled in: say so instead of an empty week.
17 if accounts.has_google() {
18 return Err(missing_client_id());
19 }
16 return Ok(Vec::new());
20 return Ok(Vec::new());
17 };
21 };
18 let mut all = Vec::new();
22 let mut all = Vec::new();
@@ -23,24 +27,25 @@ pub async fn fetch_google_events(
23 let account = &accounts.google_accounts[index];
27 let account = &accounts.google_accounts[index];
24 let access = account.tokens.access_token.clone();
28 let access = account.tokens.access_token.clone();
25 let account_id = account.id.clone();
29 let account_id = account.id.clone();
26 let calendars: Vec<_> = account
30 let calendars: Vec<(String, String)> = account
27 .calendars
31 .calendars
28 .iter()
32 .iter()
29 .filter(|calendar| calendar.selected)
33 .filter(|calendar| calendar.selected)
30 .map(|calendar| calendar.id.clone())
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
31 .collect();
35 .collect();
32 let calendars = if calendars.is_empty() {
36 let calendars = if calendars.is_empty() {
33 vec!["primary".to_owned()]
37 vec![("primary".to_owned(), "Primary".to_owned())]
34 } else {
38 } else {
35 calendars
39 calendars
36 };
40 };
37 let client = GoogleCalendar::new(access);
41 let client = GoogleCalendar::new(access);
38 for calendar_id in calendars {
42 for (calendar_id, calendar_name) in calendars {
39 match client.events(&calendar_id, start, end).await {
43 match client.events(&calendar_id, start, end).await {
40 Ok(mut events) => {
44 Ok(mut events) => {
41 for event in &mut events {
45 for event in &mut events {
42 event.account_id = Some(account_id.clone());
46 event.account_id = Some(account_id.clone());
43 event.calendar_id = Some(calendar_id.clone());
47 event.calendar_id = Some(calendar_id.clone());
48 event.calendar_name = Some(calendar_name.clone());
44 }
49 }
45 all.extend(events);
50 all.extend(events);
46 }
51 }
@@ -161,5 +166,5 @@ async fn ensure_access_token(
161}
166}
162
167
163fn missing_client_id() -> String {
168fn missing_client_id() -> String {
164 "Set TEAMS_GOOGLE_CLIENT_ID to connect Google Calendar".into()
169 app_base::ui_locale::tr("settings.calendar.not_in_build")
165}
170}
crates/app-ui-kit/src/render/mod.rs +3 −1
@@ -5,5 +5,7 @@ pub mod hooks;
5 5 mod selectable;
6 6 mod syntax;
7 7
8 pub use blocks::{Block, TableCell, layout_blocks, layout_card_blocks, table_images};
8 pub use blocks::{
9 Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,
10 };
9 11 pub use elements::{CODE_BLOCK_TAG, CODE_LINE_TAG, render_blocks, render_table};
@@ -5,5 +5,7 @@ pub mod hooks;
5mod selectable;
5mod selectable;
6mod syntax;
6mod syntax;
7
7
8pub use blocks::{Block, TableCell, layout_blocks, layout_card_blocks, table_images};
8pub use blocks::{
9 Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,
10};
9pub use elements::{CODE_BLOCK_TAG, CODE_LINE_TAG, render_blocks, render_table};
11pub use elements::{CODE_BLOCK_TAG, CODE_LINE_TAG, render_blocks, render_table};
crates/app/src/i18n.rs +21 −4
@@ -72,14 +72,31 @@ mod tests {
72 72 }
73 73
74 74 #[test]
75 fn ui_locale_auth_splash_keys() {
75 fn ui_locale_calendar_peek_keys_en_de() {
76 76 let _guard = locale_test_lock();
77 77 apply_locale("en");
78 assert_eq!(tr("calendar.peek.email_organizer"), "Email organizer");
79 assert_eq!(tr("calendar.peek.series"), "Series");
80 apply_locale("de");
78 81 assert_eq!(
79 tr("auth.splash.opening_browser"),
80 "Opening the browser for sign-in…"
82 tr("calendar.peek.email_organizer"),
83 "E-Mail an den Organisator"
81 84 );
85 assert_eq!(tr("calendar.peek.teams_meeting"), "Microsoft Teams-Besprechung");
86 assert_eq!(tr("calendar.peek.google_meet"), "Google Meet");
87 assert_eq!(tr("calendar.peek.accept"), "Annehmen");
88 }
89
90 #[test]
91 fn ui_locale_settings_calendar_connect_keys() {
92 let _guard = locale_test_lock();
93 apply_locale("en");
94 assert_eq!(tr("settings.calendar.connect_button"), "Connect Google");
82 95 apply_locale("de");
83 assert!(tr("auth.splash.awaiting_browser").contains("Browser"));
96 assert_eq!(tr("settings.calendar.connect_button"), "Google verbinden");
97 assert_eq!(
98 tr("settings.calendar.not_in_build"),
99 "Google Kalender ist in diesem Build nicht enthalten."
100 );
84 101 }
85 102 }
@@ -72,14 +72,31 @@ mod tests {
72 }
72 }
73
73
74 #[test]
74 #[test]
75 fn ui_locale_auth_splash_keys() {
75 fn ui_locale_calendar_peek_keys_en_de() {
76 let _guard = locale_test_lock();
76 let _guard = locale_test_lock();
77 apply_locale("en");
77 apply_locale("en");
78 assert_eq!(tr("calendar.peek.email_organizer"), "Email organizer");
79 assert_eq!(tr("calendar.peek.series"), "Series");
80 apply_locale("de");
78 assert_eq!(
81 assert_eq!(
79 tr("auth.splash.opening_browser"),
82 tr("calendar.peek.email_organizer"),
80 "Opening the browser for sign-in…"
83 "E-Mail an den Organisator"
81 );
84 );
85 assert_eq!(tr("calendar.peek.teams_meeting"), "Microsoft Teams-Besprechung");
86 assert_eq!(tr("calendar.peek.google_meet"), "Google Meet");
87 assert_eq!(tr("calendar.peek.accept"), "Annehmen");
88 }
89
90 #[test]
91 fn ui_locale_settings_calendar_connect_keys() {
92 let _guard = locale_test_lock();
93 apply_locale("en");
94 assert_eq!(tr("settings.calendar.connect_button"), "Connect Google");
82 apply_locale("de");
95 apply_locale("de");
83 assert!(tr("auth.splash.awaiting_browser").contains("Browser"));
96 assert_eq!(tr("settings.calendar.connect_button"), "Google verbinden");
97 assert_eq!(
98 tr("settings.calendar.not_in_build"),
99 "Google Kalender ist in diesem Build nicht enthalten."
100 );
84 }
101 }
85}
102}
crates/app/src/views/calendar_event_dialog.rs +1233 −167
@@ -1,212 +1,1278 @@
1 use chatsvc::{CalendarEvent, ResponseType, join_info_text};
2 use chrono::{Local, Offset};
1 use std::collections::HashMap;
2
3 use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, SIDEBAR_WIDTH};
4 use app_ui_kit::render::{Block, layout_blocks, render_blocks, strip_image_placeholders};
5 use chatsvc::{
6 CalendarEvent, CalendarSource, DialIn, EventAttendee, Reply, ResponseType, join_info_text,
7 };
8 use chrono::{Datelike, Local, Offset, Weekday};
3 9 use gpui_kit::assets::IconName;
4 10 use gpui_kit::component::Sizable as _;
5 11 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 use gpui_kit::component::dialog::{Dialog, DialogFooter};
7 use gpui_kit::component::menu::DropdownMenu as _;
8 use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12 use gpui_kit::component::checkbox::Checkbox;
13 use gpui_kit::component::input::{Input, InputState};
14 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
15 use gpui_kit::component::scroll::ScrollableElement as _;
16 use gpui_kit::component::{Icon, h_flex, v_flex};
17 use gpui_kit::prelude::FluentBuilder as _;
9 18 use gpui_kit::*;
10 19
11 use super::rsvp_menu::rsvp_menu;
12 20 use crate::app_state::AppState;
13 21 use crate::call::week_grid::is_effective_all_day;
14 use crate::i18n::tr;
15 use crate::theme;
22 use crate::i18n::{tr, tr_args};
23 use crate::theme::{self, ElevatedSurface as _};
16 24
17 const DIALOG_WIDTH: f32 = 440.;
18 const FIELD_GAP: f32 = 12.;
19 const LABEL_SIZE: f32 = 12.;
25 const CARD_WIDTH: f32 = 440.;
26 const CARD_RADIUS: f32 = 10.;
27 const CARD_PADDING: f32 = 16.;
28 const CARD_MARGIN: f32 = 32.;
29 const SECTION_GAP: f32 = 12.;
30 const ROW_GAP: f32 = 8.;
31 const ICON_SIZE: f32 = 16.;
32 const AVATAR_SIZE: f32 = 28.;
33 const BACKDROP_OPACITY: f32 = 0.55;
34 /// Shrink-only agenda cap (Forward-dialog preview pattern — no flex_1).
35 const AGENDA_MAX_HEIGHT: f32 = 280.;
36 const EXPANDED_WIDTH: f32 = 0.92;
37 const EXPANDED_HEIGHT: f32 = 0.88;
38 const TRACKING_GROUPS: [ResponseType; 4] = [
39 ResponseType::Accepted,
40 ResponseType::Tentative,
41 ResponseType::Declined,
42 ResponseType::NotResponded,
43 ];
20 44 const COPY_JOIN_INFO: &str = "Copy join info";
21 45
22 fn when_label(event: &CalendarEvent) -> String {
23 let offset = Local::now().offset().fix();
24 if is_effective_all_day(event, offset) {
25 let start = event.start.with_timezone(&offset).date_naive();
26 let end = event.end.with_timezone(&offset).date_naive();
27 if end > start + chrono::Duration::days(1) {
28 return format!(
29 "All day · {} – {}",
30 start.format("%a, %b %-d"),
31 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
32 );
46 pub enum EventPeekEvent {
47 Close,
48 }
49
50 pub struct EventPeek {
51 state: Entity<AppState>,
52 event: CalendarEvent,
53 expanded: bool,
54 /// Parsed `body_html`, keyed by the HTML it came from.
55 agenda: Option<(String, Vec<Block>)>,
56 collapsed: Vec<ResponseType>,
57 message: Entity<InputState>,
58 _observation: Subscription,
59 }
60
61 impl EventEmitter<EventPeekEvent> for EventPeek {}
62
63 impl EventPeek {
64 pub fn new(
65 state: Entity<AppState>,
66 event: CalendarEvent,
67 window: &mut Window,
68 cx: &mut Context<Self>,
69 ) -> Self {
70 let event_key = event.object_id.clone();
71 let opening_preview = event
72 .body_preview
73 .as_ref()
74 .map(|value| value.chars().count())
75 .unwrap_or(0);
76 app_base::diagnostics::record(format!(
77 "calendar peek: open {event_key} preview_chars={opening_preview}"
78 ));
79 state.update(cx, |app, cx| app.enrich_calendar_event(&event_key, cx));
80 let message = cx.new(|cx| {
81 InputState::new(window, cx).placeholder(tr("calendar.peek.message_placeholder"))
82 });
83 let watched = state.clone();
84 // observe (not subscribe): detail enrichment only notifies AppState, it does not emit.
85 let observation = cx.observe(&watched, |this, _, cx| {
86 this.pull_event(cx);
87 cx.notify();
88 });
89 let mut peek = EventPeek {
90 state,
91 event,
92 expanded: false,
93 agenda: None,
94 collapsed: Vec::new(),
95 message,
96 _observation: observation,
97 };
98 // The clicked calendar block can be a stale clone. If details are already
99 // cached, enrich_calendar_event() emits no notify, so pull once now.
100 peek.pull_event(cx);
101 let pulled = peek
102 .event
103 .body_preview
104 .as_ref()
105 .map(|value| value.chars().count())
106 .unwrap_or(0);
107 if pulled != opening_preview {
108 app_base::diagnostics::record(format!(
109 "calendar peek: pulled preview_chars={pulled} for {event_key}"
110 ));
33 111 }
34 return format!("All day · {}", start.format("%a, %b %-d, %Y"));
112 peek
35 113 }
36 let start = event.start.with_timezone(&offset);
37 let end = event.end.with_timezone(&offset);
38 if start.date_naive() == end.date_naive() {
39 format!(
40 "{} · {} – {}",
41 start.format("%a, %b %-d, %Y"),
42 start.format(app_base::format::clock_format()),
43 end.format(app_base::format::clock_format())
44 )
45 } else {
46 format!(
47 "{} {} – {} {}",
48 start.format("%a, %b %-d"),
49 start.format(app_base::format::clock_format()),
50 end.format("%a, %b %-d, %Y"),
51 end.format(app_base::format::clock_format())
52 )
114
115 fn pull_event(&mut self, cx: &mut Context<Self>) {
116 let key = self.event.object_id.clone();
117 let app = self.state.read(cx);
118 let best = app
119 .calendar_week
120 .events
121 .iter()
122 .chain(app.calendar_events.iter())
123 .find(|event| event.object_id == key)
124 .cloned();
125 let best = app
126 .calendar_week
127 .events
128 .iter()
129 .chain(app.calendar_events.iter())
130 .filter(|event| event.object_id == key)
131 .cloned()
132 .fold(best, |best, candidate| {
133 Some(match best {
134 Some(current) if event_detail_score(&current) >= event_detail_score(&candidate) => {
135 current
136 }
137 _ => candidate,
138 })
139 });
140 if let Some(event) = best {
141 self.event = event;
142 }
143 self.refresh_agenda();
53 144 }
54 }
55 145
56 fn source_label(event: &CalendarEvent) -> String {
57 let mut sources = event.sources.clone();
58 if sources.is_empty() {
59 sources.push(event.source);
146 fn refresh_agenda(&mut self) {
147 let Some(html) = self.event.body_html.as_ref() else {
148 self.agenda = None;
149 return;
150 };
151 if self.agenda.as_ref().is_some_and(|(source, _)| source == html) {
152 return;
153 }
154 let blocks = strip_image_placeholders(layout_blocks(&teams_core::html_to_spans(html)));
155 self.agenda = Some((html.clone(), blocks));
60 156 }
61 sources.sort_by_key(|source| source.label());
62 sources.dedup();
63 sources
64 .iter()
65 .map(|source| source.label())
66 .collect::<Vec<_>>()
67 .join(" + ")
68 }
69 157
70 fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
71 v_flex()
72 .gap(px(2.))
73 .child(
74 div()
75 .text_size(px(LABEL_SIZE))
76 .text_color(theme::text_muted())
77 .child(label.to_owned()),
78 )
79 .child(
158 fn agenda_element(&self, cx: &App) -> Option<AnyElement> {
159 if let Some((_, blocks)) = self.agenda.as_ref().filter(|(_, blocks)| !blocks.is_empty()) {
160 return Some(
161 div()
162 .w_full()
163 .min_w(px(0.))
164 .text_size(px(14.))
165 .text_color(theme::text())
166 .child(render_blocks(blocks, "calendar-peek-agenda", false, cx))
167 .into_any_element(),
168 );
169 }
170 let preview = self.event.body_preview.clone().filter(|value| !value.is_empty())?;
171 Some(
80 172 div()
81 .text_size(px(14.))
82 .text_color(theme::text())
83 .child(value.into()),
173 .w_full()
174 .min_w(px(0.))
175 .whitespace_normal()
176 .text_size(px(13.))
177 .text_color(theme::text_soft())
178 .child(preview)
179 .into_any_element(),
84 180 )
85 }
181 }
86 182
87 pub fn open_calendar_event(
88 state: Entity<AppState>,
89 event: CalendarEvent,
90 window: &mut Window,
91 cx: &mut App,
92 ) {
93 let send_response = state.read(cx).rsvp_send_response;
94 // Show Join whenever a Teams link exists — not only inside the join window.
95 let can_join = event.online && !event.cancelled && event.join_url.is_some();
96 let subject = if event.cancelled {
97 format!("Canceled: {}", event.subject)
98 } else if event.subject.is_empty() {
99 "(No title)".to_owned()
100 } else {
101 event.subject.clone()
102 };
103 let when = when_label(&event);
104 let source = source_label(&event);
105 let organizer = event
106 .organizer_name
107 .clone()
108 .or_else(|| event.organizer_address.clone());
109 let join_url = event.join_url.clone();
110 let dial_in = event.dial_in.clone();
111 let thread_id = event.thread_id.clone();
112 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
113 let response = event.response;
114 let event_key = event.object_id.clone();
115 let meeting_title = event.subject.clone();
116 let online = event.online;
117
118 window.open_dialog(cx, move |dialog: Dialog, _, _| {
119 let delete_state = state.clone();
120 let delete_key = event_key.clone();
121 let mut footer = DialogFooter::new()
183 fn toggle_expand(&mut self, cx: &mut Context<Self>) {
184 self.expanded = !self.expanded;
185 cx.notify();
186 }
187
188 fn toggle_group(&mut self, group: ResponseType, cx: &mut Context<Self>) {
189 if let Some(index) = self.collapsed.iter().position(|kind| *kind == group) {
190 self.collapsed.remove(index);
191 } else {
192 self.collapsed.push(group);
193 }
194 cx.notify();
195 }
196
197 fn toggle_email_organizer(&mut self, cx: &mut Context<Self>) {
198 self.state
199 .update(cx, |state, cx| state.toggle_rsvp_send_response(cx));
200 cx.notify();
201 }
202
203 fn close(&mut self, cx: &mut Context<Self>) {
204 cx.emit(EventPeekEvent::Close);
205 }
206
207 fn respond(&mut self, reply: Reply, cx: &mut Context<Self>) {
208 let key = self.event.object_id.clone();
209 let send = self.state.read(cx).rsvp_send_response;
210 let comment = if send && self.event.source == CalendarSource::Outlook {
211 self.message.read(cx).value().to_string()
212 } else {
213 String::new()
214 };
215 self.state
216 .update(cx, |state, cx| state.respond_to_event(&key, reply, &comment, cx));
217 self.close(cx);
218 }
219
220 fn respond_series_master(&mut self, reply: Reply, cx: &mut Context<Self>) {
221 let Some(master) = self.event.series_master_id.clone() else {
222 self.respond(reply, cx);
223 return;
224 };
225 let send = self.state.read(cx).rsvp_send_response;
226 let comment = if send && self.event.source == CalendarSource::Outlook {
227 self.message.read(cx).value().to_string()
228 } else {
229 String::new()
230 };
231 self.state
232 .update(cx, |state, cx| state.respond_to_event(&master, reply, &comment, cx));
233 self.close(cx);
234 }
235
236 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
237 if event.keystroke.key.as_str() == "escape" {
238 self.close(cx);
239 cx.stop_propagation();
240 }
241 }
242
243 fn has_scroll_content(&self) -> bool {
244 self.agenda
245 .as_ref()
246 .is_some_and(|(_, blocks)| !blocks.is_empty())
247 || self
248 .event
249 .body_preview
250 .as_ref()
251 .is_some_and(|value| !value.is_empty())
252 }
253
254 fn subject_label(&self) -> String {
255 let event = &self.event;
256 if event.cancelled {
257 format!("{}{}", tr("calendar.peek.canceled_prefix"), event.subject)
258 } else if event.subject.is_empty() {
259 tr("calendar.peek.no_title")
260 } else {
261 event.subject.clone()
262 }
263 }
264
265 fn organizer_label(&self) -> String {
266 self.event
267 .organizer_name
268 .clone()
269 .or_else(|| self.event.organizer_address.clone())
270 .unwrap_or_default()
271 }
272
273 fn expand_button(&self, cx: &mut Context<Self>) -> Button {
274 Button::new("calendar-peek-expand")
275 .ghost()
276 .small()
277 .icon(if self.expanded {
278 IconName::Minimize2
279 } else {
280 IconName::Expand
281 })
282 .on_click(cx.listener(|this, _, _, cx| this.toggle_expand(cx)))
283 }
284
285 fn when_row(&self) -> Div {
286 h_flex()
287 .gap(px(ROW_GAP))
288 .items_start()
289 .child(icon(IconName::Clock, theme::text_muted()))
122 290 .child(
123 Button::new("calendar-event-delete")
124 .danger()
125 .label(tr("common.delete"))
126 .on_click(move |_, window, cx| {
127 delete_state
128 .update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
129 window.close_dialog(cx);
291 h_flex()
292 .flex_1()
293 .min_w_0()
294 .gap(px(8.))
295 .items_center()
296 .child(
297 div()
298 .text_size(px(14.))
299 .text_color(theme::text())
300 .child(peek_when_label(&self.event)),
301 )
302 .when(self.event.series, |row| {
303 row.child(
304 h_flex()
305 .gap(px(4.))
306 .items_center()
307 .child(icon(IconName::Repeat, theme::text_muted()))
308 .child(
309 div()
310 .text_size(px(13.))
311 .text_color(theme::text_soft())
312 .child(tr("calendar.peek.series")),
313 ),
314 )
130 315 }),
131 316 )
317 }
318
319 fn location_row(&self) -> Option<Div> {
320 let location = location_label(&self.event);
321 (!location.is_empty()).then(|| {
322 h_flex()
323 .gap(px(ROW_GAP))
324 .items_start()
325 .child(icon(IconName::MapPin, theme::text_muted()))
326 .child(
327 div()
328 .text_size(px(14.))
329 .text_color(theme::text())
330 .child(location),
331 )
332 })
333 }
334
335 /// Google-only: which calendar owns the event.
336 fn calendar_row(&self) -> Option<Div> {
337 if self.event.source != CalendarSource::Google {
338 return None;
339 }
340 let name = self.event.calendar_name.clone().filter(|value| !value.is_empty())?;
341 Some(
342 h_flex()
343 .gap(px(ROW_GAP))
344 .items_center()
345 .child(icon(IconName::Calendar, theme::text_muted()))
346 .child(
347 div()
348 .text_size(px(14.))
349 .text_color(theme::text())
350 .child(name),
351 ),
352 )
353 }
354
355 fn reminder_row(&self) -> Option<Div> {
356 if self.event.reminders.is_empty() {
357 return None;
358 }
359 Some(
360 h_flex()
361 .gap(px(ROW_GAP))
362 .items_start()
363 .child(icon(IconName::Bell, theme::text_muted()))
364 .child(
365 v_flex()
366 .gap(px(2.))
367 .children(self.event.reminders.iter().map(|minutes| {
368 div()
369 .text_size(px(14.))
370 .text_color(theme::text())
371 .child(reminder_label(*minutes))
372 })),
373 ),
374 )
375 }
376
377 fn source_row(&self, _cx: &mut Context<Self>) -> Option<AnyElement> {
378 let (title, url) = self.event.source_link.clone()?;
379 let open = url.clone();
380 Some(
381 h_flex()
382 .gap(px(ROW_GAP))
383 .items_start()
384 .child(icon(IconName::Link, theme::text_muted()))
385 .child(
386 v_flex()
387 .gap(px(2.))
388 .min_w(px(0.))
389 .child(
390 div()
391 .text_size(px(14.))
392 .text_color(theme::text())
393 .whitespace_normal()
394 .child(title),
395 )
396 .child(
397 div()
398 .id("calendar-peek-view-source")
399 .text_size(px(12.))
400 .text_color(theme::accent_text())
401 .cursor_pointer()
402 .child(tr("calendar.peek.view_source"))
403 .on_click(move |_, _, cx| cx.open_url(&open)),
404 ),
405 )
406 .into_any_element(),
407 )
408 }
409
410 fn google_meta_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
411 let mut rows = Vec::new();
412 if let Some(row) = self.calendar_row() {
413 rows.push(row.into_any_element());
414 }
415 if let Some(row) = self.reminder_row() {
416 rows.push(row.into_any_element());
417 }
418 if let Some(row) = self.source_row(cx) {
419 rows.push(row);
420 }
421 rows
422 }
423
424 fn render_header(&self, cx: &mut Context<Self>) -> Stateful<Div> {
425 let event = &self.event;
426 let subject = self.subject_label();
427 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
428 let organizer = self.organizer_label();
429 let initials = app_base::format::initials(&organizer);
430 let summary = response_summary(event);
431
432 let header_actions = h_flex()
433 .gap(px(8.))
434 .children(self.google_action_buttons())
435 .children(self.join_chat_buttons(cx));
436
437 let title_row = h_flex()
438 .w_full()
439 .items_start()
440 .justify_between()
441 .gap(px(8.))
132 442 .child(
133 Button::new("calendar-event-close")
134 .label(tr("common.close"))
135 .on_click(|_, window, cx| window.close_dialog(cx)),
443 div()
444 .flex_1()
445 .min_w_0()
446 .text_size(px(18.))
447 .font_weight(FontWeight::SEMIBOLD)
448 .text_color(theme::text())
449 .child(subject),
450 )
451 .child(self.expand_button(cx));
452
453 let mut header = v_flex()
454 .id("calendar-peek-header")
455 .w_full()
456 .flex_none()
457 .gap(px(SECTION_GAP))
458 .child(title_row)
459 .child(header_actions)
460 .child(self.when_row())
461 .children(self.location_row())
462 .children(self.google_meta_rows(cx));
463
464 if !organizer.is_empty() {
465 let invite_line = if can_rsvp {
466 let mut args = HashMap::new();
467 args.insert("name".to_owned(), organizer.clone());
468 tr_args("calendar.peek.invited_you", &args)
469 } else {
470 organizer.clone()
471 };
472 header = header.child(
473 h_flex()
474 .gap(px(ROW_GAP))
475 .items_start()
476 .child(avatar(initials))
477 .child(
478 v_flex()
479 .gap(px(2.))
480 .child(
481 div()
482 .text_size(px(14.))
483 .text_color(theme::text())
484 .child(invite_line),
485 )
486 .children(summary.map(|text| {
487 div()
488 .text_size(px(12.))
489 .text_color(theme::text_muted())
490 .child(text)
491 })),
492 ),
136 493 );
137 if can_rsvp {
138 let menu_state = state.clone();
139 let menu_key = event_key.clone();
140 footer = footer.child(
141 Button::new("calendar-event-rsvp")
142 .label("RSVP")
143 .dropdown_menu(move |menu, _, _| {
144 rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
145 }),
494 }
495
496 header
497 }
498
499 /// Google-only: Open in Google Calendar + Email guests.
500 fn google_action_buttons(&self) -> Vec<AnyElement> {
501 if self.event.source != CalendarSource::Google {
502 return Vec::new();
503 }
504 let mut buttons = Vec::new();
505 if let Some(url) = self.event.web_link.clone() {
506 buttons.push(
507 Button::new("calendar-peek-open-google")
508 .outline()
509 .icon(IconName::ExternalLink)
510 .label(tr("calendar.peek.open_in_google"))
511 .on_click(move |_, _, cx| cx.open_url(&url))
512 .into_any_element(),
146 513 );
147 514 }
148 if thread_id.is_some() {
149 let chat_state = state.clone();
150 let chat_thread = thread_id.clone();
151 footer = footer.child(
152 Button::new("calendar-event-chat")
153 .label(tr("common.chat"))
154 .on_click(move |_, window, cx| {
155 chat_state.update(cx, |state, cx| {
156 state.open_meeting_chat(chat_thread.as_deref(), cx)
157 });
158 window.close_dialog(cx);
159 }),
515 let addresses: Vec<String> = self
516 .event
517 .attendees
518 .iter()
519 .filter_map(|attendee| attendee.address.clone())
520 .filter(|address| !address.is_empty())
521 .collect();
522 if !addresses.is_empty() {
523 let mut mailto = format!("mailto:{}", addresses.join(","));
524 if !self.event.subject.is_empty() {
525 let subject = self
526 .event
527 .subject
528 .replace('%', "%25")
529 .replace(' ', "%20")
530 .replace('&', "%26")
531 .replace('?', "%3F")
532 .replace('#', "%23");
533 mailto = format!("{mailto}?subject={subject}");
534 }
535 buttons.push(
536 Button::new("calendar-peek-email-guests")
537 .outline()
538 .icon(IconName::Mail)
539 .label(tr("calendar.peek.email_guests"))
540 .on_click(move |_, _, cx| cx.open_url(&mailto))
541 .into_any_element(),
160 542 );
161 543 }
544 buttons
545 }
546
547 fn join_chat_buttons(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
548 let event = &self.event;
549 let can_join = event.online && !event.cancelled && event.join_url.is_some();
550 let join_url = event.join_url.clone();
551 let dial_in = event.dial_in.clone();
552 let thread_id = event.thread_id.clone();
553 let meeting_title = event.subject.clone();
554 let mut buttons = Vec::new();
162 555 if can_join {
163 let join_state = state.clone();
556 let join_state = self.state.clone();
164 557 let url = join_url.clone();
165 558 let title = meeting_title.clone();
166 footer = footer.child(
167 Button::new("calendar-event-join")
168 .primary()
559 let clipboard = join_url
560 .as_deref()
561 .map(|url| copy_join_clipboard(url, dial_in.as_ref()));
562 buttons.push(
563 Button::new("calendar-peek-join")
564 .outline()
169 565 .label(tr("common.join"))
170 .on_click(move |_, window, cx| {
566 .icon(IconName::Video)
567 .on_click(cx.listener(move |this, _, _, cx| {
171 568 join_state.update(cx, |state, cx| {
172 569 state.join_calendar_meeting(url.as_deref(), &title, cx)
173 570 });
174 window.close_dialog(cx);
175 }),
571 this.close(cx);
572 }))
573 .into_any_element(),
176 574 );
575 if let Some(info) = clipboard {
576 buttons.push(
577 Button::new("calendar-peek-join-menu")
578 .outline()
579 .icon(IconName::ChevronDown)
580 .dropdown_menu(move |menu, _, _| {
581 let info = info.clone();
582 menu.item(
583 PopupMenuItem::new(COPY_JOIN_INFO)
584 .icon(IconName::Copy)
585 .on_click(move |_, _, cx| {
586 cx.write_to_clipboard(ClipboardItem::new_string(
587 info.clone(),
588 ))
589 }),
590 )
591 })
592 .into_any_element(),
593 );
594 }
177 595 }
596 if thread_id.is_some() {
597 let chat_state = self.state.clone();
598 let chat_thread = thread_id.clone();
599 buttons.push(
600 Button::new("calendar-peek-chat")
601 .outline()
602 .label(tr("common.chat"))
603 .icon(IconName::MessageSquare)
604 .on_click(cx.listener(move |this, _, _, cx| {
605 chat_state.update(cx, |state, cx| {
606 state.open_meeting_chat(chat_thread.as_deref(), cx)
607 });
608 this.close(cx);
609 }))
610 .into_any_element(),
611 );
612 }
613 buttons
614 }
615
616 /// Compact agenda: max_h + scrollbar on the content root (Forward-preview pattern).
617 /// A nested scroll wrapper with min_h(0) collapses to 0 height in GPUI.
618 fn render_scroll_body(agenda: AnyElement) -> impl IntoElement {
619 h_flex()
620 .id("calendar-peek-scroll-content")
621 .w_full()
622 .gap(px(ROW_GAP))
623 .items_start()
624 .child(icon(IconName::List, theme::text_muted()))
625 .child(div().flex_1().min_w(px(0.)).child(agenda))
626 .flex_shrink_0()
627 .max_h(px(AGENDA_MAX_HEIGHT))
628 .overflow_y_scrollbar()
629 }
178 630
179 let mut body = v_flex()
180 .gap(px(FIELD_GAP))
181 .child(detail_row("When", when.clone()))
182 .child(detail_row("Calendar", source.clone()));
183 if let Some(name) = organizer.clone() {
184 body = body.child(detail_row("Organizer", name));
631 fn render_expanded(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
632 let toolbar = h_flex()
633 .w_full()
634 .flex_none()
635 .gap(px(8.))
636 .items_center()
637 .children(self.action_buttons(cx))
638 .child(div().flex_1())
639 .children(self.google_action_buttons())
640 .children(self.join_chat_buttons(cx))
641 .child(self.expand_button(cx))
642 .child(
643 Button::new("calendar-peek-close")
644 .ghost()
645 .small()
646 .icon(IconName::X)
647 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
648 );
649
650 let names = self.attendee_names_line();
651 let mut details = v_flex()
652 .id("calendar-peek-expanded-details")
653 .flex_1()
654 .min_w(px(0.))
655 .h_full()
656 .gap(px(SECTION_GAP))
657 .pr(px(CARD_PADDING))
658 .child(
659 div()
660 .text_size(px(20.))
661 .font_weight(FontWeight::SEMIBOLD)
662 .text_color(theme::text())
663 .child(self.subject_label()),
664 )
665 .children(names.map(|names| {
666 h_flex()
667 .gap(px(ROW_GAP))
668 .items_start()
669 .child(icon(IconName::Users, theme::text_muted()))
670 .child(
671 div()
672 .flex_1()
673 .min_w(px(0.))
674 .whitespace_normal()
675 .text_size(px(13.))
676 .text_color(theme::text_soft())
677 .child(names),
678 )
679 }))
680 .child(self.when_row())
681 .children(self.location_row())
682 .children(self.google_meta_rows(cx))
683 .children(self.rsvp_message_controls(cx));
684 if let Some(agenda) = self.agenda_element(cx) {
685 details = details.child(
686 div()
687 .w_full()
688 .pt(px(SECTION_GAP))
689 .border_t_1()
690 .border_color(theme::border())
691 .child(agenda),
692 );
693 }
694
695 let body = h_flex()
696 .w_full()
697 .flex_1()
698 .min_h(px(0.))
699 .items_start()
700 .child(details.overflow_y_scrollbar())
701 .child(self.render_tracking(cx));
702
703 v_flex()
704 .size_full()
705 .gap(px(SECTION_GAP))
706 .child(toolbar)
707 .child(body)
708 }
709
710 fn attendee_names_line(&self) -> Option<String> {
711 let organizer = self.organizer_label();
712 let mut names: Vec<String> = Vec::new();
713 if !organizer.is_empty() {
714 names.push(organizer);
715 }
716 for attendee in &self.event.attendees {
717 if !names.contains(&attendee.name) {
718 names.push(attendee.name.clone());
719 }
720 }
721 (names.len() > 1).then(|| names.join(", "))
722 }
723
724 fn render_tracking(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
725 let organizer = self.organizer_label();
726 let mut panel = v_flex()
727 .id("calendar-peek-tracking")
728 .w(px(SIDEBAR_WIDTH))
729 .flex_none()
730 .h_full()
731 .pl(px(CARD_PADDING))
732 .gap(px(SECTION_GAP))
733 .border_l_1()
734 .border_color(theme::border())
735 .child(
736 div()
737 .text_size(px(16.))
738 .font_weight(FontWeight::SEMIBOLD)
739 .text_color(theme::text())
740 .child(tr("calendar.peek.tracking")),
741 );
742 if !organizer.is_empty() {
743 panel = panel.child(person_row(&organizer, tr("calendar.peek.organizer")));
744 }
745
746 let roster: Vec<&EventAttendee> = self
747 .event
748 .attendees
749 .iter()
750 .filter(|attendee| attendee.response != ResponseType::Organizer)
751 .collect();
752 if roster.is_empty() {
753 let note = response_summary(&self.event)
754 .unwrap_or_else(|| tr("calendar.peek.attendees_unknown"));
755 return panel
756 .child(
757 div()
758 .text_size(px(13.))
759 .text_color(theme::text_muted())
760 .child(note),
761 )
762 .overflow_y_scrollbar();
185 763 }
186 if let Some(url) = join_url.clone().filter(|_| online) {
187 let info = join_info_text(&url, dial_in.as_ref());
188 body = body.child(
189 v_flex()
190 .gap(px(6.))
191 .child(detail_row("Join link", url))
764
765 for (index, group) in TRACKING_GROUPS.into_iter().enumerate() {
766 let members: Vec<&&EventAttendee> = roster
767 .iter()
768 .filter(|attendee| attendee.response == group)
769 .collect();
770 if members.is_empty() {
771 continue;
772 }
773 let collapsed = self.collapsed.contains(&group);
774 let mut section = v_flex().gap(px(ROW_GAP)).child(
775 h_flex()
776 .id(SharedString::from(format!("calendar-peek-group-{index}")))
777 .gap(px(4.))
778 .items_center()
779 .cursor_pointer()
780 .on_click(cx.listener(move |this, _, _, cx| this.toggle_group(group, cx)))
781 .child(icon(
782 if collapsed {
783 IconName::ChevronRight
784 } else {
785 IconName::ChevronDown
786 },
787 theme::text_muted(),
788 ))
192 789 .child(
193 h_flex().child(
194 Button::new("calendar-event-copy-join")
195 .small()
196 .label(COPY_JOIN_INFO)
197 .icon(IconName::Copy)
198 .on_click(move |_, _, cx| {
199 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
200 }),
201 ),
790 div()
791 .text_size(px(13.))
792 .font_weight(FontWeight::SEMIBOLD)
793 .text_color(theme::text())
794 .child(format!("{} {}", group_label(group), members.len())),
202 795 ),
203 796 );
797 if !collapsed {
798 section = section.children(members.into_iter().map(|attendee| {
799 let role = if attendee.required {
800 tr("calendar.peek.required")
801 } else {
802 tr("calendar.peek.optional")
803 };
804 person_row(&attendee.name, role)
805 }));
806 }
807 panel = panel.child(section);
808 }
809 panel.overflow_y_scrollbar()
810 }
811
812 fn can_rsvp(&self) -> bool {
813 self.event.response != ResponseType::Organizer && self.event.organizer_name.is_some()
814 }
815
816 /// Outlook-only: Graph RSVP supports sendResponse + comment. Google does not.
817 fn rsvp_message_controls(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
818 if !self.can_rsvp() || self.event.source != CalendarSource::Outlook {
819 return Vec::new();
204 820 }
821 let send_response = self.state.read(cx).rsvp_send_response;
822 let mut controls = vec![
823 Checkbox::new("calendar-peek-email-organizer")
824 .label(tr("calendar.peek.email_organizer"))
825 .checked(send_response)
826 .on_click(cx.listener(|this, _, _, cx| this.toggle_email_organizer(cx)))
827 .into_any_element(),
828 ];
829 if send_response {
830 controls.push(Input::new(&self.message).into_any_element());
831 }
832 controls
833 }
205 834
206 dialog
207 .title(subject.clone())
208 .w(px(DIALOG_WIDTH))
209 .child(body)
210 .footer(footer)
211 });
835 /// Accept / Decline / Tentative (when invited) plus the overflow menu with Delete.
836 fn action_buttons(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
837 let response = self.event.response;
838 let series = self.event.series;
839 let has_master = self.event.series_master_id.is_some();
840 let peek = cx.entity();
841 let mut buttons = Vec::new();
842 if self.can_rsvp() {
843 buttons.push(rsvp_button(
844 "calendar-peek-accept",
845 tr("calendar.peek.accept"),
846 Reply::Accept,
847 response == ResponseType::Accepted,
848 series,
849 has_master,
850 peek.clone(),
851 ));
852 buttons.push(rsvp_button(
853 "calendar-peek-decline",
854 tr("calendar.peek.decline"),
855 Reply::Decline,
856 response == ResponseType::Declined,
857 series,
858 has_master,
859 peek.clone(),
860 ));
861 buttons.push(rsvp_button(
862 "calendar-peek-tentative",
863 tr("calendar.peek.tentative_action"),
864 Reply::Tentative,
865 response == ResponseType::Tentative,
866 false,
867 false,
868 peek.clone(),
869 ));
870 }
871 let delete_state = self.state.clone();
872 let delete_key = self.event.object_id.clone();
873 buttons.push(
874 Button::new("calendar-peek-more")
875 .ghost()
876 .icon(IconName::Ellipsis)
877 .dropdown_menu(move |menu, _, _| {
878 let delete_state = delete_state.clone();
879 let delete_key = delete_key.clone();
880 let delete_peek = peek.clone();
881 menu.item(
882 PopupMenuItem::new(tr("common.delete"))
883 .icon(IconName::Trash)
884 .on_click(move |_, _, cx| {
885 delete_state.update(cx, |state, cx| {
886 state.delete_calendar_event(&delete_key, cx)
887 });
888 delete_peek.update(cx, |peek, cx| peek.close(cx));
889 }),
890 )
891 })
892 .into_any_element(),
893 );
894 buttons
895 }
896
897 fn render_footer(&self, cx: &mut Context<Self>) -> Stateful<Div> {
898 let can_rsvp = self.can_rsvp();
899 v_flex()
900 .id("calendar-peek-footer")
901 .w_full()
902 .flex_none()
903 .gap(px(8.))
904 .children(self.rsvp_message_controls(cx))
905 .child(
906 h_flex()
907 .w_full()
908 .gap(px(8.))
909 .items_center()
910 .when(!can_rsvp, |row| row.justify_end())
911 .children(self.action_buttons(cx)),
912 )
913 }
914 }
915
916 fn avatar(initials: String) -> Div {
917 div()
918 .size(px(AVATAR_SIZE))
919 .flex_none()
920 .rounded_full()
921 .bg(theme::accent_soft())
922 .flex()
923 .items_center()
924 .justify_center()
925 .text_size(px(11.))
926 .font_weight(FontWeight::SEMIBOLD)
927 .text_color(theme::accent_text())
928 .child(initials)
929 }
930
931 fn person_row(name: &str, role: String) -> Div {
932 h_flex()
933 .gap(px(ROW_GAP))
934 .items_center()
935 .child(avatar(app_base::format::initials(name)))
936 .child(
937 v_flex()
938 .flex_1()
939 .min_w(px(0.))
940 .child(
941 div()
942 .text_size(px(14.))
943 .text_color(theme::text())
944 .truncate()
945 .child(name.to_owned()),
946 )
947 .child(
948 div()
949 .text_size(px(12.))
950 .text_color(theme::text_muted())
951 .child(role),
952 ),
953 )
954 }
955
956 fn group_label(group: ResponseType) -> String {
957 match group {
958 ResponseType::Accepted | ResponseType::Organizer => tr("calendar.peek.accepted"),
959 ResponseType::Tentative => tr("calendar.peek.tentative"),
960 ResponseType::Declined => tr("calendar.peek.declined"),
961 ResponseType::NotResponded => tr("calendar.peek.no_response"),
962 }
963 }
964
965 fn is_teams_url(url: &str) -> bool {
966 url.contains("teams.microsoft.com")
967 }
968
969 fn is_google_meet_url(url: &str) -> bool {
970 url.contains("meet.google.com")
971 }
972
973 fn copy_join_clipboard(url: &str, dial_in: Option<&DialIn>) -> String {
974 if is_teams_url(url) {
975 join_info_text(url, dial_in)
976 } else {
977 url.to_owned()
978 }
979 }
980
981 fn event_detail_score(event: &CalendarEvent) -> u8 {
982 u8::from(event.body_html.is_some()) * 32
983 + u8::from(!event.attendees.is_empty()) * 16
984 + u8::from(
985 event
986 .body_preview
987 .as_ref()
988 .is_some_and(|value| !value.is_empty()),
989 ) * 8
990 + u8::from(
991 event
992 .location
993 .as_ref()
994 .is_some_and(|value| !value.is_empty()),
995 ) * 4
996 + u8::from(event.response_counts.is_some()) * 2
997 + u8::from(event.series_master_id.is_some())
998 }
999
1000 fn peek_when_label(event: &CalendarEvent) -> String {
1001 let offset = Local::now().offset().fix();
1002 if is_effective_all_day(event, offset) {
1003 let start = event.start.with_timezone(&offset).date_naive();
1004 let end = event.end.with_timezone(&offset).date_naive();
1005 if end > start + chrono::Duration::days(1) {
1006 return format!(
1007 "{} · {} – {}",
1008 tr("calendar.peek.all_day"),
1009 start.format("%a, %b %-d"),
1010 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
1011 );
1012 }
1013 return format!(
1014 "{} · {}",
1015 tr("calendar.peek.all_day"),
1016 start.format("%a, %b %-d, %Y")
1017 );
1018 }
1019 let start = event.start.with_timezone(&offset);
1020 let end = event.end.with_timezone(&offset);
1021 let weekday = localized_weekday(start.weekday());
1022 let date = format_peek_date(start.date_naive());
1023 let clock = app_base::format::clock_format();
1024 if start.date_naive() == end.date_naive() {
1025 format!(
1026 "{weekday} {date} {} - {}",
1027 start.format(clock),
1028 end.format(clock)
1029 )
1030 } else {
1031 // Multi-day timed (Google-style): date + time on both sides.
1032 format!(
1033 "{weekday} {date}, {} – {}, {}",
1034 start.format(clock),
1035 format_peek_date(end.date_naive()),
1036 end.format(clock)
1037 )
1038 }
1039 }
1040
1041 fn reminder_label(minutes: u32) -> String {
1042 if minutes == 0 {
1043 return tr("calendar.peek.when_starts");
1044 }
1045 let mut args = HashMap::new();
1046 if minutes % 1440 == 0 {
1047 let days = minutes / 1440;
1048 args.insert("count".to_owned(), days.to_string());
1049 return tr_args(
1050 if days == 1 {
1051 "calendar.peek.day_before"
1052 } else {
1053 "calendar.peek.days_before"
1054 },
1055 &args,
1056 );
1057 }
1058 if minutes % 60 == 0 {
1059 let hours = minutes / 60;
1060 args.insert("count".to_owned(), hours.to_string());
1061 return tr_args(
1062 if hours == 1 {
1063 "calendar.peek.hour_before"
1064 } else {
1065 "calendar.peek.hours_before"
1066 },
1067 &args,
1068 );
1069 }
1070 args.insert("count".to_owned(), minutes.to_string());
1071 tr_args(
1072 if minutes == 1 {
1073 "calendar.peek.minute_before"
1074 } else {
1075 "calendar.peek.minutes_before"
1076 },
1077 &args,
1078 )
1079 }
1080
1081 fn ui_is_german() -> bool {
1082 gpui_kit::component::locale().starts_with("de")
1083 }
1084
1085 fn format_peek_date(date: chrono::NaiveDate) -> String {
1086 if ui_is_german() {
1087 date.format("%d.%m.%Y").to_string()
1088 } else {
1089 date.format("%-m/%-d/%Y").to_string()
1090 }
1091 }
1092
1093 fn localized_weekday(weekday: Weekday) -> &'static str {
1094 let de = ui_is_german();
1095 match (de, weekday) {
1096 (true, Weekday::Mon) => "Mo",
1097 (true, Weekday::Tue) => "Di",
1098 (true, Weekday::Wed) => "Mi",
1099 (true, Weekday::Thu) => "Do",
1100 (true, Weekday::Fri) => "Fr",
1101 (true, Weekday::Sat) => "Sa",
1102 (true, Weekday::Sun) => "So",
1103 (false, Weekday::Mon) => "Mon",
1104 (false, Weekday::Tue) => "Tue",
1105 (false, Weekday::Wed) => "Wed",
1106 (false, Weekday::Thu) => "Thu",
1107 (false, Weekday::Fri) => "Fri",
1108 (false, Weekday::Sat) => "Sat",
1109 (false, Weekday::Sun) => "Sun",
1110 }
1111 }
1112
1113 fn location_label(event: &CalendarEvent) -> String {
1114 if let Some(location) = event
1115 .location
1116 .clone()
1117 .filter(|value| !value.is_empty())
1118 {
1119 return location;
1120 }
1121 if !event.online {
1122 return String::new();
1123 }
1124 match event.join_url.as_deref() {
1125 Some(url) if is_google_meet_url(url) => tr("calendar.peek.google_meet"),
1126 Some(url) if is_teams_url(url) => tr("calendar.peek.teams_meeting"),
1127 _ if event.source == CalendarSource::Google => tr("calendar.peek.google_meet"),
1128 _ => tr("calendar.peek.teams_meeting"),
1129 }
1130 }
1131
1132 fn response_summary(event: &CalendarEvent) -> Option<String> {
1133 let counts = event.response_counts?;
1134 if counts.is_empty() {
1135 return None;
1136 }
1137 let mut parts = vec![
1138 format!("{} {}", tr("calendar.peek.accepted"), counts.accepted),
1139 format!("{} {}", tr("calendar.peek.declined"), counts.declined),
1140 ];
1141 if counts.tentative > 0 {
1142 parts.insert(
1143 1,
1144 format!("{} {}", tr("calendar.peek.tentative"), counts.tentative),
1145 );
1146 }
1147 parts.push(format!(
1148 "{} {}",
1149 tr("calendar.peek.no_response"),
1150 counts.not_responded
1151 ));
1152 Some(parts.join(", "))
1153 }
1154
1155 fn icon(name: IconName, color: Hsla) -> Icon {
1156 Icon::new(name).size(px(ICON_SIZE)).text_color(color)
1157 }
1158
1159 fn rsvp_button(
1160 id: &'static str,
1161 label: String,
1162 reply: Reply,
1163 chosen: bool,
1164 series: bool,
1165 has_master: bool,
1166 peek: Entity<EventPeek>,
1167 ) -> AnyElement {
1168 let button = Button::new(id).label(label).when(chosen, |button| button.primary());
1169 let button = match reply {
1170 Reply::Accept => button.icon(IconName::Check),
1171 Reply::Decline => button.icon(IconName::X),
1172 Reply::Tentative => button.icon(IconName::CalendarClock),
1173 };
1174 if series {
1175 let occurrence = peek.clone();
1176 let master = peek;
1177 button
1178 .dropdown_menu(move |menu, _, _| {
1179 let occurrence = occurrence.clone();
1180 let master = master.clone();
1181 let mut menu = menu.item(
1182 PopupMenuItem::new(tr("calendar.peek.this_occurrence")).on_click(
1183 move |_, _, cx| {
1184 occurrence.update(cx, |peek, cx| peek.respond(reply, cx));
1185 },
1186 ),
1187 );
1188 if has_master {
1189 menu = menu.item(
1190 PopupMenuItem::new(tr("calendar.peek.entire_series")).on_click(
1191 move |_, _, cx| {
1192 master.update(cx, |peek, cx| peek.respond_series_master(reply, cx));
1193 },
1194 ),
1195 );
1196 }
1197 menu
1198 })
1199 .into_any_element()
1200 } else {
1201 button
1202 .on_click(move |_, _, cx| {
1203 peek.update(cx, |peek, cx| peek.respond(reply, cx));
1204 })
1205 .into_any_element()
1206 }
1207 }
1208
1209 impl Render for EventPeek {
1210 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1211 let card = if self.expanded {
1212 v_flex()
1213 .id("calendar-peek-card")
1214 .w(relative(EXPANDED_WIDTH))
1215 .max_w(px(COMFY_RUNWAY_WIDTH))
1216 .h(relative(EXPANDED_HEIGHT))
1217 .child(self.render_expanded(cx))
1218 } else {
1219 let header = self.render_header(cx);
1220 let body = self
1221 .has_scroll_content()
1222 .then(|| self.agenda_element(cx))
1223 .flatten()
1224 .map(Self::render_scroll_body);
1225 let footer = self.render_footer(cx);
1226 // Shrink-only agenda (Forward preview pattern): max_h + scrollbar, no flex_1.
1227 v_flex()
1228 .id("calendar-peek-card")
1229 .w(px(CARD_WIDTH))
1230 .max_w(relative(1.))
1231 .max_h(relative(1.))
1232 .child(header)
1233 .children(body)
1234 .child(footer)
1235 };
1236
1237 div()
1238 .id("calendar-peek-layer")
1239 .absolute()
1240 .top_0()
1241 .left_0()
1242 .size_full()
1243 .flex()
1244 .items_center()
1245 .justify_center()
1246 .child(
1247 div()
1248 .id("calendar-peek-backdrop")
1249 .absolute()
1250 .top_0()
1251 .left_0()
1252 .size_full()
1253 .bg(black().opacity(BACKDROP_OPACITY))
1254 .occlude()
1255 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
1256 )
1257 .child(
1258 card.m(px(CARD_MARGIN))
1259 .p(px(CARD_PADDING))
1260 .gap(px(SECTION_GAP))
1261 .rounded(px(CARD_RADIUS))
1262 .dialog_surface()
1263 .text_color(theme::text())
1264 .occlude()
1265 .overflow_hidden()
1266 .capture_key_down(cx.listener(Self::on_key_down)),
1267 )
1268 }
1269 }
1270
1271 pub fn open_calendar_event(
1272 state: Entity<AppState>,
1273 event: CalendarEvent,
1274 _: &mut Window,
1275 cx: &mut App,
1276 ) {
1277 state.update(cx, |state, cx| state.request_calendar_event_peek(event, cx));
212 1278 }
@@ -1,212 +1,1278 @@
1use chatsvc::{CalendarEvent, ResponseType, join_info_text};
1use std::collections::HashMap;
2use chrono::{Local, Offset};
2
3use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, SIDEBAR_WIDTH};
4use app_ui_kit::render::{Block, layout_blocks, render_blocks, strip_image_placeholders};
5use chatsvc::{
6 CalendarEvent, CalendarSource, DialIn, EventAttendee, Reply, ResponseType, join_info_text,
7};
8use chrono::{Datelike, Local, Offset, Weekday};
3use gpui_kit::assets::IconName;
9use gpui_kit::assets::IconName;
4use gpui_kit::component::Sizable as _;
10use gpui_kit::component::Sizable as _;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
11use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::dialog::{Dialog, DialogFooter};
12use gpui_kit::component::checkbox::Checkbox;
7use gpui_kit::component::menu::DropdownMenu as _;
13use gpui_kit::component::input::{Input, InputState};
8use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
14use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
15use gpui_kit::component::scroll::ScrollableElement as _;
16use gpui_kit::component::{Icon, h_flex, v_flex};
17use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
18use gpui_kit::*;
10
19
11use super::rsvp_menu::rsvp_menu;
12use crate::app_state::AppState;
20use crate::app_state::AppState;
13use crate::call::week_grid::is_effective_all_day;
21use crate::call::week_grid::is_effective_all_day;
14use crate::i18n::tr;
22use crate::i18n::{tr, tr_args};
15use crate::theme;
23use crate::theme::{self, ElevatedSurface as _};
16
24
17const DIALOG_WIDTH: f32 = 440.;
25const CARD_WIDTH: f32 = 440.;
18const FIELD_GAP: f32 = 12.;
26const CARD_RADIUS: f32 = 10.;
19const LABEL_SIZE: f32 = 12.;
27const CARD_PADDING: f32 = 16.;
28const CARD_MARGIN: f32 = 32.;
29const SECTION_GAP: f32 = 12.;
30const ROW_GAP: f32 = 8.;
31const ICON_SIZE: f32 = 16.;
32const AVATAR_SIZE: f32 = 28.;
33const BACKDROP_OPACITY: f32 = 0.55;
34/// Shrink-only agenda cap (Forward-dialog preview pattern — no flex_1).
35const AGENDA_MAX_HEIGHT: f32 = 280.;
36const EXPANDED_WIDTH: f32 = 0.92;
37const EXPANDED_HEIGHT: f32 = 0.88;
38const TRACKING_GROUPS: [ResponseType; 4] = [
39 ResponseType::Accepted,
40 ResponseType::Tentative,
41 ResponseType::Declined,
42 ResponseType::NotResponded,
43];
20const COPY_JOIN_INFO: &str = "Copy join info";
44const COPY_JOIN_INFO: &str = "Copy join info";
21
45
22fn when_label(event: &CalendarEvent) -> String {
46pub enum EventPeekEvent {
23 let offset = Local::now().offset().fix();
47 Close,
24 if is_effective_all_day(event, offset) {
48}
25 let start = event.start.with_timezone(&offset).date_naive();
49
26 let end = event.end.with_timezone(&offset).date_naive();
50pub struct EventPeek {
27 if end > start + chrono::Duration::days(1) {
51 state: Entity<AppState>,
28 return format!(
52 event: CalendarEvent,
29 "All day · {} – {}",
53 expanded: bool,
30 start.format("%a, %b %-d"),
54 /// Parsed `body_html`, keyed by the HTML it came from.
31 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
55 agenda: Option<(String, Vec<Block>)>,
32 );
56 collapsed: Vec<ResponseType>,
57 message: Entity<InputState>,
58 _observation: Subscription,
59}
60
61impl EventEmitter<EventPeekEvent> for EventPeek {}
62
63impl EventPeek {
64 pub fn new(
65 state: Entity<AppState>,
66 event: CalendarEvent,
67 window: &mut Window,
68 cx: &mut Context<Self>,
69 ) -> Self {
70 let event_key = event.object_id.clone();
71 let opening_preview = event
72 .body_preview
73 .as_ref()
74 .map(|value| value.chars().count())
75 .unwrap_or(0);
76 app_base::diagnostics::record(format!(
77 "calendar peek: open {event_key} preview_chars={opening_preview}"
78 ));
79 state.update(cx, |app, cx| app.enrich_calendar_event(&event_key, cx));
80 let message = cx.new(|cx| {
81 InputState::new(window, cx).placeholder(tr("calendar.peek.message_placeholder"))
82 });
83 let watched = state.clone();
84 // observe (not subscribe): detail enrichment only notifies AppState, it does not emit.
85 let observation = cx.observe(&watched, |this, _, cx| {
86 this.pull_event(cx);
87 cx.notify();
88 });
89 let mut peek = EventPeek {
90 state,
91 event,
92 expanded: false,
93 agenda: None,
94 collapsed: Vec::new(),
95 message,
96 _observation: observation,
97 };
98 // The clicked calendar block can be a stale clone. If details are already
99 // cached, enrich_calendar_event() emits no notify, so pull once now.
100 peek.pull_event(cx);
101 let pulled = peek
102 .event
103 .body_preview
104 .as_ref()
105 .map(|value| value.chars().count())
106 .unwrap_or(0);
107 if pulled != opening_preview {
108 app_base::diagnostics::record(format!(
109 "calendar peek: pulled preview_chars={pulled} for {event_key}"
110 ));
33 }
111 }
34 return format!("All day · {}", start.format("%a, %b %-d, %Y"));
112 peek
35 }
113 }
36 let start = event.start.with_timezone(&offset);
114
37 let end = event.end.with_timezone(&offset);
115 fn pull_event(&mut self, cx: &mut Context<Self>) {
38 if start.date_naive() == end.date_naive() {
116 let key = self.event.object_id.clone();
39 format!(
117 let app = self.state.read(cx);
40 "{} · {} – {}",
118 let best = app
41 start.format("%a, %b %-d, %Y"),
119 .calendar_week
42 start.format(app_base::format::clock_format()),
120 .events
43 end.format(app_base::format::clock_format())
121 .iter()
44 )
122 .chain(app.calendar_events.iter())
45 } else {
123 .find(|event| event.object_id == key)
46 format!(
124 .cloned();
47 "{} {} – {} {}",
125 let best = app
48 start.format("%a, %b %-d"),
126 .calendar_week
49 start.format(app_base::format::clock_format()),
127 .events
50 end.format("%a, %b %-d, %Y"),
128 .iter()
51 end.format(app_base::format::clock_format())
129 .chain(app.calendar_events.iter())
52 )
130 .filter(|event| event.object_id == key)
131 .cloned()
132 .fold(best, |best, candidate| {
133 Some(match best {
134 Some(current) if event_detail_score(&current) >= event_detail_score(&candidate) => {
135 current
136 }
137 _ => candidate,
138 })
139 });
140 if let Some(event) = best {
141 self.event = event;
142 }
143 self.refresh_agenda();
53 }
144 }
54}
55
145
56fn source_label(event: &CalendarEvent) -> String {
146 fn refresh_agenda(&mut self) {
57 let mut sources = event.sources.clone();
147 let Some(html) = self.event.body_html.as_ref() else {
58 if sources.is_empty() {
148 self.agenda = None;
59 sources.push(event.source);
149 return;
150 };
151 if self.agenda.as_ref().is_some_and(|(source, _)| source == html) {
152 return;
153 }
154 let blocks = strip_image_placeholders(layout_blocks(&teams_core::html_to_spans(html)));
155 self.agenda = Some((html.clone(), blocks));
60 }
156 }
61 sources.sort_by_key(|source| source.label());
62 sources.dedup();
63 sources
64 .iter()
65 .map(|source| source.label())
66 .collect::<Vec<_>>()
67 .join(" + ")
68}
69
157
70fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
158 fn agenda_element(&self, cx: &App) -> Option<AnyElement> {
71 v_flex()
159 if let Some((_, blocks)) = self.agenda.as_ref().filter(|(_, blocks)| !blocks.is_empty()) {
72 .gap(px(2.))
160 return Some(
73 .child(
161 div()
74 div()
162 .w_full()
75 .text_size(px(LABEL_SIZE))
163 .min_w(px(0.))
76 .text_color(theme::text_muted())
164 .text_size(px(14.))
77 .child(label.to_owned()),
165 .text_color(theme::text())
78 )
166 .child(render_blocks(blocks, "calendar-peek-agenda", false, cx))
79 .child(
167 .into_any_element(),
168 );
169 }
170 let preview = self.event.body_preview.clone().filter(|value| !value.is_empty())?;
171 Some(
80 div()
172 div()
81 .text_size(px(14.))
173 .w_full()
82 .text_color(theme::text())
174 .min_w(px(0.))
83 .child(value.into()),
175 .whitespace_normal()
176 .text_size(px(13.))
177 .text_color(theme::text_soft())
178 .child(preview)
179 .into_any_element(),
84 )
180 )
85}
181 }
86
182
87pub fn open_calendar_event(
183 fn toggle_expand(&mut self, cx: &mut Context<Self>) {
88 state: Entity<AppState>,
184 self.expanded = !self.expanded;
89 event: CalendarEvent,
185 cx.notify();
90 window: &mut Window,
186 }
91 cx: &mut App,
187
92) {
188 fn toggle_group(&mut self, group: ResponseType, cx: &mut Context<Self>) {
93 let send_response = state.read(cx).rsvp_send_response;
189 if let Some(index) = self.collapsed.iter().position(|kind| *kind == group) {
94 // Show Join whenever a Teams link exists — not only inside the join window.
190 self.collapsed.remove(index);
95 let can_join = event.online && !event.cancelled && event.join_url.is_some();
191 } else {
96 let subject = if event.cancelled {
192 self.collapsed.push(group);
97 format!("Canceled: {}", event.subject)
193 }
98 } else if event.subject.is_empty() {
194 cx.notify();
99 "(No title)".to_owned()
195 }
100 } else {
196
101 event.subject.clone()
197 fn toggle_email_organizer(&mut self, cx: &mut Context<Self>) {
102 };
198 self.state
103 let when = when_label(&event);
199 .update(cx, |state, cx| state.toggle_rsvp_send_response(cx));
104 let source = source_label(&event);
200 cx.notify();
105 let organizer = event
201 }
106 .organizer_name
202
107 .clone()
203 fn close(&mut self, cx: &mut Context<Self>) {
108 .or_else(|| event.organizer_address.clone());
204 cx.emit(EventPeekEvent::Close);
109 let join_url = event.join_url.clone();
205 }
110 let dial_in = event.dial_in.clone();
206
111 let thread_id = event.thread_id.clone();
207 fn respond(&mut self, reply: Reply, cx: &mut Context<Self>) {
112 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
208 let key = self.event.object_id.clone();
113 let response = event.response;
209 let send = self.state.read(cx).rsvp_send_response;
114 let event_key = event.object_id.clone();
210 let comment = if send && self.event.source == CalendarSource::Outlook {
115 let meeting_title = event.subject.clone();
211 self.message.read(cx).value().to_string()
116 let online = event.online;
212 } else {
117
213 String::new()
118 window.open_dialog(cx, move |dialog: Dialog, _, _| {
214 };
119 let delete_state = state.clone();
215 self.state
120 let delete_key = event_key.clone();
216 .update(cx, |state, cx| state.respond_to_event(&key, reply, &comment, cx));
121 let mut footer = DialogFooter::new()
217 self.close(cx);
218 }
219
220 fn respond_series_master(&mut self, reply: Reply, cx: &mut Context<Self>) {
221 let Some(master) = self.event.series_master_id.clone() else {
222 self.respond(reply, cx);
223 return;
224 };
225 let send = self.state.read(cx).rsvp_send_response;
226 let comment = if send && self.event.source == CalendarSource::Outlook {
227 self.message.read(cx).value().to_string()
228 } else {
229 String::new()
230 };
231 self.state
232 .update(cx, |state, cx| state.respond_to_event(&master, reply, &comment, cx));
233 self.close(cx);
234 }
235
236 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
237 if event.keystroke.key.as_str() == "escape" {
238 self.close(cx);
239 cx.stop_propagation();
240 }
241 }
242
243 fn has_scroll_content(&self) -> bool {
244 self.agenda
245 .as_ref()
246 .is_some_and(|(_, blocks)| !blocks.is_empty())
247 || self
248 .event
249 .body_preview
250 .as_ref()
251 .is_some_and(|value| !value.is_empty())
252 }
253
254 fn subject_label(&self) -> String {
255 let event = &self.event;
256 if event.cancelled {
257 format!("{}{}", tr("calendar.peek.canceled_prefix"), event.subject)
258 } else if event.subject.is_empty() {
259 tr("calendar.peek.no_title")
260 } else {
261 event.subject.clone()
262 }
263 }
264
265 fn organizer_label(&self) -> String {
266 self.event
267 .organizer_name
268 .clone()
269 .or_else(|| self.event.organizer_address.clone())
270 .unwrap_or_default()
271 }
272
273 fn expand_button(&self, cx: &mut Context<Self>) -> Button {
274 Button::new("calendar-peek-expand")
275 .ghost()
276 .small()
277 .icon(if self.expanded {
278 IconName::Minimize2
279 } else {
280 IconName::Expand
281 })
282 .on_click(cx.listener(|this, _, _, cx| this.toggle_expand(cx)))
283 }
284
285 fn when_row(&self) -> Div {
286 h_flex()
287 .gap(px(ROW_GAP))
288 .items_start()
289 .child(icon(IconName::Clock, theme::text_muted()))
122 .child(
290 .child(
123 Button::new("calendar-event-delete")
291 h_flex()
124 .danger()
292 .flex_1()
125 .label(tr("common.delete"))
293 .min_w_0()
126 .on_click(move |_, window, cx| {
294 .gap(px(8.))
127 delete_state
295 .items_center()
128 .update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
296 .child(
129 window.close_dialog(cx);
297 div()
298 .text_size(px(14.))
299 .text_color(theme::text())
300 .child(peek_when_label(&self.event)),
301 )
302 .when(self.event.series, |row| {
303 row.child(
304 h_flex()
305 .gap(px(4.))
306 .items_center()
307 .child(icon(IconName::Repeat, theme::text_muted()))
308 .child(
309 div()
310 .text_size(px(13.))
311 .text_color(theme::text_soft())
312 .child(tr("calendar.peek.series")),
313 ),
314 )
130 }),
315 }),
131 )
316 )
317 }
318
319 fn location_row(&self) -> Option<Div> {
320 let location = location_label(&self.event);
321 (!location.is_empty()).then(|| {
322 h_flex()
323 .gap(px(ROW_GAP))
324 .items_start()
325 .child(icon(IconName::MapPin, theme::text_muted()))
326 .child(
327 div()
328 .text_size(px(14.))
329 .text_color(theme::text())
330 .child(location),
331 )
332 })
333 }
334
335 /// Google-only: which calendar owns the event.
336 fn calendar_row(&self) -> Option<Div> {
337 if self.event.source != CalendarSource::Google {
338 return None;
339 }
340 let name = self.event.calendar_name.clone().filter(|value| !value.is_empty())?;
341 Some(
342 h_flex()
343 .gap(px(ROW_GAP))
344 .items_center()
345 .child(icon(IconName::Calendar, theme::text_muted()))
346 .child(
347 div()
348 .text_size(px(14.))
349 .text_color(theme::text())
350 .child(name),
351 ),
352 )
353 }
354
355 fn reminder_row(&self) -> Option<Div> {
356 if self.event.reminders.is_empty() {
357 return None;
358 }
359 Some(
360 h_flex()
361 .gap(px(ROW_GAP))
362 .items_start()
363 .child(icon(IconName::Bell, theme::text_muted()))
364 .child(
365 v_flex()
366 .gap(px(2.))
367 .children(self.event.reminders.iter().map(|minutes| {
368 div()
369 .text_size(px(14.))
370 .text_color(theme::text())
371 .child(reminder_label(*minutes))
372 })),
373 ),
374 )
375 }
376
377 fn source_row(&self, _cx: &mut Context<Self>) -> Option<AnyElement> {
378 let (title, url) = self.event.source_link.clone()?;
379 let open = url.clone();
380 Some(
381 h_flex()
382 .gap(px(ROW_GAP))
383 .items_start()
384 .child(icon(IconName::Link, theme::text_muted()))
385 .child(
386 v_flex()
387 .gap(px(2.))
388 .min_w(px(0.))
389 .child(
390 div()
391 .text_size(px(14.))
392 .text_color(theme::text())
393 .whitespace_normal()
394 .child(title),
395 )
396 .child(
397 div()
398 .id("calendar-peek-view-source")
399 .text_size(px(12.))
400 .text_color(theme::accent_text())
401 .cursor_pointer()
402 .child(tr("calendar.peek.view_source"))
403 .on_click(move |_, _, cx| cx.open_url(&open)),
404 ),
405 )
406 .into_any_element(),
407 )
408 }
409
410 fn google_meta_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
411 let mut rows = Vec::new();
412 if let Some(row) = self.calendar_row() {
413 rows.push(row.into_any_element());
414 }
415 if let Some(row) = self.reminder_row() {
416 rows.push(row.into_any_element());
417 }
418 if let Some(row) = self.source_row(cx) {
419 rows.push(row);
420 }
421 rows
422 }
423
424 fn render_header(&self, cx: &mut Context<Self>) -> Stateful<Div> {
425 let event = &self.event;
426 let subject = self.subject_label();
427 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
428 let organizer = self.organizer_label();
429 let initials = app_base::format::initials(&organizer);
430 let summary = response_summary(event);
431
432 let header_actions = h_flex()
433 .gap(px(8.))
434 .children(self.google_action_buttons())
435 .children(self.join_chat_buttons(cx));
436
437 let title_row = h_flex()
438 .w_full()
439 .items_start()
440 .justify_between()
441 .gap(px(8.))
132 .child(
442 .child(
133 Button::new("calendar-event-close")
443 div()
134 .label(tr("common.close"))
444 .flex_1()
135 .on_click(|_, window, cx| window.close_dialog(cx)),
445 .min_w_0()
446 .text_size(px(18.))
447 .font_weight(FontWeight::SEMIBOLD)
448 .text_color(theme::text())
449 .child(subject),
450 )
451 .child(self.expand_button(cx));
452
453 let mut header = v_flex()
454 .id("calendar-peek-header")
455 .w_full()
456 .flex_none()
457 .gap(px(SECTION_GAP))
458 .child(title_row)
459 .child(header_actions)
460 .child(self.when_row())
461 .children(self.location_row())
462 .children(self.google_meta_rows(cx));
463
464 if !organizer.is_empty() {
465 let invite_line = if can_rsvp {
466 let mut args = HashMap::new();
467 args.insert("name".to_owned(), organizer.clone());
468 tr_args("calendar.peek.invited_you", &args)
469 } else {
470 organizer.clone()
471 };
472 header = header.child(
473 h_flex()
474 .gap(px(ROW_GAP))
475 .items_start()
476 .child(avatar(initials))
477 .child(
478 v_flex()
479 .gap(px(2.))
480 .child(
481 div()
482 .text_size(px(14.))
483 .text_color(theme::text())
484 .child(invite_line),
485 )
486 .children(summary.map(|text| {
487 div()
488 .text_size(px(12.))
489 .text_color(theme::text_muted())
490 .child(text)
491 })),
492 ),
136 );
493 );
137 if can_rsvp {
494 }
138 let menu_state = state.clone();
495
139 let menu_key = event_key.clone();
496 header
140 footer = footer.child(
497 }
141 Button::new("calendar-event-rsvp")
498
142 .label("RSVP")
499 /// Google-only: Open in Google Calendar + Email guests.
143 .dropdown_menu(move |menu, _, _| {
500 fn google_action_buttons(&self) -> Vec<AnyElement> {
144 rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
501 if self.event.source != CalendarSource::Google {
145 }),
502 return Vec::new();
503 }
504 let mut buttons = Vec::new();
505 if let Some(url) = self.event.web_link.clone() {
506 buttons.push(
507 Button::new("calendar-peek-open-google")
508 .outline()
509 .icon(IconName::ExternalLink)
510 .label(tr("calendar.peek.open_in_google"))
511 .on_click(move |_, _, cx| cx.open_url(&url))
512 .into_any_element(),
146 );
513 );
147 }
514 }
148 if thread_id.is_some() {
515 let addresses: Vec<String> = self
149 let chat_state = state.clone();
516 .event
150 let chat_thread = thread_id.clone();
517 .attendees
151 footer = footer.child(
518 .iter()
152 Button::new("calendar-event-chat")
519 .filter_map(|attendee| attendee.address.clone())
153 .label(tr("common.chat"))
520 .filter(|address| !address.is_empty())
154 .on_click(move |_, window, cx| {
521 .collect();
155 chat_state.update(cx, |state, cx| {
522 if !addresses.is_empty() {
156 state.open_meeting_chat(chat_thread.as_deref(), cx)
523 let mut mailto = format!("mailto:{}", addresses.join(","));
157 });
524 if !self.event.subject.is_empty() {
158 window.close_dialog(cx);
525 let subject = self
159 }),
526 .event
527 .subject
528 .replace('%', "%25")
529 .replace(' ', "%20")
530 .replace('&', "%26")
531 .replace('?', "%3F")
532 .replace('#', "%23");
533 mailto = format!("{mailto}?subject={subject}");
534 }
535 buttons.push(
536 Button::new("calendar-peek-email-guests")
537 .outline()
538 .icon(IconName::Mail)
539 .label(tr("calendar.peek.email_guests"))
540 .on_click(move |_, _, cx| cx.open_url(&mailto))
541 .into_any_element(),
160 );
542 );
161 }
543 }
544 buttons
545 }
546
547 fn join_chat_buttons(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
548 let event = &self.event;
549 let can_join = event.online && !event.cancelled && event.join_url.is_some();
550 let join_url = event.join_url.clone();
551 let dial_in = event.dial_in.clone();
552 let thread_id = event.thread_id.clone();
553 let meeting_title = event.subject.clone();
554 let mut buttons = Vec::new();
162 if can_join {
555 if can_join {
163 let join_state = state.clone();
556 let join_state = self.state.clone();
164 let url = join_url.clone();
557 let url = join_url.clone();
165 let title = meeting_title.clone();
558 let title = meeting_title.clone();
166 footer = footer.child(
559 let clipboard = join_url
167 Button::new("calendar-event-join")
560 .as_deref()
168 .primary()
561 .map(|url| copy_join_clipboard(url, dial_in.as_ref()));
562 buttons.push(
563 Button::new("calendar-peek-join")
564 .outline()
169 .label(tr("common.join"))
565 .label(tr("common.join"))
170 .on_click(move |_, window, cx| {
566 .icon(IconName::Video)
567 .on_click(cx.listener(move |this, _, _, cx| {
171 join_state.update(cx, |state, cx| {
568 join_state.update(cx, |state, cx| {
172 state.join_calendar_meeting(url.as_deref(), &title, cx)
569 state.join_calendar_meeting(url.as_deref(), &title, cx)
173 });
570 });
174 window.close_dialog(cx);
571 this.close(cx);
175 }),
572 }))
573 .into_any_element(),
176 );
574 );
575 if let Some(info) = clipboard {
576 buttons.push(
577 Button::new("calendar-peek-join-menu")
578 .outline()
579 .icon(IconName::ChevronDown)
580 .dropdown_menu(move |menu, _, _| {
581 let info = info.clone();
582 menu.item(
583 PopupMenuItem::new(COPY_JOIN_INFO)
584 .icon(IconName::Copy)
585 .on_click(move |_, _, cx| {
586 cx.write_to_clipboard(ClipboardItem::new_string(
587 info.clone(),
588 ))
589 }),
590 )
591 })
592 .into_any_element(),
593 );
594 }
177 }
595 }
596 if thread_id.is_some() {
597 let chat_state = self.state.clone();
598 let chat_thread = thread_id.clone();
599 buttons.push(
600 Button::new("calendar-peek-chat")
601 .outline()
602 .label(tr("common.chat"))
603 .icon(IconName::MessageSquare)
604 .on_click(cx.listener(move |this, _, _, cx| {
605 chat_state.update(cx, |state, cx| {
606 state.open_meeting_chat(chat_thread.as_deref(), cx)
607 });
608 this.close(cx);
609 }))
610 .into_any_element(),
611 );
612 }
613 buttons
614 }
615
616 /// Compact agenda: max_h + scrollbar on the content root (Forward-preview pattern).
617 /// A nested scroll wrapper with min_h(0) collapses to 0 height in GPUI.
618 fn render_scroll_body(agenda: AnyElement) -> impl IntoElement {
619 h_flex()
620 .id("calendar-peek-scroll-content")
621 .w_full()
622 .gap(px(ROW_GAP))
623 .items_start()
624 .child(icon(IconName::List, theme::text_muted()))
625 .child(div().flex_1().min_w(px(0.)).child(agenda))
626 .flex_shrink_0()
627 .max_h(px(AGENDA_MAX_HEIGHT))
628 .overflow_y_scrollbar()
629 }
178
630
179 let mut body = v_flex()
631 fn render_expanded(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
180 .gap(px(FIELD_GAP))
632 let toolbar = h_flex()
181 .child(detail_row("When", when.clone()))
633 .w_full()
182 .child(detail_row("Calendar", source.clone()));
634 .flex_none()
183 if let Some(name) = organizer.clone() {
635 .gap(px(8.))
184 body = body.child(detail_row("Organizer", name));
636 .items_center()
637 .children(self.action_buttons(cx))
638 .child(div().flex_1())
639 .children(self.google_action_buttons())
640 .children(self.join_chat_buttons(cx))
641 .child(self.expand_button(cx))
642 .child(
643 Button::new("calendar-peek-close")
644 .ghost()
645 .small()
646 .icon(IconName::X)
647 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
648 );
649
650 let names = self.attendee_names_line();
651 let mut details = v_flex()
652 .id("calendar-peek-expanded-details")
653 .flex_1()
654 .min_w(px(0.))
655 .h_full()
656 .gap(px(SECTION_GAP))
657 .pr(px(CARD_PADDING))
658 .child(
659 div()
660 .text_size(px(20.))
661 .font_weight(FontWeight::SEMIBOLD)
662 .text_color(theme::text())
663 .child(self.subject_label()),
664 )
665 .children(names.map(|names| {
666 h_flex()
667 .gap(px(ROW_GAP))
668 .items_start()
669 .child(icon(IconName::Users, theme::text_muted()))
670 .child(
671 div()
672 .flex_1()
673 .min_w(px(0.))
674 .whitespace_normal()
675 .text_size(px(13.))
676 .text_color(theme::text_soft())
677 .child(names),
678 )
679 }))
680 .child(self.when_row())
681 .children(self.location_row())
682 .children(self.google_meta_rows(cx))
683 .children(self.rsvp_message_controls(cx));
684 if let Some(agenda) = self.agenda_element(cx) {
685 details = details.child(
686 div()
687 .w_full()
688 .pt(px(SECTION_GAP))
689 .border_t_1()
690 .border_color(theme::border())
691 .child(agenda),
692 );
693 }
694
695 let body = h_flex()
696 .w_full()
697 .flex_1()
698 .min_h(px(0.))
699 .items_start()
700 .child(details.overflow_y_scrollbar())
701 .child(self.render_tracking(cx));
702
703 v_flex()
704 .size_full()
705 .gap(px(SECTION_GAP))
706 .child(toolbar)
707 .child(body)
708 }
709
710 fn attendee_names_line(&self) -> Option<String> {
711 let organizer = self.organizer_label();
712 let mut names: Vec<String> = Vec::new();
713 if !organizer.is_empty() {
714 names.push(organizer);
715 }
716 for attendee in &self.event.attendees {
717 if !names.contains(&attendee.name) {
718 names.push(attendee.name.clone());
719 }
720 }
721 (names.len() > 1).then(|| names.join(", "))
722 }
723
724 fn render_tracking(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
725 let organizer = self.organizer_label();
726 let mut panel = v_flex()
727 .id("calendar-peek-tracking")
728 .w(px(SIDEBAR_WIDTH))
729 .flex_none()
730 .h_full()
731 .pl(px(CARD_PADDING))
732 .gap(px(SECTION_GAP))
733 .border_l_1()
734 .border_color(theme::border())
735 .child(
736 div()
737 .text_size(px(16.))
738 .font_weight(FontWeight::SEMIBOLD)
739 .text_color(theme::text())
740 .child(tr("calendar.peek.tracking")),
741 );
742 if !organizer.is_empty() {
743 panel = panel.child(person_row(&organizer, tr("calendar.peek.organizer")));
744 }
745
746 let roster: Vec<&EventAttendee> = self
747 .event
748 .attendees
749 .iter()
750 .filter(|attendee| attendee.response != ResponseType::Organizer)
751 .collect();
752 if roster.is_empty() {
753 let note = response_summary(&self.event)
754 .unwrap_or_else(|| tr("calendar.peek.attendees_unknown"));
755 return panel
756 .child(
757 div()
758 .text_size(px(13.))
759 .text_color(theme::text_muted())
760 .child(note),
761 )
762 .overflow_y_scrollbar();
185 }
763 }
186 if let Some(url) = join_url.clone().filter(|_| online) {
764
187 let info = join_info_text(&url, dial_in.as_ref());
765 for (index, group) in TRACKING_GROUPS.into_iter().enumerate() {
188 body = body.child(
766 let members: Vec<&&EventAttendee> = roster
189 v_flex()
767 .iter()
190 .gap(px(6.))
768 .filter(|attendee| attendee.response == group)
191 .child(detail_row("Join link", url))
769 .collect();
770 if members.is_empty() {
771 continue;
772 }
773 let collapsed = self.collapsed.contains(&group);
774 let mut section = v_flex().gap(px(ROW_GAP)).child(
775 h_flex()
776 .id(SharedString::from(format!("calendar-peek-group-{index}")))
777 .gap(px(4.))
778 .items_center()
779 .cursor_pointer()
780 .on_click(cx.listener(move |this, _, _, cx| this.toggle_group(group, cx)))
781 .child(icon(
782 if collapsed {
783 IconName::ChevronRight
784 } else {
785 IconName::ChevronDown
786 },
787 theme::text_muted(),
788 ))
192 .child(
789 .child(
193 h_flex().child(
790 div()
194 Button::new("calendar-event-copy-join")
791 .text_size(px(13.))
195 .small()
792 .font_weight(FontWeight::SEMIBOLD)
196 .label(COPY_JOIN_INFO)
793 .text_color(theme::text())
197 .icon(IconName::Copy)
794 .child(format!("{} {}", group_label(group), members.len())),
198 .on_click(move |_, _, cx| {
199 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
200 }),
201 ),
202 ),
795 ),
203 );
796 );
797 if !collapsed {
798 section = section.children(members.into_iter().map(|attendee| {
799 let role = if attendee.required {
800 tr("calendar.peek.required")
801 } else {
802 tr("calendar.peek.optional")
803 };
804 person_row(&attendee.name, role)
805 }));
806 }
807 panel = panel.child(section);
808 }
809 panel.overflow_y_scrollbar()
810 }
811
812 fn can_rsvp(&self) -> bool {
813 self.event.response != ResponseType::Organizer && self.event.organizer_name.is_some()
814 }
815
816 /// Outlook-only: Graph RSVP supports sendResponse + comment. Google does not.
817 fn rsvp_message_controls(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
818 if !self.can_rsvp() || self.event.source != CalendarSource::Outlook {
819 return Vec::new();
204 }
820 }
821 let send_response = self.state.read(cx).rsvp_send_response;
822 let mut controls = vec![
823 Checkbox::new("calendar-peek-email-organizer")
824 .label(tr("calendar.peek.email_organizer"))
825 .checked(send_response)
826 .on_click(cx.listener(|this, _, _, cx| this.toggle_email_organizer(cx)))
827 .into_any_element(),
828 ];
829 if send_response {
830 controls.push(Input::new(&self.message).into_any_element());
831 }
832 controls
833 }
205
834
206 dialog
835 /// Accept / Decline / Tentative (when invited) plus the overflow menu with Delete.
207 .title(subject.clone())
836 fn action_buttons(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
208 .w(px(DIALOG_WIDTH))
837 let response = self.event.response;
209 .child(body)
838 let series = self.event.series;
210 .footer(footer)
839 let has_master = self.event.series_master_id.is_some();
211 });
840 let peek = cx.entity();
841 let mut buttons = Vec::new();
842 if self.can_rsvp() {
843 buttons.push(rsvp_button(
844 "calendar-peek-accept",
845 tr("calendar.peek.accept"),
846 Reply::Accept,
847 response == ResponseType::Accepted,
848 series,
849 has_master,
850 peek.clone(),
851 ));
852 buttons.push(rsvp_button(
853 "calendar-peek-decline",
854 tr("calendar.peek.decline"),
855 Reply::Decline,
856 response == ResponseType::Declined,
857 series,
858 has_master,
859 peek.clone(),
860 ));
861 buttons.push(rsvp_button(
862 "calendar-peek-tentative",
863 tr("calendar.peek.tentative_action"),
864 Reply::Tentative,
865 response == ResponseType::Tentative,
866 false,
867 false,
868 peek.clone(),
869 ));
870 }
871 let delete_state = self.state.clone();
872 let delete_key = self.event.object_id.clone();
873 buttons.push(
874 Button::new("calendar-peek-more")
875 .ghost()
876 .icon(IconName::Ellipsis)
877 .dropdown_menu(move |menu, _, _| {
878 let delete_state = delete_state.clone();
879 let delete_key = delete_key.clone();
880 let delete_peek = peek.clone();
881 menu.item(
882 PopupMenuItem::new(tr("common.delete"))
883 .icon(IconName::Trash)
884 .on_click(move |_, _, cx| {
885 delete_state.update(cx, |state, cx| {
886 state.delete_calendar_event(&delete_key, cx)
887 });
888 delete_peek.update(cx, |peek, cx| peek.close(cx));
889 }),
890 )
891 })
892 .into_any_element(),
893 );
894 buttons
895 }
896
897 fn render_footer(&self, cx: &mut Context<Self>) -> Stateful<Div> {
898 let can_rsvp = self.can_rsvp();
899 v_flex()
900 .id("calendar-peek-footer")
901 .w_full()
902 .flex_none()
903 .gap(px(8.))
904 .children(self.rsvp_message_controls(cx))
905 .child(
906 h_flex()
907 .w_full()
908 .gap(px(8.))
909 .items_center()
910 .when(!can_rsvp, |row| row.justify_end())
911 .children(self.action_buttons(cx)),
912 )
913 }
914}
915
916fn avatar(initials: String) -> Div {
917 div()
918 .size(px(AVATAR_SIZE))
919 .flex_none()
920 .rounded_full()
921 .bg(theme::accent_soft())
922 .flex()
923 .items_center()
924 .justify_center()
925 .text_size(px(11.))
926 .font_weight(FontWeight::SEMIBOLD)
927 .text_color(theme::accent_text())
928 .child(initials)
929}
930
931fn person_row(name: &str, role: String) -> Div {
932 h_flex()
933 .gap(px(ROW_GAP))
934 .items_center()
935 .child(avatar(app_base::format::initials(name)))
936 .child(
937 v_flex()
938 .flex_1()
939 .min_w(px(0.))
940 .child(
941 div()
942 .text_size(px(14.))
943 .text_color(theme::text())
944 .truncate()
945 .child(name.to_owned()),
946 )
947 .child(
948 div()
949 .text_size(px(12.))
950 .text_color(theme::text_muted())
951 .child(role),
952 ),
953 )
954}
955
956fn group_label(group: ResponseType) -> String {
957 match group {
958 ResponseType::Accepted | ResponseType::Organizer => tr("calendar.peek.accepted"),
959 ResponseType::Tentative => tr("calendar.peek.tentative"),
960 ResponseType::Declined => tr("calendar.peek.declined"),
961 ResponseType::NotResponded => tr("calendar.peek.no_response"),
962 }
963}
964
965fn is_teams_url(url: &str) -> bool {
966 url.contains("teams.microsoft.com")
967}
968
969fn is_google_meet_url(url: &str) -> bool {
970 url.contains("meet.google.com")
971}
972
973fn copy_join_clipboard(url: &str, dial_in: Option<&DialIn>) -> String {
974 if is_teams_url(url) {
975 join_info_text(url, dial_in)
976 } else {
977 url.to_owned()
978 }
979}
980
981fn event_detail_score(event: &CalendarEvent) -> u8 {
982 u8::from(event.body_html.is_some()) * 32
983 + u8::from(!event.attendees.is_empty()) * 16
984 + u8::from(
985 event
986 .body_preview
987 .as_ref()
988 .is_some_and(|value| !value.is_empty()),
989 ) * 8
990 + u8::from(
991 event
992 .location
993 .as_ref()
994 .is_some_and(|value| !value.is_empty()),
995 ) * 4
996 + u8::from(event.response_counts.is_some()) * 2
997 + u8::from(event.series_master_id.is_some())
998}
999
1000fn peek_when_label(event: &CalendarEvent) -> String {
1001 let offset = Local::now().offset().fix();
1002 if is_effective_all_day(event, offset) {
1003 let start = event.start.with_timezone(&offset).date_naive();
1004 let end = event.end.with_timezone(&offset).date_naive();
1005 if end > start + chrono::Duration::days(1) {
1006 return format!(
1007 "{} · {} – {}",
1008 tr("calendar.peek.all_day"),
1009 start.format("%a, %b %-d"),
1010 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
1011 );
1012 }
1013 return format!(
1014 "{} · {}",
1015 tr("calendar.peek.all_day"),
1016 start.format("%a, %b %-d, %Y")
1017 );
1018 }
1019 let start = event.start.with_timezone(&offset);
1020 let end = event.end.with_timezone(&offset);
1021 let weekday = localized_weekday(start.weekday());
1022 let date = format_peek_date(start.date_naive());
1023 let clock = app_base::format::clock_format();
1024 if start.date_naive() == end.date_naive() {
1025 format!(
1026 "{weekday} {date} {} - {}",
1027 start.format(clock),
1028 end.format(clock)
1029 )
1030 } else {
1031 // Multi-day timed (Google-style): date + time on both sides.
1032 format!(
1033 "{weekday} {date}, {} – {}, {}",
1034 start.format(clock),
1035 format_peek_date(end.date_naive()),
1036 end.format(clock)
1037 )
1038 }
1039}
1040
1041fn reminder_label(minutes: u32) -> String {
1042 if minutes == 0 {
1043 return tr("calendar.peek.when_starts");
1044 }
1045 let mut args = HashMap::new();
1046 if minutes % 1440 == 0 {
1047 let days = minutes / 1440;
1048 args.insert("count".to_owned(), days.to_string());
1049 return tr_args(
1050 if days == 1 {
1051 "calendar.peek.day_before"
1052 } else {
1053 "calendar.peek.days_before"
1054 },
1055 &args,
1056 );
1057 }
1058 if minutes % 60 == 0 {
1059 let hours = minutes / 60;
1060 args.insert("count".to_owned(), hours.to_string());
1061 return tr_args(
1062 if hours == 1 {
1063 "calendar.peek.hour_before"
1064 } else {
1065 "calendar.peek.hours_before"
1066 },
1067 &args,
1068 );
1069 }
1070 args.insert("count".to_owned(), minutes.to_string());
1071 tr_args(
1072 if minutes == 1 {
1073 "calendar.peek.minute_before"
1074 } else {
1075 "calendar.peek.minutes_before"
1076 },
1077 &args,
1078 )
1079}
1080
1081fn ui_is_german() -> bool {
1082 gpui_kit::component::locale().starts_with("de")
1083}
1084
1085fn format_peek_date(date: chrono::NaiveDate) -> String {
1086 if ui_is_german() {
1087 date.format("%d.%m.%Y").to_string()
1088 } else {
1089 date.format("%-m/%-d/%Y").to_string()
1090 }
1091}
1092
1093fn localized_weekday(weekday: Weekday) -> &'static str {
1094 let de = ui_is_german();
1095 match (de, weekday) {
1096 (true, Weekday::Mon) => "Mo",
1097 (true, Weekday::Tue) => "Di",
1098 (true, Weekday::Wed) => "Mi",
1099 (true, Weekday::Thu) => "Do",
1100 (true, Weekday::Fri) => "Fr",
1101 (true, Weekday::Sat) => "Sa",
1102 (true, Weekday::Sun) => "So",
1103 (false, Weekday::Mon) => "Mon",
1104 (false, Weekday::Tue) => "Tue",
1105 (false, Weekday::Wed) => "Wed",
1106 (false, Weekday::Thu) => "Thu",
1107 (false, Weekday::Fri) => "Fri",
1108 (false, Weekday::Sat) => "Sat",
1109 (false, Weekday::Sun) => "Sun",
1110 }
1111}
1112
1113fn location_label(event: &CalendarEvent) -> String {
1114 if let Some(location) = event
1115 .location
1116 .clone()
1117 .filter(|value| !value.is_empty())
1118 {
1119 return location;
1120 }
1121 if !event.online {
1122 return String::new();
1123 }
1124 match event.join_url.as_deref() {
1125 Some(url) if is_google_meet_url(url) => tr("calendar.peek.google_meet"),
1126 Some(url) if is_teams_url(url) => tr("calendar.peek.teams_meeting"),
1127 _ if event.source == CalendarSource::Google => tr("calendar.peek.google_meet"),
1128 _ => tr("calendar.peek.teams_meeting"),
1129 }
1130}
1131
1132fn response_summary(event: &CalendarEvent) -> Option<String> {
1133 let counts = event.response_counts?;
1134 if counts.is_empty() {
1135 return None;
1136 }
1137 let mut parts = vec![
1138 format!("{} {}", tr("calendar.peek.accepted"), counts.accepted),
1139 format!("{} {}", tr("calendar.peek.declined"), counts.declined),
1140 ];
1141 if counts.tentative > 0 {
1142 parts.insert(
1143 1,
1144 format!("{} {}", tr("calendar.peek.tentative"), counts.tentative),
1145 );
1146 }
1147 parts.push(format!(
1148 "{} {}",
1149 tr("calendar.peek.no_response"),
1150 counts.not_responded
1151 ));
1152 Some(parts.join(", "))
1153}
1154
1155fn icon(name: IconName, color: Hsla) -> Icon {
1156 Icon::new(name).size(px(ICON_SIZE)).text_color(color)
1157}
1158
1159fn rsvp_button(
1160 id: &'static str,
1161 label: String,
1162 reply: Reply,
1163 chosen: bool,
1164 series: bool,
1165 has_master: bool,
1166 peek: Entity<EventPeek>,
1167) -> AnyElement {
1168 let button = Button::new(id).label(label).when(chosen, |button| button.primary());
1169 let button = match reply {
1170 Reply::Accept => button.icon(IconName::Check),
1171 Reply::Decline => button.icon(IconName::X),
1172 Reply::Tentative => button.icon(IconName::CalendarClock),
1173 };
1174 if series {
1175 let occurrence = peek.clone();
1176 let master = peek;
1177 button
1178 .dropdown_menu(move |menu, _, _| {
1179 let occurrence = occurrence.clone();
1180 let master = master.clone();
1181 let mut menu = menu.item(
1182 PopupMenuItem::new(tr("calendar.peek.this_occurrence")).on_click(
1183 move |_, _, cx| {
1184 occurrence.update(cx, |peek, cx| peek.respond(reply, cx));
1185 },
1186 ),
1187 );
1188 if has_master {
1189 menu = menu.item(
1190 PopupMenuItem::new(tr("calendar.peek.entire_series")).on_click(
1191 move |_, _, cx| {
1192 master.update(cx, |peek, cx| peek.respond_series_master(reply, cx));
1193 },
1194 ),
1195 );
1196 }
1197 menu
1198 })
1199 .into_any_element()
1200 } else {
1201 button
1202 .on_click(move |_, _, cx| {
1203 peek.update(cx, |peek, cx| peek.respond(reply, cx));
1204 })
1205 .into_any_element()
1206 }
1207}
1208
1209impl Render for EventPeek {
1210 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1211 let card = if self.expanded {
1212 v_flex()
1213 .id("calendar-peek-card")
1214 .w(relative(EXPANDED_WIDTH))
1215 .max_w(px(COMFY_RUNWAY_WIDTH))
1216 .h(relative(EXPANDED_HEIGHT))
1217 .child(self.render_expanded(cx))
1218 } else {
1219 let header = self.render_header(cx);
1220 let body = self
1221 .has_scroll_content()
1222 .then(|| self.agenda_element(cx))
1223 .flatten()
1224 .map(Self::render_scroll_body);
1225 let footer = self.render_footer(cx);
1226 // Shrink-only agenda (Forward preview pattern): max_h + scrollbar, no flex_1.
1227 v_flex()
1228 .id("calendar-peek-card")
1229 .w(px(CARD_WIDTH))
1230 .max_w(relative(1.))
1231 .max_h(relative(1.))
1232 .child(header)
1233 .children(body)
1234 .child(footer)
1235 };
1236
1237 div()
1238 .id("calendar-peek-layer")
1239 .absolute()
1240 .top_0()
1241 .left_0()
1242 .size_full()
1243 .flex()
1244 .items_center()
1245 .justify_center()
1246 .child(
1247 div()
1248 .id("calendar-peek-backdrop")
1249 .absolute()
1250 .top_0()
1251 .left_0()
1252 .size_full()
1253 .bg(black().opacity(BACKDROP_OPACITY))
1254 .occlude()
1255 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
1256 )
1257 .child(
1258 card.m(px(CARD_MARGIN))
1259 .p(px(CARD_PADDING))
1260 .gap(px(SECTION_GAP))
1261 .rounded(px(CARD_RADIUS))
1262 .dialog_surface()
1263 .text_color(theme::text())
1264 .occlude()
1265 .overflow_hidden()
1266 .capture_key_down(cx.listener(Self::on_key_down)),
1267 )
1268 }
1269}
1270
1271pub fn open_calendar_event(
1272 state: Entity<AppState>,
1273 event: CalendarEvent,
1274 _: &mut Window,
1275 cx: &mut App,
1276) {
1277 state.update(cx, |state, cx| state.request_calendar_event_peek(event, cx));
212}
1278}
crates/app/src/views/calendar_view.rs +15 −7
@@ -427,9 +427,16 @@ impl CalendarView {
427 427 let width = 1. / block.lanes as f32;
428 428 let compact = height < 36.;
429 429 let small = height < SMALL_TITLE_HEIGHT;
430 let title_size = if small { 10. } else { 12. };
431 let title_line = if small { 14. } else { 18. };
432 let pad_y = if compact { 1. } else { 4. };
433 // Fill the block: long titles use the free height instead of clamping to 2 lines.
434 let title_lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
430 435 let look = event_look(event);
431 436 // Join on the block whenever a Teams link exists (same as detail dialog).
432 let can_join = event.online && !event.cancelled && event.join_url.is_some();
437 // Skip on tiny blocks — the button would crush the title.
438 let can_join =
439 !compact && event.online && !event.cancelled && event.join_url.is_some();
433 440 let open_state = self.state.clone();
434 441 let open_event = event.clone();
435 442 let (menu_state, menu_event) = (self.state.clone(), event.clone());
@@ -471,19 +478,20 @@ impl CalendarView {
471 478 .pl(px(5.))
472 479 .pr(px(4.))
473 480 .h_full()
474 .py(px(if compact { 1. } else { 4. }))
481 .py(px(pad_y))
482 .overflow_hidden()
475 483 .when(compact, |body| body.justify_center())
476 484 .child(
477 485 div()
478 .text_size(px(if small { 10. } else { 12. }))
479 .line_height(px(if small { 13. } else { 16. }))
486 .text_size(px(title_size))
487 .line_height(px(title_line))
480 488 .font_weight(FontWeight::SEMIBOLD)
481 489 .text_color(title_color)
482 490 .when(compact, |title| title.truncate())
483 .when(!compact, |title| title.line_clamp(2))
491 .when(!compact, |title| title.line_clamp(title_lines))
484 492 .child(event_title(event)),
485 493 )
486 .when(!compact, |body| {
494 .when(!compact && title_lines > 2, |body| {
487 495 body.children(event.organizer_name.clone().map(|organizer| {
488 496 div()
489 497 .text_size(px(12.))
@@ -496,7 +504,7 @@ impl CalendarView {
496 504 )
497 505 .when(can_join, |block| {
498 506 block.child(
499 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
507 div().flex_none().pr(px(4.)).pt(px(3.)).child(
500 508 Button::new(SharedString::from(format!(
501 509 "calendar-join-{}-{}",
502 510 event.object_id, day
@@ -427,9 +427,16 @@ impl CalendarView {
427 let width = 1. / block.lanes as f32;
427 let width = 1. / block.lanes as f32;
428 let compact = height < 36.;
428 let compact = height < 36.;
429 let small = height < SMALL_TITLE_HEIGHT;
429 let small = height < SMALL_TITLE_HEIGHT;
430 let title_size = if small { 10. } else { 12. };
431 let title_line = if small { 14. } else { 18. };
432 let pad_y = if compact { 1. } else { 4. };
433 // Fill the block: long titles use the free height instead of clamping to 2 lines.
434 let title_lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
430 let look = event_look(event);
435 let look = event_look(event);
431 // Join on the block whenever a Teams link exists (same as detail dialog).
436 // Join on the block whenever a Teams link exists (same as detail dialog).
432 let can_join = event.online && !event.cancelled && event.join_url.is_some();
437 // Skip on tiny blocks — the button would crush the title.
438 let can_join =
439 !compact && event.online && !event.cancelled && event.join_url.is_some();
433 let open_state = self.state.clone();
440 let open_state = self.state.clone();
434 let open_event = event.clone();
441 let open_event = event.clone();
435 let (menu_state, menu_event) = (self.state.clone(), event.clone());
442 let (menu_state, menu_event) = (self.state.clone(), event.clone());
@@ -471,19 +478,20 @@ impl CalendarView {
471 .pl(px(5.))
478 .pl(px(5.))
472 .pr(px(4.))
479 .pr(px(4.))
473 .h_full()
480 .h_full()
474 .py(px(if compact { 1. } else { 4. }))
481 .py(px(pad_y))
482 .overflow_hidden()
475 .when(compact, |body| body.justify_center())
483 .when(compact, |body| body.justify_center())
476 .child(
484 .child(
477 div()
485 div()
478 .text_size(px(if small { 10. } else { 12. }))
486 .text_size(px(title_size))
479 .line_height(px(if small { 13. } else { 16. }))
487 .line_height(px(title_line))
480 .font_weight(FontWeight::SEMIBOLD)
488 .font_weight(FontWeight::SEMIBOLD)
481 .text_color(title_color)
489 .text_color(title_color)
482 .when(compact, |title| title.truncate())
490 .when(compact, |title| title.truncate())
483 .when(!compact, |title| title.line_clamp(2))
491 .when(!compact, |title| title.line_clamp(title_lines))
484 .child(event_title(event)),
492 .child(event_title(event)),
485 )
493 )
486 .when(!compact, |body| {
494 .when(!compact && title_lines > 2, |body| {
487 body.children(event.organizer_name.clone().map(|organizer| {
495 body.children(event.organizer_name.clone().map(|organizer| {
488 div()
496 div()
489 .text_size(px(12.))
497 .text_size(px(12.))
@@ -496,7 +504,7 @@ impl CalendarView {
496 )
504 )
497 .when(can_join, |block| {
505 .when(can_join, |block| {
498 block.child(
506 block.child(
499 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
507 div().flex_none().pr(px(4.)).pt(px(3.)).child(
500 Button::new(SharedString::from(format!(
508 Button::new(SharedString::from(format!(
501 "calendar-join-{}-{}",
509 "calendar-join-{}-{}",
502 event.object_id, day
510 event.object_id, day
crates/app/src/views/conversation.rs +1 −0
@@ -758,6 +758,7 @@ impl ConversationView {
758 758 | AppEvent::Forward
759 759 | AppEvent::ImageViewer
760 760 | AppEvent::StatusMessage
761 | AppEvent::CalendarEventPeek
761 762 | AppEvent::Settings(_)
762 763 | AppEvent::Profile
763 764 | AppEvent::CallHistory
@@ -758,6 +758,7 @@ impl ConversationView {
758 | AppEvent::Forward
758 | AppEvent::Forward
759 | AppEvent::ImageViewer
759 | AppEvent::ImageViewer
760 | AppEvent::StatusMessage
760 | AppEvent::StatusMessage
761 | AppEvent::CalendarEventPeek
761 | AppEvent::Settings(_)
762 | AppEvent::Settings(_)
762 | AppEvent::Profile
763 | AppEvent::Profile
763 | AppEvent::CallHistory
764 | AppEvent::CallHistory
crates/app/src/views/rsvp_menu.rs +1 −1
@@ -17,7 +17,7 @@ fn rsvp_menu_item(
17 17 .checked(chosen)
18 18 .on_click(move |_, _, cx| {
19 19 state.update(cx, |state, cx| {
20 state.respond_to_event(&event_key, reply, cx)
20 state.respond_to_event(&event_key, reply, "", cx)
21 21 });
22 22 })
23 23 }
@@ -17,7 +17,7 @@ fn rsvp_menu_item(
17 .checked(chosen)
17 .checked(chosen)
18 .on_click(move |_, _, cx| {
18 .on_click(move |_, _, cx| {
19 state.update(cx, |state, cx| {
19 state.update(cx, |state, cx| {
20 state.respond_to_event(&event_key, reply, cx)
20 state.respond_to_event(&event_key, reply, "", cx)
21 });
21 });
22 })
22 })
23}
23}
crates/app/src/views/shell.rs +32 −0
@@ -7,6 +7,7 @@ use gpui_kit::*;
7 7
8 8 use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
9 9 use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
10 use super::calendar_event_dialog::{EventPeek, EventPeekEvent};
10 11 use super::calendar_view::CalendarView;
11 12 use super::call_pop_out::zoom_listener;
12 13 use super::calls_page::CallsPage;
@@ -182,6 +183,7 @@ pub struct AppShell {
182 183 forward_dialog: Option<Entity<ForwardDialog>>,
183 184 image_viewer: Option<Entity<ImageViewer>>,
184 185 status_dialog: Option<Entity<StatusMessageDialog>>,
186 calendar_event_peek: Option<Entity<EventPeek>>,
185 187 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
186 188 agent_dialog: Option<Entity<StartDialog>>,
187 189 settings_dialog: Option<Entity<SettingsDialog>>,
@@ -351,6 +353,9 @@ impl AppShell {
351 353 if matches!(event, AppEvent::StatusMessage) {
352 354 this.open_status_dialog(window, cx);
353 355 }
356 if matches!(event, AppEvent::CalendarEventPeek) {
357 this.open_calendar_event_peek(window, cx);
358 }
354 359 if let AppEvent::Settings(section) = event {
355 360 this.open_settings(*section, window, cx);
356 361 }
@@ -402,6 +407,7 @@ impl AppShell {
402 407 forward_dialog: None,
403 408 image_viewer: None,
404 409 status_dialog: None,
410 calendar_event_peek: None,
405 411 shortcuts_dialog: None,
406 412 agent_dialog: None,
407 413 settings_dialog: None,
@@ -655,6 +661,31 @@ impl AppShell {
655 661 cx.notify();
656 662 }
657 663
664
665 fn open_calendar_event_peek(&mut self, window: &mut Window, cx: &mut Context<Self>) {
666 let Some(event) = self
667 .state
668 .update(cx, |state, _| state.take_calendar_event_peek_request())
669 else {
670 return;
671 };
672 self.switcher = None;
673 let app = self.state.clone();
674 let peek = cx.new(|cx| EventPeek::new(app, event, window, cx));
675 cx.subscribe_in(
676 &peek,
677 window,
678 |this, _, _: &EventPeekEvent, window, cx| {
679 this.calendar_event_peek = None;
680 this.restore_focus(window, cx);
681 cx.notify();
682 },
683 )
684 .detach();
685 self.calendar_event_peek = Some(peek);
686 cx.notify();
687 }
688
658 689 fn open_agent_dialog(
659 690 &mut self,
660 691 request: StartRequest,
@@ -1278,6 +1309,7 @@ impl Render for AppShell {
1278 1309 .children(render_task_dialog(self.state.read(cx), cx))
1279 1310 .children(self.forward_dialog.clone())
1280 1311 .children(self.status_dialog.clone())
1312 .children(self.calendar_event_peek.clone())
1281 1313 .children(self.shortcuts_dialog.clone())
1282 1314 .children(self.agent_dialog.clone())
1283 1315 .children(self.settings_dialog.clone())
@@ -7,6 +7,7 @@ use gpui_kit::*;
7
7
8use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
8use super::actions::{NewChat, OpenSwitcher, ReplyToHovered, ToggleCallMute};
9use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
9use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
10use super::calendar_event_dialog::{EventPeek, EventPeekEvent};
10use super::calendar_view::CalendarView;
11use super::calendar_view::CalendarView;
11use super::call_pop_out::zoom_listener;
12use super::call_pop_out::zoom_listener;
12use super::calls_page::CallsPage;
13use super::calls_page::CallsPage;
@@ -182,6 +183,7 @@ pub struct AppShell {
182 forward_dialog: Option<Entity<ForwardDialog>>,
183 forward_dialog: Option<Entity<ForwardDialog>>,
183 image_viewer: Option<Entity<ImageViewer>>,
184 image_viewer: Option<Entity<ImageViewer>>,
184 status_dialog: Option<Entity<StatusMessageDialog>>,
185 status_dialog: Option<Entity<StatusMessageDialog>>,
186 calendar_event_peek: Option<Entity<EventPeek>>,
185 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
187 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
186 agent_dialog: Option<Entity<StartDialog>>,
188 agent_dialog: Option<Entity<StartDialog>>,
187 settings_dialog: Option<Entity<SettingsDialog>>,
189 settings_dialog: Option<Entity<SettingsDialog>>,
@@ -351,6 +353,9 @@ impl AppShell {
351 if matches!(event, AppEvent::StatusMessage) {
353 if matches!(event, AppEvent::StatusMessage) {
352 this.open_status_dialog(window, cx);
354 this.open_status_dialog(window, cx);
353 }
355 }
356 if matches!(event, AppEvent::CalendarEventPeek) {
357 this.open_calendar_event_peek(window, cx);
358 }
354 if let AppEvent::Settings(section) = event {
359 if let AppEvent::Settings(section) = event {
355 this.open_settings(*section, window, cx);
360 this.open_settings(*section, window, cx);
356 }
361 }
@@ -402,6 +407,7 @@ impl AppShell {
402 forward_dialog: None,
407 forward_dialog: None,
403 image_viewer: None,
408 image_viewer: None,
404 status_dialog: None,
409 status_dialog: None,
410 calendar_event_peek: None,
405 shortcuts_dialog: None,
411 shortcuts_dialog: None,
406 agent_dialog: None,
412 agent_dialog: None,
407 settings_dialog: None,
413 settings_dialog: None,
@@ -655,6 +661,31 @@ impl AppShell {
655 cx.notify();
661 cx.notify();
656 }
662 }
657
663
664
665 fn open_calendar_event_peek(&mut self, window: &mut Window, cx: &mut Context<Self>) {
666 let Some(event) = self
667 .state
668 .update(cx, |state, _| state.take_calendar_event_peek_request())
669 else {
670 return;
671 };
672 self.switcher = None;
673 let app = self.state.clone();
674 let peek = cx.new(|cx| EventPeek::new(app, event, window, cx));
675 cx.subscribe_in(
676 &peek,
677 window,
678 |this, _, _: &EventPeekEvent, window, cx| {
679 this.calendar_event_peek = None;
680 this.restore_focus(window, cx);
681 cx.notify();
682 },
683 )
684 .detach();
685 self.calendar_event_peek = Some(peek);
686 cx.notify();
687 }
688
658 fn open_agent_dialog(
689 fn open_agent_dialog(
659 &mut self,
690 &mut self,
660 request: StartRequest,
691 request: StartRequest,
@@ -1278,6 +1309,7 @@ impl Render for AppShell {
1278 .children(render_task_dialog(self.state.read(cx), cx))
1309 .children(render_task_dialog(self.state.read(cx), cx))
1279 .children(self.forward_dialog.clone())
1310 .children(self.forward_dialog.clone())
1280 .children(self.status_dialog.clone())
1311 .children(self.status_dialog.clone())
1312 .children(self.calendar_event_peek.clone())
1281 .children(self.shortcuts_dialog.clone())
1313 .children(self.shortcuts_dialog.clone())
1282 .children(self.agent_dialog.clone())
1314 .children(self.agent_dialog.clone())
1283 .children(self.settings_dialog.clone())
1315 .children(self.settings_dialog.clone())
crates/chatsvc/src/calendar.rs +468 −1
@@ -56,6 +56,31 @@ impl CalendarSource {
56 56 }
57 57 }
58 58
59 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60 pub struct AttendeeResponseCounts {
61 pub accepted: u32,
62 pub declined: u32,
63 pub tentative: u32,
64 pub not_responded: u32,
65 }
66
67 impl AttendeeResponseCounts {
68 pub fn is_empty(self) -> bool {
69 self.accepted == 0
70 && self.declined == 0
71 && self.tentative == 0
72 && self.not_responded == 0
73 }
74 }
75
76 #[derive(Debug, Clone, PartialEq, Eq)]
77 pub struct EventAttendee {
78 pub name: String,
79 pub address: Option<String>,
80 pub response: ResponseType,
81 pub required: bool,
82 }
83
59 84 #[derive(Debug, Clone, PartialEq, Eq)]
60 85 pub struct CalendarEvent {
61 86 pub object_id: String,
@@ -78,6 +103,22 @@ pub struct CalendarEvent {
78 103 pub calendar_id: Option<String>,
79 104 /// When a merge collapsed duplicates, every contributing source.
80 105 pub sources: Vec<CalendarSource>,
106 pub location: Option<String>,
107 pub body_preview: Option<String>,
108 /// Full event body (HTML). `body_preview` from list payloads is server-truncated.
109 pub body_html: Option<String>,
110 pub series: bool,
111 pub series_master_id: Option<String>,
112 pub response_counts: Option<AttendeeResponseCounts>,
113 pub attendees: Vec<EventAttendee>,
114 /// Minutes before start (Google reminders). Empty when unknown.
115 pub reminders: Vec<u32>,
116 /// Google `source` title + URL (View source).
117 pub source_link: Option<(String, String)>,
118 /// Google `htmlLink` — open in Google Calendar.
119 pub web_link: Option<String>,
120 /// Display name of the calendar that owns the event (Google).
121 pub calendar_name: Option<String>,
81 122 }
82 123
83 124 impl CalendarEvent {
@@ -119,6 +160,17 @@ impl Default for CalendarEvent {
119 160 account_id,
120 161 calendar_id,
121 162 sources,
163 location: None,
164 body_preview: None,
165 body_html: None,
166 series: false,
167 series_master_id: None,
168 response_counts: None,
169 attendees: Vec::new(),
170 reminders: Vec::new(),
171 source_link: None,
172 web_link: None,
173 calendar_name: None,
122 174 }
123 175 }
124 176 }
@@ -158,6 +210,7 @@ pub struct Calendar<T: CardTransport = SessionCardTransport> {
158 210 transport: T,
159 211 url: String,
160 212 create_url: String,
213 mt_region: String,
161 214 }
162 215
163 216 impl Calendar<SessionCardTransport> {
@@ -176,9 +229,18 @@ impl<T: CardTransport> Calendar<T> {
176 229 create_url: format!(
177 230 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create"
178 231 ),
232 mt_region: mt_region.to_owned(),
179 233 }
180 234 }
181 235
236 pub fn teams_event_url(&self, event_id: &str) -> String {
237 format!(
238 "https://teams.cloud.microsoft/api/mt/{}/beta/me/calendarEvents/{}",
239 self.mt_region,
240 crate::messages::encode(event_id)
241 )
242 }
243
182 244 pub async fn calendar_view(
183 245 &self,
184 246 start: DateTime<Utc>,
@@ -322,6 +384,247 @@ fn show_as(entry: &Value) -> ShowAs {
322 384 }
323 385 }
324 386
387 fn location_text(entry: &Value) -> Option<String> {
388 text(entry, "locationDisplayName")
389 .or_else(|| text(entry, "location"))
390 .or_else(|| {
391 entry
392 .get("location")
393 .and_then(|location| text(location, "displayName"))
394 })
395 .filter(|value| !value.is_empty())
396 }
397
398 fn body_preview_text(entry: &Value) -> Option<String> {
399 text(entry, "bodyPreview")
400 .or_else(|| text(entry, "bodyContent").map(|content| strip_html(&content)))
401 .or_else(|| {
402 entry
403 .get("body")
404 .and_then(|body| text(body, "content"))
405 .map(|content| strip_html(&content))
406 })
407 .map(|preview| normalize_preview_whitespace(&preview))
408 .map(|preview| truncate_preview(&preview))
409 .filter(|value| !value.is_empty())
410 }
411
412 /// Full body as HTML: Teams MT `bodyContent` or Graph `body.content`.
413 /// Plain-text bodies are escaped and keep their line breaks.
414 fn body_html_text(entry: &Value) -> Option<String> {
415 let (content, kind) = match text(entry, "bodyContent") {
416 Some(content) => (content, text(entry, "bodyContentType")),
417 None => {
418 let body = entry.get("body")?;
419 (text(body, "content")?, text(body, "contentType"))
420 }
421 };
422 if content.trim().is_empty() {
423 return None;
424 }
425 if kind.is_some_and(|kind| kind.eq_ignore_ascii_case("text")) {
426 let escaped = content
427 .replace('&', "&amp;")
428 .replace('<', "&lt;")
429 .replace('>', "&gt;")
430 .replace("\r\n", "\n")
431 .replace('\n', "<br>");
432 return Some(escaped);
433 }
434 Some(content)
435 }
436
437 fn attendee_response(label: &str) -> ResponseType {
438 match label {
439 "accepted" | "Accepted" => ResponseType::Accepted,
440 "organizer" | "Organizer" => ResponseType::Organizer,
441 "declined" | "Declined" => ResponseType::Declined,
442 "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => {
443 ResponseType::Tentative
444 }
445 _ => ResponseType::NotResponded,
446 }
447 }
448
449 /// Attendee roster from Graph (`emailAddress{name,address}`) or Teams MT (`name`, `address`).
450 pub fn attendees_from_entry(entry: &Value) -> Vec<EventAttendee> {
451 let Some(list) = entry.get("attendees").and_then(Value::as_array) else {
452 return Vec::new();
453 };
454 list.iter()
455 .filter_map(|attendee| {
456 let address = attendee
457 .pointer("/emailAddress/address")
458 .and_then(Value::as_str)
459 .or_else(|| attendee.get("address").and_then(Value::as_str))
460 .filter(|value| !value.is_empty())
461 .map(str::to_owned);
462 let name = attendee
463 .pointer("/emailAddress/name")
464 .and_then(Value::as_str)
465 .or_else(|| attendee.get("name").and_then(Value::as_str))
466 .filter(|value| !value.is_empty())
467 .map(str::to_owned)
468 .or_else(|| address.clone())?;
469 let required = !attendee
470 .get("type")
471 .and_then(Value::as_str)
472 .is_some_and(|kind| !kind.eq_ignore_ascii_case("required"));
473 Some(EventAttendee {
474 name,
475 address,
476 response: attendee_response(attendee_response_label(attendee).unwrap_or("none")),
477 required,
478 })
479 })
480 .collect()
481 }
482
483 fn normalize_preview_whitespace(preview: &str) -> String {
484 preview
485 .replace("\r\n", "\n")
486 .replace('\r', "\n")
487 .trim()
488 .to_owned()
489 }
490
491 pub fn strip_html(input: &str) -> String {
492 let mut out = String::with_capacity(input.len());
493 let mut in_tag = false;
494 for character in input.chars() {
495 match character {
496 '<' => {
497 in_tag = true;
498 // Keep a word break when tags sit flush against text (`</p><p>`).
499 out.push(' ');
500 }
501 '>' => in_tag = false,
502 _ if !in_tag => out.push(character),
503 _ => {}
504 }
505 }
506 html_entities(&out).split_whitespace().collect::<Vec<_>>().join(" ")
507 }
508
509 fn html_entities(input: &str) -> String {
510 input
511 .replace("&nbsp;", " ")
512 .replace("&amp;", "&")
513 .replace("&lt;", "<")
514 .replace("&gt;", ">")
515 .replace("&quot;", "\"")
516 .replace("&#39;", "'")
517 }
518
519 pub fn truncate_preview(preview: &str) -> String {
520 // Long enough for a Teams peek agenda; UI scrolls instead of hard-clipping.
521 const MAX_CHARS: usize = 4_000;
522 let trimmed = preview.trim();
523 if trimmed.chars().count() <= MAX_CHARS {
524 return trimmed.to_owned();
525 }
526 let mut cut: String = trimmed.chars().take(MAX_CHARS).collect();
527 cut.push('…');
528 cut
529 }
530
531 fn series_flag(entry: &Value) -> bool {
532 if flag(entry, "isRecurring") || flag(entry, "isSeriesMaster") {
533 return true;
534 }
535 match text(entry, "eventType")
536 .or_else(|| text(entry, "type"))
537 .as_deref()
538 {
539 Some("occurrence" | "exception" | "seriesMaster") => true,
540 _ => entry.get("seriesMasterId").and_then(Value::as_str).is_some()
541 || entry.get("recurrence").is_some(),
542 }
543 }
544
545 fn series_master_id(entry: &Value) -> Option<String> {
546 text(entry, "seriesMasterId").or_else(|| text(entry, "seriesMasterObjectId"))
547 }
548
549 fn attendee_response_label(attendee: &Value) -> Option<&str> {
550 attendee
551 .pointer("/status/response")
552 .and_then(Value::as_str)
553 .or_else(|| attendee.get("responseStatus").and_then(Value::as_str))
554 }
555
556 pub fn response_counts_from_attendees(entry: &Value) -> Option<AttendeeResponseCounts> {
557 let attendees = entry.get("attendees")?.as_array()?;
558 if attendees.is_empty() {
559 return None;
560 }
561 let mut counts = AttendeeResponseCounts::default();
562 for attendee in attendees {
563 match attendee_response_label(attendee).unwrap_or("none") {
564 "accepted" | "Accepted" | "organizer" | "Organizer" => counts.accepted += 1,
565 "declined" | "Declined" => counts.declined += 1,
566 "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => {
567 counts.tentative += 1
568 }
569 _ => counts.not_responded += 1,
570 }
571 }
572 Some(counts)
573 }
574
575 /// Merge Graph / detail fields into a calendar event without wiping list data.
576 pub fn apply_event_details(event: &mut CalendarEvent, entry: &Value) {
577 if let Some(location) = location_text(entry) {
578 event.location = Some(location);
579 }
580 if let Some(preview) = body_preview_text(entry) {
581 event.body_preview = Some(preview);
582 }
583 if let Some(html) = body_html_text(entry) {
584 event.body_html = Some(html);
585 }
586 if series_flag(entry) {
587 event.series = true;
588 }
589 if let Some(master) = series_master_id(entry) {
590 event.series_master_id = Some(master);
591 event.series = true;
592 }
593 if let Some(counts) = response_counts_from_attendees(entry) {
594 event.response_counts = Some(counts);
595 }
596 let attendees = attendees_from_entry(entry);
597 if !attendees.is_empty() {
598 event.attendees = attendees;
599 }
600 if let Some(name) = entry
601 .pointer("/organizer/emailAddress/name")
602 .and_then(Value::as_str)
603 .filter(|value| !value.is_empty())
604 {
605 event.organizer_name = Some(name.to_owned());
606 }
607 if let Some(address) = entry
608 .pointer("/organizer/emailAddress/address")
609 .and_then(Value::as_str)
610 .filter(|value| !value.is_empty())
611 {
612 event.organizer_address = Some(address.to_owned());
613 }
614 if event.join_url.is_none() {
615 if let Some(url) = entry
616 .pointer("/onlineMeeting/joinUrl")
617 .and_then(Value::as_str)
618 .map(str::to_owned)
619 .or_else(|| text(entry, "skypeTeamsMeetingUrl"))
620 .or_else(|| text(entry, "joinUrl"))
621 {
622 event.join_url = Some(url);
623 event.online = true;
624 }
625 }
626 }
627
325 628 fn parse_event(entry: &Value) -> Option<CalendarEvent> {
326 629 let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
327 630 let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
@@ -337,7 +640,9 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
337 640 thread_id: thread_id(entry),
338 641 organizer_name: text(entry, "organizerName"),
339 642 organizer_address: text(entry, "organizerAddress"),
340 ical_uid: text(entry, "iCalUid").or_else(|| text(entry, "iCalUId")),
643 ical_uid: text(entry, "iCalUid")
644 .or_else(|| text(entry, "iCalUId"))
645 .or_else(|| text(entry, "iCalUID")),
341 646 response: response_type(entry),
342 647 show_as: show_as(entry),
343 648 dial_in: dial_in(entry),
@@ -345,6 +650,17 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
345 650 account_id,
346 651 calendar_id,
347 652 sources,
653 location: location_text(entry),
654 body_preview: body_preview_text(entry),
655 body_html: body_html_text(entry),
656 series: series_flag(entry),
657 series_master_id: series_master_id(entry),
658 response_counts: response_counts_from_attendees(entry),
659 attendees: attendees_from_entry(entry),
660 reminders: Vec::new(),
661 source_link: None,
662 web_link: None,
663 calendar_name: None,
348 664 })
349 665 }
350 666
@@ -438,6 +754,157 @@ mod tests {
438 754 standup.thread_id.as_deref(),
439 755 Some("19:meeting_demo1@thread.v2")
440 756 );
757 assert_eq!(
758 standup.location.as_deref(),
759 Some("Microsoft Teams Meeting")
760 );
761 assert_eq!(
762 standup.body_preview.as_deref(),
763 Some("Daily agenda and blockers")
764 );
765 assert!(standup.series);
766 assert_eq!(
767 standup.series_master_id.as_deref(),
768 Some("evt-standup-master")
769 );
770 let counts = standup.response_counts.expect("counts");
771 assert_eq!(counts.accepted, 2);
772 assert_eq!(counts.declined, 1);
773 assert_eq!(counts.not_responded, 2);
774 }
775
776 #[test]
777 fn strip_html_flattens_markup_for_peek_preview() {
778 assert_eq!(
779 strip_html("<p>Hello&nbsp;<b>team</b></p>"),
780 "Hello team"
781 );
782 assert_eq!(
783 strip_html("<p>NEUE</p><p>Agenda</p>"),
784 "NEUE Agenda"
785 );
786 assert_eq!(truncate_preview(&"x".repeat(4_100)).chars().count(), 4_001);
787 }
788
789 #[test]
790 fn apply_event_details_fills_missing_peek_fields() {
791 let mut event = CalendarEvent {
792 object_id: "a".into(),
793 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
794 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
795 ..Default::default()
796 };
797 apply_event_details(
798 &mut event,
799 &serde_json::json!({
800 "bodyPreview": "Notes",
801 "location": {"displayName": "Room A"},
802 "type": "seriesMaster",
803 "seriesMasterId": "master",
804 "attendees": [
805 {"status": {"response": "accepted"}},
806 {"status": {"response": "tentativelyAccepted"}},
807 ],
808 "onlineMeeting": {"joinUrl": "https://teams.microsoft.com/l/meetup-join/z"}
809 }),
810 );
811 assert_eq!(event.body_preview.as_deref(), Some("Notes"));
812 assert_eq!(event.location.as_deref(), Some("Room A"));
813 assert!(event.series);
814 assert_eq!(event.series_master_id.as_deref(), Some("master"));
815 assert_eq!(event.join_url.as_deref(), Some("https://teams.microsoft.com/l/meetup-join/z"));
816 let counts = event.response_counts.expect("counts");
817 assert_eq!(counts.accepted, 1);
818 assert_eq!(counts.tentative, 1);
819 }
820
821 #[test]
822 fn parses_teams_ical_uid_and_body_content() {
823 let events = parse_calendar_events(&serde_json::json!({
824 "value": [{
825 "objectId": "evt-1",
826 "subject": "Standup",
827 "startTime": "2026-11-09T11:00:00Z",
828 "endTime": "2026-11-09T11:15:00Z",
829 "iCalUID": "uid-from-teams",
830 "bodyContent": "<p>NEUE TERMINE</p><p>Agenda</p>",
831 "location": "Microsoft Teams-Besprechung"
832 }]
833 }));
834 assert_eq!(events[0].ical_uid.as_deref(), Some("uid-from-teams"));
835 assert_eq!(
836 events[0].body_preview.as_deref(),
837 Some("NEUE TERMINE Agenda")
838 );
839 assert_eq!(
840 events[0].location.as_deref(),
841 Some("Microsoft Teams-Besprechung")
842 );
843 }
844
845 #[test]
846 fn apply_event_details_uses_body_content_when_preview_missing() {
847 let mut event = CalendarEvent {
848 object_id: "b".into(),
849 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
850 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
851 ..Default::default()
852 };
853 apply_event_details(
854 &mut event,
855 &serde_json::json!({
856 "body": {"contentType": "html", "content": "<p>NEUE TERMINE!!!!!</p><p>Agenda</p>"},
857 "attendees": [{"status": {"response": "accepted"}}]
858 }),
859 );
860 assert_eq!(
861 event.body_preview.as_deref(),
862 Some("NEUE TERMINE!!!!! Agenda")
863 );
864 assert_eq!(
865 event.body_html.as_deref(),
866 Some("<p>NEUE TERMINE!!!!!</p><p>Agenda</p>")
867 );
868 }
869
870 #[test]
871 fn attendees_parse_graph_and_teams_shapes() {
872 let mut event = CalendarEvent::default();
873 apply_event_details(
874 &mut event,
875 &serde_json::json!({
876 "attendees": [
877 {"emailAddress": {"name": "Ada", "address": "ada@x.ch"},
878 "status": {"response": "accepted"}, "type": "required"},
879 {"name": "Bob", "address": "bob@x.ch",
880 "status": {"response": "NotResponded"}, "type": "Optional"},
881 {"address": "eve@x.ch", "status": {"response": "Declined"}}
882 ]
883 }),
884 );
885 let roster: Vec<_> = event
886 .attendees
887 .iter()
888 .map(|a| (a.name.as_str(), a.response, a.required))
889 .collect();
890 assert_eq!(
891 roster,
892 vec![
893 ("Ada", ResponseType::Accepted, true),
894 ("Bob", ResponseType::NotResponded, false),
895 ("eve@x.ch", ResponseType::Declined, true),
896 ]
897 );
898 }
899
900 #[test]
901 fn plain_text_body_becomes_escaped_html() {
902 let mut event = CalendarEvent::default();
903 apply_event_details(
904 &mut event,
905 &serde_json::json!({"body": {"contentType": "text", "content": "a < b\r\nnext"}}),
906 );
907 assert_eq!(event.body_html.as_deref(), Some("a &lt; b<br>next"));
441 908 }
442 909
443 910 #[test]
@@ -56,6 +56,31 @@ impl CalendarSource {
56 }
56 }
57}
57}
58
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct AttendeeResponseCounts {
61 pub accepted: u32,
62 pub declined: u32,
63 pub tentative: u32,
64 pub not_responded: u32,
65}
66
67impl AttendeeResponseCounts {
68 pub fn is_empty(self) -> bool {
69 self.accepted == 0
70 && self.declined == 0
71 && self.tentative == 0
72 && self.not_responded == 0
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct EventAttendee {
78 pub name: String,
79 pub address: Option<String>,
80 pub response: ResponseType,
81 pub required: bool,
82}
83
59#[derive(Debug, Clone, PartialEq, Eq)]
84#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct CalendarEvent {
85pub struct CalendarEvent {
61 pub object_id: String,
86 pub object_id: String,
@@ -78,6 +103,22 @@ pub struct CalendarEvent {
78 pub calendar_id: Option<String>,
103 pub calendar_id: Option<String>,
79 /// When a merge collapsed duplicates, every contributing source.
104 /// When a merge collapsed duplicates, every contributing source.
80 pub sources: Vec<CalendarSource>,
105 pub sources: Vec<CalendarSource>,
106 pub location: Option<String>,
107 pub body_preview: Option<String>,
108 /// Full event body (HTML). `body_preview` from list payloads is server-truncated.
109 pub body_html: Option<String>,
110 pub series: bool,
111 pub series_master_id: Option<String>,
112 pub response_counts: Option<AttendeeResponseCounts>,
113 pub attendees: Vec<EventAttendee>,
114 /// Minutes before start (Google reminders). Empty when unknown.
115 pub reminders: Vec<u32>,
116 /// Google `source` title + URL (View source).
117 pub source_link: Option<(String, String)>,
118 /// Google `htmlLink` — open in Google Calendar.
119 pub web_link: Option<String>,
120 /// Display name of the calendar that owns the event (Google).
121 pub calendar_name: Option<String>,
81}
122}
82
123
83impl CalendarEvent {
124impl CalendarEvent {
@@ -119,6 +160,17 @@ impl Default for CalendarEvent {
119 account_id,
160 account_id,
120 calendar_id,
161 calendar_id,
121 sources,
162 sources,
163 location: None,
164 body_preview: None,
165 body_html: None,
166 series: false,
167 series_master_id: None,
168 response_counts: None,
169 attendees: Vec::new(),
170 reminders: Vec::new(),
171 source_link: None,
172 web_link: None,
173 calendar_name: None,
122 }
174 }
123 }
175 }
124}
176}
@@ -158,6 +210,7 @@ pub struct Calendar<T: CardTransport = SessionCardTransport> {
158 transport: T,
210 transport: T,
159 url: String,
211 url: String,
160 create_url: String,
212 create_url: String,
213 mt_region: String,
161}
214}
162
215
163impl Calendar<SessionCardTransport> {
216impl Calendar<SessionCardTransport> {
@@ -176,9 +229,18 @@ impl<T: CardTransport> Calendar<T> {
176 create_url: format!(
229 create_url: format!(
177 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create"
230 "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create"
178 ),
231 ),
232 mt_region: mt_region.to_owned(),
179 }
233 }
180 }
234 }
181
235
236 pub fn teams_event_url(&self, event_id: &str) -> String {
237 format!(
238 "https://teams.cloud.microsoft/api/mt/{}/beta/me/calendarEvents/{}",
239 self.mt_region,
240 crate::messages::encode(event_id)
241 )
242 }
243
182 pub async fn calendar_view(
244 pub async fn calendar_view(
183 &self,
245 &self,
184 start: DateTime<Utc>,
246 start: DateTime<Utc>,
@@ -322,6 +384,247 @@ fn show_as(entry: &Value) -> ShowAs {
322 }
384 }
323}
385}
324
386
387fn location_text(entry: &Value) -> Option<String> {
388 text(entry, "locationDisplayName")
389 .or_else(|| text(entry, "location"))
390 .or_else(|| {
391 entry
392 .get("location")
393 .and_then(|location| text(location, "displayName"))
394 })
395 .filter(|value| !value.is_empty())
396}
397
398fn body_preview_text(entry: &Value) -> Option<String> {
399 text(entry, "bodyPreview")
400 .or_else(|| text(entry, "bodyContent").map(|content| strip_html(&content)))
401 .or_else(|| {
402 entry
403 .get("body")
404 .and_then(|body| text(body, "content"))
405 .map(|content| strip_html(&content))
406 })
407 .map(|preview| normalize_preview_whitespace(&preview))
408 .map(|preview| truncate_preview(&preview))
409 .filter(|value| !value.is_empty())
410}
411
412/// Full body as HTML: Teams MT `bodyContent` or Graph `body.content`.
413/// Plain-text bodies are escaped and keep their line breaks.
414fn body_html_text(entry: &Value) -> Option<String> {
415 let (content, kind) = match text(entry, "bodyContent") {
416 Some(content) => (content, text(entry, "bodyContentType")),
417 None => {
418 let body = entry.get("body")?;
419 (text(body, "content")?, text(body, "contentType"))
420 }
421 };
422 if content.trim().is_empty() {
423 return None;
424 }
425 if kind.is_some_and(|kind| kind.eq_ignore_ascii_case("text")) {
426 let escaped = content
427 .replace('&', "&amp;")
428 .replace('<', "&lt;")
429 .replace('>', "&gt;")
430 .replace("\r\n", "\n")
431 .replace('\n', "<br>");
432 return Some(escaped);
433 }
434 Some(content)
435}
436
437fn attendee_response(label: &str) -> ResponseType {
438 match label {
439 "accepted" | "Accepted" => ResponseType::Accepted,
440 "organizer" | "Organizer" => ResponseType::Organizer,
441 "declined" | "Declined" => ResponseType::Declined,
442 "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => {
443 ResponseType::Tentative
444 }
445 _ => ResponseType::NotResponded,
446 }
447}
448
449/// Attendee roster from Graph (`emailAddress{name,address}`) or Teams MT (`name`, `address`).
450pub fn attendees_from_entry(entry: &Value) -> Vec<EventAttendee> {
451 let Some(list) = entry.get("attendees").and_then(Value::as_array) else {
452 return Vec::new();
453 };
454 list.iter()
455 .filter_map(|attendee| {
456 let address = attendee
457 .pointer("/emailAddress/address")
458 .and_then(Value::as_str)
459 .or_else(|| attendee.get("address").and_then(Value::as_str))
460 .filter(|value| !value.is_empty())
461 .map(str::to_owned);
462 let name = attendee
463 .pointer("/emailAddress/name")
464 .and_then(Value::as_str)
465 .or_else(|| attendee.get("name").and_then(Value::as_str))
466 .filter(|value| !value.is_empty())
467 .map(str::to_owned)
468 .or_else(|| address.clone())?;
469 let required = !attendee
470 .get("type")
471 .and_then(Value::as_str)
472 .is_some_and(|kind| !kind.eq_ignore_ascii_case("required"));
473 Some(EventAttendee {
474 name,
475 address,
476 response: attendee_response(attendee_response_label(attendee).unwrap_or("none")),
477 required,
478 })
479 })
480 .collect()
481}
482
483fn normalize_preview_whitespace(preview: &str) -> String {
484 preview
485 .replace("\r\n", "\n")
486 .replace('\r', "\n")
487 .trim()
488 .to_owned()
489}
490
491pub fn strip_html(input: &str) -> String {
492 let mut out = String::with_capacity(input.len());
493 let mut in_tag = false;
494 for character in input.chars() {
495 match character {
496 '<' => {
497 in_tag = true;
498 // Keep a word break when tags sit flush against text (`</p><p>`).
499 out.push(' ');
500 }
501 '>' => in_tag = false,
502 _ if !in_tag => out.push(character),
503 _ => {}
504 }
505 }
506 html_entities(&out).split_whitespace().collect::<Vec<_>>().join(" ")
507}
508
509fn html_entities(input: &str) -> String {
510 input
511 .replace("&nbsp;", " ")
512 .replace("&amp;", "&")
513 .replace("&lt;", "<")
514 .replace("&gt;", ">")
515 .replace("&quot;", "\"")
516 .replace("&#39;", "'")
517}
518
519pub fn truncate_preview(preview: &str) -> String {
520 // Long enough for a Teams peek agenda; UI scrolls instead of hard-clipping.
521 const MAX_CHARS: usize = 4_000;
522 let trimmed = preview.trim();
523 if trimmed.chars().count() <= MAX_CHARS {
524 return trimmed.to_owned();
525 }
526 let mut cut: String = trimmed.chars().take(MAX_CHARS).collect();
527 cut.push('…');
528 cut
529}
530
531fn series_flag(entry: &Value) -> bool {
532 if flag(entry, "isRecurring") || flag(entry, "isSeriesMaster") {
533 return true;
534 }
535 match text(entry, "eventType")
536 .or_else(|| text(entry, "type"))
537 .as_deref()
538 {
539 Some("occurrence" | "exception" | "seriesMaster") => true,
540 _ => entry.get("seriesMasterId").and_then(Value::as_str).is_some()
541 || entry.get("recurrence").is_some(),
542 }
543}
544
545fn series_master_id(entry: &Value) -> Option<String> {
546 text(entry, "seriesMasterId").or_else(|| text(entry, "seriesMasterObjectId"))
547}
548
549fn attendee_response_label(attendee: &Value) -> Option<&str> {
550 attendee
551 .pointer("/status/response")
552 .and_then(Value::as_str)
553 .or_else(|| attendee.get("responseStatus").and_then(Value::as_str))
554}
555
556pub fn response_counts_from_attendees(entry: &Value) -> Option<AttendeeResponseCounts> {
557 let attendees = entry.get("attendees")?.as_array()?;
558 if attendees.is_empty() {
559 return None;
560 }
561 let mut counts = AttendeeResponseCounts::default();
562 for attendee in attendees {
563 match attendee_response_label(attendee).unwrap_or("none") {
564 "accepted" | "Accepted" | "organizer" | "Organizer" => counts.accepted += 1,
565 "declined" | "Declined" => counts.declined += 1,
566 "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => {
567 counts.tentative += 1
568 }
569 _ => counts.not_responded += 1,
570 }
571 }
572 Some(counts)
573}
574
575/// Merge Graph / detail fields into a calendar event without wiping list data.
576pub fn apply_event_details(event: &mut CalendarEvent, entry: &Value) {
577 if let Some(location) = location_text(entry) {
578 event.location = Some(location);
579 }
580 if let Some(preview) = body_preview_text(entry) {
581 event.body_preview = Some(preview);
582 }
583 if let Some(html) = body_html_text(entry) {
584 event.body_html = Some(html);
585 }
586 if series_flag(entry) {
587 event.series = true;
588 }
589 if let Some(master) = series_master_id(entry) {
590 event.series_master_id = Some(master);
591 event.series = true;
592 }
593 if let Some(counts) = response_counts_from_attendees(entry) {
594 event.response_counts = Some(counts);
595 }
596 let attendees = attendees_from_entry(entry);
597 if !attendees.is_empty() {
598 event.attendees = attendees;
599 }
600 if let Some(name) = entry
601 .pointer("/organizer/emailAddress/name")
602 .and_then(Value::as_str)
603 .filter(|value| !value.is_empty())
604 {
605 event.organizer_name = Some(name.to_owned());
606 }
607 if let Some(address) = entry
608 .pointer("/organizer/emailAddress/address")
609 .and_then(Value::as_str)
610 .filter(|value| !value.is_empty())
611 {
612 event.organizer_address = Some(address.to_owned());
613 }
614 if event.join_url.is_none() {
615 if let Some(url) = entry
616 .pointer("/onlineMeeting/joinUrl")
617 .and_then(Value::as_str)
618 .map(str::to_owned)
619 .or_else(|| text(entry, "skypeTeamsMeetingUrl"))
620 .or_else(|| text(entry, "joinUrl"))
621 {
622 event.join_url = Some(url);
623 event.online = true;
624 }
625 }
626}
627
325fn parse_event(entry: &Value) -> Option<CalendarEvent> {
628fn parse_event(entry: &Value) -> Option<CalendarEvent> {
326 let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
629 let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl"));
327 let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
630 let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults();
@@ -337,7 +640,9 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
337 thread_id: thread_id(entry),
640 thread_id: thread_id(entry),
338 organizer_name: text(entry, "organizerName"),
641 organizer_name: text(entry, "organizerName"),
339 organizer_address: text(entry, "organizerAddress"),
642 organizer_address: text(entry, "organizerAddress"),
340 ical_uid: text(entry, "iCalUid").or_else(|| text(entry, "iCalUId")),
643 ical_uid: text(entry, "iCalUid")
644 .or_else(|| text(entry, "iCalUId"))
645 .or_else(|| text(entry, "iCalUID")),
341 response: response_type(entry),
646 response: response_type(entry),
342 show_as: show_as(entry),
647 show_as: show_as(entry),
343 dial_in: dial_in(entry),
648 dial_in: dial_in(entry),
@@ -345,6 +650,17 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
345 account_id,
650 account_id,
346 calendar_id,
651 calendar_id,
347 sources,
652 sources,
653 location: location_text(entry),
654 body_preview: body_preview_text(entry),
655 body_html: body_html_text(entry),
656 series: series_flag(entry),
657 series_master_id: series_master_id(entry),
658 response_counts: response_counts_from_attendees(entry),
659 attendees: attendees_from_entry(entry),
660 reminders: Vec::new(),
661 source_link: None,
662 web_link: None,
663 calendar_name: None,
348 })
664 })
349}
665}
350
666
@@ -438,6 +754,157 @@ mod tests {
438 standup.thread_id.as_deref(),
754 standup.thread_id.as_deref(),
439 Some("19:meeting_demo1@thread.v2")
755 Some("19:meeting_demo1@thread.v2")
440 );
756 );
757 assert_eq!(
758 standup.location.as_deref(),
759 Some("Microsoft Teams Meeting")
760 );
761 assert_eq!(
762 standup.body_preview.as_deref(),
763 Some("Daily agenda and blockers")
764 );
765 assert!(standup.series);
766 assert_eq!(
767 standup.series_master_id.as_deref(),
768 Some("evt-standup-master")
769 );
770 let counts = standup.response_counts.expect("counts");
771 assert_eq!(counts.accepted, 2);
772 assert_eq!(counts.declined, 1);
773 assert_eq!(counts.not_responded, 2);
774 }
775
776 #[test]
777 fn strip_html_flattens_markup_for_peek_preview() {
778 assert_eq!(
779 strip_html("<p>Hello&nbsp;<b>team</b></p>"),
780 "Hello team"
781 );
782 assert_eq!(
783 strip_html("<p>NEUE</p><p>Agenda</p>"),
784 "NEUE Agenda"
785 );
786 assert_eq!(truncate_preview(&"x".repeat(4_100)).chars().count(), 4_001);
787 }
788
789 #[test]
790 fn apply_event_details_fills_missing_peek_fields() {
791 let mut event = CalendarEvent {
792 object_id: "a".into(),
793 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
794 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
795 ..Default::default()
796 };
797 apply_event_details(
798 &mut event,
799 &serde_json::json!({
800 "bodyPreview": "Notes",
801 "location": {"displayName": "Room A"},
802 "type": "seriesMaster",
803 "seriesMasterId": "master",
804 "attendees": [
805 {"status": {"response": "accepted"}},
806 {"status": {"response": "tentativelyAccepted"}},
807 ],
808 "onlineMeeting": {"joinUrl": "https://teams.microsoft.com/l/meetup-join/z"}
809 }),
810 );
811 assert_eq!(event.body_preview.as_deref(), Some("Notes"));
812 assert_eq!(event.location.as_deref(), Some("Room A"));
813 assert!(event.series);
814 assert_eq!(event.series_master_id.as_deref(), Some("master"));
815 assert_eq!(event.join_url.as_deref(), Some("https://teams.microsoft.com/l/meetup-join/z"));
816 let counts = event.response_counts.expect("counts");
817 assert_eq!(counts.accepted, 1);
818 assert_eq!(counts.tentative, 1);
819 }
820
821 #[test]
822 fn parses_teams_ical_uid_and_body_content() {
823 let events = parse_calendar_events(&serde_json::json!({
824 "value": [{
825 "objectId": "evt-1",
826 "subject": "Standup",
827 "startTime": "2026-11-09T11:00:00Z",
828 "endTime": "2026-11-09T11:15:00Z",
829 "iCalUID": "uid-from-teams",
830 "bodyContent": "<p>NEUE TERMINE</p><p>Agenda</p>",
831 "location": "Microsoft Teams-Besprechung"
832 }]
833 }));
834 assert_eq!(events[0].ical_uid.as_deref(), Some("uid-from-teams"));
835 assert_eq!(
836 events[0].body_preview.as_deref(),
837 Some("NEUE TERMINE Agenda")
838 );
839 assert_eq!(
840 events[0].location.as_deref(),
841 Some("Microsoft Teams-Besprechung")
842 );
843 }
844
845 #[test]
846 fn apply_event_details_uses_body_content_when_preview_missing() {
847 let mut event = CalendarEvent {
848 object_id: "b".into(),
849 start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(),
850 end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(),
851 ..Default::default()
852 };
853 apply_event_details(
854 &mut event,
855 &serde_json::json!({
856 "body": {"contentType": "html", "content": "<p>NEUE TERMINE!!!!!</p><p>Agenda</p>"},
857 "attendees": [{"status": {"response": "accepted"}}]
858 }),
859 );
860 assert_eq!(
861 event.body_preview.as_deref(),
862 Some("NEUE TERMINE!!!!! Agenda")
863 );
864 assert_eq!(
865 event.body_html.as_deref(),
866 Some("<p>NEUE TERMINE!!!!!</p><p>Agenda</p>")
867 );
868 }
869
870 #[test]
871 fn attendees_parse_graph_and_teams_shapes() {
872 let mut event = CalendarEvent::default();
873 apply_event_details(
874 &mut event,
875 &serde_json::json!({
876 "attendees": [
877 {"emailAddress": {"name": "Ada", "address": "ada@x.ch"},
878 "status": {"response": "accepted"}, "type": "required"},
879 {"name": "Bob", "address": "bob@x.ch",
880 "status": {"response": "NotResponded"}, "type": "Optional"},
881 {"address": "eve@x.ch", "status": {"response": "Declined"}}
882 ]
883 }),
884 );
885 let roster: Vec<_> = event
886 .attendees
887 .iter()
888 .map(|a| (a.name.as_str(), a.response, a.required))
889 .collect();
890 assert_eq!(
891 roster,
892 vec![
893 ("Ada", ResponseType::Accepted, true),
894 ("Bob", ResponseType::NotResponded, false),
895 ("eve@x.ch", ResponseType::Declined, true),
896 ]
897 );
898 }
899
900 #[test]
901 fn plain_text_body_becomes_escaped_html() {
902 let mut event = CalendarEvent::default();
903 apply_event_details(
904 &mut event,
905 &serde_json::json!({"body": {"contentType": "text", "content": "a < b\r\nnext"}}),
906 );
907 assert_eq!(event.body_html.as_deref(), Some("a &lt; b<br>next"));
441 }
908 }
442
909
443 #[test]
910 #[test]
crates/chatsvc/src/calendar/schedule.rs +194 −7
@@ -200,6 +200,19 @@ fn event_item_url(event_id: &str) -> String {
200 200 format!("{}/{}", events_url(), encode(event_id))
201 201 }
202 202
203 // Include `body` — series occurrences often have an empty bodyPreview while the
204 // full HTML agenda lives in body.content (body_preview_text already falls back).
205 const EVENT_DETAIL_SELECT: &str =
206 "id,subject,body,bodyPreview,location,attendees,type,seriesMasterId,isOnlineMeeting,onlineMeeting,organizer,isAllDay,isCancelled";
207
208 fn event_details_url(event_id: &str) -> String {
209 format!(
210 "{}?$select={}",
211 event_item_url(event_id),
212 encode(EVENT_DETAIL_SELECT)
213 )
214 }
215
203 216 fn reply_url(event_id: &str, reply: Reply) -> String {
204 217 format!("{}/{}", event_item_url(event_id), reply.action())
205 218 }
@@ -216,6 +229,40 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {
216 229 Error::Session(session::Error::api(answer.status, url, answer.body))
217 230 }
218 231
232 fn details_have_agenda(entry: &Value) -> bool {
233 entry
234 .get("bodyPreview")
235 .and_then(Value::as_str)
236 .is_some_and(|value| !value.trim().is_empty())
237 || entry
238 .get("bodyContent")
239 .and_then(Value::as_str)
240 .is_some_and(|value| !value.trim().is_empty())
241 || entry
242 .pointer("/body/content")
243 .and_then(Value::as_str)
244 .is_some_and(|value| !value.trim().is_empty())
245 }
246
247 fn merge_detail_bodies(mut graph: Value, teams: Value) -> Value {
248 if let Some(content) = teams.get("bodyContent").cloned() {
249 match graph.as_object_mut() {
250 Some(map) => {
251 map.entry("bodyContent").or_insert(content);
252 }
253 None => return teams,
254 }
255 }
256 if let Some(attendees) = teams.get("attendees").cloned() {
257 if graph.get("attendees").and_then(Value::as_array).is_none_or(|a| a.is_empty()) {
258 if let Some(map) = graph.as_object_mut() {
259 map.insert("attendees".into(), attendees);
260 }
261 }
262 }
263 graph
264 }
265
219 266 impl<T: CardTransport> Calendar<T> {
220 267 pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
221 268 self.create_event_body(event, new_event_body(event)).await
@@ -255,8 +302,11 @@ impl<T: CardTransport> Calendar<T> {
255 302 ical_uid: Option<&str>,
256 303 reply: Reply,
257 304 send_response: bool,
305 comment: &str,
258 306 ) -> Result<()> {
259 let answer = self.send_reply(event_id, reply, send_response).await?;
307 let answer = self
308 .send_reply(event_id, reply, send_response, comment)
309 .await?;
260 310 if answer.is_success() {
261 311 return Ok(());
262 312 }
@@ -264,13 +314,57 @@ impl<T: CardTransport> Calendar<T> {
264 314 return Err(api_error(answer, &reply_url(event_id, reply)));
265 315 };
266 316 let graph_id = self.graph_event_id(ical_uid).await?;
267 let retried = self.send_reply(&graph_id, reply, send_response).await?;
317 let retried = self
318 .send_reply(&graph_id, reply, send_response, comment)
319 .await?;
268 320 if retried.is_success() {
269 321 return Ok(());
270 322 }
271 323 Err(api_error(retried, &reply_url(&graph_id, reply)))
272 324 }
273 325
326 pub async fn event_details(
327 &self,
328 event_id: &str,
329 ical_uid: Option<&str>,
330 ) -> Result<Value> {
331 let answer = self.fetch_event(event_id).await?;
332 if answer.is_success() {
333 if details_have_agenda(&answer.body) {
334 return Ok(answer.body);
335 }
336 // Graph can return RSVP fields with an empty body on occurrences;
337 // Teams MT beta carries bodyContent + attendees for the same objectId.
338 if let Ok(teams) = self.fetch_teams_event(event_id).await {
339 if teams.is_success() && details_have_agenda(&teams.body) {
340 return Ok(merge_detail_bodies(answer.body, teams.body));
341 }
342 }
343 return Ok(answer.body);
344 }
345 if let Ok(teams) = self.fetch_teams_event(event_id).await {
346 if teams.is_success() {
347 return Ok(teams.body);
348 }
349 }
350 let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
351 return Err(api_error(answer, &event_details_url(event_id)));
352 };
353 let graph_id = self.graph_event_id(ical_uid).await?;
354 let retried = self.fetch_event(&graph_id).await?;
355 if retried.is_success() {
356 return Ok(retried.body);
357 }
358 Err(api_error(retried, &event_details_url(&graph_id)))
359 }
360
361 async fn fetch_teams_event(&self, event_id: &str) -> Result<session::ApiResponse> {
362 let url = self.teams_event_url(event_id);
363 self.transport
364 .send(Request::get(&url), crate::cards::spaces_scope())
365 .await
366 }
367
274 368 pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {
275 369 let answer = self.send_delete(event_id).await?;
276 370 if answer.is_success() {
@@ -301,17 +395,30 @@ impl<T: CardTransport> Calendar<T> {
301 395 event_id: &str,
302 396 reply: Reply,
303 397 send_response: bool,
398 comment: &str,
304 399 ) -> Result<session::ApiResponse> {
305 400 let request = Request::with_body(
306 401 Method::Post,
307 402 reply_url(event_id, reply),
308 json!({"comment": "", "sendResponse": send_response}),
403 json!({
404 "comment": if send_response { comment } else { "" },
405 "sendResponse": send_response,
406 }),
309 407 );
310 408 self.transport
311 409 .send(request, Scope::graph(CALENDARS_SCOPE))
312 410 .await
313 411 }
314 412
413 async fn fetch_event(&self, event_id: &str) -> Result<session::ApiResponse> {
414 self.transport
415 .send(
416 Request::get(event_details_url(event_id)),
417 Scope::graph(CALENDARS_SCOPE),
418 )
419 .await
420 }
421
315 422 async fn graph_event_id(&self, ical_uid: &str) -> Result<String> {
316 423 let url = lookup_url(ical_uid);
317 424 let answer = self
@@ -355,7 +462,12 @@ mod tests {
355 462
356 463 impl CardTransport for Scripted {
357 464 async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> {
358 assert_eq!(scope, Scope::graph(CALENDARS_SCOPE));
465 let graph = Scope::graph(CALENDARS_SCOPE);
466 let spaces = crate::cards::spaces_scope();
467 assert!(
468 scope == graph || scope == spaces,
469 "unexpected scope {scope:?}"
470 );
359 471 self.sent
360 472 .lock()
361 473 .unwrap()
@@ -557,7 +669,7 @@ mod tests {
557 669 async fn respond_posts_the_reply_with_the_send_flag() {
558 670 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
559 671 calendar
560 .respond("AAMk=", None, Reply::Tentative, false)
672 .respond("AAMk=", None, Reply::Tentative, false, "ignored")
561 673 .await
562 674 .unwrap();
563 675 let sent = calendar.transport.sent.lock().unwrap();
@@ -571,6 +683,81 @@ mod tests {
571 683 );
572 684 }
573 685
686 #[tokio::test]
687 async fn respond_includes_comment_when_sending() {
688 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
689 calendar
690 .respond("AAMk=", None, Reply::Accept, true, "See you there")
691 .await
692 .unwrap();
693 let sent = calendar.transport.sent.lock().unwrap();
694 assert_eq!(
695 sent[0].2,
696 Some(json!({"comment": "See you there", "sendResponse": true}))
697 );
698 }
699
700 #[tokio::test]
701 async fn event_details_gets_selected_fields() {
702 let calendar = Calendar::with_transport(
703 Scripted::new(vec![(
704 200,
705 json!({
706 "id": "AAMk=",
707 "bodyPreview": "Agenda",
708 "location": {"displayName": "Microsoft Teams Meeting"},
709 "type": "occurrence",
710 "seriesMasterId": "master",
711 "attendees": [
712 {"status": {"response": "accepted"}},
713 {"status": {"response": "declined"}},
714 {"status": {"response": "none"}},
715 ]
716 }),
717 )]),
718 "emea",
719 );
720 let body = calendar.event_details("AAMk=", None).await.unwrap();
721 assert_eq!(body["bodyPreview"], "Agenda");
722 let sent = calendar.transport.sent.lock().unwrap();
723 assert_eq!(sent[0].0, Method::Get);
724 assert!(sent[0].1.contains("/me/events/AAMk%3D?"));
725 assert!(sent[0].1.contains("bodyPreview"));
726 assert!(sent[0].1.contains("body"));
727 }
728
729 #[tokio::test]
730 async fn event_details_merges_teams_body_when_graph_agenda_empty() {
731 let calendar = Calendar::with_transport(
732 Scripted::new(vec![
733 (
734 200,
735 json!({
736 "id": "AAMk=",
737 "bodyPreview": "",
738 "attendees": [{"status": {"response": "accepted"}}]
739 }),
740 ),
741 (
742 200,
743 json!({
744 "bodyContent": "<p>Daily agenda</p>",
745 "attendees": [
746 {"status": {"response": "Accepted"}},
747 {"status": {"response": "NotResponded"}},
748 ]
749 }),
750 ),
751 ]),
752 "emea",
753 );
754 let body = calendar.event_details("AAMk=", None).await.unwrap();
755 assert_eq!(body["bodyContent"], "<p>Daily agenda</p>");
756 let sent = calendar.transport.sent.lock().unwrap();
757 assert!(sent[0].1.contains("graph.microsoft.com"));
758 assert!(sent[1].1.contains("/beta/me/calendarEvents/"));
759 }
760
574 761 #[tokio::test]
575 762 async fn delete_event_sends_graph_delete() {
576 763 let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");
@@ -594,7 +781,7 @@ mod tests {
594 781 "emea",
595 782 );
596 783 calendar
597 .respond("mt-id", Some("uid-1"), Reply::Decline, true)
784 .respond("mt-id", Some("uid-1"), Reply::Decline, true, "")
598 785 .await
599 786 .unwrap();
600 787 let sent = calendar.transport.sent.lock().unwrap();
@@ -610,7 +797,7 @@ mod tests {
610 797 );
611 798 assert!(
612 799 calendar
613 .respond("mt-id", None, Reply::Accept, true)
800 .respond("mt-id", None, Reply::Accept, true, "")
614 801 .await
615 802 .is_err()
616 803 );
@@ -200,6 +200,19 @@ fn event_item_url(event_id: &str) -> String {
200 format!("{}/{}", events_url(), encode(event_id))
200 format!("{}/{}", events_url(), encode(event_id))
201}
201}
202
202
203// Include `body` — series occurrences often have an empty bodyPreview while the
204// full HTML agenda lives in body.content (body_preview_text already falls back).
205const EVENT_DETAIL_SELECT: &str =
206 "id,subject,body,bodyPreview,location,attendees,type,seriesMasterId,isOnlineMeeting,onlineMeeting,organizer,isAllDay,isCancelled";
207
208fn event_details_url(event_id: &str) -> String {
209 format!(
210 "{}?$select={}",
211 event_item_url(event_id),
212 encode(EVENT_DETAIL_SELECT)
213 )
214}
215
203fn reply_url(event_id: &str, reply: Reply) -> String {
216fn reply_url(event_id: &str, reply: Reply) -> String {
204 format!("{}/{}", event_item_url(event_id), reply.action())
217 format!("{}/{}", event_item_url(event_id), reply.action())
205}
218}
@@ -216,6 +229,40 @@ fn api_error(answer: session::ApiResponse, url: &str) -> Error {
216 Error::Session(session::Error::api(answer.status, url, answer.body))
229 Error::Session(session::Error::api(answer.status, url, answer.body))
217}
230}
218
231
232fn details_have_agenda(entry: &Value) -> bool {
233 entry
234 .get("bodyPreview")
235 .and_then(Value::as_str)
236 .is_some_and(|value| !value.trim().is_empty())
237 || entry
238 .get("bodyContent")
239 .and_then(Value::as_str)
240 .is_some_and(|value| !value.trim().is_empty())
241 || entry
242 .pointer("/body/content")
243 .and_then(Value::as_str)
244 .is_some_and(|value| !value.trim().is_empty())
245}
246
247fn merge_detail_bodies(mut graph: Value, teams: Value) -> Value {
248 if let Some(content) = teams.get("bodyContent").cloned() {
249 match graph.as_object_mut() {
250 Some(map) => {
251 map.entry("bodyContent").or_insert(content);
252 }
253 None => return teams,
254 }
255 }
256 if let Some(attendees) = teams.get("attendees").cloned() {
257 if graph.get("attendees").and_then(Value::as_array).is_none_or(|a| a.is_empty()) {
258 if let Some(map) = graph.as_object_mut() {
259 map.insert("attendees".into(), attendees);
260 }
261 }
262 }
263 graph
264}
265
219impl<T: CardTransport> Calendar<T> {
266impl<T: CardTransport> Calendar<T> {
220 pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
267 pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
221 self.create_event_body(event, new_event_body(event)).await
268 self.create_event_body(event, new_event_body(event)).await
@@ -255,8 +302,11 @@ impl<T: CardTransport> Calendar<T> {
255 ical_uid: Option<&str>,
302 ical_uid: Option<&str>,
256 reply: Reply,
303 reply: Reply,
257 send_response: bool,
304 send_response: bool,
305 comment: &str,
258 ) -> Result<()> {
306 ) -> Result<()> {
259 let answer = self.send_reply(event_id, reply, send_response).await?;
307 let answer = self
308 .send_reply(event_id, reply, send_response, comment)
309 .await?;
260 if answer.is_success() {
310 if answer.is_success() {
261 return Ok(());
311 return Ok(());
262 }
312 }
@@ -264,13 +314,57 @@ impl<T: CardTransport> Calendar<T> {
264 return Err(api_error(answer, &reply_url(event_id, reply)));
314 return Err(api_error(answer, &reply_url(event_id, reply)));
265 };
315 };
266 let graph_id = self.graph_event_id(ical_uid).await?;
316 let graph_id = self.graph_event_id(ical_uid).await?;
267 let retried = self.send_reply(&graph_id, reply, send_response).await?;
317 let retried = self
318 .send_reply(&graph_id, reply, send_response, comment)
319 .await?;
268 if retried.is_success() {
320 if retried.is_success() {
269 return Ok(());
321 return Ok(());
270 }
322 }
271 Err(api_error(retried, &reply_url(&graph_id, reply)))
323 Err(api_error(retried, &reply_url(&graph_id, reply)))
272 }
324 }
273
325
326 pub async fn event_details(
327 &self,
328 event_id: &str,
329 ical_uid: Option<&str>,
330 ) -> Result<Value> {
331 let answer = self.fetch_event(event_id).await?;
332 if answer.is_success() {
333 if details_have_agenda(&answer.body) {
334 return Ok(answer.body);
335 }
336 // Graph can return RSVP fields with an empty body on occurrences;
337 // Teams MT beta carries bodyContent + attendees for the same objectId.
338 if let Ok(teams) = self.fetch_teams_event(event_id).await {
339 if teams.is_success() && details_have_agenda(&teams.body) {
340 return Ok(merge_detail_bodies(answer.body, teams.body));
341 }
342 }
343 return Ok(answer.body);
344 }
345 if let Ok(teams) = self.fetch_teams_event(event_id).await {
346 if teams.is_success() {
347 return Ok(teams.body);
348 }
349 }
350 let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
351 return Err(api_error(answer, &event_details_url(event_id)));
352 };
353 let graph_id = self.graph_event_id(ical_uid).await?;
354 let retried = self.fetch_event(&graph_id).await?;
355 if retried.is_success() {
356 return Ok(retried.body);
357 }
358 Err(api_error(retried, &event_details_url(&graph_id)))
359 }
360
361 async fn fetch_teams_event(&self, event_id: &str) -> Result<session::ApiResponse> {
362 let url = self.teams_event_url(event_id);
363 self.transport
364 .send(Request::get(&url), crate::cards::spaces_scope())
365 .await
366 }
367
274 pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {
368 pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> {
275 let answer = self.send_delete(event_id).await?;
369 let answer = self.send_delete(event_id).await?;
276 if answer.is_success() {
370 if answer.is_success() {
@@ -301,17 +395,30 @@ impl<T: CardTransport> Calendar<T> {
301 event_id: &str,
395 event_id: &str,
302 reply: Reply,
396 reply: Reply,
303 send_response: bool,
397 send_response: bool,
398 comment: &str,
304 ) -> Result<session::ApiResponse> {
399 ) -> Result<session::ApiResponse> {
305 let request = Request::with_body(
400 let request = Request::with_body(
306 Method::Post,
401 Method::Post,
307 reply_url(event_id, reply),
402 reply_url(event_id, reply),
308 json!({"comment": "", "sendResponse": send_response}),
403 json!({
404 "comment": if send_response { comment } else { "" },
405 "sendResponse": send_response,
406 }),
309 );
407 );
310 self.transport
408 self.transport
311 .send(request, Scope::graph(CALENDARS_SCOPE))
409 .send(request, Scope::graph(CALENDARS_SCOPE))
312 .await
410 .await
313 }
411 }
314
412
413 async fn fetch_event(&self, event_id: &str) -> Result<session::ApiResponse> {
414 self.transport
415 .send(
416 Request::get(event_details_url(event_id)),
417 Scope::graph(CALENDARS_SCOPE),
418 )
419 .await
420 }
421
315 async fn graph_event_id(&self, ical_uid: &str) -> Result<String> {
422 async fn graph_event_id(&self, ical_uid: &str) -> Result<String> {
316 let url = lookup_url(ical_uid);
423 let url = lookup_url(ical_uid);
317 let answer = self
424 let answer = self
@@ -355,7 +462,12 @@ mod tests {
355
462
356 impl CardTransport for Scripted {
463 impl CardTransport for Scripted {
357 async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> {
464 async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> {
358 assert_eq!(scope, Scope::graph(CALENDARS_SCOPE));
465 let graph = Scope::graph(CALENDARS_SCOPE);
466 let spaces = crate::cards::spaces_scope();
467 assert!(
468 scope == graph || scope == spaces,
469 "unexpected scope {scope:?}"
470 );
359 self.sent
471 self.sent
360 .lock()
472 .lock()
361 .unwrap()
473 .unwrap()
@@ -557,7 +669,7 @@ mod tests {
557 async fn respond_posts_the_reply_with_the_send_flag() {
669 async fn respond_posts_the_reply_with_the_send_flag() {
558 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
670 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
559 calendar
671 calendar
560 .respond("AAMk=", None, Reply::Tentative, false)
672 .respond("AAMk=", None, Reply::Tentative, false, "ignored")
561 .await
673 .await
562 .unwrap();
674 .unwrap();
563 let sent = calendar.transport.sent.lock().unwrap();
675 let sent = calendar.transport.sent.lock().unwrap();
@@ -571,6 +683,81 @@ mod tests {
571 );
683 );
572 }
684 }
573
685
686 #[tokio::test]
687 async fn respond_includes_comment_when_sending() {
688 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
689 calendar
690 .respond("AAMk=", None, Reply::Accept, true, "See you there")
691 .await
692 .unwrap();
693 let sent = calendar.transport.sent.lock().unwrap();
694 assert_eq!(
695 sent[0].2,
696 Some(json!({"comment": "See you there", "sendResponse": true}))
697 );
698 }
699
700 #[tokio::test]
701 async fn event_details_gets_selected_fields() {
702 let calendar = Calendar::with_transport(
703 Scripted::new(vec![(
704 200,
705 json!({
706 "id": "AAMk=",
707 "bodyPreview": "Agenda",
708 "location": {"displayName": "Microsoft Teams Meeting"},
709 "type": "occurrence",
710 "seriesMasterId": "master",
711 "attendees": [
712 {"status": {"response": "accepted"}},
713 {"status": {"response": "declined"}},
714 {"status": {"response": "none"}},
715 ]
716 }),
717 )]),
718 "emea",
719 );
720 let body = calendar.event_details("AAMk=", None).await.unwrap();
721 assert_eq!(body["bodyPreview"], "Agenda");
722 let sent = calendar.transport.sent.lock().unwrap();
723 assert_eq!(sent[0].0, Method::Get);
724 assert!(sent[0].1.contains("/me/events/AAMk%3D?"));
725 assert!(sent[0].1.contains("bodyPreview"));
726 assert!(sent[0].1.contains("body"));
727 }
728
729 #[tokio::test]
730 async fn event_details_merges_teams_body_when_graph_agenda_empty() {
731 let calendar = Calendar::with_transport(
732 Scripted::new(vec![
733 (
734 200,
735 json!({
736 "id": "AAMk=",
737 "bodyPreview": "",
738 "attendees": [{"status": {"response": "accepted"}}]
739 }),
740 ),
741 (
742 200,
743 json!({
744 "bodyContent": "<p>Daily agenda</p>",
745 "attendees": [
746 {"status": {"response": "Accepted"}},
747 {"status": {"response": "NotResponded"}},
748 ]
749 }),
750 ),
751 ]),
752 "emea",
753 );
754 let body = calendar.event_details("AAMk=", None).await.unwrap();
755 assert_eq!(body["bodyContent"], "<p>Daily agenda</p>");
756 let sent = calendar.transport.sent.lock().unwrap();
757 assert!(sent[0].1.contains("graph.microsoft.com"));
758 assert!(sent[1].1.contains("/beta/me/calendarEvents/"));
759 }
760
574 #[tokio::test]
761 #[tokio::test]
575 async fn delete_event_sends_graph_delete() {
762 async fn delete_event_sends_graph_delete() {
576 let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");
763 let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea");
@@ -594,7 +781,7 @@ mod tests {
594 "emea",
781 "emea",
595 );
782 );
596 calendar
783 calendar
597 .respond("mt-id", Some("uid-1"), Reply::Decline, true)
784 .respond("mt-id", Some("uid-1"), Reply::Decline, true, "")
598 .await
785 .await
599 .unwrap();
786 .unwrap();
600 let sent = calendar.transport.sent.lock().unwrap();
787 let sent = calendar.transport.sent.lock().unwrap();
@@ -610,7 +797,7 @@ mod tests {
610 );
797 );
611 assert!(
798 assert!(
612 calendar
799 calendar
613 .respond("mt-id", None, Reply::Accept, true)
800 .respond("mt-id", None, Reply::Accept, true, "")
614 .await
801 .await
615 .is_err()
802 .is_err()
616 );
803 );
crates/chatsvc/src/google_calendar/merge.rs +33 −0
@@ -18,6 +18,39 @@ pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
18 18 if existing.thread_id.is_none() {
19 19 existing.thread_id = event.thread_id.clone();
20 20 }
21 if existing.location.is_none() {
22 existing.location = event.location.clone();
23 }
24 if existing.body_preview.is_none() {
25 existing.body_preview = event.body_preview.clone();
26 }
27 if existing.body_html.is_none() {
28 existing.body_html = event.body_html.clone();
29 }
30 if existing.response_counts.is_none() {
31 existing.response_counts = event.response_counts;
32 }
33 if existing.attendees.is_empty() {
34 existing.attendees = event.attendees.clone();
35 }
36 if existing.reminders.is_empty() {
37 existing.reminders = event.reminders.clone();
38 }
39 if existing.source_link.is_none() {
40 existing.source_link = event.source_link.clone();
41 }
42 if existing.web_link.is_none() {
43 existing.web_link = event.web_link.clone();
44 }
45 if existing.calendar_name.is_none() {
46 existing.calendar_name = event.calendar_name.clone();
47 }
48 if event.series {
49 existing.series = true;
50 }
51 if existing.series_master_id.is_none() {
52 existing.series_master_id = event.series_master_id.clone();
53 }
21 54 // Prefer Outlook object id when both sides contribute.
22 55 if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
23 56 {
@@ -18,6 +18,39 @@ pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
18 if existing.thread_id.is_none() {
18 if existing.thread_id.is_none() {
19 existing.thread_id = event.thread_id.clone();
19 existing.thread_id = event.thread_id.clone();
20 }
20 }
21 if existing.location.is_none() {
22 existing.location = event.location.clone();
23 }
24 if existing.body_preview.is_none() {
25 existing.body_preview = event.body_preview.clone();
26 }
27 if existing.body_html.is_none() {
28 existing.body_html = event.body_html.clone();
29 }
30 if existing.response_counts.is_none() {
31 existing.response_counts = event.response_counts;
32 }
33 if existing.attendees.is_empty() {
34 existing.attendees = event.attendees.clone();
35 }
36 if existing.reminders.is_empty() {
37 existing.reminders = event.reminders.clone();
38 }
39 if existing.source_link.is_none() {
40 existing.source_link = event.source_link.clone();
41 }
42 if existing.web_link.is_none() {
43 existing.web_link = event.web_link.clone();
44 }
45 if existing.calendar_name.is_none() {
46 existing.calendar_name = event.calendar_name.clone();
47 }
48 if event.series {
49 existing.series = true;
50 }
51 if existing.series_master_id.is_none() {
52 existing.series_master_id = event.series_master_id.clone();
53 }
21 // Prefer Outlook object id when both sides contribute.
54 // Prefer Outlook object id when both sides contribute.
22 if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
55 if existing.source == CalendarSource::Google && event.source == CalendarSource::Outlook
23 {
56 {
crates/chatsvc/src/google_calendar/parse.rs +311 −2
@@ -1,7 +1,10 @@
1 1 use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2 2 use serde_json::Value;
3 3
4 use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};
4 use crate::calendar::{
5 AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
6 strip_html, truncate_preview,
7 };
5 8
6 9 pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
7 10 body.get("items")
@@ -30,12 +33,13 @@ pub fn parse_google_events(
30 33 account_id: Option<&str>,
31 34 calendar_id: Option<&str>,
32 35 ) -> Vec<CalendarEvent> {
36 let defaults = default_reminder_minutes(body);
33 37 let mut events: Vec<CalendarEvent> = body
34 38 .get("items")
35 39 .and_then(Value::as_array)
36 40 .into_iter()
37 41 .flatten()
38 .filter_map(|entry| parse_event(entry, account_id, calendar_id))
42 .filter_map(|entry| parse_event(entry, account_id, calendar_id, &defaults))
39 43 .collect();
40 44 events.sort_by_key(|event| (event.start, event.end));
41 45 events
@@ -45,6 +49,7 @@ fn parse_event(
45 49 entry: &Value,
46 50 account_id: Option<&str>,
47 51 calendar_id: Option<&str>,
52 default_reminders: &[u32],
48 53 ) -> Option<CalendarEvent> {
49 54 if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
50 55 // Still show cancelled when times exist.
@@ -62,6 +67,21 @@ fn parse_event(
62 67 .map(str::to_owned)
63 68 })
64 69 });
70 let location = text(entry, "location").filter(|value| !value.contains("teams.microsoft.com"));
71 let description = text(entry, "description");
72 let body_preview = description
73 .as_ref()
74 .map(|value| truncate_preview(&strip_html(value)))
75 .filter(|value| !value.is_empty());
76 let body_html = description
77 .as_ref()
78 .filter(|value| !value.trim().is_empty())
79 .map(|value| description_html(value));
80 let series = entry
81 .get("recurrence")
82 .and_then(Value::as_array)
83 .is_some_and(|items| !items.is_empty())
84 || entry.get("recurringEventId").is_some();
65 85 Some(CalendarEvent {
66 86 object_id,
67 87 subject: text(entry, "summary").unwrap_or_default(),
@@ -88,9 +108,189 @@ fn parse_event(
88 108 account_id: account_id.map(str::to_owned),
89 109 calendar_id: calendar_id.map(str::to_owned),
90 110 sources: vec![CalendarSource::Google],
111 location,
112 body_preview,
113 body_html,
114 series,
115 series_master_id: text(entry, "recurringEventId"),
116 response_counts: google_response_counts(entry),
117 attendees: google_attendees(entry),
118 reminders: google_reminders(entry, default_reminders),
119 source_link: google_source_link(entry),
120 web_link: text(entry, "htmlLink"),
121 calendar_name: None,
91 122 })
92 123 }
93 124
125 /// Plain Google descriptions become escaped HTML with links and line breaks.
126 /// Descriptions that already look like HTML are kept as-is.
127 pub fn description_html(text: &str) -> String {
128 if looks_like_html(text) {
129 return text.to_owned();
130 }
131 let escaped = text
132 .replace('&', "&amp;")
133 .replace('<', "&lt;")
134 .replace('>', "&gt;");
135 let with_links = linkify_escaped(&escaped);
136 with_links
137 .replace("\r\n", "\n")
138 .replace('\r', "\n")
139 .replace('\n', "<br>")
140 }
141
142 fn looks_like_html(text: &str) -> bool {
143 let lower = text.to_ascii_lowercase();
144 lower.contains("<br")
145 || lower.contains("<p")
146 || lower.contains("<div")
147 || lower.contains("<a ")
148 || lower.contains("<b>")
149 || lower.contains("<i>")
150 || lower.contains("<ul")
151 || lower.contains("<ol")
152 || lower.contains("<li")
153 }
154
155 fn linkify_escaped(text: &str) -> String {
156 let mut out = String::with_capacity(text.len());
157 let mut rest = text;
158 while !rest.is_empty() {
159 let next_https = rest.find("https://");
160 let next_http = rest.find("http://");
161 let (at, scheme) = match (next_https, next_http) {
162 (Some(a), Some(b)) if a <= b => (a, "https://"),
163 (Some(a), None) => (a, "https://"),
164 (None, Some(b)) => (b, "http://"),
165 (None, None) => {
166 out.push_str(rest);
167 break;
168 }
169 (Some(_), Some(b)) => (b, "http://"),
170 };
171 out.push_str(&rest[..at]);
172 rest = &rest[at..];
173 let after = &rest[scheme.len()..];
174 let end = after
175 .find(|character: char| {
176 character.is_whitespace()
177 || matches!(character, '<' | '>' | '"' | '\'' | ')' | ']' | '}')
178 })
179 .unwrap_or(after.len());
180 let mut url = format!("{}{}", scheme, &after[..end]);
181 while url
182 .chars()
183 .last()
184 .is_some_and(|character| matches!(character, '.' | ',' | ';' | ':' | '!'))
185 {
186 url.pop();
187 }
188 let href = url.replace('"', "&quot;");
189 out.push_str(&format!(r#"<a href="{href}">{url}</a>"#));
190 rest = &rest[url.len()..];
191 }
192 out
193 }
194
195 fn default_reminder_minutes(body: &Value) -> Vec<u32> {
196 reminder_minutes_from(body.get("defaultReminders"))
197 }
198
199 fn google_reminders(entry: &Value, defaults: &[u32]) -> Vec<u32> {
200 let reminders = entry.get("reminders");
201 if reminders
202 .and_then(|value| value.get("overrides"))
203 .and_then(Value::as_array)
204 .is_some_and(|items| !items.is_empty())
205 {
206 return reminder_minutes_from(reminders.and_then(|value| value.get("overrides")));
207 }
208 if reminders
209 .and_then(|value| value.get("useDefault"))
210 .and_then(Value::as_bool)
211 == Some(true)
212 {
213 return defaults.to_vec();
214 }
215 Vec::new()
216 }
217
218 fn reminder_minutes_from(list: Option<&Value>) -> Vec<u32> {
219 let Some(items) = list.and_then(Value::as_array) else {
220 return Vec::new();
221 };
222 let mut minutes: Vec<u32> = items
223 .iter()
224 .filter_map(|item| {
225 let method = item.get("method").and_then(Value::as_str).unwrap_or("popup");
226 if method != "popup" && method != "email" {
227 return None;
228 }
229 item.get("minutes")
230 .and_then(Value::as_u64)
231 .map(|value| value as u32)
232 })
233 .collect();
234 minutes.sort_unstable();
235 minutes.dedup();
236 minutes
237 }
238
239 fn google_source_link(entry: &Value) -> Option<(String, String)> {
240 let source = entry.get("source")?;
241 let url = text(source, "url").filter(|value| !value.is_empty())?;
242 let title = text(source, "title")
243 .filter(|value| !value.is_empty())
244 .unwrap_or_else(|| url.clone());
245 Some((title, url))
246 }
247
248 fn google_attendees(entry: &Value) -> Vec<EventAttendee> {
249 let Some(list) = entry.get("attendees").and_then(Value::as_array) else {
250 return Vec::new();
251 };
252 list.iter()
253 .filter(|attendee| attendee.get("resource").and_then(Value::as_bool) != Some(true))
254 .filter_map(|attendee| {
255 let address = text(attendee, "email");
256 let name = text(attendee, "displayName").or_else(|| address.clone())?;
257 let response = match attendee.get("responseStatus").and_then(Value::as_str) {
258 Some("accepted") => ResponseType::Accepted,
259 Some("declined") => ResponseType::Declined,
260 Some("tentative") => ResponseType::Tentative,
261 _ => ResponseType::NotResponded,
262 };
263 Some(EventAttendee {
264 name,
265 address,
266 response,
267 required: attendee.get("optional").and_then(Value::as_bool) != Some(true),
268 })
269 })
270 .collect()
271 }
272
273 fn google_response_counts(entry: &Value) -> Option<AttendeeResponseCounts> {
274 let attendees = entry.get("attendees")?.as_array()?;
275 if attendees.is_empty() {
276 return None;
277 }
278 let mut counts = AttendeeResponseCounts::default();
279 for attendee in attendees {
280 match attendee
281 .get("responseStatus")
282 .and_then(Value::as_str)
283 .unwrap_or("needsAction")
284 {
285 "accepted" => counts.accepted += 1,
286 "declined" => counts.declined += 1,
287 "tentative" => counts.tentative += 1,
288 _ => counts.not_responded += 1,
289 }
290 }
291 Some(counts)
292 }
293
94 294 fn conference_join_url(entry: &Value) -> Option<String> {
95 295 entry
96 296 .pointer("/conferenceData/entryPoints")
@@ -178,6 +378,115 @@ mod tests {
178 378 assert_eq!(events[0].response, ResponseType::Accepted);
179 379 }
180 380
381 #[test]
382 fn parses_location_description_series_and_counts() {
383 let body = serde_json::json!({
384 "items": [{
385 "id": "evt2",
386 "summary": "Standup",
387 "description": "Bring updates",
388 "location": "Building 3",
389 "recurrence": ["RRULE:FREQ=WEEKLY"],
390 "start": {"dateTime": "2026-11-11T09:00:00Z"},
391 "end": {"dateTime": "2026-11-11T09:30:00Z"},
392 "attendees": [
393 {"self": true, "responseStatus": "accepted"},
394 {"responseStatus": "declined"},
395 {"responseStatus": "needsAction"}
396 ]
397 }]
398 });
399 let events = parse_google_events(&body, Some("acc"), Some("primary"));
400 assert_eq!(events[0].location.as_deref(), Some("Building 3"));
401 assert_eq!(events[0].body_preview.as_deref(), Some("Bring updates"));
402 assert!(events[0].series);
403 let counts = events[0].response_counts.expect("counts");
404 assert_eq!(counts.accepted, 1);
405 assert_eq!(counts.declined, 1);
406 assert_eq!(counts.not_responded, 1);
407 }
408
409 #[test]
410 fn strips_html_from_google_description() {
411 let body = serde_json::json!({
412 "items": [{
413 "id": "html",
414 "summary": "Notes",
415 "description": "<b>Agenda</b><br> Item&nbsp;1 &amp; notes",
416 "start": {"dateTime": "2026-11-11T09:00:00Z"},
417 "end": {"dateTime": "2026-11-11T09:30:00Z"}
418 }]
419 });
420 let events = parse_google_events(&body, None, None);
421 assert_eq!(
422 events[0].body_preview.as_deref(),
423 Some("Agenda Item 1 & notes")
424 );
425 assert_eq!(
426 events[0].body_html.as_deref(),
427 Some("<b>Agenda</b><br> Item&nbsp;1 &amp; notes")
428 );
429 }
430
431 #[test]
432 fn plain_description_keeps_breaks_and_links() {
433 let html = description_html(
434 "source: llm\nCloud Native\nhttps://email.linuxfoundation.org/foo?x=1\nFrom: CNCF",
435 );
436 assert!(html.contains("source: llm<br>Cloud Native<br>"));
437 assert!(html.contains(
438 r#"<a href="https://email.linuxfoundation.org/foo?x=1">https://email.linuxfoundation.org/foo?x=1</a>"#
439 ));
440 assert!(html.ends_with("From: CNCF") || html.contains("From: CNCF"));
441 assert!(!html.contains("<br><br>From") || html.contains("<br>From: CNCF"));
442 }
443
444 #[test]
445 fn reminders_from_overrides_and_defaults() {
446 let body = serde_json::json!({
447 "defaultReminders": [
448 {"method": "popup", "minutes": 10},
449 {"method": "email", "minutes": 1440}
450 ],
451 "items": [
452 {
453 "id": "override",
454 "summary": "A",
455 "start": {"dateTime": "2026-11-11T09:00:00Z"},
456 "end": {"dateTime": "2026-11-11T09:30:00Z"},
457 "reminders": {
458 "useDefault": false,
459 "overrides": [
460 {"method": "popup", "minutes": 5},
461 {"method": "popup", "minutes": 30},
462 {"method": "email", "minutes": 15}
463 ]
464 },
465 "source": {"title": "[Mail] KubeCon", "url": "https://mail.example/1"},
466 "htmlLink": "https://calendar.google.com/event?eid=abc"
467 },
468 {
469 "id": "default",
470 "summary": "B",
471 "start": {"dateTime": "2026-11-11T10:00:00Z"},
472 "end": {"dateTime": "2026-11-11T10:30:00Z"},
473 "reminders": {"useDefault": true}
474 }
475 ]
476 });
477 let events = parse_google_events(&body, None, None);
478 assert_eq!(events[0].reminders, vec![5, 15, 30]);
479 assert_eq!(
480 events[0].source_link.as_ref().map(|(t, u)| (t.as_str(), u.as_str())),
481 Some(("[Mail] KubeCon", "https://mail.example/1"))
482 );
483 assert_eq!(
484 events[0].web_link.as_deref(),
485 Some("https://calendar.google.com/event?eid=abc")
486 );
487 assert_eq!(events[1].reminders, vec![10, 1440]);
488 }
489
181 490 #[test]
182 491 fn parses_all_day_and_calendar_list() {
183 492 let body = serde_json::json!({
@@ -1,7 +1,10 @@
1use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
1use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2use serde_json::Value;
2use serde_json::Value;
3
3
4use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};
4use crate::calendar::{
5 AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
6 strip_html, truncate_preview,
7};
5
8
6pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
9pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
7 body.get("items")
10 body.get("items")
@@ -30,12 +33,13 @@ pub fn parse_google_events(
30 account_id: Option<&str>,
33 account_id: Option<&str>,
31 calendar_id: Option<&str>,
34 calendar_id: Option<&str>,
32) -> Vec<CalendarEvent> {
35) -> Vec<CalendarEvent> {
36 let defaults = default_reminder_minutes(body);
33 let mut events: Vec<CalendarEvent> = body
37 let mut events: Vec<CalendarEvent> = body
34 .get("items")
38 .get("items")
35 .and_then(Value::as_array)
39 .and_then(Value::as_array)
36 .into_iter()
40 .into_iter()
37 .flatten()
41 .flatten()
38 .filter_map(|entry| parse_event(entry, account_id, calendar_id))
42 .filter_map(|entry| parse_event(entry, account_id, calendar_id, &defaults))
39 .collect();
43 .collect();
40 events.sort_by_key(|event| (event.start, event.end));
44 events.sort_by_key(|event| (event.start, event.end));
41 events
45 events
@@ -45,6 +49,7 @@ fn parse_event(
45 entry: &Value,
49 entry: &Value,
46 account_id: Option<&str>,
50 account_id: Option<&str>,
47 calendar_id: Option<&str>,
51 calendar_id: Option<&str>,
52 default_reminders: &[u32],
48) -> Option<CalendarEvent> {
53) -> Option<CalendarEvent> {
49 if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
54 if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
50 // Still show cancelled when times exist.
55 // Still show cancelled when times exist.
@@ -62,6 +67,21 @@ fn parse_event(
62 .map(str::to_owned)
67 .map(str::to_owned)
63 })
68 })
64 });
69 });
70 let location = text(entry, "location").filter(|value| !value.contains("teams.microsoft.com"));
71 let description = text(entry, "description");
72 let body_preview = description
73 .as_ref()
74 .map(|value| truncate_preview(&strip_html(value)))
75 .filter(|value| !value.is_empty());
76 let body_html = description
77 .as_ref()
78 .filter(|value| !value.trim().is_empty())
79 .map(|value| description_html(value));
80 let series = entry
81 .get("recurrence")
82 .and_then(Value::as_array)
83 .is_some_and(|items| !items.is_empty())
84 || entry.get("recurringEventId").is_some();
65 Some(CalendarEvent {
85 Some(CalendarEvent {
66 object_id,
86 object_id,
67 subject: text(entry, "summary").unwrap_or_default(),
87 subject: text(entry, "summary").unwrap_or_default(),
@@ -88,9 +108,189 @@ fn parse_event(
88 account_id: account_id.map(str::to_owned),
108 account_id: account_id.map(str::to_owned),
89 calendar_id: calendar_id.map(str::to_owned),
109 calendar_id: calendar_id.map(str::to_owned),
90 sources: vec![CalendarSource::Google],
110 sources: vec![CalendarSource::Google],
111 location,
112 body_preview,
113 body_html,
114 series,
115 series_master_id: text(entry, "recurringEventId"),
116 response_counts: google_response_counts(entry),
117 attendees: google_attendees(entry),
118 reminders: google_reminders(entry, default_reminders),
119 source_link: google_source_link(entry),
120 web_link: text(entry, "htmlLink"),
121 calendar_name: None,
91 })
122 })
92}
123}
93
124
125/// Plain Google descriptions become escaped HTML with links and line breaks.
126/// Descriptions that already look like HTML are kept as-is.
127pub fn description_html(text: &str) -> String {
128 if looks_like_html(text) {
129 return text.to_owned();
130 }
131 let escaped = text
132 .replace('&', "&amp;")
133 .replace('<', "&lt;")
134 .replace('>', "&gt;");
135 let with_links = linkify_escaped(&escaped);
136 with_links
137 .replace("\r\n", "\n")
138 .replace('\r', "\n")
139 .replace('\n', "<br>")
140}
141
142fn looks_like_html(text: &str) -> bool {
143 let lower = text.to_ascii_lowercase();
144 lower.contains("<br")
145 || lower.contains("<p")
146 || lower.contains("<div")
147 || lower.contains("<a ")
148 || lower.contains("<b>")
149 || lower.contains("<i>")
150 || lower.contains("<ul")
151 || lower.contains("<ol")
152 || lower.contains("<li")
153}
154
155fn linkify_escaped(text: &str) -> String {
156 let mut out = String::with_capacity(text.len());
157 let mut rest = text;
158 while !rest.is_empty() {
159 let next_https = rest.find("https://");
160 let next_http = rest.find("http://");
161 let (at, scheme) = match (next_https, next_http) {
162 (Some(a), Some(b)) if a <= b => (a, "https://"),
163 (Some(a), None) => (a, "https://"),
164 (None, Some(b)) => (b, "http://"),
165 (None, None) => {
166 out.push_str(rest);
167 break;
168 }
169 (Some(_), Some(b)) => (b, "http://"),
170 };
171 out.push_str(&rest[..at]);
172 rest = &rest[at..];
173 let after = &rest[scheme.len()..];
174 let end = after
175 .find(|character: char| {
176 character.is_whitespace()
177 || matches!(character, '<' | '>' | '"' | '\'' | ')' | ']' | '}')
178 })
179 .unwrap_or(after.len());
180 let mut url = format!("{}{}", scheme, &after[..end]);
181 while url
182 .chars()
183 .last()
184 .is_some_and(|character| matches!(character, '.' | ',' | ';' | ':' | '!'))
185 {
186 url.pop();
187 }
188 let href = url.replace('"', "&quot;");
189 out.push_str(&format!(r#"<a href="{href}">{url}</a>"#));
190 rest = &rest[url.len()..];
191 }
192 out
193}
194
195fn default_reminder_minutes(body: &Value) -> Vec<u32> {
196 reminder_minutes_from(body.get("defaultReminders"))
197}
198
199fn google_reminders(entry: &Value, defaults: &[u32]) -> Vec<u32> {
200 let reminders = entry.get("reminders");
201 if reminders
202 .and_then(|value| value.get("overrides"))
203 .and_then(Value::as_array)
204 .is_some_and(|items| !items.is_empty())
205 {
206 return reminder_minutes_from(reminders.and_then(|value| value.get("overrides")));
207 }
208 if reminders
209 .and_then(|value| value.get("useDefault"))
210 .and_then(Value::as_bool)
211 == Some(true)
212 {
213 return defaults.to_vec();
214 }
215 Vec::new()
216}
217
218fn reminder_minutes_from(list: Option<&Value>) -> Vec<u32> {
219 let Some(items) = list.and_then(Value::as_array) else {
220 return Vec::new();
221 };
222 let mut minutes: Vec<u32> = items
223 .iter()
224 .filter_map(|item| {
225 let method = item.get("method").and_then(Value::as_str).unwrap_or("popup");
226 if method != "popup" && method != "email" {
227 return None;
228 }
229 item.get("minutes")
230 .and_then(Value::as_u64)
231 .map(|value| value as u32)
232 })
233 .collect();
234 minutes.sort_unstable();
235 minutes.dedup();
236 minutes
237}
238
239fn google_source_link(entry: &Value) -> Option<(String, String)> {
240 let source = entry.get("source")?;
241 let url = text(source, "url").filter(|value| !value.is_empty())?;
242 let title = text(source, "title")
243 .filter(|value| !value.is_empty())
244 .unwrap_or_else(|| url.clone());
245 Some((title, url))
246}
247
248fn google_attendees(entry: &Value) -> Vec<EventAttendee> {
249 let Some(list) = entry.get("attendees").and_then(Value::as_array) else {
250 return Vec::new();
251 };
252 list.iter()
253 .filter(|attendee| attendee.get("resource").and_then(Value::as_bool) != Some(true))
254 .filter_map(|attendee| {
255 let address = text(attendee, "email");
256 let name = text(attendee, "displayName").or_else(|| address.clone())?;
257 let response = match attendee.get("responseStatus").and_then(Value::as_str) {
258 Some("accepted") => ResponseType::Accepted,
259 Some("declined") => ResponseType::Declined,
260 Some("tentative") => ResponseType::Tentative,
261 _ => ResponseType::NotResponded,
262 };
263 Some(EventAttendee {
264 name,
265 address,
266 response,
267 required: attendee.get("optional").and_then(Value::as_bool) != Some(true),
268 })
269 })
270 .collect()
271}
272
273fn google_response_counts(entry: &Value) -> Option<AttendeeResponseCounts> {
274 let attendees = entry.get("attendees")?.as_array()?;
275 if attendees.is_empty() {
276 return None;
277 }
278 let mut counts = AttendeeResponseCounts::default();
279 for attendee in attendees {
280 match attendee
281 .get("responseStatus")
282 .and_then(Value::as_str)
283 .unwrap_or("needsAction")
284 {
285 "accepted" => counts.accepted += 1,
286 "declined" => counts.declined += 1,
287 "tentative" => counts.tentative += 1,
288 _ => counts.not_responded += 1,
289 }
290 }
291 Some(counts)
292}
293
94fn conference_join_url(entry: &Value) -> Option<String> {
294fn conference_join_url(entry: &Value) -> Option<String> {
95 entry
295 entry
96 .pointer("/conferenceData/entryPoints")
296 .pointer("/conferenceData/entryPoints")
@@ -178,6 +378,115 @@ mod tests {
178 assert_eq!(events[0].response, ResponseType::Accepted);
378 assert_eq!(events[0].response, ResponseType::Accepted);
179 }
379 }
180
380
381 #[test]
382 fn parses_location_description_series_and_counts() {
383 let body = serde_json::json!({
384 "items": [{
385 "id": "evt2",
386 "summary": "Standup",
387 "description": "Bring updates",
388 "location": "Building 3",
389 "recurrence": ["RRULE:FREQ=WEEKLY"],
390 "start": {"dateTime": "2026-11-11T09:00:00Z"},
391 "end": {"dateTime": "2026-11-11T09:30:00Z"},
392 "attendees": [
393 {"self": true, "responseStatus": "accepted"},
394 {"responseStatus": "declined"},
395 {"responseStatus": "needsAction"}
396 ]
397 }]
398 });
399 let events = parse_google_events(&body, Some("acc"), Some("primary"));
400 assert_eq!(events[0].location.as_deref(), Some("Building 3"));
401 assert_eq!(events[0].body_preview.as_deref(), Some("Bring updates"));
402 assert!(events[0].series);
403 let counts = events[0].response_counts.expect("counts");
404 assert_eq!(counts.accepted, 1);
405 assert_eq!(counts.declined, 1);
406 assert_eq!(counts.not_responded, 1);
407 }
408
409 #[test]
410 fn strips_html_from_google_description() {
411 let body = serde_json::json!({
412 "items": [{
413 "id": "html",
414 "summary": "Notes",
415 "description": "<b>Agenda</b><br> Item&nbsp;1 &amp; notes",
416 "start": {"dateTime": "2026-11-11T09:00:00Z"},
417 "end": {"dateTime": "2026-11-11T09:30:00Z"}
418 }]
419 });
420 let events = parse_google_events(&body, None, None);
421 assert_eq!(
422 events[0].body_preview.as_deref(),
423 Some("Agenda Item 1 & notes")
424 );
425 assert_eq!(
426 events[0].body_html.as_deref(),
427 Some("<b>Agenda</b><br> Item&nbsp;1 &amp; notes")
428 );
429 }
430
431 #[test]
432 fn plain_description_keeps_breaks_and_links() {
433 let html = description_html(
434 "source: llm\nCloud Native\nhttps://email.linuxfoundation.org/foo?x=1\nFrom: CNCF",
435 );
436 assert!(html.contains("source: llm<br>Cloud Native<br>"));
437 assert!(html.contains(
438 r#"<a href="https://email.linuxfoundation.org/foo?x=1">https://email.linuxfoundation.org/foo?x=1</a>"#
439 ));
440 assert!(html.ends_with("From: CNCF") || html.contains("From: CNCF"));
441 assert!(!html.contains("<br><br>From") || html.contains("<br>From: CNCF"));
442 }
443
444 #[test]
445 fn reminders_from_overrides_and_defaults() {
446 let body = serde_json::json!({
447 "defaultReminders": [
448 {"method": "popup", "minutes": 10},
449 {"method": "email", "minutes": 1440}
450 ],
451 "items": [
452 {
453 "id": "override",
454 "summary": "A",
455 "start": {"dateTime": "2026-11-11T09:00:00Z"},
456 "end": {"dateTime": "2026-11-11T09:30:00Z"},
457 "reminders": {
458 "useDefault": false,
459 "overrides": [
460 {"method": "popup", "minutes": 5},
461 {"method": "popup", "minutes": 30},
462 {"method": "email", "minutes": 15}
463 ]
464 },
465 "source": {"title": "[Mail] KubeCon", "url": "https://mail.example/1"},
466 "htmlLink": "https://calendar.google.com/event?eid=abc"
467 },
468 {
469 "id": "default",
470 "summary": "B",
471 "start": {"dateTime": "2026-11-11T10:00:00Z"},
472 "end": {"dateTime": "2026-11-11T10:30:00Z"},
473 "reminders": {"useDefault": true}
474 }
475 ]
476 });
477 let events = parse_google_events(&body, None, None);
478 assert_eq!(events[0].reminders, vec![5, 15, 30]);
479 assert_eq!(
480 events[0].source_link.as_ref().map(|(t, u)| (t.as_str(), u.as_str())),
481 Some(("[Mail] KubeCon", "https://mail.example/1"))
482 );
483 assert_eq!(
484 events[0].web_link.as_deref(),
485 Some("https://calendar.google.com/event?eid=abc")
486 );
487 assert_eq!(events[1].reminders, vec![10, 1440]);
488 }
489
181 #[test]
490 #[test]
182 fn parses_all_day_and_calendar_list() {
491 fn parses_all_day_and_calendar_list() {
183 let body = serde_json::json!({
492 let body = serde_json::json!({
crates/chatsvc/src/lib.rs +5 −4
@@ -56,10 +56,11 @@ pub use activity_feed::{
56 56 pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
57 57 pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
58 58 pub use calendar::{
59 Attendee, BusyTime, Calendar, CalendarEvent, CalendarSource, CreatedEvent, DialIn, NewEvent,
60 PersonSchedule, Reminder, Repeat, Reply, ResponseType, ShowAs, join_info_text,
61 meet_now_join_url, new_event_body, new_event_body_with_join, parse_calendar_events,
62 parse_created_event,
59 Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,
60 CreatedEvent, DialIn, EventAttendee, NewEvent, PersonSchedule, Reminder, Repeat, Reply, ResponseType, ShowAs,
61 apply_event_details, join_info_text, meet_now_join_url, new_event_body,
62 new_event_body_with_join, parse_calendar_events, parse_created_event, strip_html,
63 truncate_preview,
63 64 };
64 65 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
65 66 pub use cards::{
@@ -56,10 +56,11 @@ pub use activity_feed::{
56pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
56pub use activity_mentions::{MentionActivity, MentionKind, mentions_of};
57pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
57pub use bot_profiles::{BotProfile, BotProfiles, parse_bot_profiles};
58pub use calendar::{
58pub use calendar::{
59 Attendee, BusyTime, Calendar, CalendarEvent, CalendarSource, CreatedEvent, DialIn, NewEvent,
59 Attendee, AttendeeResponseCounts, BusyTime, Calendar, CalendarEvent, CalendarSource,
60 PersonSchedule, Reminder, Repeat, Reply, ResponseType, ShowAs, join_info_text,
60 CreatedEvent, DialIn, EventAttendee, NewEvent, PersonSchedule, Reminder, Repeat, Reply, ResponseType, ShowAs,
61 meet_now_join_url, new_event_body, new_event_body_with_join, parse_calendar_events,
61 apply_event_details, join_info_text, meet_now_join_url, new_event_body,
62 parse_created_event,
62 new_event_body_with_join, parse_calendar_events, parse_created_event, strip_html,
63 truncate_preview,
63};
64};
64pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
65pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
65pub use cards::{
66pub use cards::{
crates/chatsvc/tests/fixtures/calendar_view.json +12 −1
@@ -26,7 +26,18 @@
26 26 "organizerAddress": "mara@example.invalid",
27 27 "myResponseType": "Accepted",
28 28 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0",
29 "threadId": "19:meeting_demo1@thread.v2"
29 "threadId": "19:meeting_demo1@thread.v2",
30 "locationDisplayName": "Microsoft Teams Meeting",
31 "bodyPreview": "Daily agenda and blockers",
32 "eventType": "occurrence",
33 "seriesMasterId": "evt-standup-master",
34 "attendees": [
35 {"status": {"response": "accepted"}},
36 {"status": {"response": "accepted"}},
37 {"status": {"response": "declined"}},
38 {"status": {"response": "none"}},
39 {"status": {"response": "none"}}
40 ]
30 41 },
31 42 {
32 43 "objectId": "evt-offsite",
@@ -26,7 +26,18 @@
26 "organizerAddress": "mara@example.invalid",
26 "organizerAddress": "mara@example.invalid",
27 "myResponseType": "Accepted",
27 "myResponseType": "Accepted",
28 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0",
28 "skypeTeamsMeetingUrl": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0",
29 "threadId": "19:meeting_demo1@thread.v2"
29 "threadId": "19:meeting_demo1@thread.v2",
30 "locationDisplayName": "Microsoft Teams Meeting",
31 "bodyPreview": "Daily agenda and blockers",
32 "eventType": "occurrence",
33 "seriesMasterId": "evt-standup-master",
34 "attendees": [
35 {"status": {"response": "accepted"}},
36 {"status": {"response": "accepted"}},
37 {"status": {"response": "declined"}},
38 {"status": {"response": "none"}},
39 {"status": {"response": "none"}}
40 ]
30 },
41 },
31 {
42 {
32 "objectId": "evt-offsite",
43 "objectId": "evt-offsite",