BlueGit

ict rusty-teams

Merge pull request #31: feat(calendar): Teams-like event peek with Google fields

# Conflicts:
#	crates/app/src/i18n.rs

metis Daniel Däschle · pushed by metis

Authored 2026-11-14 · 2 weeks ago

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