BlueGit

ict rusty-teams

Merge pull request #44: feat(calendar): Teams-like view settings, grid, and list pane

- Conflict in the ADR index resolved; ADR 0015 and 0016 accepted

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
eb0afb1a8cd7e0f3a12f22d8a5a7a63ca8497a78
37 files changed +3493 −539
ROADMAP.md +4 −3
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 87 %** (103 done, 21 partial, 6 missing of 130). Partial counts half.
5 **Parity: 87 %** (103 done, 22 partial, 6 missing of 131). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18 18 | [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
21 | [Calls and meetings](#calls-and-meetings) | 63 % | 17 | 19 | 6 |
21 | [Calls and meetings](#calls-and-meetings) | 63 % | 17 | 20 | 6 |
22 22
23 23 ## Next
24 24
@@ -202,7 +202,8 @@ Feature parity with the Microsoft Teams desktop client.
202 202 | Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |
203 203 | Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |
204 204 | Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |
205 | Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
205 | Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE; release builds ship the project client, no user env). Waiting row while the browser finishes (reopen / copy link / cancel). List calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
206 | Calendar view | Partial | Day, Work week, Week, Month like Teams. Settings > Calendar: default view (Last used by default, the span survives a restart), first day of week (mailbox language region as in Outlook, override), work days and hours read from and saved to the Outlook mailbox, time scale 15/30/60 min, this or next week on a day off. Grid: day number over the weekday name, hour and lighter minor lines, off-hours shaded, now line across the week, title and organizer on one line, series icon, calendar colours. Calendar list pane: mini month, Add calendar, collapsible groups with group check box, Show all. Loads through the sign-in session (no wait for the calling engine), refreshes on the calendar poll, shows loading and a Retry notice per failed source. Demo and unit tested; live check against a real account still open |
206 207 | Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
207 208 | Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |
208 209 | Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 87 %** (103 done, 21 partial, 6 missing of 130). Partial counts half.
5**Parity: 87 %** (103 done, 22 partial, 6 missing of 131). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18| [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 6 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 100 % | 5 | 0 | 0 |
21| [Calls and meetings](#calls-and-meetings) | 63 % | 17 | 19 | 6 |
21| [Calls and meetings](#calls-and-meetings) | 63 % | 17 | 20 | 6 |
22
22
23## Next
23## Next
24
24
@@ -202,7 +202,8 @@ Feature parity with the Microsoft Teams desktop client.
202| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |
202| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Outlook-only home keeps Graph `POST /me/events` with `isOnlineMeeting`. With Google home or extra write targets: Teams join link first, then inserts per target (Outlook with join in location; Google `events.insert`). Settings > Calendar chooses home + dual-write. Body builders unit tested; live Google create needs `TEAMS_GOOGLE_CLIENT_ID` |
203| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |
203| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Outlook: Graph `accept` / `tentativelyAccept` / `decline` (+ iCalUId fallback). Google: Calendar API attendee `responseStatus` patch with `sendUpdates`. Source shown on calendar blocks |
204| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |
204| Meeting start reminder | Partial | Toast 5 min before the start of an Upcoming meeting: title, time, Join, Snooze (back at the start or first join). Corner X dismisses for good. Outlook: Snooze and X go to Graph snoozeReminder / dismissReminder; reminderView every 60 s near a meeting. Google: snooze/dismiss stay local only. Live state (green dot) from polled live-meeting state. One chime at the start or first join; quiet with sound off and during Do not disturb or a call. Ctrl+Shift+J joins from the latest. Driven by the polled calendar (Outlook + optional Google merge); push event 128 not wired |
205| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE, env `TEAMS_GOOGLE_CLIENT_ID` / optional secret), list calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
205| Google Calendar accounts | Partial | Settings > Calendar: Connect Google (OAuth Desktop + PKCE; release builds ship the project client, no user env). Waiting row while the browser finishes (reopen / copy link / cancel). List calendars, home calendar, extra write targets. Poll merges with Outlook by iCal UID / Teams join URL. Disconnect clears tokens. Manual smoke still needed against a real Google account |
206| Calendar view | Partial | Day, Work week, Week, Month like Teams. Settings > Calendar: default view (Last used by default, the span survives a restart), first day of week (mailbox language region as in Outlook, override), work days and hours read from and saved to the Outlook mailbox, time scale 15/30/60 min, this or next week on a day off. Grid: day number over the weekday name, hour and lighter minor lines, off-hours shaded, now line across the week, title and organizer on one line, series icon, calendar colours. Calendar list pane: mini month, Add calendar, collapsible groups with group check box, Show all. Loads through the sign-in session (no wait for the calling engine), refreshes on the calendar poll, shows loading and a Retry notice per failed source. Demo and unit tested; live check against a real account still open |
206| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
207| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
207| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |
208| Narrow windows in a call | Done | Controls that do not fit move into "..." (View, Reactions, Raise hand, People, Chat; mic, camera, share, "..." and Leave always stay). Below 960 px, or when a side panel would leave the call under 720 px, the chat list hides; still too narrow, the panel overlays the call. Layout guard checks 640x480, 1280x800, 1920x1080 |
208| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |
209| Give and take control | Missing | Protocol known (main-channel data channel, action codes 0-11); needs a second person and a security review |
crates/app-base/locales/app.yml +229 −0
@@ -316,6 +316,69 @@ settings:
316 316 connect_then_dual_write:
317 317 en: Connect Google, then enable dual-write on a calendar above.
318 318 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
319 section_view:
320 en: VIEW
321 de: ANSICHT
322 default_view:
323 en: Default view
324 de: Standardansicht
325 default_view_detail:
326 en: The view the calendar opens in
327 de: Die Ansicht, in der der Kalender öffnet
328 last_used:
329 en: Last used
330 de: Zuletzt verwendet
331 first_day:
332 en: First day of week
333 de: Erster Wochentag
334 first_day_detail:
335 en: Week, work week and month start on this day
336 de: Woche, Arbeitswoche und Monat beginnen an diesem Tag
337 first_day_regional:
338 en: "As in Outlook (%{day})"
339 de: "Wie in Outlook (%{day})"
340 work_days:
341 en: Work days
342 de: Arbeitstage
343 work_hours:
344 en: Work hours
345 de: Arbeitszeit
346 mailbox_detail:
347 en: Saved to your Outlook mailbox, like in Teams and Outlook
348 de: Wird wie in Teams und Outlook in Ihrem Outlook-Postfach gespeichert
349 work_start:
350 en: Start
351 de: Beginn
352 work_end:
353 en: End
354 de: Ende
355 time_scale:
356 en: Time scale
357 de: Zeitskala
358 time_scale_detail:
359 en: Height of a grid row
360 de: Höhe einer Rasterzeile
361 minutes:
362 en: "%{count} minutes"
363 de: "%{count} Minuten"
364 weekend:
365 en: Work week on a non-work day
366 de: Arbeitswoche an arbeitsfreien Tagen
367 weekend_detail:
368 en: What Today shows in Work week when today is not a work day
369 de: Was Heute in der Arbeitswoche zeigt, wenn heute kein Arbeitstag ist
370 weekend_next:
371 en: Show next week
372 de: Nächste Woche zeigen
373 weekend_this:
374 en: Show this week
375 de: Diese Woche zeigen
376 work_hours_not_saved:
377 en: Work hours were not saved to your mailbox.
378 de: Die Arbeitszeit wurde nicht im Postfach gespeichert.
379 connect_in_settings:
380 en: "Connect Google in Settings › Calendar"
381 de: "Google unter Einstellungen › Kalender verbinden"
319 382 google_label:
320 383 en: Google
321 384 de: Google
@@ -1289,6 +1352,172 @@ calendar:
1289 1352 no_title:
1290 1353 en: (No title)
1291 1354 de: (Kein Titel)
1355 view:
1356 title:
1357 en: Calendar
1358 de: Kalender
1359 today:
1360 en: Today
1361 de: Heute
1362 span_day:
1363 en: Day
1364 de: Tag
1365 span_work_week:
1366 en: Work week
1367 de: Arbeitswoche
1368 span_week:
1369 en: Week
1370 de: Woche
1371 span_month:
1372 en: Month
1373 de: Monat
1374 previous_day:
1375 en: Go to previous day
1376 de: Zum vorherigen Tag
1377 previous_week:
1378 en: Go to previous week
1379 de: Zur vorherigen Woche
1380 previous_month:
1381 en: Go to previous month
1382 de: Zum vorherigen Monat
1383 next_day:
1384 en: Go to next day
1385 de: Zum nächsten Tag
1386 next_week:
1387 en: Go to next week
1388 de: Zur nächsten Woche
1389 next_month:
1390 en: Go to next month
1391 de: Zum nächsten Monat
1392 join_with_id:
1393 en: Join with an ID
1394 de: Mit einer ID teilnehmen
1395 meet_now:
1396 en: Meet now
1397 de: Jetzt besprechen
1398 new_meeting:
1399 en: New meeting
1400 de: Neue Besprechung
1401 toggle_pane:
1402 en: Show or hide the calendar list
1403 de: Kalenderliste ein- oder ausblenden
1404 loading:
1405 en: Loading…
1406 de: Wird geladen…
1407 source_failed:
1408 en: "%{source} couldn't be loaded."
1409 de: "%{source} konnte nicht geladen werden."
1410 more:
1411 en: "+%{count} more"
1412 de: "+%{count} weitere"
1413 copy_join_info:
1414 en: Copy join info
1415 de: Teilnahmeinformationen kopieren
1416 chat_with_participants:
1417 en: Chat with participants
1418 de: Mit Teilnehmern chatten
1419 previous_month_short:
1420 en: Previous month
1421 de: Vorheriger Monat
1422 next_month_short:
1423 en: Next month
1424 de: Nächster Monat
1425 add_calendar:
1426 en: Add calendar
1427 de: Kalender hinzufügen
1428 my_calendars:
1429 en: My calendars
1430 de: Meine Kalender
1431 show_all:
1432 en: Show all
1433 de: Alle anzeigen
1434 show_fewer:
1435 en: Show fewer
1436 de: Weniger anzeigen
1437 series:
1438 en: Series
1439 de: Serie
1440 weekday:
1441 mon:
1442 en: Monday
1443 de: Montag
1444 tue:
1445 en: Tuesday
1446 de: Dienstag
1447 wed:
1448 en: Wednesday
1449 de: Mittwoch
1450 thu:
1451 en: Thursday
1452 de: Donnerstag
1453 fri:
1454 en: Friday
1455 de: Freitag
1456 sat:
1457 en: Saturday
1458 de: Samstag
1459 sun:
1460 en: Sunday
1461 de: Sonntag
1462 weekday_short:
1463 mon:
1464 en: Mon
1465 de: Mo
1466 tue:
1467 en: Tue
1468 de: Di
1469 wed:
1470 en: Wed
1471 de: Mi
1472 thu:
1473 en: Thu
1474 de: Do
1475 fri:
1476 en: Fri
1477 de: Fr
1478 sat:
1479 en: Sat
1480 de: Sa
1481 sun:
1482 en: Sun
1483 de: So
1484 month:
1485 m01:
1486 en: January
1487 de: Januar
1488 m02:
1489 en: February
1490 de: Februar
1491 m03:
1492 en: March
1493 de: März
1494 m04:
1495 en: April
1496 de: April
1497 m05:
1498 en: May
1499 de: Mai
1500 m06:
1501 en: June
1502 de: Juni
1503 m07:
1504 en: July
1505 de: Juli
1506 m08:
1507 en: August
1508 de: August
1509 m09:
1510 en: September
1511 de: September
1512 m10:
1513 en: October
1514 de: Oktober
1515 m11:
1516 en: November
1517 de: November
1518 m12:
1519 en: December
1520 de: Dezember
1292 1521 agents:
1293 1522 start:
1294 1523 new_session:
@@ -316,6 +316,69 @@ settings:
316 connect_then_dual_write:
316 connect_then_dual_write:
317 en: Connect Google, then enable dual-write on a calendar above.
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.
318 de: Google verbinden, dann oben Dual-Write für einen Kalender einschalten.
319 section_view:
320 en: VIEW
321 de: ANSICHT
322 default_view:
323 en: Default view
324 de: Standardansicht
325 default_view_detail:
326 en: The view the calendar opens in
327 de: Die Ansicht, in der der Kalender öffnet
328 last_used:
329 en: Last used
330 de: Zuletzt verwendet
331 first_day:
332 en: First day of week
333 de: Erster Wochentag
334 first_day_detail:
335 en: Week, work week and month start on this day
336 de: Woche, Arbeitswoche und Monat beginnen an diesem Tag
337 first_day_regional:
338 en: "As in Outlook (%{day})"
339 de: "Wie in Outlook (%{day})"
340 work_days:
341 en: Work days
342 de: Arbeitstage
343 work_hours:
344 en: Work hours
345 de: Arbeitszeit
346 mailbox_detail:
347 en: Saved to your Outlook mailbox, like in Teams and Outlook
348 de: Wird wie in Teams und Outlook in Ihrem Outlook-Postfach gespeichert
349 work_start:
350 en: Start
351 de: Beginn
352 work_end:
353 en: End
354 de: Ende
355 time_scale:
356 en: Time scale
357 de: Zeitskala
358 time_scale_detail:
359 en: Height of a grid row
360 de: Höhe einer Rasterzeile
361 minutes:
362 en: "%{count} minutes"
363 de: "%{count} Minuten"
364 weekend:
365 en: Work week on a non-work day
366 de: Arbeitswoche an arbeitsfreien Tagen
367 weekend_detail:
368 en: What Today shows in Work week when today is not a work day
369 de: Was Heute in der Arbeitswoche zeigt, wenn heute kein Arbeitstag ist
370 weekend_next:
371 en: Show next week
372 de: Nächste Woche zeigen
373 weekend_this:
374 en: Show this week
375 de: Diese Woche zeigen
376 work_hours_not_saved:
377 en: Work hours were not saved to your mailbox.
378 de: Die Arbeitszeit wurde nicht im Postfach gespeichert.
379 connect_in_settings:
380 en: "Connect Google in Settings › Calendar"
381 de: "Google unter Einstellungen › Kalender verbinden"
319 google_label:
382 google_label:
320 en: Google
383 en: Google
321 de: Google
384 de: Google
@@ -1289,6 +1352,172 @@ calendar:
1289 no_title:
1352 no_title:
1290 en: (No title)
1353 en: (No title)
1291 de: (Kein Titel)
1354 de: (Kein Titel)
1355 view:
1356 title:
1357 en: Calendar
1358 de: Kalender
1359 today:
1360 en: Today
1361 de: Heute
1362 span_day:
1363 en: Day
1364 de: Tag
1365 span_work_week:
1366 en: Work week
1367 de: Arbeitswoche
1368 span_week:
1369 en: Week
1370 de: Woche
1371 span_month:
1372 en: Month
1373 de: Monat
1374 previous_day:
1375 en: Go to previous day
1376 de: Zum vorherigen Tag
1377 previous_week:
1378 en: Go to previous week
1379 de: Zur vorherigen Woche
1380 previous_month:
1381 en: Go to previous month
1382 de: Zum vorherigen Monat
1383 next_day:
1384 en: Go to next day
1385 de: Zum nächsten Tag
1386 next_week:
1387 en: Go to next week
1388 de: Zur nächsten Woche
1389 next_month:
1390 en: Go to next month
1391 de: Zum nächsten Monat
1392 join_with_id:
1393 en: Join with an ID
1394 de: Mit einer ID teilnehmen
1395 meet_now:
1396 en: Meet now
1397 de: Jetzt besprechen
1398 new_meeting:
1399 en: New meeting
1400 de: Neue Besprechung
1401 toggle_pane:
1402 en: Show or hide the calendar list
1403 de: Kalenderliste ein- oder ausblenden
1404 loading:
1405 en: Loading…
1406 de: Wird geladen…
1407 source_failed:
1408 en: "%{source} couldn't be loaded."
1409 de: "%{source} konnte nicht geladen werden."
1410 more:
1411 en: "+%{count} more"
1412 de: "+%{count} weitere"
1413 copy_join_info:
1414 en: Copy join info
1415 de: Teilnahmeinformationen kopieren
1416 chat_with_participants:
1417 en: Chat with participants
1418 de: Mit Teilnehmern chatten
1419 previous_month_short:
1420 en: Previous month
1421 de: Vorheriger Monat
1422 next_month_short:
1423 en: Next month
1424 de: Nächster Monat
1425 add_calendar:
1426 en: Add calendar
1427 de: Kalender hinzufügen
1428 my_calendars:
1429 en: My calendars
1430 de: Meine Kalender
1431 show_all:
1432 en: Show all
1433 de: Alle anzeigen
1434 show_fewer:
1435 en: Show fewer
1436 de: Weniger anzeigen
1437 series:
1438 en: Series
1439 de: Serie
1440 weekday:
1441 mon:
1442 en: Monday
1443 de: Montag
1444 tue:
1445 en: Tuesday
1446 de: Dienstag
1447 wed:
1448 en: Wednesday
1449 de: Mittwoch
1450 thu:
1451 en: Thursday
1452 de: Donnerstag
1453 fri:
1454 en: Friday
1455 de: Freitag
1456 sat:
1457 en: Saturday
1458 de: Samstag
1459 sun:
1460 en: Sunday
1461 de: Sonntag
1462 weekday_short:
1463 mon:
1464 en: Mon
1465 de: Mo
1466 tue:
1467 en: Tue
1468 de: Di
1469 wed:
1470 en: Wed
1471 de: Mi
1472 thu:
1473 en: Thu
1474 de: Do
1475 fri:
1476 en: Fri
1477 de: Fr
1478 sat:
1479 en: Sat
1480 de: Sa
1481 sun:
1482 en: Sun
1483 de: So
1484 month:
1485 m01:
1486 en: January
1487 de: Januar
1488 m02:
1489 en: February
1490 de: Februar
1491 m03:
1492 en: March
1493 de: März
1494 m04:
1495 en: April
1496 de: April
1497 m05:
1498 en: May
1499 de: Mai
1500 m06:
1501 en: June
1502 de: Juni
1503 m07:
1504 en: July
1505 de: Juli
1506 m08:
1507 en: August
1508 de: August
1509 m09:
1510 en: September
1511 de: September
1512 m10:
1513 en: October
1514 de: Oktober
1515 m11:
1516 en: November
1517 de: November
1518 m12:
1519 en: December
1520 de: Dezember
1292agents:
1521agents:
1293 start:
1522 start:
1294 new_session:
1523 new_session:
crates/app-base/src/format.rs +155 −12
@@ -31,12 +31,20 @@ const WEEKDAY_WINDOW_DAYS: i64 = 6;
31 31 const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
32 32 const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
33 33 const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
34 /// Regions whose week starts on Sunday (CLDR first-day data for the common locales).
35 const SUNDAY_FIRST_LOCALES: [&str; 13] = [
36 "en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in", "ja", "ko", "zh-tw", "he", "pt-br",
37 "es-mx", "zh-hk",
38 ];
39 /// Arabic regions that start on Monday instead of Saturday.
40 const ARABIC_MONDAY_LOCALES: [&str; 2] = ["ar-ma", "ar-tn"];
34 41
35 42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36 43 pub struct DateStyle {
37 44 day_month: &'static str,
38 45 day_month_year: &'static str,
39 46 clock: &'static str,
47 first_day: Weekday,
40 48 }
41 49
42 50 thread_local! {
@@ -67,6 +75,28 @@ fn current_date_style() -> Option<DateStyle> {
67 75 DATE_STYLE.with(Cell::get)
68 76 }
69 77
78 /// First day of the week of the regional format; Monday when it is unknown.
79 pub fn regional_first_day() -> Weekday {
80 current_date_style().map_or(Weekday::Mon, |style| style.first_day)
81 }
82
83 /// First day of the week for a locale tag such as `en-CH` (CLDR region data).
84 pub fn first_day_for_locale(locale: &str) -> Weekday {
85 let locale = locale.to_ascii_lowercase().replace('_', "-");
86 let language = locale.split('-').next().unwrap_or_default().to_owned();
87 first_day_for(&locale, &language)
88 }
89
90 fn first_day_for(locale: &str, language: &str) -> Weekday {
91 if SUNDAY_FIRST_LOCALES.contains(&locale) || SUNDAY_FIRST_LOCALES.contains(&language) {
92 Weekday::Sun
93 } else if (language == "ar" && !ARABIC_MONDAY_LOCALES.contains(&locale)) || language == "fa" {
94 Weekday::Sat
95 } else {
96 Weekday::Mon
97 }
98 }
99
70 100 pub fn clock_format() -> &'static str {
71 101 current_date_style().map_or("%H:%M", |style| style.clock)
72 102 }
@@ -90,32 +120,83 @@ pub fn calendar_day_number(date: NaiveDate) -> String {
90 120 .to_string()
91 121 }
92 122
123 /// Month name in the app language (`calendar.month.mNN`), not chrono's English `%B`.
124 pub fn month_name(date: NaiveDate) -> String {
125 crate::ui_locale::tr(&format!("calendar.month.m{:02}", date.month()))
126 }
127
128 /// "November 2026" / "November 2026" — month title of the month grid.
129 pub fn month_year_label(date: NaiveDate) -> String {
130 format!("{} {}", month_name(date), date.year())
131 }
132
133 const WEEKDAY_KEYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
134
135 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
136 pub enum WeekdayWidth {
137 /// "Monday" / "Montag"
138 Full,
139 /// "Mon" / "Mo"
140 Short,
141 /// "M" / "M"
142 Letter,
143 }
144
145 /// Weekday name in the app language; chrono's `%A`/`%a` are always English.
146 pub fn weekday_name(day: Weekday, width: WeekdayWidth) -> String {
147 let key = WEEKDAY_KEYS[day.num_days_from_monday() as usize];
148 match width {
149 WeekdayWidth::Full => crate::ui_locale::tr(&format!("calendar.weekday.{key}")),
150 WeekdayWidth::Short => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}")),
151 WeekdayWidth::Letter => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}"))
152 .chars()
153 .next()
154 .map(String::from)
155 .unwrap_or_default(),
156 }
157 }
158
93 159 pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
94 160 let style = current_date_style();
95 let day = style.map_or("%-d", |style| style.day_number());
161 let day = |date: NaiveDate| {
162 date.format(style.map_or("%-d", |style| style.day_number()))
163 .to_string()
164 };
165 let (start_month, end_month) = (month_name(start), month_name(end));
96 166 if style.is_none_or(|style| style.month_first()) {
97 let from = start.format(&format!("%B {day}")).to_string();
98 let to = end.format(&format!("%B {day}, %Y")).to_string();
167 let to = format!("{end_month} {}, {}", day(end), end.year());
168 return if start == end {
169 to
170 } else if start.year() != end.year() {
171 format!("{start_month} {}, {} - {to}", day(start), start.year())
172 } else if start.month() != end.month() {
173 format!("{start_month} {} - {to}", day(start))
174 } else {
175 format!("{start_month} {}-{}, {}", day(start), day(end), end.year())
176 };
177 }
178 if style.is_some_and(|style| style.day_month.ends_with('.')) {
179 // German and other dotted styles: "16.–20. November 2026".
180 let to = format!("{}. {end_month} {}", day(end), end.year());
99 181 return if start == end {
100 182 to
101 183 } else if start.year() != end.year() {
102 format!("{} - {to}", start.format(&format!("%B {day}, %Y")))
184 format!("{}. {start_month} {} – {to}", day(start), start.year())
103 185 } else if start.month() != end.month() {
104 format!("{from} - {to}")
186 format!("{}. {start_month} – {to}", day(start))
105 187 } else {
106 format!("{from}-{}, {}", end.format(day), end.year())
188 format!("{}.–{to}", day(start))
107 189 };
108 190 }
109 let from = start.format(&format!("{day} %B")).to_string();
110 let to = end.format(&format!("{day} %B, %Y")).to_string();
191 let to = format!("{} {end_month}, {}", day(end), end.year());
111 192 if start == end {
112 193 to
113 194 } else if start.year() != end.year() {
114 format!("{} - {to}", start.format(&format!("{day} %B, %Y")))
195 format!("{} {start_month}, {} - {to}", day(start), start.year())
115 196 } else if start.month() != end.month() {
116 format!("{from} - {to}")
197 format!("{} {start_month} - {to}", day(start))
117 198 } else {
118 format!("{}-{to}", start.format(day))
199 format!("{}-{to}", day(start))
119 200 }
120 201 }
121 202
@@ -144,6 +225,7 @@ pub fn date_style(locale: &str) -> DateStyle {
144 225 day_month,
145 226 day_month_year,
146 227 clock,
228 first_day: first_day_for(&locale, language),
147 229 }
148 230 }
149 231
@@ -330,8 +412,68 @@ mod tests {
330 412
331 413 use super::*;
332 414
415 #[test]
416 fn the_first_day_of_week_follows_the_region() {
417 let first = |locale| {
418 set_date_locale(Some(locale));
419 regional_first_day()
420 };
421 assert_eq!(first("en-US"), Weekday::Sun);
422 assert_eq!(first("de-CH"), Weekday::Mon);
423 assert_eq!(first("en-GB"), Weekday::Mon);
424 assert_eq!(first("ar-SA"), Weekday::Sat);
425 assert_eq!(first("ar-MA"), Weekday::Mon);
426 assert_eq!(first("ja-JP"), Weekday::Sun);
427 assert_eq!(first_day_for_locale("en-CH"), Weekday::Mon);
428 assert_eq!(first_day_for_locale("en_US"), Weekday::Sun);
429 set_date_locale(None);
430 assert_eq!(regional_first_day(), Weekday::Mon);
431 }
432
433 #[test]
434 fn calendar_names_follow_the_app_language() {
435 let _guard = crate::ui_locale::locale_test_lock();
436 let date = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
437 rust_i18n::set_locale("de");
438 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Montag");
439 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Short), "Do");
440 assert_eq!(weekday_name(Weekday::Sun, WeekdayWidth::Letter), "S");
441 assert_eq!(month_year_label(date), "November 2026");
442 assert_eq!(
443 month_name(NaiveDate::from_ymd_opt(2026, 3, 1).unwrap()),
444 "März"
445 );
446 rust_i18n::set_locale("en");
447 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Monday");
448 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Letter), "T");
449 }
450
451 #[test]
452 fn calendar_range_reads_german_with_dots() {
453 let _guard = crate::ui_locale::locale_test_lock();
454 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
455 rust_i18n::set_locale("de");
456 set_date_locale(Some("de-CH"));
457 assert_eq!(
458 calendar_range_label(date(11, 16), date(11, 20)),
459 "16.–20. November 2026"
460 );
461 assert_eq!(
462 calendar_range_label(date(11, 30), date(12, 4)),
463 "30. November – 4. Dezember 2026"
464 );
465 assert_eq!(
466 calendar_range_label(date(11, 16), date(11, 16)),
467 "16. November 2026"
468 );
469 rust_i18n::set_locale("en");
470 set_date_locale(None);
471 }
472
333 473 #[test]
334 474 fn calendar_range_follows_the_account_locale() {
475 let _guard = crate::ui_locale::locale_test_lock();
476 rust_i18n::set_locale("en");
335 477 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
336 478 set_date_locale(Some("en-GB"));
337 479 assert_eq!(
@@ -349,10 +491,11 @@ mod tests {
349 491 "November 9-13, 2026"
350 492 );
351 493 assert_eq!(calendar_day_number(date(11, 9)), "9");
494 // Intl.DateTimeFormat in de-DE writes the day with a dot and no comma.
352 495 set_date_locale(Some("de-DE"));
353 496 assert_eq!(
354 497 calendar_range_label(date(11, 9), date(11, 9)),
355 "9 November, 2026"
498 "9. November 2026"
356 499 );
357 500 set_date_locale(None);
358 501 }
@@ -31,12 +31,20 @@ const WEEKDAY_WINDOW_DAYS: i64 = 6;
31const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
31const TWELVE_HOUR_LOCALES: [&str; 6] = ["en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in"];
32const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
32const DOTTED_LOCALES: [&str; 7] = ["de", "da", "nb", "no", "fi", "cs", "sk"];
33const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
33const PADDED_DOT_LOCALES: [&str; 4] = ["ru", "pl", "tr", "uk"];
34/// Regions whose week starts on Sunday (CLDR first-day data for the common locales).
35const SUNDAY_FIRST_LOCALES: [&str; 13] = [
36 "en-us", "en-ca", "en-ph", "en-au", "en-nz", "en-in", "ja", "ko", "zh-tw", "he", "pt-br",
37 "es-mx", "zh-hk",
38];
39/// Arabic regions that start on Monday instead of Saturday.
40const ARABIC_MONDAY_LOCALES: [&str; 2] = ["ar-ma", "ar-tn"];
34
41
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct DateStyle {
43pub struct DateStyle {
37 day_month: &'static str,
44 day_month: &'static str,
38 day_month_year: &'static str,
45 day_month_year: &'static str,
39 clock: &'static str,
46 clock: &'static str,
47 first_day: Weekday,
40}
48}
41
49
42thread_local! {
50thread_local! {
@@ -67,6 +75,28 @@ fn current_date_style() -> Option<DateStyle> {
67 DATE_STYLE.with(Cell::get)
75 DATE_STYLE.with(Cell::get)
68}
76}
69
77
78/// First day of the week of the regional format; Monday when it is unknown.
79pub fn regional_first_day() -> Weekday {
80 current_date_style().map_or(Weekday::Mon, |style| style.first_day)
81}
82
83/// First day of the week for a locale tag such as `en-CH` (CLDR region data).
84pub fn first_day_for_locale(locale: &str) -> Weekday {
85 let locale = locale.to_ascii_lowercase().replace('_', "-");
86 let language = locale.split('-').next().unwrap_or_default().to_owned();
87 first_day_for(&locale, &language)
88}
89
90fn first_day_for(locale: &str, language: &str) -> Weekday {
91 if SUNDAY_FIRST_LOCALES.contains(&locale) || SUNDAY_FIRST_LOCALES.contains(&language) {
92 Weekday::Sun
93 } else if (language == "ar" && !ARABIC_MONDAY_LOCALES.contains(&locale)) || language == "fa" {
94 Weekday::Sat
95 } else {
96 Weekday::Mon
97 }
98}
99
70pub fn clock_format() -> &'static str {
100pub fn clock_format() -> &'static str {
71 current_date_style().map_or("%H:%M", |style| style.clock)
101 current_date_style().map_or("%H:%M", |style| style.clock)
72}
102}
@@ -90,32 +120,83 @@ pub fn calendar_day_number(date: NaiveDate) -> String {
90 .to_string()
120 .to_string()
91}
121}
92
122
123/// Month name in the app language (`calendar.month.mNN`), not chrono's English `%B`.
124pub fn month_name(date: NaiveDate) -> String {
125 crate::ui_locale::tr(&format!("calendar.month.m{:02}", date.month()))
126}
127
128/// "November 2026" / "November 2026" — month title of the month grid.
129pub fn month_year_label(date: NaiveDate) -> String {
130 format!("{} {}", month_name(date), date.year())
131}
132
133const WEEKDAY_KEYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum WeekdayWidth {
137 /// "Monday" / "Montag"
138 Full,
139 /// "Mon" / "Mo"
140 Short,
141 /// "M" / "M"
142 Letter,
143}
144
145/// Weekday name in the app language; chrono's `%A`/`%a` are always English.
146pub fn weekday_name(day: Weekday, width: WeekdayWidth) -> String {
147 let key = WEEKDAY_KEYS[day.num_days_from_monday() as usize];
148 match width {
149 WeekdayWidth::Full => crate::ui_locale::tr(&format!("calendar.weekday.{key}")),
150 WeekdayWidth::Short => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}")),
151 WeekdayWidth::Letter => crate::ui_locale::tr(&format!("calendar.weekday_short.{key}"))
152 .chars()
153 .next()
154 .map(String::from)
155 .unwrap_or_default(),
156 }
157}
158
93pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
159pub fn calendar_range_label(start: NaiveDate, end: NaiveDate) -> String {
94 let style = current_date_style();
160 let style = current_date_style();
95 let day = style.map_or("%-d", |style| style.day_number());
161 let day = |date: NaiveDate| {
162 date.format(style.map_or("%-d", |style| style.day_number()))
163 .to_string()
164 };
165 let (start_month, end_month) = (month_name(start), month_name(end));
96 if style.is_none_or(|style| style.month_first()) {
166 if style.is_none_or(|style| style.month_first()) {
97 let from = start.format(&format!("%B {day}")).to_string();
167 let to = format!("{end_month} {}, {}", day(end), end.year());
98 let to = end.format(&format!("%B {day}, %Y")).to_string();
168 return if start == end {
169 to
170 } else if start.year() != end.year() {
171 format!("{start_month} {}, {} - {to}", day(start), start.year())
172 } else if start.month() != end.month() {
173 format!("{start_month} {} - {to}", day(start))
174 } else {
175 format!("{start_month} {}-{}, {}", day(start), day(end), end.year())
176 };
177 }
178 if style.is_some_and(|style| style.day_month.ends_with('.')) {
179 // German and other dotted styles: "16.–20. November 2026".
180 let to = format!("{}. {end_month} {}", day(end), end.year());
99 return if start == end {
181 return if start == end {
100 to
182 to
101 } else if start.year() != end.year() {
183 } else if start.year() != end.year() {
102 format!("{} - {to}", start.format(&format!("%B {day}, %Y")))
184 format!("{}. {start_month} {} – {to}", day(start), start.year())
103 } else if start.month() != end.month() {
185 } else if start.month() != end.month() {
104 format!("{from} - {to}")
186 format!("{}. {start_month} – {to}", day(start))
105 } else {
187 } else {
106 format!("{from}-{}, {}", end.format(day), end.year())
188 format!("{}.–{to}", day(start))
107 };
189 };
108 }
190 }
109 let from = start.format(&format!("{day} %B")).to_string();
191 let to = format!("{} {end_month}, {}", day(end), end.year());
110 let to = end.format(&format!("{day} %B, %Y")).to_string();
111 if start == end {
192 if start == end {
112 to
193 to
113 } else if start.year() != end.year() {
194 } else if start.year() != end.year() {
114 format!("{} - {to}", start.format(&format!("{day} %B, %Y")))
195 format!("{} {start_month}, {} - {to}", day(start), start.year())
115 } else if start.month() != end.month() {
196 } else if start.month() != end.month() {
116 format!("{from} - {to}")
197 format!("{} {start_month} - {to}", day(start))
117 } else {
198 } else {
118 format!("{}-{to}", start.format(day))
199 format!("{}-{to}", day(start))
119 }
200 }
120}
201}
121
202
@@ -144,6 +225,7 @@ pub fn date_style(locale: &str) -> DateStyle {
144 day_month,
225 day_month,
145 day_month_year,
226 day_month_year,
146 clock,
227 clock,
228 first_day: first_day_for(&locale, language),
147 }
229 }
148}
230}
149
231
@@ -330,8 +412,68 @@ mod tests {
330
412
331 use super::*;
413 use super::*;
332
414
415 #[test]
416 fn the_first_day_of_week_follows_the_region() {
417 let first = |locale| {
418 set_date_locale(Some(locale));
419 regional_first_day()
420 };
421 assert_eq!(first("en-US"), Weekday::Sun);
422 assert_eq!(first("de-CH"), Weekday::Mon);
423 assert_eq!(first("en-GB"), Weekday::Mon);
424 assert_eq!(first("ar-SA"), Weekday::Sat);
425 assert_eq!(first("ar-MA"), Weekday::Mon);
426 assert_eq!(first("ja-JP"), Weekday::Sun);
427 assert_eq!(first_day_for_locale("en-CH"), Weekday::Mon);
428 assert_eq!(first_day_for_locale("en_US"), Weekday::Sun);
429 set_date_locale(None);
430 assert_eq!(regional_first_day(), Weekday::Mon);
431 }
432
433 #[test]
434 fn calendar_names_follow_the_app_language() {
435 let _guard = crate::ui_locale::locale_test_lock();
436 let date = NaiveDate::from_ymd_opt(2026, 11, 16).unwrap();
437 rust_i18n::set_locale("de");
438 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Montag");
439 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Short), "Do");
440 assert_eq!(weekday_name(Weekday::Sun, WeekdayWidth::Letter), "S");
441 assert_eq!(month_year_label(date), "November 2026");
442 assert_eq!(
443 month_name(NaiveDate::from_ymd_opt(2026, 3, 1).unwrap()),
444 "März"
445 );
446 rust_i18n::set_locale("en");
447 assert_eq!(weekday_name(Weekday::Mon, WeekdayWidth::Full), "Monday");
448 assert_eq!(weekday_name(Weekday::Thu, WeekdayWidth::Letter), "T");
449 }
450
451 #[test]
452 fn calendar_range_reads_german_with_dots() {
453 let _guard = crate::ui_locale::locale_test_lock();
454 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
455 rust_i18n::set_locale("de");
456 set_date_locale(Some("de-CH"));
457 assert_eq!(
458 calendar_range_label(date(11, 16), date(11, 20)),
459 "16.–20. November 2026"
460 );
461 assert_eq!(
462 calendar_range_label(date(11, 30), date(12, 4)),
463 "30. November – 4. Dezember 2026"
464 );
465 assert_eq!(
466 calendar_range_label(date(11, 16), date(11, 16)),
467 "16. November 2026"
468 );
469 rust_i18n::set_locale("en");
470 set_date_locale(None);
471 }
472
333 #[test]
473 #[test]
334 fn calendar_range_follows_the_account_locale() {
474 fn calendar_range_follows_the_account_locale() {
475 let _guard = crate::ui_locale::locale_test_lock();
476 rust_i18n::set_locale("en");
335 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
477 let date = |month, day| NaiveDate::from_ymd_opt(2026, month, day).unwrap();
336 set_date_locale(Some("en-GB"));
478 set_date_locale(Some("en-GB"));
337 assert_eq!(
479 assert_eq!(
@@ -349,10 +491,11 @@ mod tests {
349 "November 9-13, 2026"
491 "November 9-13, 2026"
350 );
492 );
351 assert_eq!(calendar_day_number(date(11, 9)), "9");
493 assert_eq!(calendar_day_number(date(11, 9)), "9");
494 // Intl.DateTimeFormat in de-DE writes the day with a dot and no comma.
352 set_date_locale(Some("de-DE"));
495 set_date_locale(Some("de-DE"));
353 assert_eq!(
496 assert_eq!(
354 calendar_range_label(date(11, 9), date(11, 9)),
497 calendar_range_label(date(11, 9), date(11, 9)),
355 "9 November, 2026"
498 "9. November 2026"
356 );
499 );
357 set_date_locale(None);
500 set_date_locale(None);
358 }
501 }
crates/app-base/src/theme.rs +19 −0
@@ -397,6 +397,15 @@ pub fn avatar_color(index: usize) -> Hsla {
397 397 color(palette[index % palette.len()])
398 398 }
399 399
400 /// Colour of the calendar at `index` in the calendar list: Outlook (0) takes the
401 /// accent, every further calendar the next avatar palette colour.
402 pub fn calendar_color(index: usize) -> Hsla {
403 match index {
404 0 => accent(),
405 index => avatar_color(index - 1),
406 }
407 }
408
400 409 pub fn avatar_palette_len() -> usize {
401 410 palette().avatar_palette.len()
402 411 }
@@ -408,6 +417,16 @@ mod tests {
408 417 set_thread_scheme, set_thread_shade,
409 418 };
410 419
420 #[test]
421 fn calendar_colors_start_with_the_accent_then_follow_the_palette() {
422 assert_eq!(super::calendar_color(0), super::accent());
423 assert_eq!(super::calendar_color(1), avatar_color(0));
424 assert_eq!(
425 super::calendar_color(1 + avatar_palette_len()),
426 avatar_color(0)
427 );
428 }
429
411 430 #[test]
412 431 fn avatar_colors_wrap_around_the_palette() {
413 432 assert_eq!(avatar_color(0), avatar_color(avatar_palette_len()));
@@ -397,6 +397,15 @@ pub fn avatar_color(index: usize) -> Hsla {
397 color(palette[index % palette.len()])
397 color(palette[index % palette.len()])
398}
398}
399
399
400/// Colour of the calendar at `index` in the calendar list: Outlook (0) takes the
401/// accent, every further calendar the next avatar palette colour.
402pub fn calendar_color(index: usize) -> Hsla {
403 match index {
404 0 => accent(),
405 index => avatar_color(index - 1),
406 }
407}
408
400pub fn avatar_palette_len() -> usize {
409pub fn avatar_palette_len() -> usize {
401 palette().avatar_palette.len()
410 palette().avatar_palette.len()
402}
411}
@@ -408,6 +417,16 @@ mod tests {
408 set_thread_scheme, set_thread_shade,
417 set_thread_scheme, set_thread_shade,
409 };
418 };
410
419
420 #[test]
421 fn calendar_colors_start_with_the_accent_then_follow_the_palette() {
422 assert_eq!(super::calendar_color(0), super::accent());
423 assert_eq!(super::calendar_color(1), avatar_color(0));
424 assert_eq!(
425 super::calendar_color(1 + avatar_palette_len()),
426 avatar_color(0)
427 );
428 }
429
411 #[test]
430 #[test]
412 fn avatar_colors_wrap_around_the_palette() {
431 fn avatar_colors_wrap_around_the_palette() {
413 assert_eq!(avatar_color(0), avatar_color(avatar_palette_len()));
432 assert_eq!(avatar_color(0), avatar_color(avatar_palette_len()));
crates/app-base/src/ui_locale.rs +64 −5
@@ -123,16 +123,75 @@ pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124 124 }
125 125
126 /// Serialises tests in this crate that read or set the global UI language.
126 127 #[cfg(test)]
127 mod tests {
128 use std::sync::{Mutex, MutexGuard};
128 pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
129 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130 LOCK.lock().unwrap_or_else(|error| error.into_inner())
131 }
129 132
133 #[cfg(test)]
134 mod tests {
130 135 use super::*;
131 136 use tempfile::tempdir;
132 137
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
138 /// Leaf keys (`a.b.c`) with the languages they define, read from the locale file.
139 fn leaf_languages() -> Vec<(String, Vec<String>)> {
140 let mut path: Vec<(usize, String)> = Vec::new();
141 let mut leaves: Vec<(String, Vec<String>)> = Vec::new();
142 for line in include_str!("../locales/app.yml").lines() {
143 let trimmed = line.trim_start();
144 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('_') {
145 continue;
146 }
147 let indent = line.len() - trimmed.len();
148 let Some((key, value)) = trimmed.split_once(':') else {
149 continue;
150 };
151 if key == "en" || key == "de" {
152 if let Some(last) = leaves.last_mut() {
153 last.1.push(key.to_owned());
154 }
155 continue;
156 }
157 path.retain(|(depth, _)| *depth < indent);
158 path.push((indent, key.to_owned()));
159 if value.trim().is_empty() {
160 let full: Vec<&str> = path.iter().map(|(_, key)| key.as_str()).collect();
161 leaves.push((full.join("."), Vec::new()));
162 }
163 }
164 leaves.retain(|(_, languages)| !languages.is_empty());
165 leaves
166 }
167
168 #[test]
169 fn calendar_strings_exist_in_english_and_german() {
170 const PREFIXES: [&str; 5] = [
171 "calendar.view.",
172 "calendar.weekday.",
173 "calendar.weekday_short.",
174 "calendar.month.",
175 "settings.calendar.",
176 ];
177 let leaves = leaf_languages();
178 let covered: Vec<_> = leaves
179 .iter()
180 .filter(|(key, _)| PREFIXES.iter().any(|prefix| key.starts_with(prefix)))
181 .collect();
182 assert!(
183 covered.len() > 60,
184 "only {} calendar keys found",
185 covered.len()
186 );
187 let missing: Vec<_> = covered
188 .iter()
189 .filter(|(_, languages)| {
190 !(languages.contains(&"en".into()) && languages.contains(&"de".into()))
191 })
192 .map(|(key, _)| key.as_str())
193 .collect();
194 assert!(missing.is_empty(), "missing en or de: {missing:?}");
136 195 }
137 196
138 197 #[test]
@@ -123,16 +123,75 @@ pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124}
124}
125
125
126/// Serialises tests in this crate that read or set the global UI language.
126#[cfg(test)]
127#[cfg(test)]
127mod tests {
128pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
128 use std::sync::{Mutex, MutexGuard};
129 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130 LOCK.lock().unwrap_or_else(|error| error.into_inner())
131}
129
132
133#[cfg(test)]
134mod tests {
130 use super::*;
135 use super::*;
131 use tempfile::tempdir;
136 use tempfile::tempdir;
132
137
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
138 /// Leaf keys (`a.b.c`) with the languages they define, read from the locale file.
134 static LOCK: Mutex<()> = Mutex::new(());
139 fn leaf_languages() -> Vec<(String, Vec<String>)> {
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
140 let mut path: Vec<(usize, String)> = Vec::new();
141 let mut leaves: Vec<(String, Vec<String>)> = Vec::new();
142 for line in include_str!("../locales/app.yml").lines() {
143 let trimmed = line.trim_start();
144 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('_') {
145 continue;
146 }
147 let indent = line.len() - trimmed.len();
148 let Some((key, value)) = trimmed.split_once(':') else {
149 continue;
150 };
151 if key == "en" || key == "de" {
152 if let Some(last) = leaves.last_mut() {
153 last.1.push(key.to_owned());
154 }
155 continue;
156 }
157 path.retain(|(depth, _)| *depth < indent);
158 path.push((indent, key.to_owned()));
159 if value.trim().is_empty() {
160 let full: Vec<&str> = path.iter().map(|(_, key)| key.as_str()).collect();
161 leaves.push((full.join("."), Vec::new()));
162 }
163 }
164 leaves.retain(|(_, languages)| !languages.is_empty());
165 leaves
166 }
167
168 #[test]
169 fn calendar_strings_exist_in_english_and_german() {
170 const PREFIXES: [&str; 5] = [
171 "calendar.view.",
172 "calendar.weekday.",
173 "calendar.weekday_short.",
174 "calendar.month.",
175 "settings.calendar.",
176 ];
177 let leaves = leaf_languages();
178 let covered: Vec<_> = leaves
179 .iter()
180 .filter(|(key, _)| PREFIXES.iter().any(|prefix| key.starts_with(prefix)))
181 .collect();
182 assert!(
183 covered.len() > 60,
184 "only {} calendar keys found",
185 covered.len()
186 );
187 let missing: Vec<_> = covered
188 .iter()
189 .filter(|(_, languages)| {
190 !(languages.contains(&"en".into()) && languages.contains(&"de".into()))
191 })
192 .map(|(key, _)| key.as_str())
193 .collect();
194 assert!(missing.is_empty(), "missing en or de: {missing:?}");
136 }
195 }
137
196
138 #[test]
197 #[test]
crates/app-call-model/src/calendar_list.rs added +103 −0
@@ -0,0 +1,103 @@
1 //! Calendar list pane logic: group check state, Show all, mini month cells.
2
3 use chrono::{Datelike, NaiveDate};
4
5 /// Groups with more calendars than this hide the ones that are off until Show all.
6 pub const SHOW_ALL_AFTER: usize = 5;
7
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 pub enum GroupCheck {
10 All,
11 Some,
12 None,
13 }
14
15 pub fn group_check(selected: &[bool]) -> GroupCheck {
16 match selected.iter().filter(|on| **on).count() {
17 0 => GroupCheck::None,
18 count if count == selected.len() => GroupCheck::All,
19 _ => GroupCheck::Some,
20 }
21 }
22
23 /// Indexes of the calendars a group lists: all of them when short or expanded,
24 /// otherwise the ones turned on plus the primary one.
25 pub fn listed_calendars(selected: &[bool], primary: &[bool], expanded: bool) -> Vec<usize> {
26 let all = 0..selected.len();
27 if expanded || selected.len() <= SHOW_ALL_AFTER {
28 return all.collect();
29 }
30 all.filter(|&index| selected[index] || primary.get(index).copied().unwrap_or(false))
31 .collect()
32 }
33
34 /// Whether a group offers Show all / Show fewer.
35 pub fn offers_show_all(count: usize) -> bool {
36 count > SHOW_ALL_AFTER
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 pub struct MiniMonthCell {
41 pub date: NaiveDate,
42 pub in_month: bool,
43 /// Inside the range the grid shows.
44 pub shown: bool,
45 pub today: bool,
46 }
47
48 pub fn mini_month_cell(
49 date: NaiveDate,
50 month: NaiveDate,
51 shown: &[NaiveDate],
52 today: NaiveDate,
53 ) -> MiniMonthCell {
54 MiniMonthCell {
55 date,
56 in_month: date.month() == month.month() && date.year() == month.year(),
57 shown: shown.contains(&date),
58 today: date == today,
59 }
60 }
61
62 #[cfg(test)]
63 mod tests {
64 use super::*;
65
66 #[test]
67 fn the_group_box_reads_all_some_or_none() {
68 assert_eq!(group_check(&[true, true]), GroupCheck::All);
69 assert_eq!(group_check(&[true, false]), GroupCheck::Some);
70 assert_eq!(group_check(&[false, false]), GroupCheck::None);
71 }
72
73 #[test]
74 fn a_long_group_lists_the_primary_and_the_ones_on_until_show_all() {
75 let mut selected = [false; 8];
76 selected[3] = true;
77 selected[6] = true;
78 let mut primary = [false; 8];
79 primary[0] = true;
80 assert_eq!(listed_calendars(&selected, &primary, false), [0, 3, 6]);
81 assert_eq!(listed_calendars(&selected, &primary, true).len(), 8);
82 assert!(offers_show_all(8));
83 assert!(!offers_show_all(5));
84 assert_eq!(listed_calendars(&[false; 4], &[false; 4], false).len(), 4);
85 }
86
87 #[test]
88 fn mini_month_marks_the_shown_range_and_today() {
89 let day = |d| NaiveDate::from_ymd_opt(2026, 11, d).unwrap();
90 let shown: Vec<_> = (16..=20).map(day).collect();
91 let cell = mini_month_cell(day(18), day(1), &shown, day(15));
92 assert!(cell.in_month && cell.shown && !cell.today);
93 let today = mini_month_cell(day(15), day(1), &shown, day(15));
94 assert!(today.today && !today.shown);
95 let outside = mini_month_cell(
96 NaiveDate::from_ymd_opt(2026, 12, 1).unwrap(),
97 day(1),
98 &shown,
99 day(15),
100 );
101 assert!(!outside.in_month);
102 }
103 }
@@ -0,0 +1,103 @@
1//! Calendar list pane logic: group check state, Show all, mini month cells.
2
3use chrono::{Datelike, NaiveDate};
4
5/// Groups with more calendars than this hide the ones that are off until Show all.
6pub const SHOW_ALL_AFTER: usize = 5;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum GroupCheck {
10 All,
11 Some,
12 None,
13}
14
15pub fn group_check(selected: &[bool]) -> GroupCheck {
16 match selected.iter().filter(|on| **on).count() {
17 0 => GroupCheck::None,
18 count if count == selected.len() => GroupCheck::All,
19 _ => GroupCheck::Some,
20 }
21}
22
23/// Indexes of the calendars a group lists: all of them when short or expanded,
24/// otherwise the ones turned on plus the primary one.
25pub fn listed_calendars(selected: &[bool], primary: &[bool], expanded: bool) -> Vec<usize> {
26 let all = 0..selected.len();
27 if expanded || selected.len() <= SHOW_ALL_AFTER {
28 return all.collect();
29 }
30 all.filter(|&index| selected[index] || primary.get(index).copied().unwrap_or(false))
31 .collect()
32}
33
34/// Whether a group offers Show all / Show fewer.
35pub fn offers_show_all(count: usize) -> bool {
36 count > SHOW_ALL_AFTER
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct MiniMonthCell {
41 pub date: NaiveDate,
42 pub in_month: bool,
43 /// Inside the range the grid shows.
44 pub shown: bool,
45 pub today: bool,
46}
47
48pub fn mini_month_cell(
49 date: NaiveDate,
50 month: NaiveDate,
51 shown: &[NaiveDate],
52 today: NaiveDate,
53) -> MiniMonthCell {
54 MiniMonthCell {
55 date,
56 in_month: date.month() == month.month() && date.year() == month.year(),
57 shown: shown.contains(&date),
58 today: date == today,
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn the_group_box_reads_all_some_or_none() {
68 assert_eq!(group_check(&[true, true]), GroupCheck::All);
69 assert_eq!(group_check(&[true, false]), GroupCheck::Some);
70 assert_eq!(group_check(&[false, false]), GroupCheck::None);
71 }
72
73 #[test]
74 fn a_long_group_lists_the_primary_and_the_ones_on_until_show_all() {
75 let mut selected = [false; 8];
76 selected[3] = true;
77 selected[6] = true;
78 let mut primary = [false; 8];
79 primary[0] = true;
80 assert_eq!(listed_calendars(&selected, &primary, false), [0, 3, 6]);
81 assert_eq!(listed_calendars(&selected, &primary, true).len(), 8);
82 assert!(offers_show_all(8));
83 assert!(!offers_show_all(5));
84 assert_eq!(listed_calendars(&[false; 4], &[false; 4], false).len(), 4);
85 }
86
87 #[test]
88 fn mini_month_marks_the_shown_range_and_today() {
89 let day = |d| NaiveDate::from_ymd_opt(2026, 11, d).unwrap();
90 let shown: Vec<_> = (16..=20).map(day).collect();
91 let cell = mini_month_cell(day(18), day(1), &shown, day(15));
92 assert!(cell.in_month && cell.shown && !cell.today);
93 let today = mini_month_cell(day(15), day(1), &shown, day(15));
94 assert!(today.today && !today.shown);
95 let outside = mini_month_cell(
96 NaiveDate::from_ymd_opt(2026, 12, 1).unwrap(),
97 day(1),
98 &shown,
99 day(15),
100 );
101 assert!(!outside.in_month);
102 }
103}
crates/app-call-model/src/calendar_now.rs +42 −0
@@ -1,3 +1,4 @@
1 use super::calendar_prefs::TimeScale;
1 2 use super::week_grid::CalendarSpan;
2 3
3 4 /// Fraction of the hour-grid viewport used to keep «now» below the top edge.
@@ -28,6 +29,31 @@ pub fn now_scroll_offset_y(
28 29 (bias - now_y).clamp(min_offset, 0.)
29 30 }
30 31
32 /// Height of one hour row for a time scale; finer scales get taller rows.
33 pub fn hour_height(scale: TimeScale) -> f32 {
34 match scale {
35 TimeScale::Min15 => 120.,
36 TimeScale::Min30 => 96.,
37 TimeScale::Min60 => 64.,
38 }
39 }
40
41 /// Minutes shown above work start when the grid opens on a range without today.
42 pub const WORK_START_LEAD_MINUTES: i64 = 30;
43
44 /// Vertical scroll offset (negative Y) that puts work start, minus a short lead, at the top.
45 pub fn work_start_scroll_offset_y(
46 work_start_minute: i64,
47 hour_height: f32,
48 viewport_height: f32,
49 ) -> f32 {
50 let day_height = 24. * hour_height;
51 let target =
52 (work_start_minute - WORK_START_LEAD_MINUTES).clamp(0, 24 * 60) as f32 / 60. * hour_height;
53 let min_offset = -(day_height - viewport_height.max(0.)).max(0.);
54 (-target).clamp(min_offset, 0.)
55 }
56
31 57 pub fn shows_hour_grid(span: CalendarSpan) -> bool {
32 58 !matches!(span, CalendarSpan::Month)
33 59 }
@@ -70,6 +96,22 @@ mod tests {
70 96 assert!((offset - (bias - now_y)).abs() < 0.01);
71 97 }
72 98
99 #[test]
100 fn work_start_sits_at_the_top_with_a_short_lead() {
101 let hour = hour_height(TimeScale::Min30);
102 assert_eq!(work_start_scroll_offset_y(8 * 60, hour, 480.), -7.5 * hour);
103 assert_eq!(work_start_scroll_offset_y(0, hour, 480.), 0.);
104 // A late start never scrolls past the end of the day.
105 let late = work_start_scroll_offset_y(23 * 60 + 30, hour, 480.);
106 assert_eq!(late, -(24. * hour - 480.));
107 }
108
109 #[test]
110 fn finer_time_scales_get_taller_rows() {
111 assert!(hour_height(TimeScale::Min15) > hour_height(TimeScale::Min30));
112 assert!(hour_height(TimeScale::Min30) > hour_height(TimeScale::Min60));
113 }
114
73 115 #[test]
74 116 fn midnight_stays_at_top() {
75 117 let offset = now_scroll_offset_y(0, 0, 120., 480., NOW_BIAS_FRACTION);
@@ -1,3 +1,4 @@
1use super::calendar_prefs::TimeScale;
1use super::week_grid::CalendarSpan;
2use super::week_grid::CalendarSpan;
2
3
3/// Fraction of the hour-grid viewport used to keep «now» below the top edge.
4/// Fraction of the hour-grid viewport used to keep «now» below the top edge.
@@ -28,6 +29,31 @@ pub fn now_scroll_offset_y(
28 (bias - now_y).clamp(min_offset, 0.)
29 (bias - now_y).clamp(min_offset, 0.)
29}
30}
30
31
32/// Height of one hour row for a time scale; finer scales get taller rows.
33pub fn hour_height(scale: TimeScale) -> f32 {
34 match scale {
35 TimeScale::Min15 => 120.,
36 TimeScale::Min30 => 96.,
37 TimeScale::Min60 => 64.,
38 }
39}
40
41/// Minutes shown above work start when the grid opens on a range without today.
42pub const WORK_START_LEAD_MINUTES: i64 = 30;
43
44/// Vertical scroll offset (negative Y) that puts work start, minus a short lead, at the top.
45pub fn work_start_scroll_offset_y(
46 work_start_minute: i64,
47 hour_height: f32,
48 viewport_height: f32,
49) -> f32 {
50 let day_height = 24. * hour_height;
51 let target =
52 (work_start_minute - WORK_START_LEAD_MINUTES).clamp(0, 24 * 60) as f32 / 60. * hour_height;
53 let min_offset = -(day_height - viewport_height.max(0.)).max(0.);
54 (-target).clamp(min_offset, 0.)
55}
56
31pub fn shows_hour_grid(span: CalendarSpan) -> bool {
57pub fn shows_hour_grid(span: CalendarSpan) -> bool {
32 !matches!(span, CalendarSpan::Month)
58 !matches!(span, CalendarSpan::Month)
33}
59}
@@ -70,6 +96,22 @@ mod tests {
70 assert!((offset - (bias - now_y)).abs() < 0.01);
96 assert!((offset - (bias - now_y)).abs() < 0.01);
71 }
97 }
72
98
99 #[test]
100 fn work_start_sits_at_the_top_with_a_short_lead() {
101 let hour = hour_height(TimeScale::Min30);
102 assert_eq!(work_start_scroll_offset_y(8 * 60, hour, 480.), -7.5 * hour);
103 assert_eq!(work_start_scroll_offset_y(0, hour, 480.), 0.);
104 // A late start never scrolls past the end of the day.
105 let late = work_start_scroll_offset_y(23 * 60 + 30, hour, 480.);
106 assert_eq!(late, -(24. * hour - 480.));
107 }
108
109 #[test]
110 fn finer_time_scales_get_taller_rows() {
111 assert!(hour_height(TimeScale::Min15) > hour_height(TimeScale::Min30));
112 assert!(hour_height(TimeScale::Min30) > hour_height(TimeScale::Min60));
113 }
114
73 #[test]
115 #[test]
74 fn midnight_stays_at_top() {
116 fn midnight_stays_at_top() {
75 let offset = now_scroll_offset_y(0, 0, 120., 480., NOW_BIAS_FRACTION);
117 let offset = now_scroll_offset_y(0, 0, 120., 480., NOW_BIAS_FRACTION);
crates/app-call-model/src/calendar_prefs.rs added +264 −0
@@ -0,0 +1,264 @@
1 //! Local calendar preferences: default view, last span, week layout, time scale.
2 //!
3 //! Work days and hours belong to the Outlook mailbox (Teams and Outlook read them
4 //! there); the copy here is only a cache so the grid has them before the mailbox
5 //! answers and while offline.
6
7 use chrono::{NaiveTime, Weekday};
8 use serde::{Deserialize, Serialize};
9 use store::Store;
10
11 use crate::week_grid::{CalendarSpan, WeekLayout};
12
13 pub const CALENDAR_PREFS_KEY: &str = "calendar.prefs";
14
15 /// Groups in the calendar list are keyed by this id for Outlook.
16 pub const OUTLOOK_GROUP: &str = "outlook";
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
19 #[serde(rename_all = "snake_case")]
20 pub enum DefaultView {
21 #[default]
22 LastUsed,
23 Day,
24 WorkWeek,
25 Week,
26 Month,
27 }
28
29 impl DefaultView {
30 pub const ALL: [DefaultView; 5] = [
31 DefaultView::LastUsed,
32 DefaultView::Day,
33 DefaultView::WorkWeek,
34 DefaultView::Week,
35 DefaultView::Month,
36 ];
37
38 pub fn span(self) -> Option<CalendarSpan> {
39 match self {
40 DefaultView::LastUsed => None,
41 DefaultView::Day => Some(CalendarSpan::Day),
42 DefaultView::WorkWeek => Some(CalendarSpan::WorkWeek),
43 DefaultView::Week => Some(CalendarSpan::Week),
44 DefaultView::Month => Some(CalendarSpan::Month),
45 }
46 }
47 }
48
49 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50 #[serde(rename_all = "snake_case")]
51 pub enum TimeScale {
52 Min15,
53 /// Teams default.
54 #[default]
55 Min30,
56 Min60,
57 }
58
59 impl TimeScale {
60 pub const ALL: [TimeScale; 3] = [TimeScale::Min15, TimeScale::Min30, TimeScale::Min60];
61
62 pub fn minutes(self) -> u32 {
63 match self {
64 TimeScale::Min15 => 15,
65 TimeScale::Min30 => 30,
66 TimeScale::Min60 => 60,
67 }
68 }
69
70 /// Minor grid lines inside one hour.
71 pub fn steps_per_hour(self) -> u32 {
72 60 / self.minutes()
73 }
74 }
75
76 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
77 #[serde(rename_all = "snake_case")]
78 pub enum WeekendWorkWeek {
79 /// Outlook and Teams show the coming work week on a weekend.
80 #[default]
81 NextWeek,
82 ThisWeek,
83 }
84
85 /// Work days and hours as the mailbox stores them, in the mailbox's local time.
86 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87 pub struct WorkHours {
88 pub days: Vec<Weekday>,
89 pub start: NaiveTime,
90 pub end: NaiveTime,
91 }
92
93 impl Default for WorkHours {
94 fn default() -> Self {
95 WorkHours {
96 days: vec![
97 Weekday::Mon,
98 Weekday::Tue,
99 Weekday::Wed,
100 Weekday::Thu,
101 Weekday::Fri,
102 ],
103 start: NaiveTime::from_hms_opt(8, 0, 0).unwrap_or_default(),
104 end: NaiveTime::from_hms_opt(17, 0, 0).unwrap_or_default(),
105 }
106 }
107 }
108
109 impl WorkHours {
110 pub fn is_work_day(&self, day: Weekday) -> bool {
111 self.days.contains(&day)
112 }
113
114 /// Minutes after midnight where work time starts and ends.
115 pub fn minute_range(&self) -> (i64, i64) {
116 let minute = |time: NaiveTime| {
117 i64::from(chrono::Timelike::hour(&time)) * 60
118 + i64::from(chrono::Timelike::minute(&time))
119 };
120 (minute(self.start), minute(self.end))
121 }
122 }
123
124 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
125 #[serde(default)]
126 pub struct CalendarPrefs {
127 pub default_view: DefaultView,
128 pub last_span: CalendarSpan,
129 /// `None` follows the regional format.
130 pub first_day: Option<Weekday>,
131 pub time_scale: TimeScale,
132 pub weekend_work_week: WeekendWorkWeek,
133 pub pane_hidden: bool,
134 pub collapsed_groups: Vec<String>,
135 pub work_hours: WorkHours,
136 /// Mailbox language (`en-CH`), cached; Outlook takes the default week start from it.
137 pub mailbox_locale: Option<String>,
138 }
139
140 impl CalendarPrefs {
141 /// The span the calendar opens in.
142 pub fn initial_span(&self) -> CalendarSpan {
143 self.default_view.span().unwrap_or(self.last_span)
144 }
145
146 pub fn first_day_or(&self, regional: Weekday) -> Weekday {
147 self.first_day.unwrap_or(regional)
148 }
149
150 /// Week layout for the grid; `regional` is the regional format's first day.
151 pub fn layout(&self, regional: Weekday) -> WeekLayout {
152 WeekLayout {
153 first_day: self.first_day_or(regional),
154 work_days: self.work_hours.days.clone(),
155 weekend: self.weekend_work_week,
156 }
157 }
158
159 pub fn group_collapsed(&self, group: &str) -> bool {
160 self.collapsed_groups.iter().any(|id| id == group)
161 }
162
163 pub fn toggle_group(&mut self, group: &str) {
164 if self.group_collapsed(group) {
165 self.collapsed_groups.retain(|id| id != group);
166 } else {
167 self.collapsed_groups.push(group.to_owned());
168 }
169 }
170
171 pub fn from_json(text: &str) -> Self {
172 serde_json::from_str(text).unwrap_or_default()
173 }
174
175 pub fn to_json(&self) -> String {
176 serde_json::to_string(self).unwrap_or_default()
177 }
178 }
179
180 pub fn load_calendar_prefs(store: &Store) -> CalendarPrefs {
181 store
182 .meta(CALENDAR_PREFS_KEY)
183 .ok()
184 .flatten()
185 .map(|json| CalendarPrefs::from_json(&json))
186 .unwrap_or_default()
187 }
188
189 pub fn save_calendar_prefs(store: &Store, prefs: &CalendarPrefs) {
190 if let Err(error) = store.set_meta(CALENDAR_PREFS_KEY, &prefs.to_json()) {
191 log::warn!("calendar prefs not saved: {error}");
192 }
193 }
194
195 #[cfg(test)]
196 mod tests {
197 use super::*;
198
199 #[test]
200 fn defaults_keep_todays_behaviour() {
201 let prefs = CalendarPrefs::default();
202 assert_eq!(prefs.default_view, DefaultView::LastUsed);
203 assert_eq!(prefs.initial_span(), CalendarSpan::WorkWeek);
204 assert_eq!(prefs.time_scale.minutes(), 30);
205 assert_eq!(prefs.weekend_work_week, WeekendWorkWeek::NextWeek);
206 assert_eq!(prefs.work_hours.minute_range(), (8 * 60, 17 * 60));
207 assert!(!prefs.work_hours.is_work_day(Weekday::Sat));
208 }
209
210 #[test]
211 fn a_fixed_default_view_wins_over_the_last_span() {
212 let prefs = CalendarPrefs {
213 default_view: DefaultView::Week,
214 last_span: CalendarSpan::Month,
215 ..CalendarPrefs::default()
216 };
217 assert_eq!(prefs.initial_span(), CalendarSpan::Week);
218 let last_used = CalendarPrefs {
219 default_view: DefaultView::LastUsed,
220 ..prefs
221 };
222 assert_eq!(last_used.initial_span(), CalendarSpan::Month);
223 }
224
225 #[test]
226 fn prefs_round_trip_through_the_store() {
227 let store = Store::open_in_memory().unwrap();
228 let mut prefs = CalendarPrefs {
229 default_view: DefaultView::Month,
230 first_day: Some(Weekday::Sun),
231 time_scale: TimeScale::Min15,
232 pane_hidden: true,
233 ..CalendarPrefs::default()
234 };
235 prefs.toggle_group("g1");
236 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
237 save_calendar_prefs(&store, &prefs);
238 assert_eq!(load_calendar_prefs(&store), prefs);
239 }
240
241 #[test]
242 fn missing_fields_take_defaults_and_broken_json_resets() {
243 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
244 assert_eq!(partial.default_view, DefaultView::Month);
245 assert_eq!(partial.time_scale, TimeScale::Min30);
246 assert_eq!(
247 CalendarPrefs::from_json("{not json"),
248 CalendarPrefs::default()
249 );
250 assert_eq!(
251 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
252 CalendarPrefs::default()
253 );
254 }
255
256 #[test]
257 fn a_group_collapses_and_expands() {
258 let mut prefs = CalendarPrefs::default();
259 prefs.toggle_group(OUTLOOK_GROUP);
260 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
261 prefs.toggle_group(OUTLOOK_GROUP);
262 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
263 }
264 }
@@ -0,0 +1,264 @@
1//! Local calendar preferences: default view, last span, week layout, time scale.
2//!
3//! Work days and hours belong to the Outlook mailbox (Teams and Outlook read them
4//! there); the copy here is only a cache so the grid has them before the mailbox
5//! answers and while offline.
6
7use chrono::{NaiveTime, Weekday};
8use serde::{Deserialize, Serialize};
9use store::Store;
10
11use crate::week_grid::{CalendarSpan, WeekLayout};
12
13pub const CALENDAR_PREFS_KEY: &str = "calendar.prefs";
14
15/// Groups in the calendar list are keyed by this id for Outlook.
16pub const OUTLOOK_GROUP: &str = "outlook";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum DefaultView {
21 #[default]
22 LastUsed,
23 Day,
24 WorkWeek,
25 Week,
26 Month,
27}
28
29impl DefaultView {
30 pub const ALL: [DefaultView; 5] = [
31 DefaultView::LastUsed,
32 DefaultView::Day,
33 DefaultView::WorkWeek,
34 DefaultView::Week,
35 DefaultView::Month,
36 ];
37
38 pub fn span(self) -> Option<CalendarSpan> {
39 match self {
40 DefaultView::LastUsed => None,
41 DefaultView::Day => Some(CalendarSpan::Day),
42 DefaultView::WorkWeek => Some(CalendarSpan::WorkWeek),
43 DefaultView::Week => Some(CalendarSpan::Week),
44 DefaultView::Month => Some(CalendarSpan::Month),
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum TimeScale {
52 Min15,
53 /// Teams default.
54 #[default]
55 Min30,
56 Min60,
57}
58
59impl TimeScale {
60 pub const ALL: [TimeScale; 3] = [TimeScale::Min15, TimeScale::Min30, TimeScale::Min60];
61
62 pub fn minutes(self) -> u32 {
63 match self {
64 TimeScale::Min15 => 15,
65 TimeScale::Min30 => 30,
66 TimeScale::Min60 => 60,
67 }
68 }
69
70 /// Minor grid lines inside one hour.
71 pub fn steps_per_hour(self) -> u32 {
72 60 / self.minutes()
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum WeekendWorkWeek {
79 /// Outlook and Teams show the coming work week on a weekend.
80 #[default]
81 NextWeek,
82 ThisWeek,
83}
84
85/// Work days and hours as the mailbox stores them, in the mailbox's local time.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct WorkHours {
88 pub days: Vec<Weekday>,
89 pub start: NaiveTime,
90 pub end: NaiveTime,
91}
92
93impl Default for WorkHours {
94 fn default() -> Self {
95 WorkHours {
96 days: vec![
97 Weekday::Mon,
98 Weekday::Tue,
99 Weekday::Wed,
100 Weekday::Thu,
101 Weekday::Fri,
102 ],
103 start: NaiveTime::from_hms_opt(8, 0, 0).unwrap_or_default(),
104 end: NaiveTime::from_hms_opt(17, 0, 0).unwrap_or_default(),
105 }
106 }
107}
108
109impl WorkHours {
110 pub fn is_work_day(&self, day: Weekday) -> bool {
111 self.days.contains(&day)
112 }
113
114 /// Minutes after midnight where work time starts and ends.
115 pub fn minute_range(&self) -> (i64, i64) {
116 let minute = |time: NaiveTime| {
117 i64::from(chrono::Timelike::hour(&time)) * 60
118 + i64::from(chrono::Timelike::minute(&time))
119 };
120 (minute(self.start), minute(self.end))
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
125#[serde(default)]
126pub struct CalendarPrefs {
127 pub default_view: DefaultView,
128 pub last_span: CalendarSpan,
129 /// `None` follows the regional format.
130 pub first_day: Option<Weekday>,
131 pub time_scale: TimeScale,
132 pub weekend_work_week: WeekendWorkWeek,
133 pub pane_hidden: bool,
134 pub collapsed_groups: Vec<String>,
135 pub work_hours: WorkHours,
136 /// Mailbox language (`en-CH`), cached; Outlook takes the default week start from it.
137 pub mailbox_locale: Option<String>,
138}
139
140impl CalendarPrefs {
141 /// The span the calendar opens in.
142 pub fn initial_span(&self) -> CalendarSpan {
143 self.default_view.span().unwrap_or(self.last_span)
144 }
145
146 pub fn first_day_or(&self, regional: Weekday) -> Weekday {
147 self.first_day.unwrap_or(regional)
148 }
149
150 /// Week layout for the grid; `regional` is the regional format's first day.
151 pub fn layout(&self, regional: Weekday) -> WeekLayout {
152 WeekLayout {
153 first_day: self.first_day_or(regional),
154 work_days: self.work_hours.days.clone(),
155 weekend: self.weekend_work_week,
156 }
157 }
158
159 pub fn group_collapsed(&self, group: &str) -> bool {
160 self.collapsed_groups.iter().any(|id| id == group)
161 }
162
163 pub fn toggle_group(&mut self, group: &str) {
164 if self.group_collapsed(group) {
165 self.collapsed_groups.retain(|id| id != group);
166 } else {
167 self.collapsed_groups.push(group.to_owned());
168 }
169 }
170
171 pub fn from_json(text: &str) -> Self {
172 serde_json::from_str(text).unwrap_or_default()
173 }
174
175 pub fn to_json(&self) -> String {
176 serde_json::to_string(self).unwrap_or_default()
177 }
178}
179
180pub fn load_calendar_prefs(store: &Store) -> CalendarPrefs {
181 store
182 .meta(CALENDAR_PREFS_KEY)
183 .ok()
184 .flatten()
185 .map(|json| CalendarPrefs::from_json(&json))
186 .unwrap_or_default()
187}
188
189pub fn save_calendar_prefs(store: &Store, prefs: &CalendarPrefs) {
190 if let Err(error) = store.set_meta(CALENDAR_PREFS_KEY, &prefs.to_json()) {
191 log::warn!("calendar prefs not saved: {error}");
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn defaults_keep_todays_behaviour() {
201 let prefs = CalendarPrefs::default();
202 assert_eq!(prefs.default_view, DefaultView::LastUsed);
203 assert_eq!(prefs.initial_span(), CalendarSpan::WorkWeek);
204 assert_eq!(prefs.time_scale.minutes(), 30);
205 assert_eq!(prefs.weekend_work_week, WeekendWorkWeek::NextWeek);
206 assert_eq!(prefs.work_hours.minute_range(), (8 * 60, 17 * 60));
207 assert!(!prefs.work_hours.is_work_day(Weekday::Sat));
208 }
209
210 #[test]
211 fn a_fixed_default_view_wins_over_the_last_span() {
212 let prefs = CalendarPrefs {
213 default_view: DefaultView::Week,
214 last_span: CalendarSpan::Month,
215 ..CalendarPrefs::default()
216 };
217 assert_eq!(prefs.initial_span(), CalendarSpan::Week);
218 let last_used = CalendarPrefs {
219 default_view: DefaultView::LastUsed,
220 ..prefs
221 };
222 assert_eq!(last_used.initial_span(), CalendarSpan::Month);
223 }
224
225 #[test]
226 fn prefs_round_trip_through_the_store() {
227 let store = Store::open_in_memory().unwrap();
228 let mut prefs = CalendarPrefs {
229 default_view: DefaultView::Month,
230 first_day: Some(Weekday::Sun),
231 time_scale: TimeScale::Min15,
232 pane_hidden: true,
233 ..CalendarPrefs::default()
234 };
235 prefs.toggle_group("g1");
236 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
237 save_calendar_prefs(&store, &prefs);
238 assert_eq!(load_calendar_prefs(&store), prefs);
239 }
240
241 #[test]
242 fn missing_fields_take_defaults_and_broken_json_resets() {
243 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
244 assert_eq!(partial.default_view, DefaultView::Month);
245 assert_eq!(partial.time_scale, TimeScale::Min30);
246 assert_eq!(
247 CalendarPrefs::from_json("{not json"),
248 CalendarPrefs::default()
249 );
250 assert_eq!(
251 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
252 CalendarPrefs::default()
253 );
254 }
255
256 #[test]
257 fn a_group_collapses_and_expands() {
258 let mut prefs = CalendarPrefs::default();
259 prefs.toggle_group(OUTLOOK_GROUP);
260 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
261 prefs.toggle_group(OUTLOOK_GROUP);
262 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
263 }
264}
crates/app-call-model/src/lib.rs +2 −0
@@ -1,7 +1,9 @@
1 1 pub mod agenda;
2 2 pub mod background;
3 3 pub mod bubbles;
4 pub mod calendar_list;
4 5 pub mod calendar_now;
6 pub mod calendar_prefs;
5 7 pub mod caption_style;
6 8 pub mod demo;
7 9 pub mod demo_scene;
@@ -1,7 +1,9 @@
1pub mod agenda;
1pub mod agenda;
2pub mod background;
2pub mod background;
3pub mod bubbles;
3pub mod bubbles;
4pub mod calendar_list;
4pub mod calendar_now;
5pub mod calendar_now;
6pub mod calendar_prefs;
5pub mod caption_style;
7pub mod caption_style;
6pub mod demo;
8pub mod demo;
7pub mod demo_scene;
9pub mod demo_scene;
crates/app-call-model/src/week_grid.rs +313 −90
@@ -1,9 +1,10 @@
1 1 use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
3 pub use crate::calendar_prefs::WeekendWorkWeek;
2 4 use chrono::{
3 5 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4 6 };
5 7
6 pub const WORK_WEEK_DAYS: i64 = 5;
7 8 pub const MINUTES_PER_DAY: i64 = 24 * 60;
8 9 pub const MONTH_GRID_DAYS: i64 = 42;
9 10
@@ -23,11 +24,62 @@ pub struct WeekDay {
23 24 pub blocks: Vec<WeekBlock>,
24 25 }
25 26
26 pub fn week_start(date: NaiveDate) -> NaiveDate {
27 date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
27 /// How weeks are laid out: first day, work days, and what Work week shows on a day off.
28 #[derive(Debug, Clone, PartialEq, Eq)]
29 pub struct WeekLayout {
30 pub first_day: Weekday,
31 pub work_days: Vec<Weekday>,
32 pub weekend: WeekendWorkWeek,
33 }
34
35 impl Default for WeekLayout {
36 fn default() -> Self {
37 WeekLayout {
38 first_day: Weekday::Mon,
39 work_days: vec![
40 Weekday::Mon,
41 Weekday::Tue,
42 Weekday::Wed,
43 Weekday::Thu,
44 Weekday::Fri,
45 ],
46 weekend: WeekendWorkWeek::NextWeek,
47 }
48 }
49 }
50
51 impl WeekLayout {
52 pub fn is_work_day(&self, day: Weekday) -> bool {
53 self.work_days.contains(&day)
54 }
55
56 /// Work days, or Monday to Friday when none are set (an empty work week shows nothing).
57 fn effective_work_days(&self) -> Vec<Weekday> {
58 if self.work_days.is_empty() {
59 WeekLayout::default().work_days
60 } else {
61 self.work_days.clone()
62 }
63 }
64
65 /// The seven weekdays in order from the first day.
66 pub fn weekdays(&self) -> [Weekday; 7] {
67 let mut day = self.first_day;
68 std::array::from_fn(|_| {
69 let current = day;
70 day = day.succ();
71 current
72 })
73 }
74 }
75
76 pub fn week_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
77 let back = (7 + date.weekday().num_days_from_monday() - first_day.num_days_from_monday()) % 7;
78 date - Duration::days(i64::from(back))
28 79 }
29 80
30 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
82 #[serde(rename_all = "snake_case")]
31 83 pub enum CalendarSpan {
32 84 Day,
33 85 #[default]
@@ -44,34 +96,31 @@ impl CalendarSpan {
44 96 CalendarSpan::Month,
45 97 ];
46 98
47 pub fn label(self) -> &'static str {
99 /// Locale key of the span's name (`calendar.view.span_*`).
100 pub fn label_key(self) -> &'static str {
48 101 match self {
49 CalendarSpan::Day => "Day",
50 CalendarSpan::WorkWeek => "Work week",
51 CalendarSpan::Week => "Week",
52 CalendarSpan::Month => "Month",
102 CalendarSpan::Day => "calendar.view.span_day",
103 CalendarSpan::WorkWeek => "calendar.view.span_work_week",
104 CalendarSpan::Week => "calendar.view.span_week",
105 CalendarSpan::Month => "calendar.view.span_month",
53 106 }
54 107 }
55 108
56 pub fn days(self) -> i64 {
57 match self {
58 CalendarSpan::Day => 1,
59 CalendarSpan::WorkWeek => WORK_WEEK_DAYS,
60 CalendarSpan::Week => 7,
61 CalendarSpan::Month => MONTH_GRID_DAYS,
62 }
109 pub fn label(self) -> String {
110 app_base::ui_locale::tr(self.label_key())
63 111 }
64 112
65 pub fn start_for(self, date: NaiveDate) -> NaiveDate {
113 /// First date of the range that contains `date`.
114 pub fn start_for(self, date: NaiveDate, layout: &WeekLayout) -> NaiveDate {
66 115 match self {
67 116 CalendarSpan::Day => date,
68 CalendarSpan::WorkWeek => work_week_for(date),
69 CalendarSpan::Week => week_start(date),
70 CalendarSpan::Month => month_grid_start(date),
117 CalendarSpan::WorkWeek => work_week_for(date, layout),
118 CalendarSpan::Week => week_start(date, layout.first_day),
119 CalendarSpan::Month => month_grid_start(date, layout.first_day),
71 120 }
72 121 }
73 122
74 pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {
123 pub fn shifted(self, start: NaiveDate, steps: i32, layout: &WeekLayout) -> NaiveDate {
75 124 match self {
76 125 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
77 126 CalendarSpan::WorkWeek | CalendarSpan::Week => {
@@ -84,15 +133,37 @@ impl CalendarSpan {
84 133 } else {
85 134 month.checked_sub_months(Months::new(steps.unsigned_abs()))
86 135 };
87 month_grid_start(moved.unwrap_or(month))
136 month_grid_start(moved.unwrap_or(month), layout.first_day)
88 137 }
89 138 }
90 139 }
91 140
92 pub fn title(self, start: NaiveDate) -> String {
141 pub fn title(self, start: NaiveDate, layout: &WeekLayout) -> String {
93 142 match self {
94 CalendarSpan::Month => month_shown(start).format("%B %Y").to_string(),
95 _ => range_label(start, self.days()),
143 CalendarSpan::Month => app_base::format::month_year_label(month_shown(start)),
144 _ => {
145 let dates = visible_dates(self, start, layout);
146 let first = dates.first().copied().unwrap_or(start);
147 let last = dates.last().copied().unwrap_or(start);
148 app_base::format::calendar_range_label(first, last)
149 }
150 }
151 }
152 }
153
154 /// The dates a span draws, in column order. Work week keeps only work days.
155 pub fn visible_dates(span: CalendarSpan, start: NaiveDate, layout: &WeekLayout) -> Vec<NaiveDate> {
156 let run = |days: i64| (0..days).map(|day| start + Duration::days(day)).collect();
157 match span {
158 CalendarSpan::Day => vec![start],
159 CalendarSpan::Week => run(7),
160 CalendarSpan::Month => run(MONTH_GRID_DAYS),
161 CalendarSpan::WorkWeek => {
162 let work_days = layout.effective_work_days();
163 (0..7)
164 .map(|day| start + Duration::days(day))
165 .filter(|date| work_days.contains(&date.weekday()))
166 .collect()
96 167 }
97 168 }
98 169 }
@@ -101,8 +172,8 @@ pub fn first_of_month(date: NaiveDate) -> NaiveDate {
101 172 date.with_day(1).unwrap_or(date)
102 173 }
103 174
104 pub fn month_grid_start(date: NaiveDate) -> NaiveDate {
105 week_start(first_of_month(date))
175 pub fn month_grid_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
176 week_start(first_of_month(date), first_day)
106 177 }
107 178
108 179 /// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
@@ -110,11 +181,19 @@ pub fn month_shown(grid_start: NaiveDate) -> NaiveDate {
110 181 first_of_month(grid_start + Duration::weeks(1))
111 182 }
112 183
113 /// On a weekend the work week view shows the coming week, as Outlook does.
114 pub fn work_week_for(today: NaiveDate) -> NaiveDate {
115 match today.weekday() {
116 Weekday::Sat | Weekday::Sun => week_start(today) + Duration::weeks(1),
117 _ => week_start(today),
184 /// Start of the week Work week shows for `today`.
185 ///
186 /// On a day off with no work day left in this week, Outlook and Teams show the
187 /// coming week; `WeekendWorkWeek::ThisWeek` keeps the current one.
188 pub fn work_week_for(today: NaiveDate, layout: &WeekLayout) -> NaiveDate {
189 let week = week_start(today, layout.first_day);
190 let work_days = layout.effective_work_days();
191 let work_left = (0..7)
192 .map(|day| week + Duration::days(day))
193 .any(|date| date >= today && work_days.contains(&date.weekday()));
194 match layout.weekend {
195 WeekendWorkWeek::NextWeek if !work_left => week + Duration::weeks(1),
196 _ => week,
118 197 }
119 198 }
120 199
@@ -125,6 +204,16 @@ pub fn local_midnight(date: NaiveDate, offset: FixedOffset) -> DateTime<Utc> {
125 204 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
126 205 }
127 206
207 /// UTC range from the first date's midnight to the midnight after the last date.
208 pub fn dates_range(dates: &[NaiveDate], offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
209 let first = dates.first().copied().unwrap_or_default();
210 let last = dates.last().copied().unwrap_or(first);
211 (
212 local_midnight(first, offset),
213 local_midnight(last + Duration::days(1), offset),
214 )
215 }
216
128 217 pub fn week_range(
129 218 start: NaiveDate,
130 219 days: i64,
@@ -136,6 +225,38 @@ pub fn week_range(
136 225 )
137 226 }
138 227
228 /// Position of a Google calendar in the calendar list; Outlook is 0.
229 pub fn google_calendar_index(
230 accounts: &store::CalendarAccounts,
231 account_id: &str,
232 calendar_id: &str,
233 ) -> Option<usize> {
234 accounts
235 .google_accounts
236 .iter()
237 .flat_map(|account| {
238 account
239 .calendars
240 .iter()
241 .map(move |calendar| (account.id.as_str(), calendar.id.as_str()))
242 })
243 .position(|(account, calendar)| account == account_id && calendar == calendar_id)
244 .map(|position| position + 1)
245 }
246
247 /// Calendar list position that colours an event (merged events keep Outlook's colour).
248 pub fn calendar_index(event: &CalendarEvent, accounts: &store::CalendarAccounts) -> usize {
249 match event.source {
250 chatsvc::CalendarSource::Outlook => 0,
251 chatsvc::CalendarSource::Google => event
252 .account_id
253 .as_deref()
254 .zip(event.calendar_id.as_deref())
255 .and_then(|(account, calendar)| google_calendar_index(accounts, account, calendar))
256 .unwrap_or(1),
257 }
258 }
259
139 260 pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
140 261 event.response != ResponseType::Declined
141 262 }
@@ -161,13 +282,12 @@ pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool
161 282
162 283 pub fn week_days(
163 284 events: &[CalendarEvent],
164 start: NaiveDate,
165 days: i64,
285 dates: &[NaiveDate],
166 286 offset: FixedOffset,
167 287 ) -> Vec<WeekDay> {
168 (0..days)
169 .map(|day| {
170 let date = start + Duration::days(day);
288 dates
289 .iter()
290 .map(|&date| {
171 291 let (day_start, day_end) = week_range(date, 1, offset);
172 292 let mut all_day = Vec::new();
173 293 let mut spans = Vec::new();
@@ -233,10 +353,6 @@ fn close_cluster(blocks: &mut [WeekBlock], lanes: usize) {
233 353 }
234 354 }
235 355
236 pub fn range_label(start: NaiveDate, days: i64) -> String {
237 app_base::format::calendar_range_label(start, start + Duration::days(days - 1))
238 }
239
240 356 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
241 357 pub enum EventLook {
242 358 Busy,
@@ -254,7 +370,7 @@ pub fn event_look(event: &CalendarEvent) -> EventLook {
254 370
255 371 pub fn hour_label(hour: u32, twelve_hour: bool) -> String {
256 372 if !twelve_hour {
257 return hour.to_string();
373 return format!("{hour:02}:00");
258 374 }
259 375 match hour {
260 376 0 => "12 AM".to_owned(),
@@ -298,40 +414,113 @@ mod tests {
298 414 FixedOffset::east_opt(0).unwrap()
299 415 }
300 416
417 fn run(start: NaiveDate, days: i64) -> Vec<NaiveDate> {
418 (0..days).map(|day| start + Duration::days(day)).collect()
419 }
420
421 fn nov(day: u32) -> NaiveDate {
422 NaiveDate::from_ymd_opt(2026, 11, day).unwrap()
423 }
424
425 fn layout() -> WeekLayout {
426 WeekLayout::default()
427 }
428
429 fn sunday_first() -> WeekLayout {
430 WeekLayout {
431 first_day: Weekday::Sun,
432 ..WeekLayout::default()
433 }
434 }
435
301 436 #[test]
302 437 fn month_view_steps_whole_months_from_a_monday_grid() {
303 let date = |day| NaiveDate::from_ymd_opt(2026, 11, day).unwrap();
304 let start = CalendarSpan::Month.start_for(date(18));
438 let layout = layout();
439 let start = CalendarSpan::Month.start_for(nov(18), &layout);
305 440 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
306 assert_eq!(CalendarSpan::Month.title(start), "November 2026");
307 let next = CalendarSpan::Month.shifted(start, 1);
308 assert_eq!(next, NaiveDate::from_ymd_opt(2026, 11, 30).unwrap());
309 assert_eq!(CalendarSpan::Month.title(next), "December 2026");
310 let back = CalendarSpan::Month.shifted(start, -11);
311 assert_eq!(CalendarSpan::Month.title(back), "December 2025");
441 assert_eq!(month_shown(start), nov(1));
442 let next = CalendarSpan::Month.shifted(start, 1, &layout);
443 assert_eq!(next, nov(30));
444 let back = CalendarSpan::Month.shifted(start, -11, &layout);
312 445 assert_eq!(
313 CalendarSpan::Week.shifted(date(2), -1),
314 date(2) - Duration::weeks(1)
446 month_shown(back),
447 NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
448 );
449 assert_eq!(
450 CalendarSpan::Week.shifted(nov(2), -1, &layout),
451 nov(2) - Duration::weeks(1)
315 452 );
316 453 }
317 454
318 455 #[test]
319 fn the_week_starts_on_monday() {
320 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
456 fn a_sunday_first_week_and_month_start_on_sunday() {
457 let layout = sunday_first();
458 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(15));
459 assert_eq!(
460 visible_dates(CalendarSpan::Week, nov(15), &layout),
461 run(nov(15), 7)
462 );
463 assert_eq!(
464 CalendarSpan::Month.start_for(nov(18), &layout),
465 NaiveDate::from_ymd_opt(2026, 11, 1).unwrap()
466 );
467 assert_eq!(layout.weekdays()[0], Weekday::Sun);
468 assert_eq!(layout.weekdays()[6], Weekday::Sat);
469 }
470
471 #[test]
472 fn a_saturday_first_week_starts_on_saturday() {
473 let layout = WeekLayout {
474 first_day: Weekday::Sat,
475 ..WeekLayout::default()
476 };
477 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(14));
478 assert_eq!(week_start(nov(14), Weekday::Sat), nov(14));
479 }
480
481 #[test]
482 fn work_week_shows_only_the_work_days_even_with_gaps() {
483 let layout = WeekLayout {
484 work_days: vec![Weekday::Mon, Weekday::Tue, Weekday::Thu],
485 ..WeekLayout::default()
486 };
487 let start = CalendarSpan::WorkWeek.start_for(nov(18), &layout);
488 assert_eq!(
489 visible_dates(CalendarSpan::WorkWeek, start, &layout),
490 [nov(16), nov(17), nov(19)]
491 );
492 }
493
494 #[test]
495 fn on_sunday_work_week_shows_next_or_this_week() {
496 let next = layout();
497 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &next), nov(16));
498 let this = WeekLayout {
499 weekend: WeekendWorkWeek::ThisWeek,
500 ..WeekLayout::default()
501 };
502 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &this), nov(9));
503 // Sunday-first weeks still have work days ahead on Sunday.
321 504 assert_eq!(
322 week_start(sunday),
323 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
505 CalendarSpan::WorkWeek.start_for(nov(15), &sunday_first()),
506 nov(15)
324 507 );
325 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
326 508 assert_eq!(
327 work_week_for(sunday),
328 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
509 visible_dates(CalendarSpan::WorkWeek, nov(15), &sunday_first()),
510 run(nov(16), 5)
329 511 );
330 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
512 }
513
514 #[test]
515 fn the_week_starts_on_monday() {
516 let sunday = nov(15);
517 assert_eq!(week_start(sunday, Weekday::Mon), nov(9));
331 518 assert_eq!(
332 work_week_for(friday),
333 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
519 week_start(week_start(sunday, Weekday::Mon), Weekday::Mon),
520 nov(9)
334 521 );
522 assert_eq!(work_week_for(sunday, &layout()), nov(16));
523 assert_eq!(work_week_for(nov(13), &layout()), nov(9));
335 524 }
336 525
337 526 #[test]
@@ -343,7 +532,7 @@ mod tests {
343 532 event(13, 0, 30),
344 533 ];
345 534 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
346 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
535 let days = week_days(&events, &run(monday, 5), utc());
347 536 assert_eq!(days.len(), 5);
348 537 let lanes: Vec<(usize, usize, usize)> = days[0]
349 538 .blocks
@@ -363,7 +552,7 @@ mod tests {
363 552 all_day.all_day = true;
364 553 let late = event(23, 30, 60);
365 554 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
366 let days = week_days(&[declined, all_day, late], monday, 2, utc());
555 let days = week_days(&[declined, all_day, late], &run(monday, 2), utc());
367 556 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
368 557 assert_eq!(days[0].all_day, [1]);
369 558 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
@@ -381,7 +570,7 @@ mod tests {
381 570 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382 571 assert!(is_effective_all_day(&holiday, utc()));
383 572 assert!(!is_effective_all_day(&meeting, utc()));
384 let days = week_days(&[holiday, meeting], monday, 1, utc());
573 let days = week_days(&[holiday, meeting], &run(monday, 1), utc());
385 574 assert_eq!(days[0].all_day, [0]);
386 575 assert_eq!(days[0].blocks.len(), 1);
387 576 assert_eq!(days[0].blocks[0].event_index, 1);
@@ -393,7 +582,7 @@ mod tests {
393 582 let conference = event(0, 0, 4 * 24 * 60 - 1);
394 583 assert!(is_effective_all_day(&conference, utc()));
395 584 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396 let days = week_days(&[conference], monday, 5, utc());
585 let days = week_days(&[conference], &run(monday, 5), utc());
397 586 assert!(days.iter().all(|day| day.blocks.is_empty()));
398 587 assert_eq!(days[0].all_day, [0]);
399 588 assert_eq!(days[3].all_day, [0]);
@@ -401,39 +590,73 @@ mod tests {
401 590
402 591 #[test]
403 592 fn spans_start_and_step_like_teams() {
404 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
405 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
406 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
407 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
408 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
409 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
410 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
593 let layout = layout();
594 let (wednesday, monday) = (nov(11), nov(9));
595 assert_eq!(CalendarSpan::Day.start_for(wednesday, &layout), wednesday);
596 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday, &layout), monday);
597 assert_eq!(CalendarSpan::Week.start_for(wednesday, &layout), monday);
598 assert_eq!(CalendarSpan::Week.start_for(nov(15), &layout), monday);
411 599 assert_eq!(
412 CalendarSpan::Day.shifted(wednesday, 1),
600 CalendarSpan::Day.shifted(wednesday, 1, &layout),
413 601 wednesday + Duration::days(1)
414 602 );
415 assert_eq!(CalendarSpan::Week.days(), 7);
416 }
417
418 #[test]
419 fn labels_read_like_teams() {
420 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
421 assert_eq!(range_label(monday, 5), "November 30 - December 4, 2026");
422 assert_eq!(
423 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
424 "November 9-13, 2026"
425 );
603 assert_eq!(visible_dates(CalendarSpan::Week, monday, &layout).len(), 7);
426 604 assert_eq!(
427 range_label(NaiveDate::from_ymd_opt(2026, 12, 28).unwrap(), 7),
428 "December 28, 2026 - January 3, 2027"
605 visible_dates(CalendarSpan::WorkWeek, monday, &layout).len(),
606 5
429 607 );
430 608 assert_eq!(
431 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 1),
432 "November 9, 2026"
609 dates_range(&run(monday, 5), utc()),
610 (
611 local_midnight(monday, utc()),
612 local_midnight(nov(14), utc())
613 )
433 614 );
615 }
616
617 #[test]
618 fn events_take_the_colour_index_of_their_calendar() {
619 use store::{CalendarAccounts, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};
620 let calendar = |id: &str| GoogleCalendarInfo {
621 id: id.into(),
622 summary: id.into(),
623 selected: true,
624 primary: false,
625 };
626 let accounts = CalendarAccounts {
627 google_accounts: vec![
628 GoogleAccount {
629 id: "a".into(),
630 email: "a@example.com".into(),
631 calendars: vec![calendar("primary"), calendar("family")],
632 tokens: GoogleTokenSet::default(),
633 },
634 GoogleAccount {
635 id: "b".into(),
636 email: "b@example.com".into(),
637 calendars: vec![calendar("work")],
638 tokens: GoogleTokenSet::default(),
639 },
640 ],
641 ..CalendarAccounts::default()
642 };
643 let mut google = event(9, 0, 30);
644 google.source = chatsvc::CalendarSource::Google;
645 google.account_id = Some("b".into());
646 google.calendar_id = Some("work".into());
647 assert_eq!(calendar_index(&google, &accounts), 3);
648 google.account_id = Some("a".into());
649 google.calendar_id = Some("family".into());
650 assert_eq!(calendar_index(&google, &accounts), 2);
651 assert_eq!(calendar_index(&event(9, 0, 30), &accounts), 0);
652 }
653
654 #[test]
655 fn labels_read_like_teams() {
434 656 assert_eq!(hour_label(0, true), "12 AM");
435 657 assert_eq!(hour_label(13, true), "1 PM");
436 assert_eq!(hour_label(13, false), "13");
658 assert_eq!(hour_label(13, false), "13:00");
659 assert_eq!(hour_label(7, false), "07:00");
437 660 }
438 661
439 662 #[test]
@@ -1,9 +1,10 @@
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2
3pub use crate::calendar_prefs::WeekendWorkWeek;
2use chrono::{
4use chrono::{
3 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
5 DateTime, Datelike, Duration, FixedOffset, Months, NaiveDate, NaiveTime, Utc, Weekday,
4};
6};
5
7
6pub const WORK_WEEK_DAYS: i64 = 5;
7pub const MINUTES_PER_DAY: i64 = 24 * 60;
8pub const MINUTES_PER_DAY: i64 = 24 * 60;
8pub const MONTH_GRID_DAYS: i64 = 42;
9pub const MONTH_GRID_DAYS: i64 = 42;
9
10
@@ -23,11 +24,62 @@ pub struct WeekDay {
23 pub blocks: Vec<WeekBlock>,
24 pub blocks: Vec<WeekBlock>,
24}
25}
25
26
26pub fn week_start(date: NaiveDate) -> NaiveDate {
27/// How weeks are laid out: first day, work days, and what Work week shows on a day off.
27 date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct WeekLayout {
30 pub first_day: Weekday,
31 pub work_days: Vec<Weekday>,
32 pub weekend: WeekendWorkWeek,
33}
34
35impl Default for WeekLayout {
36 fn default() -> Self {
37 WeekLayout {
38 first_day: Weekday::Mon,
39 work_days: vec![
40 Weekday::Mon,
41 Weekday::Tue,
42 Weekday::Wed,
43 Weekday::Thu,
44 Weekday::Fri,
45 ],
46 weekend: WeekendWorkWeek::NextWeek,
47 }
48 }
49}
50
51impl WeekLayout {
52 pub fn is_work_day(&self, day: Weekday) -> bool {
53 self.work_days.contains(&day)
54 }
55
56 /// Work days, or Monday to Friday when none are set (an empty work week shows nothing).
57 fn effective_work_days(&self) -> Vec<Weekday> {
58 if self.work_days.is_empty() {
59 WeekLayout::default().work_days
60 } else {
61 self.work_days.clone()
62 }
63 }
64
65 /// The seven weekdays in order from the first day.
66 pub fn weekdays(&self) -> [Weekday; 7] {
67 let mut day = self.first_day;
68 std::array::from_fn(|_| {
69 let current = day;
70 day = day.succ();
71 current
72 })
73 }
74}
75
76pub fn week_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
77 let back = (7 + date.weekday().num_days_from_monday() - first_day.num_days_from_monday()) % 7;
78 date - Duration::days(i64::from(back))
28}
79}
29
80
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
82#[serde(rename_all = "snake_case")]
31pub enum CalendarSpan {
83pub enum CalendarSpan {
32 Day,
84 Day,
33 #[default]
85 #[default]
@@ -44,34 +96,31 @@ impl CalendarSpan {
44 CalendarSpan::Month,
96 CalendarSpan::Month,
45 ];
97 ];
46
98
47 pub fn label(self) -> &'static str {
99 /// Locale key of the span's name (`calendar.view.span_*`).
100 pub fn label_key(self) -> &'static str {
48 match self {
101 match self {
49 CalendarSpan::Day => "Day",
102 CalendarSpan::Day => "calendar.view.span_day",
50 CalendarSpan::WorkWeek => "Work week",
103 CalendarSpan::WorkWeek => "calendar.view.span_work_week",
51 CalendarSpan::Week => "Week",
104 CalendarSpan::Week => "calendar.view.span_week",
52 CalendarSpan::Month => "Month",
105 CalendarSpan::Month => "calendar.view.span_month",
53 }
106 }
54 }
107 }
55
108
56 pub fn days(self) -> i64 {
109 pub fn label(self) -> String {
57 match self {
110 app_base::ui_locale::tr(self.label_key())
58 CalendarSpan::Day => 1,
59 CalendarSpan::WorkWeek => WORK_WEEK_DAYS,
60 CalendarSpan::Week => 7,
61 CalendarSpan::Month => MONTH_GRID_DAYS,
62 }
63 }
111 }
64
112
65 pub fn start_for(self, date: NaiveDate) -> NaiveDate {
113 /// First date of the range that contains `date`.
114 pub fn start_for(self, date: NaiveDate, layout: &WeekLayout) -> NaiveDate {
66 match self {
115 match self {
67 CalendarSpan::Day => date,
116 CalendarSpan::Day => date,
68 CalendarSpan::WorkWeek => work_week_for(date),
117 CalendarSpan::WorkWeek => work_week_for(date, layout),
69 CalendarSpan::Week => week_start(date),
118 CalendarSpan::Week => week_start(date, layout.first_day),
70 CalendarSpan::Month => month_grid_start(date),
119 CalendarSpan::Month => month_grid_start(date, layout.first_day),
71 }
120 }
72 }
121 }
73
122
74 pub fn shifted(self, start: NaiveDate, steps: i32) -> NaiveDate {
123 pub fn shifted(self, start: NaiveDate, steps: i32, layout: &WeekLayout) -> NaiveDate {
75 match self {
124 match self {
76 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
125 CalendarSpan::Day => start + Duration::days(i64::from(steps)),
77 CalendarSpan::WorkWeek | CalendarSpan::Week => {
126 CalendarSpan::WorkWeek | CalendarSpan::Week => {
@@ -84,15 +133,37 @@ impl CalendarSpan {
84 } else {
133 } else {
85 month.checked_sub_months(Months::new(steps.unsigned_abs()))
134 month.checked_sub_months(Months::new(steps.unsigned_abs()))
86 };
135 };
87 month_grid_start(moved.unwrap_or(month))
136 month_grid_start(moved.unwrap_or(month), layout.first_day)
88 }
137 }
89 }
138 }
90 }
139 }
91
140
92 pub fn title(self, start: NaiveDate) -> String {
141 pub fn title(self, start: NaiveDate, layout: &WeekLayout) -> String {
93 match self {
142 match self {
94 CalendarSpan::Month => month_shown(start).format("%B %Y").to_string(),
143 CalendarSpan::Month => app_base::format::month_year_label(month_shown(start)),
95 _ => range_label(start, self.days()),
144 _ => {
145 let dates = visible_dates(self, start, layout);
146 let first = dates.first().copied().unwrap_or(start);
147 let last = dates.last().copied().unwrap_or(start);
148 app_base::format::calendar_range_label(first, last)
149 }
150 }
151 }
152}
153
154/// The dates a span draws, in column order. Work week keeps only work days.
155pub fn visible_dates(span: CalendarSpan, start: NaiveDate, layout: &WeekLayout) -> Vec<NaiveDate> {
156 let run = |days: i64| (0..days).map(|day| start + Duration::days(day)).collect();
157 match span {
158 CalendarSpan::Day => vec![start],
159 CalendarSpan::Week => run(7),
160 CalendarSpan::Month => run(MONTH_GRID_DAYS),
161 CalendarSpan::WorkWeek => {
162 let work_days = layout.effective_work_days();
163 (0..7)
164 .map(|day| start + Duration::days(day))
165 .filter(|date| work_days.contains(&date.weekday()))
166 .collect()
96 }
167 }
97 }
168 }
98}
169}
@@ -101,8 +172,8 @@ pub fn first_of_month(date: NaiveDate) -> NaiveDate {
101 date.with_day(1).unwrap_or(date)
172 date.with_day(1).unwrap_or(date)
102}
173}
103
174
104pub fn month_grid_start(date: NaiveDate) -> NaiveDate {
175pub fn month_grid_start(date: NaiveDate, first_day: Weekday) -> NaiveDate {
105 week_start(first_of_month(date))
176 week_start(first_of_month(date), first_day)
106}
177}
107
178
108/// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
179/// The grid starts up to six days before the 1st, so a week in is always inside the shown month.
@@ -110,11 +181,19 @@ pub fn month_shown(grid_start: NaiveDate) -> NaiveDate {
110 first_of_month(grid_start + Duration::weeks(1))
181 first_of_month(grid_start + Duration::weeks(1))
111}
182}
112
183
113/// On a weekend the work week view shows the coming week, as Outlook does.
184/// Start of the week Work week shows for `today`.
114pub fn work_week_for(today: NaiveDate) -> NaiveDate {
185///
115 match today.weekday() {
186/// On a day off with no work day left in this week, Outlook and Teams show the
116 Weekday::Sat | Weekday::Sun => week_start(today) + Duration::weeks(1),
187/// coming week; `WeekendWorkWeek::ThisWeek` keeps the current one.
117 _ => week_start(today),
188pub fn work_week_for(today: NaiveDate, layout: &WeekLayout) -> NaiveDate {
189 let week = week_start(today, layout.first_day);
190 let work_days = layout.effective_work_days();
191 let work_left = (0..7)
192 .map(|day| week + Duration::days(day))
193 .any(|date| date >= today && work_days.contains(&date.weekday()));
194 match layout.weekend {
195 WeekendWorkWeek::NextWeek if !work_left => week + Duration::weeks(1),
196 _ => week,
118 }
197 }
119}
198}
120
199
@@ -125,6 +204,16 @@ pub fn local_midnight(date: NaiveDate, offset: FixedOffset) -> DateTime<Utc> {
125 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
204 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
126}
205}
127
206
207/// UTC range from the first date's midnight to the midnight after the last date.
208pub fn dates_range(dates: &[NaiveDate], offset: FixedOffset) -> (DateTime<Utc>, DateTime<Utc>) {
209 let first = dates.first().copied().unwrap_or_default();
210 let last = dates.last().copied().unwrap_or(first);
211 (
212 local_midnight(first, offset),
213 local_midnight(last + Duration::days(1), offset),
214 )
215}
216
128pub fn week_range(
217pub fn week_range(
129 start: NaiveDate,
218 start: NaiveDate,
130 days: i64,
219 days: i64,
@@ -136,6 +225,38 @@ pub fn week_range(
136 )
225 )
137}
226}
138
227
228/// Position of a Google calendar in the calendar list; Outlook is 0.
229pub fn google_calendar_index(
230 accounts: &store::CalendarAccounts,
231 account_id: &str,
232 calendar_id: &str,
233) -> Option<usize> {
234 accounts
235 .google_accounts
236 .iter()
237 .flat_map(|account| {
238 account
239 .calendars
240 .iter()
241 .map(move |calendar| (account.id.as_str(), calendar.id.as_str()))
242 })
243 .position(|(account, calendar)| account == account_id && calendar == calendar_id)
244 .map(|position| position + 1)
245}
246
247/// Calendar list position that colours an event (merged events keep Outlook's colour).
248pub fn calendar_index(event: &CalendarEvent, accounts: &store::CalendarAccounts) -> usize {
249 match event.source {
250 chatsvc::CalendarSource::Outlook => 0,
251 chatsvc::CalendarSource::Google => event
252 .account_id
253 .as_deref()
254 .zip(event.calendar_id.as_deref())
255 .and_then(|(account, calendar)| google_calendar_index(accounts, account, calendar))
256 .unwrap_or(1),
257 }
258}
259
139pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
260pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
140 event.response != ResponseType::Declined
261 event.response != ResponseType::Declined
141}
262}
@@ -161,13 +282,12 @@ pub fn is_effective_all_day(event: &CalendarEvent, offset: FixedOffset) -> bool
161
282
162pub fn week_days(
283pub fn week_days(
163 events: &[CalendarEvent],
284 events: &[CalendarEvent],
164 start: NaiveDate,
285 dates: &[NaiveDate],
165 days: i64,
166 offset: FixedOffset,
286 offset: FixedOffset,
167) -> Vec<WeekDay> {
287) -> Vec<WeekDay> {
168 (0..days)
288 dates
169 .map(|day| {
289 .iter()
170 let date = start + Duration::days(day);
290 .map(|&date| {
171 let (day_start, day_end) = week_range(date, 1, offset);
291 let (day_start, day_end) = week_range(date, 1, offset);
172 let mut all_day = Vec::new();
292 let mut all_day = Vec::new();
173 let mut spans = Vec::new();
293 let mut spans = Vec::new();
@@ -233,10 +353,6 @@ fn close_cluster(blocks: &mut [WeekBlock], lanes: usize) {
233 }
353 }
234}
354}
235
355
236pub fn range_label(start: NaiveDate, days: i64) -> String {
237 app_base::format::calendar_range_label(start, start + Duration::days(days - 1))
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub enum EventLook {
357pub enum EventLook {
242 Busy,
358 Busy,
@@ -254,7 +370,7 @@ pub fn event_look(event: &CalendarEvent) -> EventLook {
254
370
255pub fn hour_label(hour: u32, twelve_hour: bool) -> String {
371pub fn hour_label(hour: u32, twelve_hour: bool) -> String {
256 if !twelve_hour {
372 if !twelve_hour {
257 return hour.to_string();
373 return format!("{hour:02}:00");
258 }
374 }
259 match hour {
375 match hour {
260 0 => "12 AM".to_owned(),
376 0 => "12 AM".to_owned(),
@@ -298,40 +414,113 @@ mod tests {
298 FixedOffset::east_opt(0).unwrap()
414 FixedOffset::east_opt(0).unwrap()
299 }
415 }
300
416
417 fn run(start: NaiveDate, days: i64) -> Vec<NaiveDate> {
418 (0..days).map(|day| start + Duration::days(day)).collect()
419 }
420
421 fn nov(day: u32) -> NaiveDate {
422 NaiveDate::from_ymd_opt(2026, 11, day).unwrap()
423 }
424
425 fn layout() -> WeekLayout {
426 WeekLayout::default()
427 }
428
429 fn sunday_first() -> WeekLayout {
430 WeekLayout {
431 first_day: Weekday::Sun,
432 ..WeekLayout::default()
433 }
434 }
435
301 #[test]
436 #[test]
302 fn month_view_steps_whole_months_from_a_monday_grid() {
437 fn month_view_steps_whole_months_from_a_monday_grid() {
303 let date = |day| NaiveDate::from_ymd_opt(2026, 11, day).unwrap();
438 let layout = layout();
304 let start = CalendarSpan::Month.start_for(date(18));
439 let start = CalendarSpan::Month.start_for(nov(18), &layout);
305 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
440 assert_eq!(start, NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
306 assert_eq!(CalendarSpan::Month.title(start), "November 2026");
441 assert_eq!(month_shown(start), nov(1));
307 let next = CalendarSpan::Month.shifted(start, 1);
442 let next = CalendarSpan::Month.shifted(start, 1, &layout);
308 assert_eq!(next, NaiveDate::from_ymd_opt(2026, 11, 30).unwrap());
443 assert_eq!(next, nov(30));
309 assert_eq!(CalendarSpan::Month.title(next), "December 2026");
444 let back = CalendarSpan::Month.shifted(start, -11, &layout);
310 let back = CalendarSpan::Month.shifted(start, -11);
311 assert_eq!(CalendarSpan::Month.title(back), "December 2025");
312 assert_eq!(
445 assert_eq!(
313 CalendarSpan::Week.shifted(date(2), -1),
446 month_shown(back),
314 date(2) - Duration::weeks(1)
447 NaiveDate::from_ymd_opt(2025, 12, 1).unwrap()
448 );
449 assert_eq!(
450 CalendarSpan::Week.shifted(nov(2), -1, &layout),
451 nov(2) - Duration::weeks(1)
315 );
452 );
316 }
453 }
317
454
318 #[test]
455 #[test]
319 fn the_week_starts_on_monday() {
456 fn a_sunday_first_week_and_month_start_on_sunday() {
320 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
457 let layout = sunday_first();
458 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(15));
459 assert_eq!(
460 visible_dates(CalendarSpan::Week, nov(15), &layout),
461 run(nov(15), 7)
462 );
463 assert_eq!(
464 CalendarSpan::Month.start_for(nov(18), &layout),
465 NaiveDate::from_ymd_opt(2026, 11, 1).unwrap()
466 );
467 assert_eq!(layout.weekdays()[0], Weekday::Sun);
468 assert_eq!(layout.weekdays()[6], Weekday::Sat);
469 }
470
471 #[test]
472 fn a_saturday_first_week_starts_on_saturday() {
473 let layout = WeekLayout {
474 first_day: Weekday::Sat,
475 ..WeekLayout::default()
476 };
477 assert_eq!(CalendarSpan::Week.start_for(nov(18), &layout), nov(14));
478 assert_eq!(week_start(nov(14), Weekday::Sat), nov(14));
479 }
480
481 #[test]
482 fn work_week_shows_only_the_work_days_even_with_gaps() {
483 let layout = WeekLayout {
484 work_days: vec![Weekday::Mon, Weekday::Tue, Weekday::Thu],
485 ..WeekLayout::default()
486 };
487 let start = CalendarSpan::WorkWeek.start_for(nov(18), &layout);
488 assert_eq!(
489 visible_dates(CalendarSpan::WorkWeek, start, &layout),
490 [nov(16), nov(17), nov(19)]
491 );
492 }
493
494 #[test]
495 fn on_sunday_work_week_shows_next_or_this_week() {
496 let next = layout();
497 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &next), nov(16));
498 let this = WeekLayout {
499 weekend: WeekendWorkWeek::ThisWeek,
500 ..WeekLayout::default()
501 };
502 assert_eq!(CalendarSpan::WorkWeek.start_for(nov(15), &this), nov(9));
503 // Sunday-first weeks still have work days ahead on Sunday.
321 assert_eq!(
504 assert_eq!(
322 week_start(sunday),
505 CalendarSpan::WorkWeek.start_for(nov(15), &sunday_first()),
323 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
506 nov(15)
324 );
507 );
325 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
326 assert_eq!(
508 assert_eq!(
327 work_week_for(sunday),
509 visible_dates(CalendarSpan::WorkWeek, nov(15), &sunday_first()),
328 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
510 run(nov(16), 5)
329 );
511 );
330 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
512 }
513
514 #[test]
515 fn the_week_starts_on_monday() {
516 let sunday = nov(15);
517 assert_eq!(week_start(sunday, Weekday::Mon), nov(9));
331 assert_eq!(
518 assert_eq!(
332 work_week_for(friday),
519 week_start(week_start(sunday, Weekday::Mon), Weekday::Mon),
333 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
520 nov(9)
334 );
521 );
522 assert_eq!(work_week_for(sunday, &layout()), nov(16));
523 assert_eq!(work_week_for(nov(13), &layout()), nov(9));
335 }
524 }
336
525
337 #[test]
526 #[test]
@@ -343,7 +532,7 @@ mod tests {
343 event(13, 0, 30),
532 event(13, 0, 30),
344 ];
533 ];
345 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
534 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
346 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
535 let days = week_days(&events, &run(monday, 5), utc());
347 assert_eq!(days.len(), 5);
536 assert_eq!(days.len(), 5);
348 let lanes: Vec<(usize, usize, usize)> = days[0]
537 let lanes: Vec<(usize, usize, usize)> = days[0]
349 .blocks
538 .blocks
@@ -363,7 +552,7 @@ mod tests {
363 all_day.all_day = true;
552 all_day.all_day = true;
364 let late = event(23, 30, 60);
553 let late = event(23, 30, 60);
365 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
554 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
366 let days = week_days(&[declined, all_day, late], monday, 2, utc());
555 let days = week_days(&[declined, all_day, late], &run(monday, 2), utc());
367 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
556 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
368 assert_eq!(days[0].all_day, [1]);
557 assert_eq!(days[0].all_day, [1]);
369 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
558 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
@@ -381,7 +570,7 @@ mod tests {
381 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
570 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
382 assert!(is_effective_all_day(&holiday, utc()));
571 assert!(is_effective_all_day(&holiday, utc()));
383 assert!(!is_effective_all_day(&meeting, utc()));
572 assert!(!is_effective_all_day(&meeting, utc()));
384 let days = week_days(&[holiday, meeting], monday, 1, utc());
573 let days = week_days(&[holiday, meeting], &run(monday, 1), utc());
385 assert_eq!(days[0].all_day, [0]);
574 assert_eq!(days[0].all_day, [0]);
386 assert_eq!(days[0].blocks.len(), 1);
575 assert_eq!(days[0].blocks.len(), 1);
387 assert_eq!(days[0].blocks[0].event_index, 1);
576 assert_eq!(days[0].blocks[0].event_index, 1);
@@ -393,7 +582,7 @@ mod tests {
393 let conference = event(0, 0, 4 * 24 * 60 - 1);
582 let conference = event(0, 0, 4 * 24 * 60 - 1);
394 assert!(is_effective_all_day(&conference, utc()));
583 assert!(is_effective_all_day(&conference, utc()));
395 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
584 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
396 let days = week_days(&[conference], monday, 5, utc());
585 let days = week_days(&[conference], &run(monday, 5), utc());
397 assert!(days.iter().all(|day| day.blocks.is_empty()));
586 assert!(days.iter().all(|day| day.blocks.is_empty()));
398 assert_eq!(days[0].all_day, [0]);
587 assert_eq!(days[0].all_day, [0]);
399 assert_eq!(days[3].all_day, [0]);
588 assert_eq!(days[3].all_day, [0]);
@@ -401,39 +590,73 @@ mod tests {
401
590
402 #[test]
591 #[test]
403 fn spans_start_and_step_like_teams() {
592 fn spans_start_and_step_like_teams() {
404 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
593 let layout = layout();
405 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
594 let (wednesday, monday) = (nov(11), nov(9));
406 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
595 assert_eq!(CalendarSpan::Day.start_for(wednesday, &layout), wednesday);
407 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
596 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday, &layout), monday);
408 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
597 assert_eq!(CalendarSpan::Week.start_for(wednesday, &layout), monday);
409 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
598 assert_eq!(CalendarSpan::Week.start_for(nov(15), &layout), monday);
410 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
411 assert_eq!(
599 assert_eq!(
412 CalendarSpan::Day.shifted(wednesday, 1),
600 CalendarSpan::Day.shifted(wednesday, 1, &layout),
413 wednesday + Duration::days(1)
601 wednesday + Duration::days(1)
414 );
602 );
415 assert_eq!(CalendarSpan::Week.days(), 7);
603 assert_eq!(visible_dates(CalendarSpan::Week, monday, &layout).len(), 7);
416 }
417
418 #[test]
419 fn labels_read_like_teams() {
420 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
421 assert_eq!(range_label(monday, 5), "November 30 - December 4, 2026");
422 assert_eq!(
423 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
424 "November 9-13, 2026"
425 );
426 assert_eq!(
604 assert_eq!(
427 range_label(NaiveDate::from_ymd_opt(2026, 12, 28).unwrap(), 7),
605 visible_dates(CalendarSpan::WorkWeek, monday, &layout).len(),
428 "December 28, 2026 - January 3, 2027"
606 5
429 );
607 );
430 assert_eq!(
608 assert_eq!(
431 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 1),
609 dates_range(&run(monday, 5), utc()),
432 "November 9, 2026"
610 (
611 local_midnight(monday, utc()),
612 local_midnight(nov(14), utc())
613 )
433 );
614 );
615 }
616
617 #[test]
618 fn events_take_the_colour_index_of_their_calendar() {
619 use store::{CalendarAccounts, GoogleAccount, GoogleCalendarInfo, GoogleTokenSet};
620 let calendar = |id: &str| GoogleCalendarInfo {
621 id: id.into(),
622 summary: id.into(),
623 selected: true,
624 primary: false,
625 };
626 let accounts = CalendarAccounts {
627 google_accounts: vec![
628 GoogleAccount {
629 id: "a".into(),
630 email: "a@example.com".into(),
631 calendars: vec![calendar("primary"), calendar("family")],
632 tokens: GoogleTokenSet::default(),
633 },
634 GoogleAccount {
635 id: "b".into(),
636 email: "b@example.com".into(),
637 calendars: vec![calendar("work")],
638 tokens: GoogleTokenSet::default(),
639 },
640 ],
641 ..CalendarAccounts::default()
642 };
643 let mut google = event(9, 0, 30);
644 google.source = chatsvc::CalendarSource::Google;
645 google.account_id = Some("b".into());
646 google.calendar_id = Some("work".into());
647 assert_eq!(calendar_index(&google, &accounts), 3);
648 google.account_id = Some("a".into());
649 google.calendar_id = Some("family".into());
650 assert_eq!(calendar_index(&google, &accounts), 2);
651 assert_eq!(calendar_index(&event(9, 0, 30), &accounts), 0);
652 }
653
654 #[test]
655 fn labels_read_like_teams() {
434 assert_eq!(hour_label(0, true), "12 AM");
656 assert_eq!(hour_label(0, true), "12 AM");
435 assert_eq!(hour_label(13, true), "1 PM");
657 assert_eq!(hour_label(13, true), "1 PM");
436 assert_eq!(hour_label(13, false), "13");
658 assert_eq!(hour_label(13, false), "13:00");
659 assert_eq!(hour_label(7, false), "07:00");
437 }
660 }
438
661
439 #[test]
662 #[test]
crates/app-state/src/app_state.rs +27 −5
@@ -160,6 +160,10 @@ pub struct AppState {
160 160 pub call_history: Vec<teams_core::CallLogEntry>,
161 161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
162 162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
163 /// Authorize URL while Google OAuth waits on the loopback redirect.
164 pub google_connect_pending: Option<String>,
165 /// Bumped on cancel so a late loopback result is discarded.
166 pub google_connect_generation: u64,
163 167 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
164 168 pub calls_list: crate::call::CallsList,
165 169 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
@@ -210,9 +214,14 @@ pub struct AppState {
210 214 pub rsvp_send_response: bool,
211 215 pub meeting_toasts: crate::call::MeetingToasts,
212 216 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,
215 217 pub calendar_week: crate::call::week::CalendarWeek,
218 pub calendar_prefs: crate::call::calendar_prefs::CalendarPrefs,
219 /// Month the mini month shows after the user moved it; `None` follows the grid.
220 pub calendar_mini_month: Option<chrono::NaiveDate>,
221 /// Calendar list groups expanded with Show all (this session only).
222 pub calendar_expanded_groups: Vec<String>,
223 /// Mailbox time zone name, written back unchanged with the work hours.
224 pub mailbox_time_zone: Option<String>,
216 225 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
217 226 pub calendar_scroll_to_now: u64,
218 227 pub call_backgrounds: crate::call::BackgroundLibrary,
@@ -277,6 +286,7 @@ impl AppState {
277 286 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
278 287 let actions_on_right_click =
279 288 crate::chat_settings_actions::stored_actions_on_right_click(&store);
289 let calendar_prefs = crate::call::calendar_prefs::load_calendar_prefs(&store);
280 290 let mut state = AppState {
281 291 store,
282 292 engine: None,
@@ -327,6 +337,8 @@ impl AppState {
327 337 call_history: Vec::new(),
328 338 calendar_events: Vec::new(),
329 339 calendar_event_peek_request: None,
340 google_connect_pending: None,
341 google_connect_generation: 0,
330 342 calendar_nudge: None,
331 343 calls_list: crate::call::CallsList::default(),
332 344 speed_dial,
@@ -377,8 +389,13 @@ impl AppState {
377 389 rsvp_send_response: true,
378 390 meeting_toasts: crate::call::MeetingToasts::default(),
379 391 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
381 calendar_week: crate::call::week::CalendarWeek::default(),
392 calendar_week: crate::call::week::CalendarWeek::with_span(
393 calendar_prefs.initial_span(),
394 ),
395 calendar_prefs,
396 calendar_mini_month: None,
397 calendar_expanded_groups: Vec::new(),
398 mailbox_time_zone: None,
382 399 calendar_scroll_to_now: 0,
383 400 call_backgrounds: if mode.demo {
384 401 crate::call::demo_library()
@@ -1168,7 +1185,10 @@ impl AppState {
1168 1185 self.call_launcher = Some(launcher);
1169 1186 self.load_own_time_zone(cx);
1170 1187 }
1171 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1188 BackendEvent::Calendar(events) => {
1189 self.apply_calendar(events, cx);
1190 self.refresh_visible_calendar(cx);
1191 }
1172 1192 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1173 1193 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1174 1194 BackendEvent::ThreadChanged(conversation_id) => {
@@ -1177,6 +1197,8 @@ impl AppState {
1177 1197 BackendEvent::Engine(engine) => {
1178 1198 crate::agent_api::engine_ready(engine.clone(), cx);
1179 1199 self.engine = Some(engine);
1200 self.run_pending_calendar_load(cx);
1201 self.load_work_hours(cx);
1180 1202 self.resend_outbox(cx);
1181 1203 self.refresh_scheduled(cx);
1182 1204 self.refresh_translation_settings(cx);
@@ -160,6 +160,10 @@ pub struct AppState {
160 pub call_history: Vec<teams_core::CallLogEntry>,
160 pub call_history: Vec<teams_core::CallLogEntry>,
161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
161 pub calendar_events: Vec<chatsvc::CalendarEvent>,
162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
162 pub calendar_event_peek_request: Option<chatsvc::CalendarEvent>,
163 /// Authorize URL while Google OAuth waits on the loopback redirect.
164 pub google_connect_pending: Option<String>,
165 /// Bumped on cancel so a late loopback result is discarded.
166 pub google_connect_generation: u64,
163 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
167 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
164 pub calls_list: crate::call::CallsList,
168 pub calls_list: crate::call::CallsList,
165 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
169 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
@@ -210,9 +214,14 @@ pub struct AppState {
210 pub rsvp_send_response: bool,
214 pub rsvp_send_response: bool,
211 pub meeting_toasts: crate::call::MeetingToasts,
215 pub meeting_toasts: crate::call::MeetingToasts,
212 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
216 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,
215 pub calendar_week: crate::call::week::CalendarWeek,
217 pub calendar_week: crate::call::week::CalendarWeek,
218 pub calendar_prefs: crate::call::calendar_prefs::CalendarPrefs,
219 /// Month the mini month shows after the user moved it; `None` follows the grid.
220 pub calendar_mini_month: Option<chrono::NaiveDate>,
221 /// Calendar list groups expanded with Show all (this session only).
222 pub calendar_expanded_groups: Vec<String>,
223 /// Mailbox time zone name, written back unchanged with the work hours.
224 pub mailbox_time_zone: Option<String>,
216 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
225 /// Bumped when the hour grid should align to local «now» (open / Today / day-week span).
217 pub calendar_scroll_to_now: u64,
226 pub calendar_scroll_to_now: u64,
218 pub call_backgrounds: crate::call::BackgroundLibrary,
227 pub call_backgrounds: crate::call::BackgroundLibrary,
@@ -277,6 +286,7 @@ impl AppState {
277 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
286 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
278 let actions_on_right_click =
287 let actions_on_right_click =
279 crate::chat_settings_actions::stored_actions_on_right_click(&store);
288 crate::chat_settings_actions::stored_actions_on_right_click(&store);
289 let calendar_prefs = crate::call::calendar_prefs::load_calendar_prefs(&store);
280 let mut state = AppState {
290 let mut state = AppState {
281 store,
291 store,
282 engine: None,
292 engine: None,
@@ -327,6 +337,8 @@ impl AppState {
327 call_history: Vec::new(),
337 call_history: Vec::new(),
328 calendar_events: Vec::new(),
338 calendar_events: Vec::new(),
329 calendar_event_peek_request: None,
339 calendar_event_peek_request: None,
340 google_connect_pending: None,
341 google_connect_generation: 0,
330 calendar_nudge: None,
342 calendar_nudge: None,
331 calls_list: crate::call::CallsList::default(),
343 calls_list: crate::call::CallsList::default(),
332 speed_dial,
344 speed_dial,
@@ -377,8 +389,13 @@ impl AppState {
377 rsvp_send_response: true,
389 rsvp_send_response: true,
378 meeting_toasts: crate::call::MeetingToasts::default(),
390 meeting_toasts: crate::call::MeetingToasts::default(),
379 demo_meetings: Vec::new(),
391 demo_meetings: Vec::new(),
380 google_sync_notice_shown: false,
392 calendar_week: crate::call::week::CalendarWeek::with_span(
381 calendar_week: crate::call::week::CalendarWeek::default(),
393 calendar_prefs.initial_span(),
394 ),
395 calendar_prefs,
396 calendar_mini_month: None,
397 calendar_expanded_groups: Vec::new(),
398 mailbox_time_zone: None,
382 calendar_scroll_to_now: 0,
399 calendar_scroll_to_now: 0,
383 call_backgrounds: if mode.demo {
400 call_backgrounds: if mode.demo {
384 crate::call::demo_library()
401 crate::call::demo_library()
@@ -1168,7 +1185,10 @@ impl AppState {
1168 self.call_launcher = Some(launcher);
1185 self.call_launcher = Some(launcher);
1169 self.load_own_time_zone(cx);
1186 self.load_own_time_zone(cx);
1170 }
1187 }
1171 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1188 BackendEvent::Calendar(events) => {
1189 self.apply_calendar(events, cx);
1190 self.refresh_visible_calendar(cx);
1191 }
1172 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1192 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1173 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1193 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1174 BackendEvent::ThreadChanged(conversation_id) => {
1194 BackendEvent::ThreadChanged(conversation_id) => {
@@ -1177,6 +1197,8 @@ impl AppState {
1177 BackendEvent::Engine(engine) => {
1197 BackendEvent::Engine(engine) => {
1178 crate::agent_api::engine_ready(engine.clone(), cx);
1198 crate::agent_api::engine_ready(engine.clone(), cx);
1179 self.engine = Some(engine);
1199 self.engine = Some(engine);
1200 self.run_pending_calendar_load(cx);
1201 self.load_work_hours(cx);
1180 self.resend_outbox(cx);
1202 self.resend_outbox(cx);
1181 self.refresh_scheduled(cx);
1203 self.refresh_scheduled(cx);
1182 self.refresh_translation_settings(cx);
1204 self.refresh_translation_settings(cx);
crates/app-state/src/backend.rs +7 −3
@@ -490,7 +490,8 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
490 490 deferred_fetch = None;
491 491 last_fetch = Some(tokio::time::Instant::now());
492 492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
493 let mut accounts = store::load_calendar_accounts(&store);
493 let accounts = store::load_calendar_accounts(&store);
494 let mut fetched_accounts = accounts.clone();
494 495 let mut combined = Vec::new();
495 496 let mut outlook_failed = false;
496 497 if accounts.outlook_selected {
@@ -505,9 +506,12 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 506 }
506 507 }
507 508 }
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
510 .await
511 {
509 512 Ok(google_events) => {
510 let _ = store::save_calendar_accounts(&store, &accounts);
513 // Only refreshed tokens: a calendar toggle made during the fetch stays.
514 let _ = store::merge_google_tokens(&store, &fetched_accounts);
511 515 combined.extend(google_events);
512 516 }
513 517 Err(error) => crate::diagnostics::record(format!(
@@ -490,7 +490,8 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
490 deferred_fetch = None;
490 deferred_fetch = None;
491 last_fetch = Some(tokio::time::Instant::now());
491 last_fetch = Some(tokio::time::Instant::now());
492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
492 let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
493 let mut accounts = store::load_calendar_accounts(&store);
493 let accounts = store::load_calendar_accounts(&store);
494 let mut fetched_accounts = accounts.clone();
494 let mut combined = Vec::new();
495 let mut combined = Vec::new();
495 let mut outlook_failed = false;
496 let mut outlook_failed = false;
496 if accounts.outlook_selected {
497 if accounts.outlook_selected {
@@ -505,9 +506,12 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
505 }
506 }
506 }
507 }
507 }
508 }
508 match crate::google_calendar_sync::fetch_google_events(&mut accounts, start, end).await {
509 match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
510 .await
511 {
509 Ok(google_events) => {
512 Ok(google_events) => {
510 let _ = store::save_calendar_accounts(&store, &accounts);
513 // Only refreshed tokens: a calendar toggle made during the fetch stays.
514 let _ = store::merge_google_tokens(&store, &fetched_accounts);
511 combined.extend(google_events);
515 combined.extend(google_events);
512 }
516 }
513 Err(error) => crate::diagnostics::record(format!(
517 Err(error) => crate::diagnostics::record(format!(
crates/app-state/src/calendar_accounts_actions.rs +92 −21
@@ -1,3 +1,4 @@
1 use app_base::ui_locale::{tr, tr_args};
1 2 use chrono::Utc;
2 3 use gpui_kit::Context;
3 4 use store::{
@@ -19,6 +20,10 @@ impl AppState {
19 20 load_calendar_accounts(&self.store)
20 21 }
21 22
23 pub fn google_connect_pending(&self) -> Option<&str> {
24 self.google_connect_pending.as_deref()
25 }
26
22 27 pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
23 28 let mut accounts = load_calendar_accounts(&self.store);
24 29 accounts.disconnect_google(account_id);
@@ -71,6 +76,24 @@ impl AppState {
71 76 cx.notify();
72 77 }
73 78
79 /// Group check box: turn every calendar of one Google account on or off.
80 pub fn set_google_account_selected(
81 &mut self,
82 account_id: &str,
83 on: bool,
84 cx: &mut Context<Self>,
85 ) {
86 let mut accounts = load_calendar_accounts(&self.store);
87 if let Some(account) = accounts.google_account_mut(account_id) {
88 for calendar in &mut account.calendars {
89 calendar.selected = on;
90 }
91 }
92 let _ = save_calendar_accounts(&self.store, &accounts);
93 self.refresh_calendar(cx);
94 cx.notify();
95 }
96
74 97 pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {
75 98 let mut accounts = load_calendar_accounts(&self.store);
76 99 accounts.outlook_selected = !accounts.outlook_selected;
@@ -80,17 +103,31 @@ impl AppState {
80 103 cx.notify();
81 104 }
82 105
106 pub fn reopen_google_connect(&mut self, cx: &mut Context<Self>) {
107 if let Some(url) = self.google_connect_pending.clone() {
108 crate::external_browser::open_url(cx, &self.store, &url);
109 }
110 }
111
112 pub fn cancel_google_connect(&mut self, cx: &mut Context<Self>) {
113 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
114 self.google_connect_pending = None;
115 self.raise_notice(tr("settings.calendar.sign_in_cancelled"), None, cx);
116 cx.notify();
117 }
118
83 119 pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {
120 if self.google_connect_pending.is_some() {
121 self.reopen_google_connect(cx);
122 return;
123 }
84 124 let Some(oauth) = client_id_from_env() else {
85 self.raise_notice(
86 "Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."
87 .to_owned(),
88 None,
89 cx,
90 );
125 self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);
91 126 return;
92 127 };
93 128 let store = self.store.clone();
129 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
130 let generation = self.google_connect_generation;
94 131 cx.spawn(async move |this, cx| {
95 132 let prepared = runtime::spawn({
96 133 let oauth = oauth.clone();
@@ -106,45 +143,73 @@ impl AppState {
106 143 let (authorize_url, pending, listener, oauth) = match prepared.await {
107 144 Ok(Ok(value)) => value,
108 145 Ok(Err(error)) => {
109 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
110 .ok();
146 this.update(cx, |state, cx| {
147 clear_google_connect_if(state, generation);
148 state.raise_notice(error, None, cx);
149 })
150 .ok();
111 151 return;
112 152 }
113 153 Err(_) => {
114 154 this.update(cx, |state, cx| {
115 state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)
155 clear_google_connect_if(state, generation);
156 state.raise_notice(tr("settings.calendar.sign_in_start_failed"), None, cx);
116 157 })
117 158 .ok();
118 159 return;
119 160 }
120 161 };
121 this.update(cx, |state, cx| {
122 crate::external_browser::open_url(cx, &state.store, &authorize_url);
123 })
124 .ok();
162 let still_current = this
163 .update(cx, |state, cx| {
164 if state.google_connect_generation != generation {
165 return false;
166 }
167 state.google_connect_pending = Some(authorize_url.clone());
168 crate::external_browser::open_url(cx, &state.store, &authorize_url);
169 cx.notify();
170 true
171 })
172 .unwrap_or(false);
173 if !still_current {
174 return;
175 }
125 176 let finished = runtime::spawn(async move {
126 177 finish_google_connect(oauth, pending, listener, store).await
127 178 });
128 179 match finished.await {
129 180 Ok(Ok(email)) => {
130 181 this.update(cx, |state, cx| {
131 state.raise_notice(
132 format!("Google Calendar connected ({email})."),
133 None,
134 cx,
135 );
182 if state.google_connect_generation != generation {
183 return;
184 }
185 state.google_connect_pending = None;
186 let mut args = std::collections::HashMap::new();
187 args.insert("email".to_owned(), email);
188 state.raise_notice(tr_args("settings.calendar.connected", &args), None, cx);
136 189 state.refresh_calendar(cx);
137 190 cx.notify();
138 191 })
139 192 .ok();
140 193 }
141 194 Ok(Err(error)) => {
142 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
143 .ok();
195 this.update(cx, |state, cx| {
196 if state.google_connect_generation != generation {
197 return;
198 }
199 state.google_connect_pending = None;
200 state.raise_notice(error, None, cx);
201 cx.notify();
202 })
203 .ok();
144 204 }
145 205 Err(_) => {
146 206 this.update(cx, |state, cx| {
147 state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)
207 if state.google_connect_generation != generation {
208 return;
209 }
210 state.google_connect_pending = None;
211 state.raise_notice(tr("settings.calendar.sign_in_cancelled"), None, cx);
212 cx.notify();
148 213 })
149 214 .ok();
150 215 }
@@ -154,6 +219,12 @@ impl AppState {
154 219 }
155 220 }
156 221
222 fn clear_google_connect_if(state: &mut AppState, generation: u64) {
223 if state.google_connect_generation == generation {
224 state.google_connect_pending = None;
225 }
226 }
227
157 228 async fn finish_google_connect(
158 229 oauth: GoogleOAuth,
159 230 pending: chatsvc::AuthPending,
@@ -1,3 +1,4 @@
1use app_base::ui_locale::{tr, tr_args};
1use chrono::Utc;
2use chrono::Utc;
2use gpui_kit::Context;
3use gpui_kit::Context;
3use store::{
4use store::{
@@ -19,6 +20,10 @@ impl AppState {
19 load_calendar_accounts(&self.store)
20 load_calendar_accounts(&self.store)
20 }
21 }
21
22
23 pub fn google_connect_pending(&self) -> Option<&str> {
24 self.google_connect_pending.as_deref()
25 }
26
22 pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
27 pub fn disconnect_google_account(&mut self, account_id: &str, cx: &mut Context<Self>) {
23 let mut accounts = load_calendar_accounts(&self.store);
28 let mut accounts = load_calendar_accounts(&self.store);
24 accounts.disconnect_google(account_id);
29 accounts.disconnect_google(account_id);
@@ -71,6 +76,24 @@ impl AppState {
71 cx.notify();
76 cx.notify();
72 }
77 }
73
78
79 /// Group check box: turn every calendar of one Google account on or off.
80 pub fn set_google_account_selected(
81 &mut self,
82 account_id: &str,
83 on: bool,
84 cx: &mut Context<Self>,
85 ) {
86 let mut accounts = load_calendar_accounts(&self.store);
87 if let Some(account) = accounts.google_account_mut(account_id) {
88 for calendar in &mut account.calendars {
89 calendar.selected = on;
90 }
91 }
92 let _ = save_calendar_accounts(&self.store, &accounts);
93 self.refresh_calendar(cx);
94 cx.notify();
95 }
96
74 pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {
97 pub fn toggle_outlook_calendar_selected(&mut self, cx: &mut Context<Self>) {
75 let mut accounts = load_calendar_accounts(&self.store);
98 let mut accounts = load_calendar_accounts(&self.store);
76 accounts.outlook_selected = !accounts.outlook_selected;
99 accounts.outlook_selected = !accounts.outlook_selected;
@@ -80,17 +103,31 @@ impl AppState {
80 cx.notify();
103 cx.notify();
81 }
104 }
82
105
106 pub fn reopen_google_connect(&mut self, cx: &mut Context<Self>) {
107 if let Some(url) = self.google_connect_pending.clone() {
108 crate::external_browser::open_url(cx, &self.store, &url);
109 }
110 }
111
112 pub fn cancel_google_connect(&mut self, cx: &mut Context<Self>) {
113 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
114 self.google_connect_pending = None;
115 self.raise_notice(tr("settings.calendar.sign_in_cancelled"), None, cx);
116 cx.notify();
117 }
118
83 pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {
119 pub fn connect_google_calendar(&mut self, cx: &mut Context<Self>) {
120 if self.google_connect_pending.is_some() {
121 self.reopen_google_connect(cx);
122 return;
123 }
84 let Some(oauth) = client_id_from_env() else {
124 let Some(oauth) = client_id_from_env() else {
85 self.raise_notice(
125 self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);
86 "Set TEAMS_GOOGLE_CLIENT_ID (and optional TEAMS_GOOGLE_CLIENT_SECRET) to connect Google Calendar."
87 .to_owned(),
88 None,
89 cx,
90 );
91 return;
126 return;
92 };
127 };
93 let store = self.store.clone();
128 let store = self.store.clone();
129 self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
130 let generation = self.google_connect_generation;
94 cx.spawn(async move |this, cx| {
131 cx.spawn(async move |this, cx| {
95 let prepared = runtime::spawn({
132 let prepared = runtime::spawn({
96 let oauth = oauth.clone();
133 let oauth = oauth.clone();
@@ -106,45 +143,73 @@ impl AppState {
106 let (authorize_url, pending, listener, oauth) = match prepared.await {
143 let (authorize_url, pending, listener, oauth) = match prepared.await {
107 Ok(Ok(value)) => value,
144 Ok(Ok(value)) => value,
108 Ok(Err(error)) => {
145 Ok(Err(error)) => {
109 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
146 this.update(cx, |state, cx| {
110 .ok();
147 clear_google_connect_if(state, generation);
148 state.raise_notice(error, None, cx);
149 })
150 .ok();
111 return;
151 return;
112 }
152 }
113 Err(_) => {
153 Err(_) => {
114 this.update(cx, |state, cx| {
154 this.update(cx, |state, cx| {
115 state.raise_notice("Could not start Google sign-in.".to_owned(), None, cx)
155 clear_google_connect_if(state, generation);
156 state.raise_notice(tr("settings.calendar.sign_in_start_failed"), None, cx);
116 })
157 })
117 .ok();
158 .ok();
118 return;
159 return;
119 }
160 }
120 };
161 };
121 this.update(cx, |state, cx| {
162 let still_current = this
122 crate::external_browser::open_url(cx, &state.store, &authorize_url);
163 .update(cx, |state, cx| {
123 })
164 if state.google_connect_generation != generation {
124 .ok();
165 return false;
166 }
167 state.google_connect_pending = Some(authorize_url.clone());
168 crate::external_browser::open_url(cx, &state.store, &authorize_url);
169 cx.notify();
170 true
171 })
172 .unwrap_or(false);
173 if !still_current {
174 return;
175 }
125 let finished = runtime::spawn(async move {
176 let finished = runtime::spawn(async move {
126 finish_google_connect(oauth, pending, listener, store).await
177 finish_google_connect(oauth, pending, listener, store).await
127 });
178 });
128 match finished.await {
179 match finished.await {
129 Ok(Ok(email)) => {
180 Ok(Ok(email)) => {
130 this.update(cx, |state, cx| {
181 this.update(cx, |state, cx| {
131 state.raise_notice(
182 if state.google_connect_generation != generation {
132 format!("Google Calendar connected ({email})."),
183 return;
133 None,
184 }
134 cx,
185 state.google_connect_pending = None;
135 );
186 let mut args = std::collections::HashMap::new();
187 args.insert("email".to_owned(), email);
188 state.raise_notice(tr_args("settings.calendar.connected", &args), None, cx);
136 state.refresh_calendar(cx);
189 state.refresh_calendar(cx);
137 cx.notify();
190 cx.notify();
138 })
191 })
139 .ok();
192 .ok();
140 }
193 }
141 Ok(Err(error)) => {
194 Ok(Err(error)) => {
142 this.update(cx, |state, cx| state.raise_notice(error, None, cx))
195 this.update(cx, |state, cx| {
143 .ok();
196 if state.google_connect_generation != generation {
197 return;
198 }
199 state.google_connect_pending = None;
200 state.raise_notice(error, None, cx);
201 cx.notify();
202 })
203 .ok();
144 }
204 }
145 Err(_) => {
205 Err(_) => {
146 this.update(cx, |state, cx| {
206 this.update(cx, |state, cx| {
147 state.raise_notice("Google sign-in was cancelled.".to_owned(), None, cx)
207 if state.google_connect_generation != generation {
208 return;
209 }
210 state.google_connect_pending = None;
211 state.raise_notice(tr("settings.calendar.sign_in_cancelled"), None, cx);
212 cx.notify();
148 })
213 })
149 .ok();
214 .ok();
150 }
215 }
@@ -154,6 +219,12 @@ impl AppState {
154 }
219 }
155}
220}
156
221
222fn clear_google_connect_if(state: &mut AppState, generation: u64) {
223 if state.google_connect_generation == generation {
224 state.google_connect_pending = None;
225 }
226}
227
157async fn finish_google_connect(
228async fn finish_google_connect(
158 oauth: GoogleOAuth,
229 oauth: GoogleOAuth,
159 pending: chatsvc::AuthPending,
230 pending: chatsvc::AuthPending,
crates/app-state/src/call/calendar_settings.rs added +197 −0
@@ -0,0 +1,197 @@
1 //! Calendar view settings on `AppState`: local preferences plus the mailbox work hours.
2
3 use app_base::ui_locale::tr;
4 use gpui_kit::Context;
5 use graph::MailboxWorkingHours;
6
7 use super::calendar_prefs::{CalendarPrefs, WorkHours, save_calendar_prefs};
8 use crate::app_state::AppState;
9
10 impl AppState {
11 /// Change local calendar preferences, save them and redraw the visible range.
12 pub fn update_calendar_prefs(
13 &mut self,
14 change: impl FnOnce(&mut CalendarPrefs),
15 cx: &mut Context<Self>,
16 ) {
17 let anchor = self.calendar_week.start;
18 change(&mut self.calendar_prefs);
19 save_calendar_prefs(&self.store, &self.calendar_prefs);
20 if let Some(anchor) = anchor {
21 // Week start or work days may have moved: re-anchor on the same date.
22 self.calendar_week.start = Some(self.calendar_span_start(anchor));
23 self.request_calendar_scroll_to_now(cx);
24 self.load_calendar_week(cx);
25 }
26 cx.notify();
27 }
28
29 /// Read the mailbox work hours once the session is there and cache them.
30 pub(crate) fn load_work_hours(&mut self, cx: &mut Context<Self>) {
31 if self.mode.demo {
32 return;
33 }
34 let Some(engine) = self.engine.clone() else {
35 return;
36 };
37 let receiver = crate::runtime::spawn(async move { engine.remote().working_hours().await });
38 cx.spawn(async move |this, cx| {
39 let Ok(result) = receiver.await else {
40 return;
41 };
42 this.update(cx, |state, cx| match result {
43 Ok(mailbox) => {
44 state.mailbox_time_zone = mailbox.time_zone.clone();
45 let hours = work_hours_from(&mailbox);
46 let locale = mailbox.locale.clone();
47 let prefs = &state.calendar_prefs;
48 if hours != prefs.work_hours || locale != prefs.mailbox_locale {
49 state.update_calendar_prefs(
50 |prefs| {
51 prefs.work_hours = hours;
52 prefs.mailbox_locale = locale;
53 },
54 cx,
55 );
56 }
57 }
58 Err(error) => crate::diagnostics::record(format!(
59 "calendar: mailbox work hours not read: {error}"
60 )),
61 })
62 .ok();
63 })
64 .detach();
65 }
66
67 /// Save work days and hours to the mailbox; on failure the previous value returns.
68 pub fn set_work_hours(&mut self, hours: WorkHours, cx: &mut Context<Self>) {
69 let previous = self.calendar_prefs.work_hours.clone();
70 if previous == hours {
71 return;
72 }
73 let wanted = hours.clone();
74 self.update_calendar_prefs(|prefs| prefs.work_hours = wanted, cx);
75 if self.mode.demo {
76 return;
77 }
78 let Some(engine) = self.engine.clone() else {
79 self.revert_work_hours(previous, "no session".to_owned(), cx);
80 return;
81 };
82 let mailbox = MailboxWorkingHours {
83 days: hours.days,
84 start: hours.start,
85 end: hours.end,
86 time_zone: self.mailbox_time_zone.clone(),
87 locale: None,
88 };
89 let receiver =
90 crate::runtime::spawn(async move { engine.remote().set_working_hours(&mailbox).await });
91 cx.spawn(async move |this, cx| {
92 let result = receiver
93 .await
94 .unwrap_or_else(|_| Err(graph::Error::Decode("mailbox task cancelled".into())));
95 this.update(cx, |state, cx| {
96 if let Err(error) = result {
97 state.revert_work_hours(previous, error.to_string(), cx);
98 }
99 })
100 .ok();
101 })
102 .detach();
103 }
104
105 fn revert_work_hours(&mut self, previous: WorkHours, error: String, cx: &mut Context<Self>) {
106 crate::diagnostics::record(format!("calendar: mailbox work hours not saved: {error}"));
107 self.update_calendar_prefs(|prefs| prefs.work_hours = previous, cx);
108 self.raise_notice(tr("settings.calendar.work_hours_not_saved"), None, cx);
109 }
110 }
111
112 fn work_hours_from(mailbox: &MailboxWorkingHours) -> WorkHours {
113 WorkHours {
114 days: mailbox.days.clone(),
115 start: mailbox.start,
116 end: mailbox.end,
117 }
118 }
119
120 #[cfg(test)]
121 mod tests {
122 use std::sync::Arc;
123
124 use chrono::Weekday;
125 use gpui_kit::{AppContext as _, TestAppContext};
126 use store::Store;
127
128 use crate::app_state::{AppState, Mode};
129 use crate::call::calendar_prefs::{DefaultView, WorkHours, load_calendar_prefs};
130 use crate::call::week_grid::CalendarSpan;
131
132 #[gpui_kit::test]
133 fn the_week_start_follows_the_mailbox_language(cx: &mut TestAppContext) {
134 cx.update(gpui_kit::init);
135 let store = Arc::new(Store::open_in_memory().unwrap());
136 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
137 cx.update(|cx| {
138 app.update(cx, |state, cx| {
139 state
140 .update_calendar_prefs(|prefs| prefs.mailbox_locale = Some("en-US".into()), cx);
141 assert_eq!(state.calendar_layout().first_day, Weekday::Sun);
142 state
143 .update_calendar_prefs(|prefs| prefs.mailbox_locale = Some("en-CH".into()), cx);
144 assert_eq!(state.calendar_layout().first_day, Weekday::Mon);
145 state.update_calendar_prefs(|prefs| prefs.first_day = Some(Weekday::Sat), cx);
146 assert_eq!(state.calendar_layout().first_day, Weekday::Sat);
147 })
148 });
149 }
150
151 #[gpui_kit::test]
152 fn the_chosen_span_survives_a_restart(cx: &mut TestAppContext) {
153 cx.update(gpui_kit::init);
154 let store = Arc::new(Store::open_in_memory().unwrap());
155 let first = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
156 cx.update(|cx| {
157 first.update(cx, |state, cx| {
158 assert_eq!(state.calendar_week.span, CalendarSpan::WorkWeek);
159 state.set_calendar_span(CalendarSpan::Month, cx);
160 // A day opened from a month cell is temporary navigation.
161 let today = chrono::Local::now().date_naive();
162 state.show_calendar_day(today, cx);
163 })
164 });
165 let second = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
166 cx.update(|cx| {
167 second.update(cx, |state, cx| {
168 assert_eq!(state.calendar_week.span, CalendarSpan::Month);
169 state.update_calendar_prefs(|prefs| prefs.default_view = DefaultView::Week, cx);
170 state.set_calendar_span(CalendarSpan::Day, cx);
171 })
172 });
173 let third = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
174 cx.update(|cx| {
175 third.update(cx, |state, _| {
176 assert_eq!(state.calendar_week.span, CalendarSpan::Week)
177 })
178 });
179 }
180
181 #[gpui_kit::test]
182 fn work_hours_fall_back_when_the_mailbox_cannot_be_written(cx: &mut TestAppContext) {
183 cx.update(gpui_kit::init);
184 let store = Arc::new(Store::open_in_memory().unwrap());
185 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
186 cx.update(|cx| {
187 app.update(cx, |state, cx| {
188 let mut hours = WorkHours::default();
189 hours.days.retain(|day| *day != Weekday::Fri);
190 state.set_work_hours(hours, cx);
191 assert_eq!(state.calendar_prefs.work_hours, WorkHours::default());
192 assert!(state.notice.is_some());
193 })
194 });
195 assert_eq!(load_calendar_prefs(&store).work_hours, WorkHours::default());
196 }
197 }
@@ -0,0 +1,197 @@
1//! Calendar view settings on `AppState`: local preferences plus the mailbox work hours.
2
3use app_base::ui_locale::tr;
4use gpui_kit::Context;
5use graph::MailboxWorkingHours;
6
7use super::calendar_prefs::{CalendarPrefs, WorkHours, save_calendar_prefs};
8use crate::app_state::AppState;
9
10impl AppState {
11 /// Change local calendar preferences, save them and redraw the visible range.
12 pub fn update_calendar_prefs(
13 &mut self,
14 change: impl FnOnce(&mut CalendarPrefs),
15 cx: &mut Context<Self>,
16 ) {
17 let anchor = self.calendar_week.start;
18 change(&mut self.calendar_prefs);
19 save_calendar_prefs(&self.store, &self.calendar_prefs);
20 if let Some(anchor) = anchor {
21 // Week start or work days may have moved: re-anchor on the same date.
22 self.calendar_week.start = Some(self.calendar_span_start(anchor));
23 self.request_calendar_scroll_to_now(cx);
24 self.load_calendar_week(cx);
25 }
26 cx.notify();
27 }
28
29 /// Read the mailbox work hours once the session is there and cache them.
30 pub(crate) fn load_work_hours(&mut self, cx: &mut Context<Self>) {
31 if self.mode.demo {
32 return;
33 }
34 let Some(engine) = self.engine.clone() else {
35 return;
36 };
37 let receiver = crate::runtime::spawn(async move { engine.remote().working_hours().await });
38 cx.spawn(async move |this, cx| {
39 let Ok(result) = receiver.await else {
40 return;
41 };
42 this.update(cx, |state, cx| match result {
43 Ok(mailbox) => {
44 state.mailbox_time_zone = mailbox.time_zone.clone();
45 let hours = work_hours_from(&mailbox);
46 let locale = mailbox.locale.clone();
47 let prefs = &state.calendar_prefs;
48 if hours != prefs.work_hours || locale != prefs.mailbox_locale {
49 state.update_calendar_prefs(
50 |prefs| {
51 prefs.work_hours = hours;
52 prefs.mailbox_locale = locale;
53 },
54 cx,
55 );
56 }
57 }
58 Err(error) => crate::diagnostics::record(format!(
59 "calendar: mailbox work hours not read: {error}"
60 )),
61 })
62 .ok();
63 })
64 .detach();
65 }
66
67 /// Save work days and hours to the mailbox; on failure the previous value returns.
68 pub fn set_work_hours(&mut self, hours: WorkHours, cx: &mut Context<Self>) {
69 let previous = self.calendar_prefs.work_hours.clone();
70 if previous == hours {
71 return;
72 }
73 let wanted = hours.clone();
74 self.update_calendar_prefs(|prefs| prefs.work_hours = wanted, cx);
75 if self.mode.demo {
76 return;
77 }
78 let Some(engine) = self.engine.clone() else {
79 self.revert_work_hours(previous, "no session".to_owned(), cx);
80 return;
81 };
82 let mailbox = MailboxWorkingHours {
83 days: hours.days,
84 start: hours.start,
85 end: hours.end,
86 time_zone: self.mailbox_time_zone.clone(),
87 locale: None,
88 };
89 let receiver =
90 crate::runtime::spawn(async move { engine.remote().set_working_hours(&mailbox).await });
91 cx.spawn(async move |this, cx| {
92 let result = receiver
93 .await
94 .unwrap_or_else(|_| Err(graph::Error::Decode("mailbox task cancelled".into())));
95 this.update(cx, |state, cx| {
96 if let Err(error) = result {
97 state.revert_work_hours(previous, error.to_string(), cx);
98 }
99 })
100 .ok();
101 })
102 .detach();
103 }
104
105 fn revert_work_hours(&mut self, previous: WorkHours, error: String, cx: &mut Context<Self>) {
106 crate::diagnostics::record(format!("calendar: mailbox work hours not saved: {error}"));
107 self.update_calendar_prefs(|prefs| prefs.work_hours = previous, cx);
108 self.raise_notice(tr("settings.calendar.work_hours_not_saved"), None, cx);
109 }
110}
111
112fn work_hours_from(mailbox: &MailboxWorkingHours) -> WorkHours {
113 WorkHours {
114 days: mailbox.days.clone(),
115 start: mailbox.start,
116 end: mailbox.end,
117 }
118}
119
120#[cfg(test)]
121mod tests {
122 use std::sync::Arc;
123
124 use chrono::Weekday;
125 use gpui_kit::{AppContext as _, TestAppContext};
126 use store::Store;
127
128 use crate::app_state::{AppState, Mode};
129 use crate::call::calendar_prefs::{DefaultView, WorkHours, load_calendar_prefs};
130 use crate::call::week_grid::CalendarSpan;
131
132 #[gpui_kit::test]
133 fn the_week_start_follows_the_mailbox_language(cx: &mut TestAppContext) {
134 cx.update(gpui_kit::init);
135 let store = Arc::new(Store::open_in_memory().unwrap());
136 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
137 cx.update(|cx| {
138 app.update(cx, |state, cx| {
139 state
140 .update_calendar_prefs(|prefs| prefs.mailbox_locale = Some("en-US".into()), cx);
141 assert_eq!(state.calendar_layout().first_day, Weekday::Sun);
142 state
143 .update_calendar_prefs(|prefs| prefs.mailbox_locale = Some("en-CH".into()), cx);
144 assert_eq!(state.calendar_layout().first_day, Weekday::Mon);
145 state.update_calendar_prefs(|prefs| prefs.first_day = Some(Weekday::Sat), cx);
146 assert_eq!(state.calendar_layout().first_day, Weekday::Sat);
147 })
148 });
149 }
150
151 #[gpui_kit::test]
152 fn the_chosen_span_survives_a_restart(cx: &mut TestAppContext) {
153 cx.update(gpui_kit::init);
154 let store = Arc::new(Store::open_in_memory().unwrap());
155 let first = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
156 cx.update(|cx| {
157 first.update(cx, |state, cx| {
158 assert_eq!(state.calendar_week.span, CalendarSpan::WorkWeek);
159 state.set_calendar_span(CalendarSpan::Month, cx);
160 // A day opened from a month cell is temporary navigation.
161 let today = chrono::Local::now().date_naive();
162 state.show_calendar_day(today, cx);
163 })
164 });
165 let second = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
166 cx.update(|cx| {
167 second.update(cx, |state, cx| {
168 assert_eq!(state.calendar_week.span, CalendarSpan::Month);
169 state.update_calendar_prefs(|prefs| prefs.default_view = DefaultView::Week, cx);
170 state.set_calendar_span(CalendarSpan::Day, cx);
171 })
172 });
173 let third = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
174 cx.update(|cx| {
175 third.update(cx, |state, _| {
176 assert_eq!(state.calendar_week.span, CalendarSpan::Week)
177 })
178 });
179 }
180
181 #[gpui_kit::test]
182 fn work_hours_fall_back_when_the_mailbox_cannot_be_written(cx: &mut TestAppContext) {
183 cx.update(gpui_kit::init);
184 let store = Arc::new(Store::open_in_memory().unwrap());
185 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
186 cx.update(|cx| {
187 app.update(cx, |state, cx| {
188 let mut hours = WorkHours::default();
189 hours.days.retain(|day| *day != Weekday::Fri);
190 state.set_work_hours(hours, cx);
191 assert_eq!(state.calendar_prefs.work_hours, WorkHours::default());
192 assert!(state.notice.is_some());
193 })
194 });
195 assert_eq!(load_calendar_prefs(&store).work_hours, WorkHours::default());
196 }
197}
crates/app-state/src/call/mod.rs +5 −3
@@ -1,5 +1,6 @@
1 1 pub mod actions;
2 2 pub mod calendar;
3 pub mod calendar_settings;
3 4 pub mod consult;
4 5 pub mod end_actions;
5 6 pub mod features;
@@ -24,9 +25,10 @@ pub mod view_actions;
24 25 pub mod week;
25 26
26 27 pub use app_call_model::{
27 agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,
28 media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,
29 ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
28 agenda, background, bubbles, calendar_list, calendar_now, calendar_prefs, caption_style, demo,
29 end_screen, fullscreen, health, media, mic, model, options_dialog, people, preview,
30 record_rights, recording_menu, report, ring, share_view, stage_layout, stage_split, transcript,
31 view_settings, week_grid,
30 32 };
31 33
32 34 pub use actions::{
@@ -1,5 +1,6 @@
1pub mod actions;
1pub mod actions;
2pub mod calendar;
2pub mod calendar;
3pub mod calendar_settings;
3pub mod consult;
4pub mod consult;
4pub mod end_actions;
5pub mod end_actions;
5pub mod features;
6pub mod features;
@@ -24,9 +25,10 @@ pub mod view_actions;
24pub mod week;
25pub mod week;
25
26
26pub use app_call_model::{
27pub use app_call_model::{
27 agenda, background, bubbles, calendar_now, caption_style, demo, end_screen, fullscreen, health,
28 agenda, background, bubbles, calendar_list, calendar_now, calendar_prefs, caption_style, demo,
28 media, mic, model, options_dialog, people, preview, record_rights, recording_menu, report,
29 end_screen, fullscreen, health, media, mic, model, options_dialog, people, preview,
29 ring, share_view, stage_layout, stage_split, transcript, view_settings, week_grid,
30 record_rights, recording_menu, report, ring, share_view, stage_layout, stage_split, transcript,
31 view_settings, week_grid,
30};
32};
31
33
32pub use actions::{
34pub use actions::{
crates/app-state/src/call/week.rs +403 −55
@@ -1,39 +1,133 @@
1 use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2 use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
1 use std::time::Instant;
2
3 use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4 use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
3 5 use gpui_kit::Context;
4 6
5 7 use super::agenda::demo_events;
6 8 use super::calendar::demo_anchor;
7 use super::week_grid::{CalendarSpan, local_midnight, week_range, week_start};
9 use super::calendar_prefs::save_calendar_prefs;
10 use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12 };
8 13 use crate::app_state::AppState;
9 14
10 15 pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
11 16
17 /// One calendar source that did not load for the visible range.
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct CalendarLoadFailure {
20 pub source: CalendarSource,
21 pub message: String,
22 }
23
12 24 #[derive(Debug, Clone, Default)]
13 25 pub struct CalendarWeek {
14 26 pub start: Option<NaiveDate>,
15 27 pub span: CalendarSpan,
16 28 pub events: Vec<CalendarEvent>,
17 29 pub loading: bool,
30 /// Sources that failed on the last load; cleared by the next load.
31 pub failures: Vec<CalendarLoadFailure>,
32 /// The calendar section is on screen (drives refresh on the poll interval).
33 pub visible: bool,
34 /// A load was asked for before the session existed; run it once it does.
35 pending: bool,
18 36 request: u64,
19 37 }
20 38
39 impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
47 /// True once when a skipped load should run now.
48 pub(crate) fn take_pending(&mut self) -> bool {
49 std::mem::take(&mut self.pending)
50 }
51 }
52
21 53 impl AppState {
54 /// Week layout from the calendar settings and the regional first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs.layout(self.default_first_day())
57 }
58
59 /// First day of week without an override: the mailbox language's region, as in
60 /// Outlook and Teams, else the regional format.
61 pub fn default_first_day(&self) -> Weekday {
62 self.calendar_prefs
63 .mailbox_locale
64 .as_deref()
65 .map(app_base::format::first_day_for_locale)
66 .unwrap_or_else(app_base::format::regional_first_day)
67 }
68
22 69 pub fn calendar_start(&self) -> NaiveDate {
23 70 self.calendar_week
24 71 .start
25 .unwrap_or_else(|| self.calendar_week.span.start_for(Local::now().date_naive()))
72 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
73 }
74
75 /// Start of the visible span's range that contains `date`.
76 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
77 self.calendar_week
78 .span
79 .start_for(date, &self.calendar_layout())
80 }
81
82 /// The dates the grid draws, in column order.
83 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
84 visible_dates(
85 self.calendar_week.span,
86 self.calendar_start(),
87 &self.calendar_layout(),
88 )
89 }
90
91 pub fn calendar_shows_today(&self) -> bool {
92 self.calendar_dates().contains(&Local::now().date_naive())
26 93 }
27 94
28 95 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
96 self.calendar_week.visible = true;
29 97 self.calendar_week.start = Some(self.calendar_start());
30 98 self.request_calendar_scroll_to_now(cx);
31 99 self.load_calendar_week(cx);
32 100 }
33 101
102 /// The user left the calendar section; stop refreshing its range.
103 pub fn close_calendar(&mut self) {
104 self.calendar_week.visible = false;
105 }
106
107 /// Reload the visible range after an agenda poll while the calendar is on screen.
108 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
109 if self.calendar_week.visible && self.calendar_week.start.is_some() {
110 self.load_calendar_week(cx);
111 }
112 }
113
114 /// Retry from the inline notice after a source failed.
115 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
116 self.load_calendar_week(cx);
117 }
118
119 /// Run a grid load that was skipped because no session existed yet.
120 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
121 if self.calendar_week.take_pending() {
122 self.load_calendar_week(cx);
123 }
124 }
125
34 126 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
35 127 let span = self.calendar_week.span;
36 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
128 let layout = self.calendar_layout();
129 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
130 self.request_calendar_scroll_to_now(cx);
37 131 self.load_calendar_week(cx);
38 132 }
39 133
@@ -42,7 +136,42 @@ impl AppState {
42 136 self.open_calendar(cx);
43 137 }
44 138
139 /// Month the mini month shows: the user's own choice, else the visible range.
140 pub fn calendar_mini_month_shown(&self) -> NaiveDate {
141 self.calendar_mini_month.unwrap_or_else(|| {
142 let dates = self.calendar_dates();
143 let middle = dates.get(dates.len() / 2).copied();
144 super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start()))
145 })
146 }
147
148 pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) {
149 let month = self.calendar_mini_month_shown();
150 let moved = if steps >= 0 {
151 month.checked_add_months(chrono::Months::new(steps.unsigned_abs()))
152 } else {
153 month.checked_sub_months(chrono::Months::new(steps.unsigned_abs()))
154 };
155 self.calendar_mini_month = Some(moved.unwrap_or(month));
156 cx.notify();
157 }
158
159 pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) {
160 if let Some(index) = self
161 .calendar_expanded_groups
162 .iter()
163 .position(|existing| existing == group)
164 {
165 self.calendar_expanded_groups.remove(index);
166 } else {
167 self.calendar_expanded_groups.push(group.to_owned());
168 }
169 cx.notify();
170 }
171
45 172 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
173 // Every navigation lands here: the mini month follows the grid again.
174 self.calendar_mini_month = None;
46 175 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
47 176 return;
48 177 }
@@ -50,13 +179,22 @@ impl AppState {
50 179 cx.notify();
51 180 }
52 181
182 /// Span chosen from the view menu; remembered as the last used span.
53 183 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
54 184 let today = Local::now().date_naive();
55 185 let start = self.calendar_start();
56 let shown =
57 start <= today && today < start + Duration::days(self.calendar_week.span.days());
186 let anchor = if self.calendar_shows_today() {
187 today
188 } else {
189 start
190 };
58 191 self.calendar_week.span = span;
59 self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));
192 self.calendar_week.start = Some(self.calendar_span_start(anchor));
193 self.calendar_mini_month = None;
194 if self.calendar_prefs.last_span != span {
195 self.calendar_prefs.last_span = span;
196 save_calendar_prefs(&self.store, &self.calendar_prefs);
197 }
60 198 if crate::call::calendar_now::shows_hour_grid(span) {
61 199 self.request_calendar_scroll_to_now(cx);
62 200 }
@@ -64,7 +202,8 @@ impl AppState {
64 202 }
65 203
66 204 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
67 self.calendar_week.start = Some(self.calendar_week.span.start_for(date));
205 self.calendar_week.start = Some(self.calendar_span_start(date));
206 self.request_calendar_scroll_to_now(cx);
68 207 self.load_calendar_week(cx);
69 208 }
70 209
@@ -76,10 +215,14 @@ impl AppState {
76 215 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
77 216 let start = self.calendar_start();
78 217 let offset = Local::now().offset().fix();
79 let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
218 let (from, to) = dates_range(&self.calendar_dates(), offset);
80 219 if self.mode.demo {
81 220 let mut events = demo_events(demo_anchor());
82 events.extend(demo_week(week_start(start), offset));
221 // Demo meetings sit Monday to Friday of the week the grid shows.
222 // The Monday inside the first shown week, whatever day the week starts on.
223 let dates = self.calendar_dates();
224 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
225 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
83 226 events.extend(self.demo_meetings.iter().cloned());
84 227 events.retain(|event| event.end > from && event.start < to);
85 228 events.sort_by_key(|event| (event.start, event.end));
@@ -87,7 +230,9 @@ impl AppState {
87 230 cx.notify();
88 231 return;
89 232 }
90 let Some(launcher) = self.call_launcher.clone() else {
233 // Grid load needs only the signed-in session, never the calling engine.
234 let Some(engine) = self.engine.clone() else {
235 self.calendar_week.pending = true;
91 236 return;
92 237 };
93 238 self.calendar_week.request += 1;
@@ -96,63 +241,79 @@ impl AppState {
96 241 cx.notify();
97 242 let store = self.store.clone();
98 243 let receiver = crate::runtime::spawn(async move {
99 let mut accounts = store::load_calendar_accounts(&store);
244 let started = Instant::now();
245 let accounts = store::load_calendar_accounts(&store);
246 let mut fetched_accounts = accounts.clone();
100 247 let mut combined = Vec::new();
101 let mut outlook_failed = false;
248 let mut failures = Vec::new();
249 let mut outlook_count = None;
102 250 if accounts.outlook_selected {
103 match launcher.calendar_view(from, to).await {
104 Ok(events) => combined.extend(events),
105 Err(error) => {
106 outlook_failed = true;
107 crate::diagnostics::record(format!(
108 "calls: outlook calendar week not loaded: {error}"
109 ));
251 match Calendar::new(engine.remote().session())
252 .calendar_view(from, to)
253 .await
254 {
255 Ok(events) => {
256 outlook_count = Some(events.len());
257 combined.extend(events);
110 258 }
259 Err(error) => failures.push(CalendarLoadFailure {
260 source: CalendarSource::Outlook,
261 message: error.to_string(),
262 }),
111 263 }
112 264 }
113 let mut google_error = None;
114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
115 Ok(events) => {
116 let _ = store::save_calendar_accounts(&store, &accounts);
117 combined.extend(events);
118 }
119 Err(error) => {
120 crate::diagnostics::record(format!(
121 "calls: google calendar week not loaded: {error}"
122 ));
123 google_error = Some(error);
265 let mut google_count = None;
266 if accounts.has_google() {
267 match crate::google_calendar_sync::fetch_google_events(
268 &mut fetched_accounts,
269 from,
270 to,
271 )
272 .await
273 {
274 Ok(events) => {
275 // Keep only refreshed tokens: a toggle made meanwhile must survive.
276 let _ = store::merge_google_tokens(&store, &fetched_accounts);
277 google_count = Some(events.len());
278 combined.extend(events);
279 }
280 Err(error) => failures.push(CalendarLoadFailure {
281 source: CalendarSource::Google,
282 message: error,
283 }),
124 284 }
125 285 }
126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
128 }
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
286 crate::diagnostics::record(load_summary(
287 from,
288 to,
289 outlook_count,
290 google_count,
291 started.elapsed().as_millis(),
292 &failures,
293 ));
294 (chatsvc::merge_calendar_events(combined), failures)
130 295 });
131 296 cx.spawn(async move |this, cx| {
132 let loaded = receiver
133 .await
134 .unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
297 let loaded = receiver.await.unwrap_or_else(|_| {
298 (
299 Vec::new(),
300 vec![CalendarLoadFailure {
301 source: CalendarSource::Outlook,
302 message: CALENDAR_LOAD_FAILURE.to_owned(),
303 }],
304 )
305 });
135 306 this.update(cx, |state, cx| {
136 307 if state.calendar_week.request != request {
137 308 return;
138 309 }
139 310 state.calendar_week.loading = false;
140 match loaded {
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 }
154 Err(notice) => state.raise_notice(notice, None, cx),
155 }
311 let (events, failures) = loaded;
312 let previous = std::mem::take(&mut state.calendar_week.events);
313 let mut events = keep_failed_sources(&previous, events, &failures);
314 retain_peek_details(&previous, &mut events);
315 state.calendar_week.events = events;
316 state.calendar_week.failures = failures;
156 317 cx.notify();
157 318 })
158 319 .ok();
@@ -161,6 +322,51 @@ impl AppState {
161 322 }
162 323 }
163 324
325 /// A source that failed keeps its previous events on screen instead of blanking the week.
326 pub(crate) fn keep_failed_sources(
327 previous: &[CalendarEvent],
328 mut events: Vec<CalendarEvent>,
329 failures: &[CalendarLoadFailure],
330 ) -> Vec<CalendarEvent> {
331 for failure in failures {
332 events.extend(
333 previous
334 .iter()
335 .filter(|event| event.source == failure.source)
336 .cloned(),
337 );
338 }
339 events.sort_by_key(|event| (event.start, event.end));
340 events
341 }
342
343 /// One diagnostics line per grid load, so an empty week can be traced to its cause.
344 pub(crate) fn load_summary(
345 from: chrono::DateTime<chrono::Utc>,
346 to: chrono::DateTime<chrono::Utc>,
347 outlook: Option<usize>,
348 google: Option<usize>,
349 elapsed_ms: u128,
350 failures: &[CalendarLoadFailure],
351 ) -> String {
352 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
353 let mut line = format!(
354 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
355 from.format("%Y-%m-%dT%H:%MZ"),
356 to.format("%Y-%m-%dT%H:%MZ"),
357 count(outlook),
358 count(google),
359 );
360 for failure in failures {
361 line.push_str(&format!(
362 "; {} failed: {}",
363 failure.source.label(),
364 failure.message.chars().take(160).collect::<String>()
365 ));
366 }
367 line
368 }
369
164 370 fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 371 for event in events {
166 372 let Some(old) = previous
@@ -309,3 +515,145 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
309 515 })
310 516 .collect()
311 517 }
518
519 #[cfg(test)]
520 mod tests {
521 use std::sync::Arc;
522
523 use chatsvc::{CalendarEvent, CalendarSource};
524 use chrono::{Offset as _, TimeZone, Utc};
525 use gpui_kit::{AppContext as _, TestAppContext};
526 use store::Store;
527
528 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
529 use crate::app_state::{AppState, Mode};
530
531 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
532 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
533 CalendarEvent {
534 object_id: id.into(),
535 subject: id.into(),
536 start,
537 end: start + chrono::Duration::minutes(30),
538 source,
539 ..Default::default()
540 }
541 }
542
543 #[gpui_kit::test]
544 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
545 cx.update(gpui_kit::init);
546 let store = Arc::new(Store::open_in_memory().unwrap());
547 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
548 cx.update(|cx| {
549 app.update(cx, |state, cx| {
550 state.open_calendar(cx);
551 assert!(state.calendar_week.visible);
552 assert!(state.calendar_week.take_pending());
553 assert!(!state.calendar_week.take_pending());
554 })
555 });
556 }
557
558 #[gpui_kit::test]
559 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
560 cx.update(gpui_kit::init);
561 let store = Arc::new(Store::open_in_memory().unwrap());
562 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
563 cx.update(|cx| {
564 app.update(cx, |state, cx| {
565 state.open_calendar(cx);
566 state.calendar_week.take_pending();
567 state.close_calendar();
568 state.refresh_visible_calendar(cx);
569 assert!(!state.calendar_week.take_pending());
570 state.open_calendar(cx);
571 state.calendar_week.take_pending();
572 state.refresh_visible_calendar(cx);
573 assert!(state.calendar_week.take_pending());
574 })
575 });
576 }
577
578 #[gpui_kit::test]
579 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
580 cx.update(gpui_kit::init);
581 let store = Arc::new(Store::open_in_memory().unwrap());
582 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
583 cx.update(|cx| {
584 app.update(cx, |state, cx| {
585 state.open_calendar(cx);
586 let opened = state.calendar_scroll_to_now;
587 state.shift_calendar_week(1, cx);
588 assert_ne!(state.calendar_scroll_to_now, opened);
589 let shifted = state.calendar_scroll_to_now;
590 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
591 assert_ne!(state.calendar_scroll_to_now, shifted);
592 })
593 });
594 }
595
596 #[gpui_kit::test]
597 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
598 cx.update(gpui_kit::init);
599 let store = Arc::new(Store::open_in_memory().unwrap());
600 let mode = Mode {
601 demo: true,
602 ..Mode::default()
603 };
604 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
605 cx.update(|cx| {
606 app.update(cx, |state, cx| {
607 state.open_calendar(cx);
608 let dates = state.calendar_dates();
609 let offset = chrono::Local::now().offset().fix();
610 let days =
611 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
612 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
613 assert!(
614 blocks >= 8,
615 "dates {dates:?}, events {}, blocks {blocks}",
616 state.calendar_week.events.len()
617 );
618 })
619 });
620 }
621
622 #[test]
623 fn a_failed_source_keeps_its_previous_events() {
624 let previous = vec![
625 event("outlook-old", CalendarSource::Outlook, 9),
626 event("google-old", CalendarSource::Google, 10),
627 ];
628 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
629 let failures = [CalendarLoadFailure {
630 source: CalendarSource::Outlook,
631 message: "HTTP 503".into(),
632 }];
633 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
634 .into_iter()
635 .map(|event| event.object_id)
636 .collect();
637 assert_eq!(ids, ["google-new", "outlook-old"]);
638 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
639 .into_iter()
640 .map(|event| event.object_id)
641 .collect();
642 assert_eq!(ids, ["google-new"]);
643 }
644
645 #[test]
646 fn the_load_summary_names_counts_and_failures() {
647 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
648 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
649 let failures = [CalendarLoadFailure {
650 source: CalendarSource::Google,
651 message: "client_secret is missing".into(),
652 }];
653 assert_eq!(
654 load_summary(from, to, Some(3), None, 412, &failures),
655 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
656 Google failed: client_secret is missing"
657 );
658 }
659 }
@@ -1,39 +1,133 @@
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
1use std::time::Instant;
2use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset};
2
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
3use gpui_kit::Context;
5use gpui_kit::Context;
4
6
5use super::agenda::demo_events;
7use super::agenda::demo_events;
6use super::calendar::demo_anchor;
8use super::calendar::demo_anchor;
7use super::week_grid::{CalendarSpan, local_midnight, week_range, week_start};
9use super::calendar_prefs::save_calendar_prefs;
10use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12};
8use crate::app_state::AppState;
13use crate::app_state::AppState;
9
14
10pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
15pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
11
16
17/// One calendar source that did not load for the visible range.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CalendarLoadFailure {
20 pub source: CalendarSource,
21 pub message: String,
22}
23
12#[derive(Debug, Clone, Default)]
24#[derive(Debug, Clone, Default)]
13pub struct CalendarWeek {
25pub struct CalendarWeek {
14 pub start: Option<NaiveDate>,
26 pub start: Option<NaiveDate>,
15 pub span: CalendarSpan,
27 pub span: CalendarSpan,
16 pub events: Vec<CalendarEvent>,
28 pub events: Vec<CalendarEvent>,
17 pub loading: bool,
29 pub loading: bool,
30 /// Sources that failed on the last load; cleared by the next load.
31 pub failures: Vec<CalendarLoadFailure>,
32 /// The calendar section is on screen (drives refresh on the poll interval).
33 pub visible: bool,
34 /// A load was asked for before the session existed; run it once it does.
35 pending: bool,
18 request: u64,
36 request: u64,
19}
37}
20
38
39impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
47 /// True once when a skipped load should run now.
48 pub(crate) fn take_pending(&mut self) -> bool {
49 std::mem::take(&mut self.pending)
50 }
51}
52
21impl AppState {
53impl AppState {
54 /// Week layout from the calendar settings and the regional first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs.layout(self.default_first_day())
57 }
58
59 /// First day of week without an override: the mailbox language's region, as in
60 /// Outlook and Teams, else the regional format.
61 pub fn default_first_day(&self) -> Weekday {
62 self.calendar_prefs
63 .mailbox_locale
64 .as_deref()
65 .map(app_base::format::first_day_for_locale)
66 .unwrap_or_else(app_base::format::regional_first_day)
67 }
68
22 pub fn calendar_start(&self) -> NaiveDate {
69 pub fn calendar_start(&self) -> NaiveDate {
23 self.calendar_week
70 self.calendar_week
24 .start
71 .start
25 .unwrap_or_else(|| self.calendar_week.span.start_for(Local::now().date_naive()))
72 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
73 }
74
75 /// Start of the visible span's range that contains `date`.
76 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
77 self.calendar_week
78 .span
79 .start_for(date, &self.calendar_layout())
80 }
81
82 /// The dates the grid draws, in column order.
83 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
84 visible_dates(
85 self.calendar_week.span,
86 self.calendar_start(),
87 &self.calendar_layout(),
88 )
89 }
90
91 pub fn calendar_shows_today(&self) -> bool {
92 self.calendar_dates().contains(&Local::now().date_naive())
26 }
93 }
27
94
28 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
95 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
96 self.calendar_week.visible = true;
29 self.calendar_week.start = Some(self.calendar_start());
97 self.calendar_week.start = Some(self.calendar_start());
30 self.request_calendar_scroll_to_now(cx);
98 self.request_calendar_scroll_to_now(cx);
31 self.load_calendar_week(cx);
99 self.load_calendar_week(cx);
32 }
100 }
33
101
102 /// The user left the calendar section; stop refreshing its range.
103 pub fn close_calendar(&mut self) {
104 self.calendar_week.visible = false;
105 }
106
107 /// Reload the visible range after an agenda poll while the calendar is on screen.
108 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
109 if self.calendar_week.visible && self.calendar_week.start.is_some() {
110 self.load_calendar_week(cx);
111 }
112 }
113
114 /// Retry from the inline notice after a source failed.
115 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
116 self.load_calendar_week(cx);
117 }
118
119 /// Run a grid load that was skipped because no session existed yet.
120 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
121 if self.calendar_week.take_pending() {
122 self.load_calendar_week(cx);
123 }
124 }
125
34 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
126 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
35 let span = self.calendar_week.span;
127 let span = self.calendar_week.span;
36 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps));
128 let layout = self.calendar_layout();
129 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
130 self.request_calendar_scroll_to_now(cx);
37 self.load_calendar_week(cx);
131 self.load_calendar_week(cx);
38 }
132 }
39
133
@@ -42,7 +136,42 @@ impl AppState {
42 self.open_calendar(cx);
136 self.open_calendar(cx);
43 }
137 }
44
138
139 /// Month the mini month shows: the user's own choice, else the visible range.
140 pub fn calendar_mini_month_shown(&self) -> NaiveDate {
141 self.calendar_mini_month.unwrap_or_else(|| {
142 let dates = self.calendar_dates();
143 let middle = dates.get(dates.len() / 2).copied();
144 super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start()))
145 })
146 }
147
148 pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) {
149 let month = self.calendar_mini_month_shown();
150 let moved = if steps >= 0 {
151 month.checked_add_months(chrono::Months::new(steps.unsigned_abs()))
152 } else {
153 month.checked_sub_months(chrono::Months::new(steps.unsigned_abs()))
154 };
155 self.calendar_mini_month = Some(moved.unwrap_or(month));
156 cx.notify();
157 }
158
159 pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) {
160 if let Some(index) = self
161 .calendar_expanded_groups
162 .iter()
163 .position(|existing| existing == group)
164 {
165 self.calendar_expanded_groups.remove(index);
166 } else {
167 self.calendar_expanded_groups.push(group.to_owned());
168 }
169 cx.notify();
170 }
171
45 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
172 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
173 // Every navigation lands here: the mini month follows the grid again.
174 self.calendar_mini_month = None;
46 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
175 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
47 return;
176 return;
48 }
177 }
@@ -50,13 +179,22 @@ impl AppState {
50 cx.notify();
179 cx.notify();
51 }
180 }
52
181
182 /// Span chosen from the view menu; remembered as the last used span.
53 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
183 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
54 let today = Local::now().date_naive();
184 let today = Local::now().date_naive();
55 let start = self.calendar_start();
185 let start = self.calendar_start();
56 let shown =
186 let anchor = if self.calendar_shows_today() {
57 start <= today && today < start + Duration::days(self.calendar_week.span.days());
187 today
188 } else {
189 start
190 };
58 self.calendar_week.span = span;
191 self.calendar_week.span = span;
59 self.calendar_week.start = Some(span.start_for(if shown { today } else { start }));
192 self.calendar_week.start = Some(self.calendar_span_start(anchor));
193 self.calendar_mini_month = None;
194 if self.calendar_prefs.last_span != span {
195 self.calendar_prefs.last_span = span;
196 save_calendar_prefs(&self.store, &self.calendar_prefs);
197 }
60 if crate::call::calendar_now::shows_hour_grid(span) {
198 if crate::call::calendar_now::shows_hour_grid(span) {
61 self.request_calendar_scroll_to_now(cx);
199 self.request_calendar_scroll_to_now(cx);
62 }
200 }
@@ -64,7 +202,8 @@ impl AppState {
64 }
202 }
65
203
66 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
204 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
67 self.calendar_week.start = Some(self.calendar_week.span.start_for(date));
205 self.calendar_week.start = Some(self.calendar_span_start(date));
206 self.request_calendar_scroll_to_now(cx);
68 self.load_calendar_week(cx);
207 self.load_calendar_week(cx);
69 }
208 }
70
209
@@ -76,10 +215,14 @@ impl AppState {
76 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
215 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
77 let start = self.calendar_start();
216 let start = self.calendar_start();
78 let offset = Local::now().offset().fix();
217 let offset = Local::now().offset().fix();
79 let (from, to) = week_range(start, self.calendar_week.span.days(), offset);
218 let (from, to) = dates_range(&self.calendar_dates(), offset);
80 if self.mode.demo {
219 if self.mode.demo {
81 let mut events = demo_events(demo_anchor());
220 let mut events = demo_events(demo_anchor());
82 events.extend(demo_week(week_start(start), offset));
221 // Demo meetings sit Monday to Friday of the week the grid shows.
222 // The Monday inside the first shown week, whatever day the week starts on.
223 let dates = self.calendar_dates();
224 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
225 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
83 events.extend(self.demo_meetings.iter().cloned());
226 events.extend(self.demo_meetings.iter().cloned());
84 events.retain(|event| event.end > from && event.start < to);
227 events.retain(|event| event.end > from && event.start < to);
85 events.sort_by_key(|event| (event.start, event.end));
228 events.sort_by_key(|event| (event.start, event.end));
@@ -87,7 +230,9 @@ impl AppState {
87 cx.notify();
230 cx.notify();
88 return;
231 return;
89 }
232 }
90 let Some(launcher) = self.call_launcher.clone() else {
233 // Grid load needs only the signed-in session, never the calling engine.
234 let Some(engine) = self.engine.clone() else {
235 self.calendar_week.pending = true;
91 return;
236 return;
92 };
237 };
93 self.calendar_week.request += 1;
238 self.calendar_week.request += 1;
@@ -96,63 +241,79 @@ impl AppState {
96 cx.notify();
241 cx.notify();
97 let store = self.store.clone();
242 let store = self.store.clone();
98 let receiver = crate::runtime::spawn(async move {
243 let receiver = crate::runtime::spawn(async move {
99 let mut accounts = store::load_calendar_accounts(&store);
244 let started = Instant::now();
245 let accounts = store::load_calendar_accounts(&store);
246 let mut fetched_accounts = accounts.clone();
100 let mut combined = Vec::new();
247 let mut combined = Vec::new();
101 let mut outlook_failed = false;
248 let mut failures = Vec::new();
249 let mut outlook_count = None;
102 if accounts.outlook_selected {
250 if accounts.outlook_selected {
103 match launcher.calendar_view(from, to).await {
251 match Calendar::new(engine.remote().session())
104 Ok(events) => combined.extend(events),
252 .calendar_view(from, to)
105 Err(error) => {
253 .await
106 outlook_failed = true;
254 {
107 crate::diagnostics::record(format!(
255 Ok(events) => {
108 "calls: outlook calendar week not loaded: {error}"
256 outlook_count = Some(events.len());
109 ));
257 combined.extend(events);
110 }
258 }
259 Err(error) => failures.push(CalendarLoadFailure {
260 source: CalendarSource::Outlook,
261 message: error.to_string(),
262 }),
111 }
263 }
112 }
264 }
113 let mut google_error = None;
265 let mut google_count = None;
114 match crate::google_calendar_sync::fetch_google_events(&mut accounts, from, to).await {
266 if accounts.has_google() {
115 Ok(events) => {
267 match crate::google_calendar_sync::fetch_google_events(
116 let _ = store::save_calendar_accounts(&store, &accounts);
268 &mut fetched_accounts,
117 combined.extend(events);
269 from,
118 }
270 to,
119 Err(error) => {
271 )
120 crate::diagnostics::record(format!(
272 .await
121 "calls: google calendar week not loaded: {error}"
273 {
122 ));
274 Ok(events) => {
123 google_error = Some(error);
275 // Keep only refreshed tokens: a toggle made meanwhile must survive.
276 let _ = store::merge_google_tokens(&store, &fetched_accounts);
277 google_count = Some(events.len());
278 combined.extend(events);
279 }
280 Err(error) => failures.push(CalendarLoadFailure {
281 source: CalendarSource::Google,
282 message: error,
283 }),
124 }
284 }
125 }
285 }
126 if combined.is_empty() && outlook_failed && !accounts.has_google() {
286 crate::diagnostics::record(load_summary(
127 return Err(CALENDAR_LOAD_FAILURE.to_owned());
287 from,
128 }
288 to,
129 Ok((chatsvc::merge_calendar_events(combined), google_error))
289 outlook_count,
290 google_count,
291 started.elapsed().as_millis(),
292 &failures,
293 ));
294 (chatsvc::merge_calendar_events(combined), failures)
130 });
295 });
131 cx.spawn(async move |this, cx| {
296 cx.spawn(async move |this, cx| {
132 let loaded = receiver
297 let loaded = receiver.await.unwrap_or_else(|_| {
133 .await
298 (
134 .unwrap_or_else(|_| Err(CALENDAR_LOAD_FAILURE.to_owned()));
299 Vec::new(),
300 vec![CalendarLoadFailure {
301 source: CalendarSource::Outlook,
302 message: CALENDAR_LOAD_FAILURE.to_owned(),
303 }],
304 )
305 });
135 this.update(cx, |state, cx| {
306 this.update(cx, |state, cx| {
136 if state.calendar_week.request != request {
307 if state.calendar_week.request != request {
137 return;
308 return;
138 }
309 }
139 state.calendar_week.loading = false;
310 state.calendar_week.loading = false;
140 match loaded {
311 let (events, failures) = loaded;
141 Ok((events, google_error)) => {
312 let previous = std::mem::take(&mut state.calendar_week.events);
142 // Keep detail enrichment (agenda/location/RSVP counts) across week reloads.
313 let mut events = keep_failed_sources(&previous, events, &failures);
143 let previous = std::mem::take(&mut state.calendar_week.events);
314 retain_peek_details(&previous, &mut events);
144 let mut events = events;
315 state.calendar_week.events = events;
145 retain_peek_details(&previous, &mut events);
316 state.calendar_week.failures = failures;
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 }
154 Err(notice) => state.raise_notice(notice, None, cx),
155 }
156 cx.notify();
317 cx.notify();
157 })
318 })
158 .ok();
319 .ok();
@@ -161,6 +322,51 @@ impl AppState {
161 }
322 }
162}
323}
163
324
325/// A source that failed keeps its previous events on screen instead of blanking the week.
326pub(crate) fn keep_failed_sources(
327 previous: &[CalendarEvent],
328 mut events: Vec<CalendarEvent>,
329 failures: &[CalendarLoadFailure],
330) -> Vec<CalendarEvent> {
331 for failure in failures {
332 events.extend(
333 previous
334 .iter()
335 .filter(|event| event.source == failure.source)
336 .cloned(),
337 );
338 }
339 events.sort_by_key(|event| (event.start, event.end));
340 events
341}
342
343/// One diagnostics line per grid load, so an empty week can be traced to its cause.
344pub(crate) fn load_summary(
345 from: chrono::DateTime<chrono::Utc>,
346 to: chrono::DateTime<chrono::Utc>,
347 outlook: Option<usize>,
348 google: Option<usize>,
349 elapsed_ms: u128,
350 failures: &[CalendarLoadFailure],
351) -> String {
352 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
353 let mut line = format!(
354 "calendar grid: {}..{} outlook={} google={} in {elapsed_ms} ms",
355 from.format("%Y-%m-%dT%H:%MZ"),
356 to.format("%Y-%m-%dT%H:%MZ"),
357 count(outlook),
358 count(google),
359 );
360 for failure in failures {
361 line.push_str(&format!(
362 "; {} failed: {}",
363 failure.source.label(),
364 failure.message.chars().take(160).collect::<String>()
365 ));
366 }
367 line
368}
369
164fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
370fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
165 for event in events {
371 for event in events {
166 let Some(old) = previous
372 let Some(old) = previous
@@ -309,3 +515,145 @@ fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
309 })
515 })
310 .collect()
516 .collect()
311}
517}
518
519#[cfg(test)]
520mod tests {
521 use std::sync::Arc;
522
523 use chatsvc::{CalendarEvent, CalendarSource};
524 use chrono::{Offset as _, TimeZone, Utc};
525 use gpui_kit::{AppContext as _, TestAppContext};
526 use store::Store;
527
528 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
529 use crate::app_state::{AppState, Mode};
530
531 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
532 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
533 CalendarEvent {
534 object_id: id.into(),
535 subject: id.into(),
536 start,
537 end: start + chrono::Duration::minutes(30),
538 source,
539 ..Default::default()
540 }
541 }
542
543 #[gpui_kit::test]
544 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
545 cx.update(gpui_kit::init);
546 let store = Arc::new(Store::open_in_memory().unwrap());
547 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
548 cx.update(|cx| {
549 app.update(cx, |state, cx| {
550 state.open_calendar(cx);
551 assert!(state.calendar_week.visible);
552 assert!(state.calendar_week.take_pending());
553 assert!(!state.calendar_week.take_pending());
554 })
555 });
556 }
557
558 #[gpui_kit::test]
559 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
560 cx.update(gpui_kit::init);
561 let store = Arc::new(Store::open_in_memory().unwrap());
562 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
563 cx.update(|cx| {
564 app.update(cx, |state, cx| {
565 state.open_calendar(cx);
566 state.calendar_week.take_pending();
567 state.close_calendar();
568 state.refresh_visible_calendar(cx);
569 assert!(!state.calendar_week.take_pending());
570 state.open_calendar(cx);
571 state.calendar_week.take_pending();
572 state.refresh_visible_calendar(cx);
573 assert!(state.calendar_week.take_pending());
574 })
575 });
576 }
577
578 #[gpui_kit::test]
579 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
580 cx.update(gpui_kit::init);
581 let store = Arc::new(Store::open_in_memory().unwrap());
582 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
583 cx.update(|cx| {
584 app.update(cx, |state, cx| {
585 state.open_calendar(cx);
586 let opened = state.calendar_scroll_to_now;
587 state.shift_calendar_week(1, cx);
588 assert_ne!(state.calendar_scroll_to_now, opened);
589 let shifted = state.calendar_scroll_to_now;
590 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
591 assert_ne!(state.calendar_scroll_to_now, shifted);
592 })
593 });
594 }
595
596 #[gpui_kit::test]
597 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
598 cx.update(gpui_kit::init);
599 let store = Arc::new(Store::open_in_memory().unwrap());
600 let mode = Mode {
601 demo: true,
602 ..Mode::default()
603 };
604 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
605 cx.update(|cx| {
606 app.update(cx, |state, cx| {
607 state.open_calendar(cx);
608 let dates = state.calendar_dates();
609 let offset = chrono::Local::now().offset().fix();
610 let days =
611 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
612 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
613 assert!(
614 blocks >= 8,
615 "dates {dates:?}, events {}, blocks {blocks}",
616 state.calendar_week.events.len()
617 );
618 })
619 });
620 }
621
622 #[test]
623 fn a_failed_source_keeps_its_previous_events() {
624 let previous = vec![
625 event("outlook-old", CalendarSource::Outlook, 9),
626 event("google-old", CalendarSource::Google, 10),
627 ];
628 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
629 let failures = [CalendarLoadFailure {
630 source: CalendarSource::Outlook,
631 message: "HTTP 503".into(),
632 }];
633 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
634 .into_iter()
635 .map(|event| event.object_id)
636 .collect();
637 assert_eq!(ids, ["google-new", "outlook-old"]);
638 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
639 .into_iter()
640 .map(|event| event.object_id)
641 .collect();
642 assert_eq!(ids, ["google-new"]);
643 }
644
645 #[test]
646 fn the_load_summary_names_counts_and_failures() {
647 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
648 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
649 let failures = [CalendarLoadFailure {
650 source: CalendarSource::Google,
651 message: "client_secret is missing".into(),
652 }];
653 assert_eq!(
654 load_summary(from, to, Some(3), None, 412, &failures),
655 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- in 412 ms; \
656 Google failed: client_secret is missing"
657 );
658 }
659}
crates/app-state/src/google_calendar_sync.rs +4 −0
@@ -33,6 +33,10 @@ pub async fn fetch_google_events(
33 33 .filter(|calendar| calendar.selected)
34 34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
35 35 .collect();
36 // Every calendar turned off (group check box): the account shows nothing.
37 if calendars.is_empty() && !account.calendars.is_empty() {
38 continue;
39 }
36 40 let calendars = if calendars.is_empty() {
37 41 vec![(
38 42 "primary".to_owned(),
@@ -33,6 +33,10 @@ pub async fn fetch_google_events(
33 .filter(|calendar| calendar.selected)
33 .filter(|calendar| calendar.selected)
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
34 .map(|calendar| (calendar.id.clone(), calendar.summary.clone()))
35 .collect();
35 .collect();
36 // Every calendar turned off (group check box): the account shows nothing.
37 if calendars.is_empty() && !account.calendars.is_empty() {
38 continue;
39 }
36 let calendars = if calendars.is_empty() {
40 let calendars = if calendars.is_empty() {
37 vec![(
41 vec![(
38 "primary".to_owned(),
42 "primary".to_owned(),
crates/app/src/i18n.rs +8 −6
@@ -1,15 +1,17 @@
1 1 pub use app_base::ui_locale::{tr, tr_args};
2 2
3 /// Serialises tests that set the global UI language (`rust_i18n` keeps one locale per process).
3 4 #[cfg(test)]
4 mod tests {
5 use std::sync::{Mutex, MutexGuard};
5 pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
6 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
7 LOCK.lock().unwrap_or_else(|error| error.into_inner())
8 }
6 9
10 #[cfg(test)]
11 mod tests {
7 12 use app_base::ui_locale::{apply_locale, tr};
8 13
9 fn locale_test_lock() -> MutexGuard<'static, ()> {
10 static LOCK: Mutex<()> = Mutex::new(());
11 LOCK.lock().unwrap_or_else(|error| error.into_inner())
12 }
14 use super::locale_test_lock;
13 15
14 16 #[test]
15 17 fn ui_locale_settings_common_actions() {
@@ -1,15 +1,17 @@
1pub use app_base::ui_locale::{tr, tr_args};
1pub use app_base::ui_locale::{tr, tr_args};
2
2
3/// Serialises tests that set the global UI language (`rust_i18n` keeps one locale per process).
3#[cfg(test)]
4#[cfg(test)]
4mod tests {
5pub(crate) fn locale_test_lock() -> std::sync::MutexGuard<'static, ()> {
5 use std::sync::{Mutex, MutexGuard};
6 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
7 LOCK.lock().unwrap_or_else(|error| error.into_inner())
8}
6
9
10#[cfg(test)]
11mod tests {
7 use app_base::ui_locale::{apply_locale, tr};
12 use app_base::ui_locale::{apply_locale, tr};
8
13
9 fn locale_test_lock() -> MutexGuard<'static, ()> {
14 use super::locale_test_lock;
10 static LOCK: Mutex<()> = Mutex::new(());
11 LOCK.lock().unwrap_or_else(|error| error.into_inner())
12 }
13
15
14 #[test]
16 #[test]
15 fn ui_locale_settings_common_actions() {
17 fn ui_locale_settings_common_actions() {
crates/app/src/layout_guard.rs +42 −7
@@ -265,6 +265,10 @@ mod frames {
265 265 ];
266 266 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
267 267 const CALENDAR: &str = "shell/islands/calendar";
268 use crate::views::calendar_picker::{CALENDAR_PANE_TAG, MINI_MONTH_TAG};
269 use crate::views::calendar_view::{
270 CALENDAR_DAY_HEADERS_TAG, CALENDAR_HEADER_TAG, CALENDAR_NEW_MEETING_TAG,
271 };
268 272 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
269 273 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
270 274 const FIND_TAGS: &[&str] = &[
@@ -633,6 +637,11 @@ mod frames {
633 637 &ACTIVITY_PROPOSALS_TAG,
634 638 &AGENTS_LIST,
635 639 &CALENDAR,
640 &CALENDAR_HEADER_TAG,
641 &CALENDAR_DAY_HEADERS_TAG,
642 &CALENDAR_NEW_MEETING_TAG,
643 &CALENDAR_PANE_TAG,
644 &MINI_MONTH_TAG,
636 645 &CALL_TRANSCRIPT,
637 646 &MENU,
638 647 &RECAP_TAB,
@@ -1043,6 +1052,11 @@ mod frames {
1043 1052 !matches!(*path, "shell/islands/sidebar" | "shell/islands/main")
1044 1053 });
1045 1054 expected.push(CALENDAR);
1055 expected.extend([CALENDAR_HEADER_TAG, CALENDAR_DAY_HEADERS_TAG]);
1056 // The calendar list pane hides on narrow windows.
1057 if width >= crate::views::calendar_view::COMPACT_HEADER_WIDTH {
1058 expected.extend([CALENDAR_PANE_TAG, MINI_MONTH_TAG]);
1059 }
1046 1060 }
1047 1061 "prejoin" => expected.extend(PREJOIN_TAGS),
1048 1062 _ => {}
@@ -1066,6 +1080,21 @@ mod frames {
1066 1080 ));
1067 1081 }
1068 1082 }
1083 if screen_name == "calendar"
1084 && let (Some(header), Some(button)) = (
1085 bounds_of(CALENDAR_HEADER_TAG),
1086 bounds_of(CALENDAR_NEW_MEETING_TAG),
1087 )
1088 {
1089 let overflow = f32::from(button.origin.x + button.size.width)
1090 - f32::from(header.origin.x + header.size.width);
1091 if overflow > TOLERANCE {
1092 found.push((
1093 CALENDAR_HEADER_TAG.to_owned(),
1094 format!("header controls overflow by {overflow} px"),
1095 ));
1096 }
1097 }
1069 1098 if status_menu {
1070 1099 let menu = tags
1071 1100 .iter()
@@ -1915,6 +1944,7 @@ mod frames {
1915 1944 const MENU_ITEMS_SCANNED: usize = 40;
1916 1945 const MENU_CHAT: &str = "demo-chat-release";
1917 1946 const THEME_SELECT: &str = "settings-theme";
1947 const CALENDAR_DEFAULT_VIEW_SELECT: &str = "settings-calendar-default-view";
1918 1948
1919 1949 struct MenuRow {
1920 1950 index: usize,
@@ -2136,17 +2166,22 @@ mod frames {
2136 2166
2137 2167 #[gpui_kit::test]
2138 2168 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2169 select_list_lines_up(cx, SettingsSection::Appearance, THEME_SELECT);
2170 }
2171
2172 #[gpui_kit::test]
2173 fn calendar_default_view_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2174 select_list_lines_up(cx, SettingsSection::Calendar, CALENDAR_DEFAULT_VIEW_SELECT);
2175 }
2176
2177 fn select_list_lines_up(cx: &mut TestAppContext, section: SettingsSection, id: &str) {
2139 2178 let (handle, state) = mount(cx);
2140 2179 let mut visual = VisualTestContext::from_window(handle, cx);
2141 2180 visual.simulate_resize(size(px(1280.), px(800.)));
2142 visual.update(|_, cx| {
2143 state.update(cx, |state, cx| {
2144 state.open_settings(SettingsSection::Appearance, cx)
2145 })
2146 });
2147 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
2181 visual.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
2182 let select: &'static str = Box::leak(select_selector(id).into_boxed_str());
2148 2183 collect(&mut visual, Some(select));
2149 let trigger = visual.debug_bounds(select).expect("theme select rendered");
2184 let trigger = visual.debug_bounds(select).expect("select rendered");
2150 2185 visual.simulate_click(trigger.center(), Default::default());
2151 2186 collect(&mut visual, Some(MENU));
2152 2187 let menu = visual.debug_bounds(MENU).expect("list rendered");
@@ -265,6 +265,10 @@ mod frames {
265 ];
265 ];
266 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
266 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
267 const CALENDAR: &str = "shell/islands/calendar";
267 const CALENDAR: &str = "shell/islands/calendar";
268 use crate::views::calendar_picker::{CALENDAR_PANE_TAG, MINI_MONTH_TAG};
269 use crate::views::calendar_view::{
270 CALENDAR_DAY_HEADERS_TAG, CALENDAR_HEADER_TAG, CALENDAR_NEW_MEETING_TAG,
271 };
268 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
272 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
269 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
273 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
270 const FIND_TAGS: &[&str] = &[
274 const FIND_TAGS: &[&str] = &[
@@ -633,6 +637,11 @@ mod frames {
633 &ACTIVITY_PROPOSALS_TAG,
637 &ACTIVITY_PROPOSALS_TAG,
634 &AGENTS_LIST,
638 &AGENTS_LIST,
635 &CALENDAR,
639 &CALENDAR,
640 &CALENDAR_HEADER_TAG,
641 &CALENDAR_DAY_HEADERS_TAG,
642 &CALENDAR_NEW_MEETING_TAG,
643 &CALENDAR_PANE_TAG,
644 &MINI_MONTH_TAG,
636 &CALL_TRANSCRIPT,
645 &CALL_TRANSCRIPT,
637 &MENU,
646 &MENU,
638 &RECAP_TAB,
647 &RECAP_TAB,
@@ -1043,6 +1052,11 @@ mod frames {
1043 !matches!(*path, "shell/islands/sidebar" | "shell/islands/main")
1052 !matches!(*path, "shell/islands/sidebar" | "shell/islands/main")
1044 });
1053 });
1045 expected.push(CALENDAR);
1054 expected.push(CALENDAR);
1055 expected.extend([CALENDAR_HEADER_TAG, CALENDAR_DAY_HEADERS_TAG]);
1056 // The calendar list pane hides on narrow windows.
1057 if width >= crate::views::calendar_view::COMPACT_HEADER_WIDTH {
1058 expected.extend([CALENDAR_PANE_TAG, MINI_MONTH_TAG]);
1059 }
1046 }
1060 }
1047 "prejoin" => expected.extend(PREJOIN_TAGS),
1061 "prejoin" => expected.extend(PREJOIN_TAGS),
1048 _ => {}
1062 _ => {}
@@ -1066,6 +1080,21 @@ mod frames {
1066 ));
1080 ));
1067 }
1081 }
1068 }
1082 }
1083 if screen_name == "calendar"
1084 && let (Some(header), Some(button)) = (
1085 bounds_of(CALENDAR_HEADER_TAG),
1086 bounds_of(CALENDAR_NEW_MEETING_TAG),
1087 )
1088 {
1089 let overflow = f32::from(button.origin.x + button.size.width)
1090 - f32::from(header.origin.x + header.size.width);
1091 if overflow > TOLERANCE {
1092 found.push((
1093 CALENDAR_HEADER_TAG.to_owned(),
1094 format!("header controls overflow by {overflow} px"),
1095 ));
1096 }
1097 }
1069 if status_menu {
1098 if status_menu {
1070 let menu = tags
1099 let menu = tags
1071 .iter()
1100 .iter()
@@ -1915,6 +1944,7 @@ mod frames {
1915 const MENU_ITEMS_SCANNED: usize = 40;
1944 const MENU_ITEMS_SCANNED: usize = 40;
1916 const MENU_CHAT: &str = "demo-chat-release";
1945 const MENU_CHAT: &str = "demo-chat-release";
1917 const THEME_SELECT: &str = "settings-theme";
1946 const THEME_SELECT: &str = "settings-theme";
1947 const CALENDAR_DEFAULT_VIEW_SELECT: &str = "settings-calendar-default-view";
1918
1948
1919 struct MenuRow {
1949 struct MenuRow {
1920 index: usize,
1950 index: usize,
@@ -2136,17 +2166,22 @@ mod frames {
2136
2166
2137 #[gpui_kit::test]
2167 #[gpui_kit::test]
2138 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2168 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2169 select_list_lines_up(cx, SettingsSection::Appearance, THEME_SELECT);
2170 }
2171
2172 #[gpui_kit::test]
2173 fn calendar_default_view_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
2174 select_list_lines_up(cx, SettingsSection::Calendar, CALENDAR_DEFAULT_VIEW_SELECT);
2175 }
2176
2177 fn select_list_lines_up(cx: &mut TestAppContext, section: SettingsSection, id: &str) {
2139 let (handle, state) = mount(cx);
2178 let (handle, state) = mount(cx);
2140 let mut visual = VisualTestContext::from_window(handle, cx);
2179 let mut visual = VisualTestContext::from_window(handle, cx);
2141 visual.simulate_resize(size(px(1280.), px(800.)));
2180 visual.simulate_resize(size(px(1280.), px(800.)));
2142 visual.update(|_, cx| {
2181 visual.update(|_, cx| state.update(cx, |state, cx| state.open_settings(section, cx)));
2143 state.update(cx, |state, cx| {
2182 let select: &'static str = Box::leak(select_selector(id).into_boxed_str());
2144 state.open_settings(SettingsSection::Appearance, cx)
2145 })
2146 });
2147 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
2148 collect(&mut visual, Some(select));
2183 collect(&mut visual, Some(select));
2149 let trigger = visual.debug_bounds(select).expect("theme select rendered");
2184 let trigger = visual.debug_bounds(select).expect("select rendered");
2150 visual.simulate_click(trigger.center(), Default::default());
2185 visual.simulate_click(trigger.center(), Default::default());
2151 collect(&mut visual, Some(MENU));
2186 collect(&mut visual, Some(MENU));
2152 let menu = visual.debug_bounds(MENU).expect("list rendered");
2187 let menu = visual.debug_bounds(MENU).expect("list rendered");
crates/app/src/settings/calendar.rs +345 −24
@@ -1,24 +1,40 @@
1 use gpui_kit::ClipboardItem;
1 2 use gpui_kit::component::v_flex;
2 3 use gpui_kit::*;
3 4 use store::{CalendarProvider, CalendarRef};
4 5
5 use super::rows::{caption, control_row, text_button, toggle_row};
6 use std::collections::HashMap;
7
8 use app_base::format::{WeekdayWidth, clock_format, weekday_name};
9 use chrono::{NaiveTime, Weekday};
10 use gpui_kit::component::h_flex;
11 use gpui_kit::prelude::FluentBuilder as _;
12
13 use super::rows::{
14 Choice, caption, control_row, select, select_with_width, text_button, toggle_row,
15 };
6 16 use crate::app_state::AppState;
17 use crate::call::calendar_prefs::{CalendarPrefs, DefaultView, TimeScale, WeekendWorkWeek};
18 use crate::i18n::tr;
7 19 use crate::theme;
8 20
9 21 pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10 22 let accounts = app.read(cx).calendar_accounts();
23 let pending = app.read(cx).google_connect_pending().is_some();
24 let prefs = app.read(cx).calendar_prefs.clone();
11 25 let mut body = v_flex()
12 26 .w_full()
13 .child(caption("GOOGLE"))
14 .child(connect_row(app, accounts.has_google()));
27 .child(caption(tr("settings.calendar.section_view")))
28 .children(view_rows(app, &prefs, app.read(cx).default_first_day()))
29 .child(caption(tr("settings.calendar.section_google")))
30 .child(connect_row(app, accounts.has_google(), pending));
15 31 for account in &accounts.google_accounts {
16 32 body = body.child(account_block(app, account, &accounts));
17 33 }
18 34 body = body
19 .child(caption("HOME CALENDAR"))
35 .child(caption(tr("settings.calendar.section_home")))
20 36 .child(home_choices(app, &accounts))
21 .child(caption("ALSO WRITE TO"));
37 .child(caption(tr("settings.calendar.section_write")));
22 38 if accounts.home.provider != CalendarProvider::Outlook {
23 39 let write_app = app.clone();
24 40 let target = CalendarRef::outlook();
@@ -29,8 +45,8 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
29 45 body = body.child(
30 46 toggle_row(
31 47 "settings-write-outlook",
32 "Outlook (Microsoft mailbox)",
33 "Dual-write when home is Google",
48 tr("settings.calendar.outlook_mailbox"),
49 tr("settings.calendar.dual_write_when_google_home"),
34 50 theme::text_muted(),
35 51 selected,
36 52 )
@@ -42,28 +58,70 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
42 58 );
43 59 } else if accounts.google_accounts.is_empty() {
44 60 body = body.child(control_row(
45 "No extra write targets",
46 "Connect Google, then enable dual-write on a calendar above.",
61 tr("settings.calendar.no_extra_targets"),
62 tr("settings.calendar.connect_then_dual_write"),
47 63 div(),
48 64 ));
49 65 }
50 66 body
51 67 }
52 68
53 fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {
69 fn connect_row(app: &Entity<AppState>, connected: bool, pending: bool) -> Div {
54 70 let app = app.clone();
55 71 if connected {
56 72 control_row(
57 "Google Calendar",
58 "Connected accounts appear below. Disconnect removes tokens from this device.",
73 tr("settings.calendar.google_title"),
74 tr("settings.calendar.connected_detail"),
59 75 div(),
60 76 )
77 } else if pending {
78 let reopen = app.clone();
79 let copy = app.clone();
80 let cancel = app.clone();
81 control_row(
82 tr("settings.calendar.google_title"),
83 tr("settings.calendar.finish_in_browser"),
84 div()
85 .flex()
86 .gap_2()
87 .child(
88 text_button(
89 "settings-google-reopen",
90 tr("settings.calendar.open_browser_again"),
91 )
92 .on_click(move |_, _, cx| {
93 reopen.update(cx, |state, cx| state.reopen_google_connect(cx))
94 }),
95 )
96 .child(
97 text_button("settings-google-copy", tr("settings.calendar.copy_link"))
98 .on_click(move |_, _, cx| {
99 if let Some(url) =
100 copy.read(cx).google_connect_pending().map(str::to_owned)
101 {
102 cx.write_to_clipboard(ClipboardItem::new_string(url));
103 }
104 }),
105 )
106 .child(
107 text_button("settings-google-cancel", tr("common.cancel")).on_click(
108 move |_, _, cx| {
109 cancel.update(cx, |state, cx| state.cancel_google_connect(cx))
110 },
111 ),
112 ),
113 )
61 114 } else {
115 let connect = app.clone();
62 116 control_row(
63 "Google Calendar",
64 "Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",
65 text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {
66 app.update(cx, |state, cx| state.connect_google_calendar(cx))
117 tr("settings.calendar.google_title"),
118 tr("settings.calendar.connect_hint"),
119 text_button(
120 "settings-google-connect",
121 tr("settings.calendar.connect_button"),
122 )
123 .on_click(move |_, _, cx| {
124 connect.update(cx, |state, cx| state.connect_google_calendar(cx))
67 125 }),
68 126 )
69 127 }
@@ -78,10 +136,10 @@ fn account_block(
78 136 let account_id = account.id.clone();
79 137 let mut block = v_flex().w_full().child(control_row(
80 138 account.email.clone(),
81 "Google account",
139 tr("settings.calendar.google_account"),
82 140 text_button(
83 141 format!("settings-google-disconnect-{}", account.id),
84 "Disconnect",
142 tr("settings.calendar.disconnect"),
85 143 )
86 144 .on_click(move |_, _, cx| {
87 145 disconnect_app.update(cx, |state, cx| {
@@ -104,9 +162,9 @@ fn account_block(
104 162 format!("settings-google-cal-{}", calendar.id),
105 163 calendar.summary.clone(),
106 164 if calendar.primary {
107 "Primary calendar"
165 tr("settings.calendar.primary")
108 166 } else {
109 "Show in calendar grid"
167 tr("settings.calendar.show_in_grid")
110 168 },
111 169 theme::text_muted(),
112 170 calendar.selected,
@@ -123,7 +181,7 @@ fn account_block(
123 181 block = block.child(
124 182 toggle_row(
125 183 format!("settings-google-write-{}", calendar.id),
126 format!("Also write new meetings to {}", calendar.summary),
184 tr_args_write(&calendar.summary),
127 185 "",
128 186 theme::text_muted(),
129 187 is_write,
@@ -139,6 +197,12 @@ fn account_block(
139 197 block
140 198 }
141 199
200 fn tr_args_write(summary: &str) -> String {
201 let mut args = std::collections::HashMap::new();
202 args.insert("name".to_owned(), summary.to_owned());
203 crate::i18n::tr_args("settings.calendar.also_write_to", &args)
204 }
205
142 206 fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
143 207 let mut choices = v_flex().w_full();
144 208 let outlook_app = app.clone();
@@ -146,8 +210,8 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
146 210 choices = choices.child(
147 211 toggle_row(
148 212 "settings-home-outlook",
149 "Outlook (Microsoft mailbox)",
150 "Default when no Google home is chosen",
213 tr("settings.calendar.outlook_mailbox"),
214 tr("settings.calendar.outlook_home_detail"),
151 215 theme::text_muted(),
152 216 outlook_home,
153 217 )
@@ -165,7 +229,11 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
165 229 choices = choices.child(
166 230 toggle_row(
167 231 format!("settings-home-google-{}", calendar.id),
168 format!("Google · {}", calendar.summary),
232 format!(
233 "{} · {}",
234 tr("settings.calendar.google_label"),
235 calendar.summary
236 ),
169 237 account.email.clone(),
170 238 theme::text_muted(),
171 239 selected,
@@ -178,3 +246,256 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
178 246 }
179 247 choices
180 248 }
249
250 const FIRST_DAY_CHOICES: [Weekday; 3] = [Weekday::Mon, Weekday::Sun, Weekday::Sat];
251 const CHIP_SIZE: f32 = 32.;
252 const TIME_SELECT_WIDTH: f32 = 104.;
253
254 /// Default view, first day, work days and hours, time scale, weekend Work week.
255 fn view_rows(
256 app: &Entity<AppState>,
257 prefs: &CalendarPrefs,
258 default_first_day: Weekday,
259 ) -> Vec<Div> {
260 vec![
261 control_row(
262 tr("settings.calendar.default_view"),
263 tr("settings.calendar.default_view_detail"),
264 select(
265 "settings-calendar-default-view",
266 default_view_label(prefs.default_view),
267 false,
268 DefaultView::ALL
269 .into_iter()
270 .map(|view| {
271 prefs_choice(
272 app,
273 default_view_label(view),
274 prefs.default_view == view,
275 move |prefs| prefs.default_view = view,
276 )
277 })
278 .collect(),
279 ),
280 ),
281 control_row(
282 tr("settings.calendar.first_day"),
283 tr("settings.calendar.first_day_detail"),
284 select(
285 "settings-calendar-first-day",
286 first_day_label(prefs.first_day, default_first_day),
287 false,
288 std::iter::once(None)
289 .chain(FIRST_DAY_CHOICES.into_iter().map(Some))
290 .map(|day| {
291 prefs_choice(
292 app,
293 first_day_label(day, default_first_day),
294 prefs.first_day == day,
295 move |prefs| prefs.first_day = day,
296 )
297 })
298 .collect(),
299 ),
300 ),
301 control_row(
302 tr("settings.calendar.work_days"),
303 tr("settings.calendar.mailbox_detail"),
304 work_day_chips(app, prefs, default_first_day),
305 ),
306 control_row(
307 tr("settings.calendar.work_hours"),
308 tr("settings.calendar.mailbox_detail"),
309 h_flex()
310 .gap(px(8.))
311 .child(work_time_select(app, prefs, true))
312 .child(work_time_select(app, prefs, false)),
313 ),
314 control_row(
315 tr("settings.calendar.time_scale"),
316 tr("settings.calendar.time_scale_detail"),
317 select(
318 "settings-calendar-time-scale",
319 time_scale_label(prefs.time_scale),
320 false,
321 TimeScale::ALL
322 .into_iter()
323 .map(|scale| {
324 prefs_choice(
325 app,
326 time_scale_label(scale),
327 prefs.time_scale == scale,
328 move |prefs| prefs.time_scale = scale,
329 )
330 })
331 .collect(),
332 ),
333 ),
334 control_row(
335 tr("settings.calendar.weekend"),
336 tr("settings.calendar.weekend_detail"),
337 select(
338 "settings-calendar-weekend",
339 weekend_label(prefs.weekend_work_week),
340 false,
341 [WeekendWorkWeek::NextWeek, WeekendWorkWeek::ThisWeek]
342 .into_iter()
343 .map(|rule| {
344 prefs_choice(
345 app,
346 weekend_label(rule),
347 prefs.weekend_work_week == rule,
348 move |prefs| prefs.weekend_work_week = rule,
349 )
350 })
351 .collect(),
352 ),
353 ),
354 ]
355 }
356
357 fn prefs_choice(
358 app: &Entity<AppState>,
359 label: String,
360 checked: bool,
361 change: impl Fn(&mut CalendarPrefs) + 'static,
362 ) -> Choice {
363 let app = app.clone();
364 let change = std::rc::Rc::new(change);
365 Choice::new(label, checked, move |cx| {
366 let change = change.clone();
367 app.update(cx, |state, cx| {
368 state.update_calendar_prefs(|prefs| change(prefs), cx)
369 });
370 })
371 }
372
373 fn default_view_label(view: DefaultView) -> String {
374 view.span()
375 .map_or_else(|| tr("settings.calendar.last_used"), |span| span.label())
376 }
377
378 fn first_day_label(day: Option<Weekday>, default_first_day: Weekday) -> String {
379 match day {
380 Some(day) => weekday_name(day, WeekdayWidth::Full),
381 None => {
382 let mut args = HashMap::new();
383 args.insert(
384 "day".to_owned(),
385 weekday_name(default_first_day, WeekdayWidth::Full),
386 );
387 crate::i18n::tr_args("settings.calendar.first_day_regional", &args)
388 }
389 }
390 }
391
392 fn time_scale_label(scale: TimeScale) -> String {
393 let mut args = HashMap::new();
394 args.insert("count".to_owned(), scale.minutes().to_string());
395 crate::i18n::tr_args("settings.calendar.minutes", &args)
396 }
397
398 fn weekend_label(rule: WeekendWorkWeek) -> String {
399 match rule {
400 WeekendWorkWeek::NextWeek => tr("settings.calendar.weekend_next"),
401 WeekendWorkWeek::ThisWeek => tr("settings.calendar.weekend_this"),
402 }
403 }
404
405 /// Seven day chips from the first day of week; the last work day cannot be turned off.
406 fn work_day_chips(
407 app: &Entity<AppState>,
408 prefs: &CalendarPrefs,
409 default_first_day: Weekday,
410 ) -> Div {
411 let layout = prefs.layout(default_first_day);
412 h_flex()
413 .gap(px(4.))
414 .children(layout.weekdays().into_iter().map(|day| {
415 let on = prefs.work_hours.is_work_day(day);
416 let last = on && prefs.work_hours.days.len() == 1;
417 let app = app.clone();
418 let hours = prefs.work_hours.clone();
419 div()
420 .id(SharedString::from(format!(
421 "settings-calendar-work-day-{day}"
422 )))
423 .size(px(CHIP_SIZE))
424 .flex()
425 .items_center()
426 .justify_center()
427 .rounded(px(6.))
428 .text_size(px(12.))
429 .font_weight(FontWeight::SEMIBOLD)
430 .map(|chip| {
431 if on {
432 chip.bg(theme::accent()).text_color(theme::on_accent())
433 } else {
434 chip.bg(theme::surface_raised())
435 .text_color(theme::text_soft())
436 .hover(|chip| chip.bg(theme::popup_hover()))
437 }
438 })
439 .when(!last, |chip| {
440 chip.cursor_pointer().on_click(move |_, _, cx| {
441 let mut hours = hours.clone();
442 if on {
443 hours.days.retain(|existing| *existing != day);
444 } else {
445 hours.days.push(day);
446 hours.days.sort_by_key(Weekday::num_days_from_monday);
447 }
448 app.update(cx, |state, cx| state.set_work_hours(hours, cx));
449 })
450 })
451 .child(weekday_name(day, WeekdayWidth::Short))
452 }))
453 }
454
455 /// Start or end of work in 30-minute steps; end choices stay after the start.
456 fn work_time_select(
457 app: &Entity<AppState>,
458 prefs: &CalendarPrefs,
459 start: bool,
460 ) -> impl IntoElement {
461 let hours = prefs.work_hours.clone();
462 let current = if start { hours.start } else { hours.end };
463 let choices = (0..48)
464 .filter_map(|step| NaiveTime::from_hms_opt(step / 2, (step % 2) * 30, 0))
465 .filter(|time| {
466 if start {
467 *time < hours.end
468 } else {
469 *time > hours.start
470 }
471 })
472 .map(|time| {
473 let app = app.clone();
474 let mut wanted = hours.clone();
475 if start {
476 wanted.start = time;
477 } else {
478 wanted.end = time;
479 }
480 Choice::new(
481 time.format(clock_format()).to_string(),
482 time == current,
483 move |cx| {
484 let wanted = wanted.clone();
485 app.update(cx, |state, cx| state.set_work_hours(wanted, cx));
486 },
487 )
488 })
489 .collect();
490 select_with_width(
491 if start {
492 "settings-calendar-work-start"
493 } else {
494 "settings-calendar-work-end"
495 },
496 current.format(clock_format()).to_string(),
497 TIME_SELECT_WIDTH,
498 false,
499 choices,
500 )
501 }
@@ -1,24 +1,40 @@
1use gpui_kit::ClipboardItem;
1use gpui_kit::component::v_flex;
2use gpui_kit::component::v_flex;
2use gpui_kit::*;
3use gpui_kit::*;
3use store::{CalendarProvider, CalendarRef};
4use store::{CalendarProvider, CalendarRef};
4
5
5use super::rows::{caption, control_row, text_button, toggle_row};
6use std::collections::HashMap;
7
8use app_base::format::{WeekdayWidth, clock_format, weekday_name};
9use chrono::{NaiveTime, Weekday};
10use gpui_kit::component::h_flex;
11use gpui_kit::prelude::FluentBuilder as _;
12
13use super::rows::{
14 Choice, caption, control_row, select, select_with_width, text_button, toggle_row,
15};
6use crate::app_state::AppState;
16use crate::app_state::AppState;
17use crate::call::calendar_prefs::{CalendarPrefs, DefaultView, TimeScale, WeekendWorkWeek};
18use crate::i18n::tr;
7use crate::theme;
19use crate::theme;
8
20
9pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
21pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10 let accounts = app.read(cx).calendar_accounts();
22 let accounts = app.read(cx).calendar_accounts();
23 let pending = app.read(cx).google_connect_pending().is_some();
24 let prefs = app.read(cx).calendar_prefs.clone();
11 let mut body = v_flex()
25 let mut body = v_flex()
12 .w_full()
26 .w_full()
13 .child(caption("GOOGLE"))
27 .child(caption(tr("settings.calendar.section_view")))
14 .child(connect_row(app, accounts.has_google()));
28 .children(view_rows(app, &prefs, app.read(cx).default_first_day()))
29 .child(caption(tr("settings.calendar.section_google")))
30 .child(connect_row(app, accounts.has_google(), pending));
15 for account in &accounts.google_accounts {
31 for account in &accounts.google_accounts {
16 body = body.child(account_block(app, account, &accounts));
32 body = body.child(account_block(app, account, &accounts));
17 }
33 }
18 body = body
34 body = body
19 .child(caption("HOME CALENDAR"))
35 .child(caption(tr("settings.calendar.section_home")))
20 .child(home_choices(app, &accounts))
36 .child(home_choices(app, &accounts))
21 .child(caption("ALSO WRITE TO"));
37 .child(caption(tr("settings.calendar.section_write")));
22 if accounts.home.provider != CalendarProvider::Outlook {
38 if accounts.home.provider != CalendarProvider::Outlook {
23 let write_app = app.clone();
39 let write_app = app.clone();
24 let target = CalendarRef::outlook();
40 let target = CalendarRef::outlook();
@@ -29,8 +45,8 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
29 body = body.child(
45 body = body.child(
30 toggle_row(
46 toggle_row(
31 "settings-write-outlook",
47 "settings-write-outlook",
32 "Outlook (Microsoft mailbox)",
48 tr("settings.calendar.outlook_mailbox"),
33 "Dual-write when home is Google",
49 tr("settings.calendar.dual_write_when_google_home"),
34 theme::text_muted(),
50 theme::text_muted(),
35 selected,
51 selected,
36 )
52 )
@@ -42,28 +58,70 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
42 );
58 );
43 } else if accounts.google_accounts.is_empty() {
59 } else if accounts.google_accounts.is_empty() {
44 body = body.child(control_row(
60 body = body.child(control_row(
45 "No extra write targets",
61 tr("settings.calendar.no_extra_targets"),
46 "Connect Google, then enable dual-write on a calendar above.",
62 tr("settings.calendar.connect_then_dual_write"),
47 div(),
63 div(),
48 ));
64 ));
49 }
65 }
50 body
66 body
51}
67}
52
68
53fn connect_row(app: &Entity<AppState>, connected: bool) -> Div {
69fn connect_row(app: &Entity<AppState>, connected: bool, pending: bool) -> Div {
54 let app = app.clone();
70 let app = app.clone();
55 if connected {
71 if connected {
56 control_row(
72 control_row(
57 "Google Calendar",
73 tr("settings.calendar.google_title"),
58 "Connected accounts appear below. Disconnect removes tokens from this device.",
74 tr("settings.calendar.connected_detail"),
59 div(),
75 div(),
60 )
76 )
77 } else if pending {
78 let reopen = app.clone();
79 let copy = app.clone();
80 let cancel = app.clone();
81 control_row(
82 tr("settings.calendar.google_title"),
83 tr("settings.calendar.finish_in_browser"),
84 div()
85 .flex()
86 .gap_2()
87 .child(
88 text_button(
89 "settings-google-reopen",
90 tr("settings.calendar.open_browser_again"),
91 )
92 .on_click(move |_, _, cx| {
93 reopen.update(cx, |state, cx| state.reopen_google_connect(cx))
94 }),
95 )
96 .child(
97 text_button("settings-google-copy", tr("settings.calendar.copy_link"))
98 .on_click(move |_, _, cx| {
99 if let Some(url) =
100 copy.read(cx).google_connect_pending().map(str::to_owned)
101 {
102 cx.write_to_clipboard(ClipboardItem::new_string(url));
103 }
104 }),
105 )
106 .child(
107 text_button("settings-google-cancel", tr("common.cancel")).on_click(
108 move |_, _, cx| {
109 cancel.update(cx, |state, cx| state.cancel_google_connect(cx))
110 },
111 ),
112 ),
113 )
61 } else {
114 } else {
115 let connect = app.clone();
62 control_row(
116 control_row(
63 "Google Calendar",
117 tr("settings.calendar.google_title"),
64 "Requires TEAMS_GOOGLE_CLIENT_ID. Opens a browser for sign-in.",
118 tr("settings.calendar.connect_hint"),
65 text_button("settings-google-connect", "Connect Google").on_click(move |_, _, cx| {
119 text_button(
66 app.update(cx, |state, cx| state.connect_google_calendar(cx))
120 "settings-google-connect",
121 tr("settings.calendar.connect_button"),
122 )
123 .on_click(move |_, _, cx| {
124 connect.update(cx, |state, cx| state.connect_google_calendar(cx))
67 }),
125 }),
68 )
126 )
69 }
127 }
@@ -78,10 +136,10 @@ fn account_block(
78 let account_id = account.id.clone();
136 let account_id = account.id.clone();
79 let mut block = v_flex().w_full().child(control_row(
137 let mut block = v_flex().w_full().child(control_row(
80 account.email.clone(),
138 account.email.clone(),
81 "Google account",
139 tr("settings.calendar.google_account"),
82 text_button(
140 text_button(
83 format!("settings-google-disconnect-{}", account.id),
141 format!("settings-google-disconnect-{}", account.id),
84 "Disconnect",
142 tr("settings.calendar.disconnect"),
85 )
143 )
86 .on_click(move |_, _, cx| {
144 .on_click(move |_, _, cx| {
87 disconnect_app.update(cx, |state, cx| {
145 disconnect_app.update(cx, |state, cx| {
@@ -104,9 +162,9 @@ fn account_block(
104 format!("settings-google-cal-{}", calendar.id),
162 format!("settings-google-cal-{}", calendar.id),
105 calendar.summary.clone(),
163 calendar.summary.clone(),
106 if calendar.primary {
164 if calendar.primary {
107 "Primary calendar"
165 tr("settings.calendar.primary")
108 } else {
166 } else {
109 "Show in calendar grid"
167 tr("settings.calendar.show_in_grid")
110 },
168 },
111 theme::text_muted(),
169 theme::text_muted(),
112 calendar.selected,
170 calendar.selected,
@@ -123,7 +181,7 @@ fn account_block(
123 block = block.child(
181 block = block.child(
124 toggle_row(
182 toggle_row(
125 format!("settings-google-write-{}", calendar.id),
183 format!("settings-google-write-{}", calendar.id),
126 format!("Also write new meetings to {}", calendar.summary),
184 tr_args_write(&calendar.summary),
127 "",
185 "",
128 theme::text_muted(),
186 theme::text_muted(),
129 is_write,
187 is_write,
@@ -139,6 +197,12 @@ fn account_block(
139 block
197 block
140}
198}
141
199
200fn tr_args_write(summary: &str) -> String {
201 let mut args = std::collections::HashMap::new();
202 args.insert("name".to_owned(), summary.to_owned());
203 crate::i18n::tr_args("settings.calendar.also_write_to", &args)
204}
205
142fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
206fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> Div {
143 let mut choices = v_flex().w_full();
207 let mut choices = v_flex().w_full();
144 let outlook_app = app.clone();
208 let outlook_app = app.clone();
@@ -146,8 +210,8 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
146 choices = choices.child(
210 choices = choices.child(
147 toggle_row(
211 toggle_row(
148 "settings-home-outlook",
212 "settings-home-outlook",
149 "Outlook (Microsoft mailbox)",
213 tr("settings.calendar.outlook_mailbox"),
150 "Default when no Google home is chosen",
214 tr("settings.calendar.outlook_home_detail"),
151 theme::text_muted(),
215 theme::text_muted(),
152 outlook_home,
216 outlook_home,
153 )
217 )
@@ -165,7 +229,11 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
165 choices = choices.child(
229 choices = choices.child(
166 toggle_row(
230 toggle_row(
167 format!("settings-home-google-{}", calendar.id),
231 format!("settings-home-google-{}", calendar.id),
168 format!("Google · {}", calendar.summary),
232 format!(
233 "{} · {}",
234 tr("settings.calendar.google_label"),
235 calendar.summary
236 ),
169 account.email.clone(),
237 account.email.clone(),
170 theme::text_muted(),
238 theme::text_muted(),
171 selected,
239 selected,
@@ -178,3 +246,256 @@ fn home_choices(app: &Entity<AppState>, accounts: &store::CalendarAccounts) -> D
178 }
246 }
179 choices
247 choices
180}
248}
249
250const FIRST_DAY_CHOICES: [Weekday; 3] = [Weekday::Mon, Weekday::Sun, Weekday::Sat];
251const CHIP_SIZE: f32 = 32.;
252const TIME_SELECT_WIDTH: f32 = 104.;
253
254/// Default view, first day, work days and hours, time scale, weekend Work week.
255fn view_rows(
256 app: &Entity<AppState>,
257 prefs: &CalendarPrefs,
258 default_first_day: Weekday,
259) -> Vec<Div> {
260 vec![
261 control_row(
262 tr("settings.calendar.default_view"),
263 tr("settings.calendar.default_view_detail"),
264 select(
265 "settings-calendar-default-view",
266 default_view_label(prefs.default_view),
267 false,
268 DefaultView::ALL
269 .into_iter()
270 .map(|view| {
271 prefs_choice(
272 app,
273 default_view_label(view),
274 prefs.default_view == view,
275 move |prefs| prefs.default_view = view,
276 )
277 })
278 .collect(),
279 ),
280 ),
281 control_row(
282 tr("settings.calendar.first_day"),
283 tr("settings.calendar.first_day_detail"),
284 select(
285 "settings-calendar-first-day",
286 first_day_label(prefs.first_day, default_first_day),
287 false,
288 std::iter::once(None)
289 .chain(FIRST_DAY_CHOICES.into_iter().map(Some))
290 .map(|day| {
291 prefs_choice(
292 app,
293 first_day_label(day, default_first_day),
294 prefs.first_day == day,
295 move |prefs| prefs.first_day = day,
296 )
297 })
298 .collect(),
299 ),
300 ),
301 control_row(
302 tr("settings.calendar.work_days"),
303 tr("settings.calendar.mailbox_detail"),
304 work_day_chips(app, prefs, default_first_day),
305 ),
306 control_row(
307 tr("settings.calendar.work_hours"),
308 tr("settings.calendar.mailbox_detail"),
309 h_flex()
310 .gap(px(8.))
311 .child(work_time_select(app, prefs, true))
312 .child(work_time_select(app, prefs, false)),
313 ),
314 control_row(
315 tr("settings.calendar.time_scale"),
316 tr("settings.calendar.time_scale_detail"),
317 select(
318 "settings-calendar-time-scale",
319 time_scale_label(prefs.time_scale),
320 false,
321 TimeScale::ALL
322 .into_iter()
323 .map(|scale| {
324 prefs_choice(
325 app,
326 time_scale_label(scale),
327 prefs.time_scale == scale,
328 move |prefs| prefs.time_scale = scale,
329 )
330 })
331 .collect(),
332 ),
333 ),
334 control_row(
335 tr("settings.calendar.weekend"),
336 tr("settings.calendar.weekend_detail"),
337 select(
338 "settings-calendar-weekend",
339 weekend_label(prefs.weekend_work_week),
340 false,
341 [WeekendWorkWeek::NextWeek, WeekendWorkWeek::ThisWeek]
342 .into_iter()
343 .map(|rule| {
344 prefs_choice(
345 app,
346 weekend_label(rule),
347 prefs.weekend_work_week == rule,
348 move |prefs| prefs.weekend_work_week = rule,
349 )
350 })
351 .collect(),
352 ),
353 ),
354 ]
355}
356
357fn prefs_choice(
358 app: &Entity<AppState>,
359 label: String,
360 checked: bool,
361 change: impl Fn(&mut CalendarPrefs) + 'static,
362) -> Choice {
363 let app = app.clone();
364 let change = std::rc::Rc::new(change);
365 Choice::new(label, checked, move |cx| {
366 let change = change.clone();
367 app.update(cx, |state, cx| {
368 state.update_calendar_prefs(|prefs| change(prefs), cx)
369 });
370 })
371}
372
373fn default_view_label(view: DefaultView) -> String {
374 view.span()
375 .map_or_else(|| tr("settings.calendar.last_used"), |span| span.label())
376}
377
378fn first_day_label(day: Option<Weekday>, default_first_day: Weekday) -> String {
379 match day {
380 Some(day) => weekday_name(day, WeekdayWidth::Full),
381 None => {
382 let mut args = HashMap::new();
383 args.insert(
384 "day".to_owned(),
385 weekday_name(default_first_day, WeekdayWidth::Full),
386 );
387 crate::i18n::tr_args("settings.calendar.first_day_regional", &args)
388 }
389 }
390}
391
392fn time_scale_label(scale: TimeScale) -> String {
393 let mut args = HashMap::new();
394 args.insert("count".to_owned(), scale.minutes().to_string());
395 crate::i18n::tr_args("settings.calendar.minutes", &args)
396}
397
398fn weekend_label(rule: WeekendWorkWeek) -> String {
399 match rule {
400 WeekendWorkWeek::NextWeek => tr("settings.calendar.weekend_next"),
401 WeekendWorkWeek::ThisWeek => tr("settings.calendar.weekend_this"),
402 }
403}
404
405/// Seven day chips from the first day of week; the last work day cannot be turned off.
406fn work_day_chips(
407 app: &Entity<AppState>,
408 prefs: &CalendarPrefs,
409 default_first_day: Weekday,
410) -> Div {
411 let layout = prefs.layout(default_first_day);
412 h_flex()
413 .gap(px(4.))
414 .children(layout.weekdays().into_iter().map(|day| {
415 let on = prefs.work_hours.is_work_day(day);
416 let last = on && prefs.work_hours.days.len() == 1;
417 let app = app.clone();
418 let hours = prefs.work_hours.clone();
419 div()
420 .id(SharedString::from(format!(
421 "settings-calendar-work-day-{day}"
422 )))
423 .size(px(CHIP_SIZE))
424 .flex()
425 .items_center()
426 .justify_center()
427 .rounded(px(6.))
428 .text_size(px(12.))
429 .font_weight(FontWeight::SEMIBOLD)
430 .map(|chip| {
431 if on {
432 chip.bg(theme::accent()).text_color(theme::on_accent())
433 } else {
434 chip.bg(theme::surface_raised())
435 .text_color(theme::text_soft())
436 .hover(|chip| chip.bg(theme::popup_hover()))
437 }
438 })
439 .when(!last, |chip| {
440 chip.cursor_pointer().on_click(move |_, _, cx| {
441 let mut hours = hours.clone();
442 if on {
443 hours.days.retain(|existing| *existing != day);
444 } else {
445 hours.days.push(day);
446 hours.days.sort_by_key(Weekday::num_days_from_monday);
447 }
448 app.update(cx, |state, cx| state.set_work_hours(hours, cx));
449 })
450 })
451 .child(weekday_name(day, WeekdayWidth::Short))
452 }))
453}
454
455/// Start or end of work in 30-minute steps; end choices stay after the start.
456fn work_time_select(
457 app: &Entity<AppState>,
458 prefs: &CalendarPrefs,
459 start: bool,
460) -> impl IntoElement {
461 let hours = prefs.work_hours.clone();
462 let current = if start { hours.start } else { hours.end };
463 let choices = (0..48)
464 .filter_map(|step| NaiveTime::from_hms_opt(step / 2, (step % 2) * 30, 0))
465 .filter(|time| {
466 if start {
467 *time < hours.end
468 } else {
469 *time > hours.start
470 }
471 })
472 .map(|time| {
473 let app = app.clone();
474 let mut wanted = hours.clone();
475 if start {
476 wanted.start = time;
477 } else {
478 wanted.end = time;
479 }
480 Choice::new(
481 time.format(clock_format()).to_string(),
482 time == current,
483 move |cx| {
484 let wanted = wanted.clone();
485 app.update(cx, |state, cx| state.set_work_hours(wanted, cx));
486 },
487 )
488 })
489 .collect();
490 select_with_width(
491 if start {
492 "settings-calendar-work-start"
493 } else {
494 "settings-calendar-work-end"
495 },
496 current.format(clock_format()).to_string(),
497 TIME_SELECT_WIDTH,
498 false,
499 choices,
500 )
501}
crates/app/src/settings/nav.rs +19 −11
@@ -27,6 +27,20 @@ const ITEM_RADIUS: f32 = 6.;
27 27 const ITEM_ICON: f32 = 16.;
28 28 const NAV_PADDING_X: f32 = 12.;
29 29
30 const CALENDAR_TERMS: [&str; 11] = [
31 "settings.calendar.default_view",
32 "settings.calendar.first_day",
33 "settings.calendar.work_days",
34 "settings.calendar.work_hours",
35 "settings.calendar.time_scale",
36 "settings.calendar.weekend",
37 "settings.calendar.google_title",
38 "settings.calendar.connect_button",
39 "settings.calendar.section_home",
40 "settings.calendar.section_write",
41 "settings.calendar.outlook_mailbox",
42 ];
43
30 44 fn search_terms(section: SettingsSection) -> Vec<String> {
31 45 match section {
32 46 SettingsSection::General => vec![
@@ -34,10 +48,6 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
34 48 tr("settings.general.open_in_background"),
35 49 tr("settings.general.close_to_tray"),
36 50 tr("settings.general.external_browser"),
37 #[cfg(target_os = "linux")]
38 tr("install.menu_title"),
39 #[cfg(target_os = "linux")]
40 tr("install.updates_title"),
41 51 tr("settings.general.up_arrow"),
42 52 tr("settings.general.translate_into"),
43 53 tr("settings.general.behavior_title"),
@@ -70,13 +80,7 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
70 80 tr("settings.chats.markdown"),
71 81 ],
72 82 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
73 SettingsSection::Calendar => vec![
74 "Google Calendar".to_owned(),
75 "Connect Google".to_owned(),
76 "Home calendar".to_owned(),
77 "Also write to".to_owned(),
78 "Outlook".to_owned(),
79 ],
83 SettingsSection::Calendar => CALENDAR_TERMS.iter().map(|key| tr(key)).collect(),
80 84 SettingsSection::Devices => vec![
81 85 "Speaker".to_owned(),
82 86 "Microphone".to_owned(),
@@ -369,6 +373,7 @@ mod tests {
369 373
370 374 #[test]
371 375 fn search_finds_sections_by_name_and_by_setting() {
376 let _guard = crate::i18n::locale_test_lock();
372 377 apply_locale("en");
373 378 assert!(matches(SettingsSection::Chats, "read receipts"));
374 379 assert!(matches(SettingsSection::Devices, "MICRO"));
@@ -417,12 +422,14 @@ mod tests {
417 422 "settings.chats.enter_to",
418 423 "settings.chats.markdown",
419 424 ],
425 SettingsSection::Calendar => &super::CALENDAR_TERMS,
420 426 _ => &[],
421 427 }
422 428 }
423 429
424 430 #[test]
425 431 fn every_search_term_names_a_setting_on_its_page() {
432 let _guard = crate::i18n::locale_test_lock();
426 433 apply_locale("en");
427 434 let pages = [
428 435 (SettingsSection::General, include_str!("general.rs")),
@@ -432,6 +439,7 @@ mod tests {
432 439 ),
433 440 (SettingsSection::Appearance, include_str!("appearance.rs")),
434 441 (SettingsSection::Devices, include_str!("devices.rs")),
442 (SettingsSection::Calendar, include_str!("calendar.rs")),
435 443 ];
436 444 for (section, source) in pages {
437 445 for key in search_term_keys(section) {
@@ -27,6 +27,20 @@ const ITEM_RADIUS: f32 = 6.;
27const ITEM_ICON: f32 = 16.;
27const ITEM_ICON: f32 = 16.;
28const NAV_PADDING_X: f32 = 12.;
28const NAV_PADDING_X: f32 = 12.;
29
29
30const CALENDAR_TERMS: [&str; 11] = [
31 "settings.calendar.default_view",
32 "settings.calendar.first_day",
33 "settings.calendar.work_days",
34 "settings.calendar.work_hours",
35 "settings.calendar.time_scale",
36 "settings.calendar.weekend",
37 "settings.calendar.google_title",
38 "settings.calendar.connect_button",
39 "settings.calendar.section_home",
40 "settings.calendar.section_write",
41 "settings.calendar.outlook_mailbox",
42];
43
30fn search_terms(section: SettingsSection) -> Vec<String> {
44fn search_terms(section: SettingsSection) -> Vec<String> {
31 match section {
45 match section {
32 SettingsSection::General => vec![
46 SettingsSection::General => vec![
@@ -34,10 +48,6 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
34 tr("settings.general.open_in_background"),
48 tr("settings.general.open_in_background"),
35 tr("settings.general.close_to_tray"),
49 tr("settings.general.close_to_tray"),
36 tr("settings.general.external_browser"),
50 tr("settings.general.external_browser"),
37 #[cfg(target_os = "linux")]
38 tr("install.menu_title"),
39 #[cfg(target_os = "linux")]
40 tr("install.updates_title"),
41 tr("settings.general.up_arrow"),
51 tr("settings.general.up_arrow"),
42 tr("settings.general.translate_into"),
52 tr("settings.general.translate_into"),
43 tr("settings.general.behavior_title"),
53 tr("settings.general.behavior_title"),
@@ -70,13 +80,7 @@ fn search_terms(section: SettingsSection) -> Vec<String> {
70 tr("settings.chats.markdown"),
80 tr("settings.chats.markdown"),
71 ],
81 ],
72 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
82 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
73 SettingsSection::Calendar => vec![
83 SettingsSection::Calendar => CALENDAR_TERMS.iter().map(|key| tr(key)).collect(),
74 "Google Calendar".to_owned(),
75 "Connect Google".to_owned(),
76 "Home calendar".to_owned(),
77 "Also write to".to_owned(),
78 "Outlook".to_owned(),
79 ],
80 SettingsSection::Devices => vec![
84 SettingsSection::Devices => vec![
81 "Speaker".to_owned(),
85 "Speaker".to_owned(),
82 "Microphone".to_owned(),
86 "Microphone".to_owned(),
@@ -369,6 +373,7 @@ mod tests {
369
373
370 #[test]
374 #[test]
371 fn search_finds_sections_by_name_and_by_setting() {
375 fn search_finds_sections_by_name_and_by_setting() {
376 let _guard = crate::i18n::locale_test_lock();
372 apply_locale("en");
377 apply_locale("en");
373 assert!(matches(SettingsSection::Chats, "read receipts"));
378 assert!(matches(SettingsSection::Chats, "read receipts"));
374 assert!(matches(SettingsSection::Devices, "MICRO"));
379 assert!(matches(SettingsSection::Devices, "MICRO"));
@@ -417,12 +422,14 @@ mod tests {
417 "settings.chats.enter_to",
422 "settings.chats.enter_to",
418 "settings.chats.markdown",
423 "settings.chats.markdown",
419 ],
424 ],
425 SettingsSection::Calendar => &super::CALENDAR_TERMS,
420 _ => &[],
426 _ => &[],
421 }
427 }
422 }
428 }
423
429
424 #[test]
430 #[test]
425 fn every_search_term_names_a_setting_on_its_page() {
431 fn every_search_term_names_a_setting_on_its_page() {
432 let _guard = crate::i18n::locale_test_lock();
426 apply_locale("en");
433 apply_locale("en");
427 let pages = [
434 let pages = [
428 (SettingsSection::General, include_str!("general.rs")),
435 (SettingsSection::General, include_str!("general.rs")),
@@ -432,6 +439,7 @@ mod tests {
432 ),
439 ),
433 (SettingsSection::Appearance, include_str!("appearance.rs")),
440 (SettingsSection::Appearance, include_str!("appearance.rs")),
434 (SettingsSection::Devices, include_str!("devices.rs")),
441 (SettingsSection::Devices, include_str!("devices.rs")),
442 (SettingsSection::Calendar, include_str!("calendar.rs")),
435 ];
443 ];
436 for (section, source) in pages {
444 for (section, source) in pages {
437 for key in search_term_keys(section) {
445 for key in search_term_keys(section) {
crates/app/src/views/calendar_date_picker.rs +31 −71
@@ -1,45 +1,44 @@
1 1 use std::cell::RefCell;
2 2 use std::rc::Rc;
3 3
4 use chrono::{Datelike, Duration, Local, Months, NaiveDate};
4 use chrono::{Local, Months, NaiveDate, Weekday};
5 5 use gpui_kit::assets::IconName;
6 6 use gpui_kit::component::Sizable as _;
7 7 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 8 use gpui_kit::component::popover::{Popover, PopoverState};
9 9 use gpui_kit::component::{h_flex, v_flex};
10 use gpui_kit::prelude::FluentBuilder as _;
11 10 use gpui_kit::*;
12 11
12 use super::calendar_mini_month::mini_month_grid;
13 13 use crate::app_state::AppState;
14 use crate::call::week_grid::{MONTH_GRID_DAYS, first_of_month, month_grid_start};
14 use crate::call::week_grid::first_of_month;
15 15 use crate::theme;
16 16
17 17 pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
18 const WEEKDAY_LETTERS: [&str; 7] = ["M", "T", "W", "T", "F", "S", "S"];
19 18 const CELL_SIZE: f32 = 32.;
20 19 const PICKER_PADDING: f32 = 12.;
21 20
22 21 pub struct DatePicker {
23 22 app: Entity<AppState>,
24 23 month: NaiveDate,
25 shown_start: NaiveDate,
26 shown_days: i64,
24 shown: Vec<NaiveDate>,
25 first_day: Weekday,
27 26 popover: WeakEntity<PopoverState>,
28 27 }
29 28
30 29 impl DatePicker {
31 30 fn new(
32 31 app: Entity<AppState>,
33 shown_start: NaiveDate,
34 shown_days: i64,
32 shown: Vec<NaiveDate>,
33 first_day: Weekday,
35 34 month: NaiveDate,
36 35 popover: WeakEntity<PopoverState>,
37 36 ) -> Self {
38 37 DatePicker {
39 38 app,
40 39 month: first_of_month(month),
41 shown_start,
42 shown_days,
40 shown,
41 first_day,
43 42 popover,
44 43 }
45 44 }
@@ -61,55 +60,25 @@ impl DatePicker {
61 60 .update(cx, |popover, cx| popover.dismiss(window, cx))
62 61 .ok();
63 62 }
64
65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 let in_month = date.month() == self.month.month();
67 let shown =
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
69 let is_today = date == today;
70 div()
71 .id(SharedString::from(format!("date-picker-{date}")))
72 .size(px(CELL_SIZE))
73 .flex()
74 .items_center()
75 .justify_center()
76 .rounded_full()
77 .cursor_pointer()
78 .text_size(px(12.))
79 .text_color(if in_month {
80 theme::text()
81 } else {
82 theme::text_faint()
83 })
84 .when(shown && !is_today, |cell| cell.bg(theme::popup_hover()))
85 .when(is_today, |cell| {
86 cell.bg(theme::accent()).text_color(theme::on_accent())
87 })
88 .when(!is_today, |cell| {
89 cell.hover(|cell| cell.bg(theme::border_strong()))
90 })
91 .child(date.day().to_string())
92 .on_click(cx.listener(move |this, _, window, cx| this.pick(date, window, cx)))
93 }
94 63 }
95 64
96 65 impl Render for DatePicker {
97 66 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
98 67 let today = Local::now().date_naive();
99 let start = month_grid_start(self.month);
100 let days: Vec<NaiveDate> = (0..MONTH_GRID_DAYS)
101 .map(|offset| start + Duration::days(offset))
102 .collect();
103 let weeks = days
104 .chunks(7)
105 .map(|week| {
106 h_flex().children(
107 week.iter()
108 .map(|date| self.day_cell(*date, today, cx))
109 .collect::<Vec<_>>(),
110 )
111 })
112 .collect::<Vec<_>>();
68 let picker = cx.entity().downgrade();
69 let grid = mini_month_grid(
70 "date-picker",
71 self.month,
72 &self.shown,
73 self.first_day,
74 today,
75 CELL_SIZE,
76 Rc::new(move |date, window, cx| {
77 picker
78 .update(cx, |picker, cx| picker.pick(date, window, cx))
79 .ok();
80 }),
81 );
113 82 v_flex()
114 83 .debug_selector(|| DATE_PICKER_TAG.into())
115 84 .p(px(PICKER_PADDING))
@@ -125,7 +94,7 @@ impl Render for DatePicker {
125 94 .text_size(px(14.))
126 95 .font_weight(FontWeight::SEMIBOLD)
127 96 .text_color(theme::text())
128 .child(self.month.format("%B %Y").to_string()),
97 .child(app_base::format::month_year_label(self.month)),
129 98 )
130 99 .child(
131 100 h_flex()
@@ -134,7 +103,7 @@ impl Render for DatePicker {
134 103 .small()
135 104 .ghost()
136 105 .icon(IconName::ChevronLeft)
137 .tooltip("Previous month")
106 .tooltip(crate::i18n::tr("calendar.view.previous_month_short"))
138 107 .on_click(
139 108 cx.listener(|this, _, _, cx| this.move_month(false, cx)),
140 109 ),
@@ -144,32 +113,22 @@ impl Render for DatePicker {
144 113 .small()
145 114 .ghost()
146 115 .icon(IconName::ChevronRight)
147 .tooltip("Next month")
116 .tooltip(crate::i18n::tr("calendar.view.next_month_short"))
148 117 .on_click(
149 118 cx.listener(|this, _, _, cx| this.move_month(true, cx)),
150 119 ),
151 120 ),
152 121 ),
153 122 )
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
155 div()
156 .size(px(CELL_SIZE))
157 .flex()
158 .items_center()
159 .justify_center()
160 .text_size(px(11.))
161 .text_color(theme::text_muted())
162 .child(*letter)
163 })))
164 .children(weeks)
123 .child(grid)
165 124 }
166 125 }
167 126
168 127 pub fn date_picker_button(
169 128 app: &Entity<AppState>,
170 129 title: String,
171 shown_start: NaiveDate,
172 shown_days: i64,
130 shown: Vec<NaiveDate>,
131 first_day: Weekday,
173 132 month: NaiveDate,
174 133 ) -> AnyElement {
175 134 let app = app.clone();
@@ -196,7 +155,8 @@ pub fn date_picker_button(
196 155 }
197 156 let popover = cx.entity().downgrade();
198 157 let app = app.clone();
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
158 let created =
159 cx.new(|_| DatePicker::new(app, shown.clone(), first_day, month, popover));
200 160 *picker.borrow_mut() = Some(created.clone());
201 161 created
202 162 })
@@ -1,45 +1,44 @@
1use std::cell::RefCell;
1use std::cell::RefCell;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use chrono::{Datelike, Duration, Local, Months, NaiveDate};
4use chrono::{Local, Months, NaiveDate, Weekday};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::Sizable as _;
6use gpui_kit::component::Sizable as _;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::popover::{Popover, PopoverState};
8use gpui_kit::component::popover::{Popover, PopoverState};
9use gpui_kit::component::{h_flex, v_flex};
9use gpui_kit::component::{h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
10use gpui_kit::*;
12
11
12use super::calendar_mini_month::mini_month_grid;
13use crate::app_state::AppState;
13use crate::app_state::AppState;
14use crate::call::week_grid::{MONTH_GRID_DAYS, first_of_month, month_grid_start};
14use crate::call::week_grid::first_of_month;
15use crate::theme;
15use crate::theme;
16
16
17pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
17pub const DATE_PICKER_TAG: &str = "shell/islands/calendar/date-picker";
18const WEEKDAY_LETTERS: [&str; 7] = ["M", "T", "W", "T", "F", "S", "S"];
19const CELL_SIZE: f32 = 32.;
18const CELL_SIZE: f32 = 32.;
20const PICKER_PADDING: f32 = 12.;
19const PICKER_PADDING: f32 = 12.;
21
20
22pub struct DatePicker {
21pub struct DatePicker {
23 app: Entity<AppState>,
22 app: Entity<AppState>,
24 month: NaiveDate,
23 month: NaiveDate,
25 shown_start: NaiveDate,
24 shown: Vec<NaiveDate>,
26 shown_days: i64,
25 first_day: Weekday,
27 popover: WeakEntity<PopoverState>,
26 popover: WeakEntity<PopoverState>,
28}
27}
29
28
30impl DatePicker {
29impl DatePicker {
31 fn new(
30 fn new(
32 app: Entity<AppState>,
31 app: Entity<AppState>,
33 shown_start: NaiveDate,
32 shown: Vec<NaiveDate>,
34 shown_days: i64,
33 first_day: Weekday,
35 month: NaiveDate,
34 month: NaiveDate,
36 popover: WeakEntity<PopoverState>,
35 popover: WeakEntity<PopoverState>,
37 ) -> Self {
36 ) -> Self {
38 DatePicker {
37 DatePicker {
39 app,
38 app,
40 month: first_of_month(month),
39 month: first_of_month(month),
41 shown_start,
40 shown,
42 shown_days,
41 first_day,
43 popover,
42 popover,
44 }
43 }
45 }
44 }
@@ -61,55 +60,25 @@ impl DatePicker {
61 .update(cx, |popover, cx| popover.dismiss(window, cx))
60 .update(cx, |popover, cx| popover.dismiss(window, cx))
62 .ok();
61 .ok();
63 }
62 }
64
65 fn day_cell(&self, date: NaiveDate, today: NaiveDate, cx: &mut Context<Self>) -> Stateful<Div> {
66 let in_month = date.month() == self.month.month();
67 let shown =
68 self.shown_start <= date && date < self.shown_start + Duration::days(self.shown_days);
69 let is_today = date == today;
70 div()
71 .id(SharedString::from(format!("date-picker-{date}")))
72 .size(px(CELL_SIZE))
73 .flex()
74 .items_center()
75 .justify_center()
76 .rounded_full()
77 .cursor_pointer()
78 .text_size(px(12.))
79 .text_color(if in_month {
80 theme::text()
81 } else {
82 theme::text_faint()
83 })
84 .when(shown && !is_today, |cell| cell.bg(theme::popup_hover()))
85 .when(is_today, |cell| {
86 cell.bg(theme::accent()).text_color(theme::on_accent())
87 })
88 .when(!is_today, |cell| {
89 cell.hover(|cell| cell.bg(theme::border_strong()))
90 })
91 .child(date.day().to_string())
92 .on_click(cx.listener(move |this, _, window, cx| this.pick(date, window, cx)))
93 }
94}
63}
95
64
96impl Render for DatePicker {
65impl Render for DatePicker {
97 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
66 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
98 let today = Local::now().date_naive();
67 let today = Local::now().date_naive();
99 let start = month_grid_start(self.month);
68 let picker = cx.entity().downgrade();
100 let days: Vec<NaiveDate> = (0..MONTH_GRID_DAYS)
69 let grid = mini_month_grid(
101 .map(|offset| start + Duration::days(offset))
70 "date-picker",
102 .collect();
71 self.month,
103 let weeks = days
72 &self.shown,
104 .chunks(7)
73 self.first_day,
105 .map(|week| {
74 today,
106 h_flex().children(
75 CELL_SIZE,
107 week.iter()
76 Rc::new(move |date, window, cx| {
108 .map(|date| self.day_cell(*date, today, cx))
77 picker
109 .collect::<Vec<_>>(),
78 .update(cx, |picker, cx| picker.pick(date, window, cx))
110 )
79 .ok();
111 })
80 }),
112 .collect::<Vec<_>>();
81 );
113 v_flex()
82 v_flex()
114 .debug_selector(|| DATE_PICKER_TAG.into())
83 .debug_selector(|| DATE_PICKER_TAG.into())
115 .p(px(PICKER_PADDING))
84 .p(px(PICKER_PADDING))
@@ -125,7 +94,7 @@ impl Render for DatePicker {
125 .text_size(px(14.))
94 .text_size(px(14.))
126 .font_weight(FontWeight::SEMIBOLD)
95 .font_weight(FontWeight::SEMIBOLD)
127 .text_color(theme::text())
96 .text_color(theme::text())
128 .child(self.month.format("%B %Y").to_string()),
97 .child(app_base::format::month_year_label(self.month)),
129 )
98 )
130 .child(
99 .child(
131 h_flex()
100 h_flex()
@@ -134,7 +103,7 @@ impl Render for DatePicker {
134 .small()
103 .small()
135 .ghost()
104 .ghost()
136 .icon(IconName::ChevronLeft)
105 .icon(IconName::ChevronLeft)
137 .tooltip("Previous month")
106 .tooltip(crate::i18n::tr("calendar.view.previous_month_short"))
138 .on_click(
107 .on_click(
139 cx.listener(|this, _, _, cx| this.move_month(false, cx)),
108 cx.listener(|this, _, _, cx| this.move_month(false, cx)),
140 ),
109 ),
@@ -144,32 +113,22 @@ impl Render for DatePicker {
144 .small()
113 .small()
145 .ghost()
114 .ghost()
146 .icon(IconName::ChevronRight)
115 .icon(IconName::ChevronRight)
147 .tooltip("Next month")
116 .tooltip(crate::i18n::tr("calendar.view.next_month_short"))
148 .on_click(
117 .on_click(
149 cx.listener(|this, _, _, cx| this.move_month(true, cx)),
118 cx.listener(|this, _, _, cx| this.move_month(true, cx)),
150 ),
119 ),
151 ),
120 ),
152 ),
121 ),
153 )
122 )
154 .child(h_flex().children(WEEKDAY_LETTERS.iter().map(|letter| {
123 .child(grid)
155 div()
156 .size(px(CELL_SIZE))
157 .flex()
158 .items_center()
159 .justify_center()
160 .text_size(px(11.))
161 .text_color(theme::text_muted())
162 .child(*letter)
163 })))
164 .children(weeks)
165 }
124 }
166}
125}
167
126
168pub fn date_picker_button(
127pub fn date_picker_button(
169 app: &Entity<AppState>,
128 app: &Entity<AppState>,
170 title: String,
129 title: String,
171 shown_start: NaiveDate,
130 shown: Vec<NaiveDate>,
172 shown_days: i64,
131 first_day: Weekday,
173 month: NaiveDate,
132 month: NaiveDate,
174) -> AnyElement {
133) -> AnyElement {
175 let app = app.clone();
134 let app = app.clone();
@@ -196,7 +155,8 @@ pub fn date_picker_button(
196 }
155 }
197 let popover = cx.entity().downgrade();
156 let popover = cx.entity().downgrade();
198 let app = app.clone();
157 let app = app.clone();
199 let created = cx.new(|_| DatePicker::new(app, shown_start, shown_days, month, popover));
158 let created =
159 cx.new(|_| DatePicker::new(app, shown.clone(), first_day, month, popover));
200 *picker.borrow_mut() = Some(created.clone());
160 *picker.borrow_mut() = Some(created.clone());
201 created
161 created
202 })
162 })
crates/app/src/views/calendar_mini_month.rs added +95 −0
@@ -0,0 +1,95 @@
1 //! Mini month grid shared by the date picker popover and the calendar list pane.
2
3 use std::rc::Rc;
4
5 use chrono::{Datelike, Duration, NaiveDate, Weekday};
6 use gpui_kit::component::{h_flex, v_flex};
7 use gpui_kit::prelude::FluentBuilder as _;
8 use gpui_kit::*;
9
10 use crate::call::calendar_list::mini_month_cell;
11 use crate::call::week_grid::{MONTH_GRID_DAYS, month_grid_start};
12 use crate::theme;
13
14 pub type PickDate = Rc<dyn Fn(NaiveDate, &mut Window, &mut App)>;
15
16 /// Weekday initials in column order from the first day, in the app language.
17 pub fn weekday_letters(first_day: Weekday) -> [String; 7] {
18 let mut day = first_day;
19 std::array::from_fn(|_| {
20 let letter = app_base::format::weekday_name(day, app_base::format::WeekdayWidth::Letter);
21 day = day.succ();
22 letter
23 })
24 }
25
26 /// Weekday initials and six weeks of day cells; the shown range is a band, today a circle.
27 #[allow(clippy::too_many_arguments)]
28 pub fn mini_month_grid(
29 id: &'static str,
30 month: NaiveDate,
31 shown: &[NaiveDate],
32 first_day: Weekday,
33 today: NaiveDate,
34 cell_size: f32,
35 on_pick: PickDate,
36 ) -> Div {
37 let start = month_grid_start(month, first_day);
38 let weeks = (0..MONTH_GRID_DAYS)
39 .map(|offset| start + Duration::days(offset))
40 .collect::<Vec<_>>()
41 .chunks(7)
42 .map(|week| {
43 h_flex().children(week.iter().map(|date| {
44 let cell = mini_month_cell(*date, month, shown, today);
45 let pick = on_pick.clone();
46 let date = *date;
47 div()
48 .id(SharedString::from(format!("{id}-{date}")))
49 .size(px(cell_size))
50 .flex()
51 .items_center()
52 .justify_center()
53 .when(cell.shown, |band| band.bg(theme::popup_hover()))
54 .child(
55 div()
56 .size(px(cell_size - 4.))
57 .flex()
58 .items_center()
59 .justify_center()
60 .rounded_full()
61 .cursor_pointer()
62 .text_size(px(12.))
63 .text_color(if cell.in_month {
64 theme::text()
65 } else {
66 theme::text_faint()
67 })
68 .when(cell.today, |circle| {
69 circle
70 .bg(theme::accent())
71 .text_color(theme::on_accent())
72 .font_weight(FontWeight::SEMIBOLD)
73 })
74 .when(!cell.today, |circle| {
75 circle.hover(|circle| circle.bg(theme::border_strong()))
76 })
77 .child(date.day().to_string()),
78 )
79 .on_click(move |_, window, cx| pick(date, window, cx))
80 }))
81 })
82 .collect::<Vec<_>>();
83 v_flex()
84 .child(h_flex().children(weekday_letters(first_day).map(|letter| {
85 div()
86 .size(px(cell_size))
87 .flex()
88 .items_center()
89 .justify_center()
90 .text_size(px(11.))
91 .text_color(theme::text_muted())
92 .child(letter)
93 })))
94 .children(weeks)
95 }
@@ -0,0 +1,95 @@
1//! Mini month grid shared by the date picker popover and the calendar list pane.
2
3use std::rc::Rc;
4
5use chrono::{Datelike, Duration, NaiveDate, Weekday};
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9
10use crate::call::calendar_list::mini_month_cell;
11use crate::call::week_grid::{MONTH_GRID_DAYS, month_grid_start};
12use crate::theme;
13
14pub type PickDate = Rc<dyn Fn(NaiveDate, &mut Window, &mut App)>;
15
16/// Weekday initials in column order from the first day, in the app language.
17pub fn weekday_letters(first_day: Weekday) -> [String; 7] {
18 let mut day = first_day;
19 std::array::from_fn(|_| {
20 let letter = app_base::format::weekday_name(day, app_base::format::WeekdayWidth::Letter);
21 day = day.succ();
22 letter
23 })
24}
25
26/// Weekday initials and six weeks of day cells; the shown range is a band, today a circle.
27#[allow(clippy::too_many_arguments)]
28pub fn mini_month_grid(
29 id: &'static str,
30 month: NaiveDate,
31 shown: &[NaiveDate],
32 first_day: Weekday,
33 today: NaiveDate,
34 cell_size: f32,
35 on_pick: PickDate,
36) -> Div {
37 let start = month_grid_start(month, first_day);
38 let weeks = (0..MONTH_GRID_DAYS)
39 .map(|offset| start + Duration::days(offset))
40 .collect::<Vec<_>>()
41 .chunks(7)
42 .map(|week| {
43 h_flex().children(week.iter().map(|date| {
44 let cell = mini_month_cell(*date, month, shown, today);
45 let pick = on_pick.clone();
46 let date = *date;
47 div()
48 .id(SharedString::from(format!("{id}-{date}")))
49 .size(px(cell_size))
50 .flex()
51 .items_center()
52 .justify_center()
53 .when(cell.shown, |band| band.bg(theme::popup_hover()))
54 .child(
55 div()
56 .size(px(cell_size - 4.))
57 .flex()
58 .items_center()
59 .justify_center()
60 .rounded_full()
61 .cursor_pointer()
62 .text_size(px(12.))
63 .text_color(if cell.in_month {
64 theme::text()
65 } else {
66 theme::text_faint()
67 })
68 .when(cell.today, |circle| {
69 circle
70 .bg(theme::accent())
71 .text_color(theme::on_accent())
72 .font_weight(FontWeight::SEMIBOLD)
73 })
74 .when(!cell.today, |circle| {
75 circle.hover(|circle| circle.bg(theme::border_strong()))
76 })
77 .child(date.day().to_string()),
78 )
79 .on_click(move |_, window, cx| pick(date, window, cx))
80 }))
81 })
82 .collect::<Vec<_>>();
83 v_flex()
84 .child(h_flex().children(weekday_letters(first_day).map(|letter| {
85 div()
86 .size(px(cell_size))
87 .flex()
88 .items_center()
89 .justify_center()
90 .text_size(px(11.))
91 .text_color(theme::text_muted())
92 .child(letter)
93 })))
94 .children(weeks)
95}
crates/app/src/views/calendar_month.rs +38 −12
@@ -1,6 +1,7 @@
1 1 use app_base::format::clock_format;
2 use app_base::format::{WeekdayWidth, weekday_name};
2 3 use chatsvc::CalendarEvent;
3 use chrono::{Datelike, FixedOffset, NaiveDate};
4 use chrono::{Datelike, FixedOffset, NaiveDate, Weekday};
4 5 use gpui_kit::component::{h_flex, v_flex};
5 6 use gpui_kit::prelude::FluentBuilder as _;
6 7 use gpui_kit::*;
@@ -10,7 +11,6 @@ use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10 11 use crate::theme;
11 12
12 13 pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13 const WEEKDAY_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
14 14 const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
15 15 const VISIBLE_EVENTS: usize = 3;
16 16 const DAY_NUMBER_SIZE: f32 = 24.;
@@ -31,10 +31,12 @@ fn day_events(day: &WeekDay) -> Vec<usize> {
31 31 }
32 32
33 33 fn more_label(hidden: usize) -> String {
34 format!("+{hidden} more")
34 let mut args = std::collections::HashMap::new();
35 args.insert("count".to_owned(), hidden.to_string());
36 app_base::ui_locale::tr_args("calendar.view.more", &args)
35 37 }
36 38
37 fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
39 fn event_chip(event: &CalendarEvent, color: Hsla, offset: FixedOffset) -> Div {
38 40 let all_day = is_effective_all_day(event, offset);
39 41 let time = (!all_day).then(|| {
40 42 event
@@ -50,8 +52,8 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
50 52 .px(px(6.))
51 53 .gap(px(6.))
52 54 .items_center()
53 .rounded(px(4.))
54 .bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))
55 .rounded(px(6.))
56 .bg(color.opacity(if all_day { 0.28 } else { 0.14 }))
55 57 .text_size(px(11.5))
56 58 .text_color(theme::text())
57 59 .children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
@@ -79,6 +81,7 @@ fn day_cell(
79 81 state: &Entity<AppState>,
80 82 day: &WeekDay,
81 83 events: &[CalendarEvent],
84 colors: &[Hsla],
82 85 shown_month: NaiveDate,
83 86 today: NaiveDate,
84 87 offset: FixedOffset,
@@ -89,7 +92,14 @@ fn day_cell(
89 92 let indexes = day_events(day);
90 93 let hidden = indexes.len().saturating_sub(VISIBLE_EVENTS);
91 94 let number = if date.day() == 1 {
92 date.format("%b %-d").to_string()
95 format!(
96 "{} {}",
97 app_base::format::month_name(date)
98 .chars()
99 .take(3)
100 .collect::<String>(),
101 date.day()
102 )
93 103 } else {
94 104 date.day().to_string()
95 105 };
@@ -136,8 +146,8 @@ fn day_cell(
136 146 indexes
137 147 .iter()
138 148 .take(VISIBLE_EVENTS)
139 .filter_map(|index| events.get(*index))
140 .map(|event| event_chip(event, offset)),
149 .filter_map(|index| Some((events.get(*index)?, *colors.get(*index)?)))
150 .map(|(event, color)| event_chip(event, color, offset)),
141 151 )
142 152 .when(hidden > 0, |cell| {
143 153 cell.child(
@@ -161,13 +171,16 @@ fn vertical_line() -> Div {
161 171 div().w(px(1.)).h_full().flex_none().bg(theme::border())
162 172 }
163 173
174 #[allow(clippy::too_many_arguments)]
164 175 pub fn month_grid(
165 176 state: &Entity<AppState>,
166 177 start: NaiveDate,
167 178 days: &[WeekDay],
168 179 events: &[CalendarEvent],
180 colors: &[Hsla],
169 181 today: NaiveDate,
170 182 offset: FixedOffset,
183 weekdays: [Weekday; 7],
171 184 ) -> Div {
172 185 let shown_month = month_shown(start);
173 186 let mut rows = v_flex().flex_1().min_h_0().w_full();
@@ -177,7 +190,15 @@ pub fn month_grid(
177 190 if position > 0 {
178 191 row = row.child(vertical_line());
179 192 }
180 row = row.child(day_cell(state, day, events, shown_month, today, offset));
193 row = row.child(day_cell(
194 state,
195 day,
196 events,
197 colors,
198 shown_month,
199 today,
200 offset,
201 ));
181 202 }
182 203 rows = rows.child(horizontal_line()).child(row);
183 204 }
@@ -191,13 +212,13 @@ pub fn month_grid(
191 212 .h(px(WEEKDAY_HEADER_HEIGHT))
192 213 .flex_none()
193 214 .w_full()
194 .children(WEEKDAY_NAMES.iter().map(|name| {
215 .children(weekdays.iter().map(|day| {
195 216 div()
196 217 .flex_1()
197 218 .px(px(10.))
198 219 .text_size(px(12.))
199 220 .text_color(theme::text_muted())
200 .child(*name)
221 .child(weekday_name(*day, WeekdayWidth::Short))
201 222 })),
202 223 )
203 224 .child(rows)
@@ -224,6 +245,11 @@ mod tests {
224 245 blocks: vec![block(2, 600), block(1, 540)],
225 246 };
226 247 assert_eq!(day_events(&day), [4, 1, 2]);
248 let _guard = crate::i18n::locale_test_lock();
249 app_base::ui_locale::apply_locale("en");
227 250 assert_eq!(more_label(2), "+2 more");
251 app_base::ui_locale::apply_locale("de");
252 assert_eq!(more_label(2), "+2 weitere");
253 app_base::ui_locale::apply_locale("en");
228 254 }
229 255 }
@@ -1,6 +1,7 @@
1use app_base::format::clock_format;
1use app_base::format::clock_format;
2use app_base::format::{WeekdayWidth, weekday_name};
2use chatsvc::CalendarEvent;
3use chatsvc::CalendarEvent;
3use chrono::{Datelike, FixedOffset, NaiveDate};
4use chrono::{Datelike, FixedOffset, NaiveDate, Weekday};
4use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use gpui_kit::*;
@@ -10,7 +11,6 @@ use crate::call::week_grid::{WeekDay, is_effective_all_day, month_shown};
10use crate::theme;
11use crate::theme;
11
12
12pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13pub const MONTH_GRID_TAG: &str = "shell/islands/calendar/month";
13const WEEKDAY_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
14const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
14const WEEKDAY_HEADER_HEIGHT: f32 = 32.;
15const VISIBLE_EVENTS: usize = 3;
15const VISIBLE_EVENTS: usize = 3;
16const DAY_NUMBER_SIZE: f32 = 24.;
16const DAY_NUMBER_SIZE: f32 = 24.;
@@ -31,10 +31,12 @@ fn day_events(day: &WeekDay) -> Vec<usize> {
31}
31}
32
32
33fn more_label(hidden: usize) -> String {
33fn more_label(hidden: usize) -> String {
34 format!("+{hidden} more")
34 let mut args = std::collections::HashMap::new();
35 args.insert("count".to_owned(), hidden.to_string());
36 app_base::ui_locale::tr_args("calendar.view.more", &args)
35}
37}
36
38
37fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
39fn event_chip(event: &CalendarEvent, color: Hsla, offset: FixedOffset) -> Div {
38 let all_day = is_effective_all_day(event, offset);
40 let all_day = is_effective_all_day(event, offset);
39 let time = (!all_day).then(|| {
41 let time = (!all_day).then(|| {
40 event
42 event
@@ -50,8 +52,8 @@ fn event_chip(event: &CalendarEvent, offset: FixedOffset) -> Div {
50 .px(px(6.))
52 .px(px(6.))
51 .gap(px(6.))
53 .gap(px(6.))
52 .items_center()
54 .items_center()
53 .rounded(px(4.))
55 .rounded(px(6.))
54 .bg(theme::accent().opacity(if all_day { 0.28 } else { 0.14 }))
56 .bg(color.opacity(if all_day { 0.28 } else { 0.14 }))
55 .text_size(px(11.5))
57 .text_size(px(11.5))
56 .text_color(theme::text())
58 .text_color(theme::text())
57 .children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
59 .children(time.map(|time| div().flex_none().text_color(theme::text_soft()).child(time)))
@@ -79,6 +81,7 @@ fn day_cell(
79 state: &Entity<AppState>,
81 state: &Entity<AppState>,
80 day: &WeekDay,
82 day: &WeekDay,
81 events: &[CalendarEvent],
83 events: &[CalendarEvent],
84 colors: &[Hsla],
82 shown_month: NaiveDate,
85 shown_month: NaiveDate,
83 today: NaiveDate,
86 today: NaiveDate,
84 offset: FixedOffset,
87 offset: FixedOffset,
@@ -89,7 +92,14 @@ fn day_cell(
89 let indexes = day_events(day);
92 let indexes = day_events(day);
90 let hidden = indexes.len().saturating_sub(VISIBLE_EVENTS);
93 let hidden = indexes.len().saturating_sub(VISIBLE_EVENTS);
91 let number = if date.day() == 1 {
94 let number = if date.day() == 1 {
92 date.format("%b %-d").to_string()
95 format!(
96 "{} {}",
97 app_base::format::month_name(date)
98 .chars()
99 .take(3)
100 .collect::<String>(),
101 date.day()
102 )
93 } else {
103 } else {
94 date.day().to_string()
104 date.day().to_string()
95 };
105 };
@@ -136,8 +146,8 @@ fn day_cell(
136 indexes
146 indexes
137 .iter()
147 .iter()
138 .take(VISIBLE_EVENTS)
148 .take(VISIBLE_EVENTS)
139 .filter_map(|index| events.get(*index))
149 .filter_map(|index| Some((events.get(*index)?, *colors.get(*index)?)))
140 .map(|event| event_chip(event, offset)),
150 .map(|(event, color)| event_chip(event, color, offset)),
141 )
151 )
142 .when(hidden > 0, |cell| {
152 .when(hidden > 0, |cell| {
143 cell.child(
153 cell.child(
@@ -161,13 +171,16 @@ fn vertical_line() -> Div {
161 div().w(px(1.)).h_full().flex_none().bg(theme::border())
171 div().w(px(1.)).h_full().flex_none().bg(theme::border())
162}
172}
163
173
174#[allow(clippy::too_many_arguments)]
164pub fn month_grid(
175pub fn month_grid(
165 state: &Entity<AppState>,
176 state: &Entity<AppState>,
166 start: NaiveDate,
177 start: NaiveDate,
167 days: &[WeekDay],
178 days: &[WeekDay],
168 events: &[CalendarEvent],
179 events: &[CalendarEvent],
180 colors: &[Hsla],
169 today: NaiveDate,
181 today: NaiveDate,
170 offset: FixedOffset,
182 offset: FixedOffset,
183 weekdays: [Weekday; 7],
171) -> Div {
184) -> Div {
172 let shown_month = month_shown(start);
185 let shown_month = month_shown(start);
173 let mut rows = v_flex().flex_1().min_h_0().w_full();
186 let mut rows = v_flex().flex_1().min_h_0().w_full();
@@ -177,7 +190,15 @@ pub fn month_grid(
177 if position > 0 {
190 if position > 0 {
178 row = row.child(vertical_line());
191 row = row.child(vertical_line());
179 }
192 }
180 row = row.child(day_cell(state, day, events, shown_month, today, offset));
193 row = row.child(day_cell(
194 state,
195 day,
196 events,
197 colors,
198 shown_month,
199 today,
200 offset,
201 ));
181 }
202 }
182 rows = rows.child(horizontal_line()).child(row);
203 rows = rows.child(horizontal_line()).child(row);
183 }
204 }
@@ -191,13 +212,13 @@ pub fn month_grid(
191 .h(px(WEEKDAY_HEADER_HEIGHT))
212 .h(px(WEEKDAY_HEADER_HEIGHT))
192 .flex_none()
213 .flex_none()
193 .w_full()
214 .w_full()
194 .children(WEEKDAY_NAMES.iter().map(|name| {
215 .children(weekdays.iter().map(|day| {
195 div()
216 div()
196 .flex_1()
217 .flex_1()
197 .px(px(10.))
218 .px(px(10.))
198 .text_size(px(12.))
219 .text_size(px(12.))
199 .text_color(theme::text_muted())
220 .text_color(theme::text_muted())
200 .child(*name)
221 .child(weekday_name(*day, WeekdayWidth::Short))
201 })),
222 })),
202 )
223 )
203 .child(rows)
224 .child(rows)
@@ -224,6 +245,11 @@ mod tests {
224 blocks: vec![block(2, 600), block(1, 540)],
245 blocks: vec![block(2, 600), block(1, 540)],
225 };
246 };
226 assert_eq!(day_events(&day), [4, 1, 2]);
247 assert_eq!(day_events(&day), [4, 1, 2]);
248 let _guard = crate::i18n::locale_test_lock();
249 app_base::ui_locale::apply_locale("en");
227 assert_eq!(more_label(2), "+2 more");
250 assert_eq!(more_label(2), "+2 more");
251 app_base::ui_locale::apply_locale("de");
252 assert_eq!(more_label(2), "+2 weitere");
253 app_base::ui_locale::apply_locale("en");
228 }
254 }
229}
255}
crates/app/src/views/calendar_picker.rs +335 −77
@@ -1,21 +1,40 @@
1 //! Calendar list pane left of the grid, laid out like Teams: heading, mini month,
2 //! Add calendar, and one collapsible group per account with show/hide boxes.
3
4 use std::rc::Rc;
5
6 use chrono::Local;
1 7 use gpui_kit::assets::IconName;
8 use gpui_kit::component::Sizable as _;
9 use gpui_kit::component::button::{Button, ButtonVariants as _};
2 10 use gpui_kit::component::{h_flex, v_flex};
3 11 use gpui_kit::prelude::FluentBuilder as _;
4 12 use gpui_kit::*;
5 use store::CalendarAccounts;
13 use store::{CalendarAccounts, GoogleAccount};
6 14
15 use super::calendar_mini_month::mini_month_grid;
7 16 use crate::app_state::AppState;
17 use crate::call::calendar_list::{GroupCheck, group_check, listed_calendars, offers_show_all};
18 use crate::call::calendar_prefs::OUTLOOK_GROUP;
19 use crate::call::week_grid::google_calendar_index;
20 use crate::i18n::tr;
21 use crate::settings_section::SettingsSection;
8 22 use crate::theme;
9 23 use crate::views::widgets::icon;
10 24
11 pub const PICKER_WIDTH: f32 = 220.;
25 pub const PICKER_WIDTH: f32 = 236.;
26 pub const CALENDAR_PANE_TAG: &str = "shell/islands/calendar/picker";
27 pub const MINI_MONTH_TAG: &str = "shell/islands/calendar/picker/mini-month";
12 28 const ROW_HEIGHT: f32 = 28.;
29 const MINI_CELL: f32 = 30.;
30 const CHECK_SIZE: f32 = 14.;
13 31
14 /// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.
15 32 pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
16 let accounts = app.read(cx).calendar_accounts();
33 let state = app.read(cx);
34 let accounts = state.calendar_accounts();
35 let prefs = &state.calendar_prefs;
17 36 let mut column = v_flex()
18 .debug_selector(|| "shell/islands/calendar/picker".into())
37 .debug_selector(|| CALENDAR_PANE_TAG.into())
19 38 .w(px(PICKER_WIDTH))
20 39 .flex_none()
21 40 .h_full()
@@ -27,76 +46,293 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
27 46 .gap(px(4.))
28 47 .child(
29 48 div()
30 .text_size(px(11.))
31 .font_weight(FontWeight::SEMIBOLD)
32 .text_color(theme::text_muted())
33 .mb(px(6.))
34 .child("CALENDARS"),
49 .text_size(px(16.))
50 .font_weight(FontWeight::BOLD)
51 .text_color(theme::text())
52 .pb(px(8.))
53 .child(tr("calendar.view.title")),
35 54 )
36 .child(outlook_row(app, &accounts));
55 .child(mini_month(app, state))
56 .child(add_calendar_row(app))
57 .child(outlook_group(
58 app,
59 &accounts,
60 prefs.group_collapsed(OUTLOOK_GROUP),
61 ));
37 62 for account in &accounts.google_accounts {
38 column = column.child(
39 div()
40 .mt(px(8.))
41 .mb(px(2.))
42 .text_size(px(11.))
43 .font_weight(FontWeight::SEMIBOLD)
44 .text_color(theme::text_muted())
45 .truncate()
46 .child(account.email.clone()),
47 );
48 for calendar in &account.calendars {
49 let toggle_app = app.clone();
50 let account_id = account.id.clone();
51 let calendar_id = calendar.id.clone();
52 let color = if calendar.primary {
53 theme::accent()
54 } else {
55 theme::text_soft()
56 };
57 column = column.child(toggle_row(
58 format!("calendar-picker-{}", calendar.id),
59 calendar.summary.clone(),
60 calendar.selected,
61 color,
62 move |cx| {
63 toggle_app.update(cx, |state, cx| {
64 state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
65 });
66 },
67 ));
68 }
69 }
70 if !accounts.has_google() {
71 column = column.child(
72 div()
73 .mt(px(8.))
74 .text_size(px(12.))
75 .text_color(theme::text_muted())
76 .child("Connect Google in Settings › Calendar"),
77 );
63 column = column.child(google_group(
64 app,
65 &accounts,
66 account,
67 prefs.group_collapsed(&account.id),
68 state.calendar_expanded_groups.contains(&account.id),
69 ));
78 70 }
79 71 column
80 72 }
81 73
82 fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {
74 /// Mini month with its own month arrows; a click shows the span around that day.
75 fn mini_month(app: &Entity<AppState>, state: &AppState) -> Div {
76 let month = state.calendar_mini_month_shown();
77 let (back, forward, pick) = (app.clone(), app.clone(), app.clone());
78 v_flex()
79 .debug_selector(|| MINI_MONTH_TAG.into())
80 .pb(px(8.))
81 .child(
82 h_flex()
83 .items_center()
84 .justify_between()
85 .pb(px(4.))
86 .child(
87 div()
88 .pl(px(4.))
89 .text_size(px(13.))
90 .font_weight(FontWeight::SEMIBOLD)
91 .text_color(theme::text())
92 .child(app_base::format::month_year_label(month)),
93 )
94 .child(
95 h_flex()
96 .child(
97 Button::new("calendar-mini-back")
98 .xsmall()
99 .ghost()
100 .icon(IconName::ChevronUp)
101 .tooltip(tr("calendar.view.previous_month_short"))
102 .on_click(move |_, _, cx| {
103 back.update(cx, |state, cx| {
104 state.move_calendar_mini_month(-1, cx)
105 })
106 }),
107 )
108 .child(
109 Button::new("calendar-mini-forward")
110 .xsmall()
111 .ghost()
112 .icon(IconName::ChevronDown)
113 .tooltip(tr("calendar.view.next_month_short"))
114 .on_click(move |_, _, cx| {
115 forward.update(cx, |state, cx| {
116 state.move_calendar_mini_month(1, cx)
117 })
118 }),
119 ),
120 ),
121 )
122 .child(mini_month_grid(
123 "calendar-mini",
124 month,
125 &state.calendar_dates(),
126 state.calendar_layout().first_day,
127 Local::now().date_naive(),
128 MINI_CELL,
129 Rc::new(move |date, _, cx| {
130 pick.update(cx, |state, cx| state.show_calendar_date(date, cx))
131 }),
132 ))
133 }
134
135 fn add_calendar_row(app: &Entity<AppState>) -> Stateful<Div> {
83 136 let app = app.clone();
84 toggle_row(
85 "calendar-picker-outlook",
86 "Outlook",
87 accounts.outlook_selected,
88 theme::accent(),
137 h_flex()
138 .id("calendar-add-calendar")
139 .h(px(ROW_HEIGHT))
140 .flex_none()
141 .w_full()
142 .items_center()
143 .gap(px(8.))
144 .px(px(4.))
145 .rounded(px(6.))
146 .cursor_pointer()
147 .hover(|row| row.bg(theme::popup_hover()))
148 .text_size(px(13.))
149 .text_color(theme::accent_text())
150 .child(icon(IconName::Plus, 14., theme::accent_text()))
151 .child(tr("calendar.view.add_calendar"))
152 .on_click(move |_, _, cx| {
153 app.update(cx, |state, cx| {
154 state.open_settings(SettingsSection::Calendar, cx)
155 })
156 })
157 }
158
159 fn outlook_group(app: &Entity<AppState>, accounts: &CalendarAccounts, collapsed: bool) -> Div {
160 let on = accounts.outlook_selected;
161 let (toggle_group, toggle_row) = (app.clone(), app.clone());
162 let collapse = app.clone();
163 group(
164 format!("calendar-group-{OUTLOOK_GROUP}"),
165 tr("calendar.view.my_calendars"),
166 if on {
167 GroupCheck::All
168 } else {
169 GroupCheck::None
170 },
171 collapsed,
172 move |cx| toggle_group.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx)),
173 move |cx| {
174 collapse.update(cx, |state, cx| {
175 state.update_calendar_prefs(|prefs| prefs.toggle_group(OUTLOOK_GROUP), cx)
176 })
177 },
178 )
179 .when(!collapsed, |group| {
180 group.child(calendar_row(
181 "calendar-picker-outlook",
182 "Outlook".to_owned(),
183 on,
184 theme::calendar_color(0),
185 move |cx| toggle_row.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx)),
186 ))
187 })
188 }
189
190 fn google_group(
191 app: &Entity<AppState>,
192 accounts: &CalendarAccounts,
193 account: &GoogleAccount,
194 collapsed: bool,
195 expanded: bool,
196 ) -> Div {
197 let selected: Vec<bool> = account
198 .calendars
199 .iter()
200 .map(|calendar| calendar.selected)
201 .collect();
202 let primary: Vec<bool> = account
203 .calendars
204 .iter()
205 .map(|calendar| calendar.primary)
206 .collect();
207 let check = group_check(&selected);
208 let (toggle_group, collapse, expand) = (app.clone(), app.clone(), app.clone());
209 let (group_id, collapse_id, expand_id) =
210 (account.id.clone(), account.id.clone(), account.id.clone());
211 let mut body = group(
212 format!("calendar-group-{}", account.id),
213 account.email.clone(),
214 check,
215 collapsed,
89 216 move |cx| {
90 app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));
217 toggle_group.update(cx, |state, cx| {
218 state.set_google_account_selected(&group_id, check != GroupCheck::All, cx)
219 })
91 220 },
221 move |cx| {
222 collapse.update(cx, |state, cx| {
223 state.update_calendar_prefs(|prefs| prefs.toggle_group(&collapse_id), cx)
224 })
225 },
226 );
227 if collapsed {
228 return body;
229 }
230 for index in listed_calendars(&selected, &primary, expanded) {
231 let calendar = &account.calendars[index];
232 let toggle = app.clone();
233 let (account_id, calendar_id) = (account.id.clone(), calendar.id.clone());
234 let color = google_calendar_index(accounts, &account.id, &calendar.id)
235 .map_or_else(theme::accent, theme::calendar_color);
236 body = body.child(calendar_row(
237 format!("calendar-picker-{}-{}", account.id, calendar.id),
238 calendar.summary.clone(),
239 calendar.selected,
240 color,
241 move |cx| {
242 toggle.update(cx, |state, cx| {
243 state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
244 });
245 },
246 ));
247 }
248 if offers_show_all(account.calendars.len()) {
249 body = body.child(
250 div()
251 .id(SharedString::from(format!(
252 "calendar-show-all-{}",
253 account.id
254 )))
255 .pl(px(28.))
256 .h(px(ROW_HEIGHT))
257 .flex_none()
258 .flex()
259 .items_center()
260 .cursor_pointer()
261 .text_size(px(12.))
262 .text_color(theme::accent_text())
263 .child(if expanded {
264 tr("calendar.view.show_fewer")
265 } else {
266 tr("calendar.view.show_all")
267 })
268 .on_click(move |_, _, cx| {
269 expand.update(cx, |state, cx| {
270 state.toggle_calendar_group_expanded(&expand_id, cx)
271 })
272 }),
273 );
274 }
275 body
276 }
277
278 /// Group header: chevron to collapse, a check box for the whole group, the title.
279 fn group(
280 id: String,
281 title: String,
282 check: GroupCheck,
283 collapsed: bool,
284 toggle: impl Fn(&mut App) + 'static,
285 collapse: impl Fn(&mut App) + 'static,
286 ) -> Div {
287 v_flex().w_full().pt(px(6.)).child(
288 h_flex()
289 .h(px(ROW_HEIGHT))
290 .flex_none()
291 .w_full()
292 .items_center()
293 .gap(px(6.))
294 .child(
295 div()
296 .id(SharedString::from(format!("{id}-chevron")))
297 .flex_none()
298 .cursor_pointer()
299 .child(icon(
300 if collapsed {
301 IconName::ChevronRight
302 } else {
303 IconName::ChevronDown
304 },
305 14.,
306 theme::text_muted(),
307 ))
308 .on_click(move |_, _, cx| collapse(cx)),
309 )
310 .child(
311 div()
312 .id(SharedString::from(format!("{id}-check")))
313 .flex_none()
314 .cursor_pointer()
315 .child(check_box(check, theme::accent()))
316 .on_click(move |_, _, cx| toggle(cx)),
317 )
318 .child(
319 div()
320 .flex_1()
321 .min_w_0()
322 .truncate()
323 .text_size(px(13.))
324 .font_weight(FontWeight::SEMIBOLD)
325 .text_color(theme::text())
326 .child(title),
327 ),
92 328 )
93 329 }
94 330
95 fn toggle_row(
331 fn calendar_row(
96 332 id: impl Into<ElementId>,
97 label: impl Into<SharedString>,
333 label: String,
98 334 on: bool,
99 swatch: Hsla,
335 color: Hsla,
100 336 on_click: impl Fn(&mut App) + 'static,
101 337 ) -> Stateful<Div> {
102 338 h_flex()
@@ -106,25 +342,20 @@ fn toggle_row(
106 342 .w_full()
107 343 .items_center()
108 344 .gap(px(8.))
345 .pl(px(24.))
346 .pr(px(4.))
109 347 .rounded(px(6.))
110 .px(px(4.))
111 348 .cursor_pointer()
112 349 .hover(|row| row.bg(theme::popup_hover()))
113 350 .on_click(move |_, _, cx| on_click(cx))
114 .child(
115 div()
116 .size(px(14.))
117 .flex_none()
118 .rounded(px(3.))
119 .bg(if on { swatch } else { theme::border() })
120 .when(on, |box_| {
121 box_.flex().items_center().justify_center().child(icon(
122 IconName::Check,
123 10.,
124 theme::text(),
125 ))
126 }),
127 )
351 .child(check_box(
352 if on {
353 GroupCheck::All
354 } else {
355 GroupCheck::None
356 },
357 color,
358 ))
128 359 .child(
129 360 div()
130 361 .flex_1()
@@ -132,6 +363,33 @@ fn toggle_row(
132 363 .truncate()
133 364 .text_size(px(13.))
134 365 .text_color(theme::text())
135 .child(label.into()),
366 .child(label),
136 367 )
137 368 }
369
370 /// Check box in the calendar's colour: filled with a tick when on, a dash when partly on.
371 fn check_box(check: GroupCheck, color: Hsla) -> Div {
372 div()
373 .size(px(CHECK_SIZE))
374 .flex_none()
375 .flex()
376 .items_center()
377 .justify_center()
378 .rounded(px(3.))
379 .map(|check_box| match check {
380 GroupCheck::All => {
381 check_box
382 .bg(color)
383 .child(icon(IconName::Check, 10., theme::on_accent()))
384 }
385 GroupCheck::Some => check_box.bg(color.opacity(0.5)).child(
386 div()
387 .w(px(8.))
388 .h(px(2.))
389 .rounded_full()
390 .bg(theme::on_accent()),
391 ),
392 // Lines stay soft: an empty box is a light fill of the calendar colour.
393 GroupCheck::None => check_box.bg(color.opacity(0.22)),
394 })
395 }
@@ -1,21 +1,40 @@
1//! Calendar list pane left of the grid, laid out like Teams: heading, mini month,
2//! Add calendar, and one collapsible group per account with show/hide boxes.
3
4use std::rc::Rc;
5
6use chrono::Local;
1use gpui_kit::assets::IconName;
7use gpui_kit::assets::IconName;
8use gpui_kit::component::Sizable as _;
9use gpui_kit::component::button::{Button, ButtonVariants as _};
2use gpui_kit::component::{h_flex, v_flex};
10use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
12use gpui_kit::*;
5use store::CalendarAccounts;
13use store::{CalendarAccounts, GoogleAccount};
6
14
15use super::calendar_mini_month::mini_month_grid;
7use crate::app_state::AppState;
16use crate::app_state::AppState;
17use crate::call::calendar_list::{GroupCheck, group_check, listed_calendars, offers_show_all};
18use crate::call::calendar_prefs::OUTLOOK_GROUP;
19use crate::call::week_grid::google_calendar_index;
20use crate::i18n::tr;
21use crate::settings_section::SettingsSection;
8use crate::theme;
22use crate::theme;
9use crate::views::widgets::icon;
23use crate::views::widgets::icon;
10
24
11pub const PICKER_WIDTH: f32 = 220.;
25pub const PICKER_WIDTH: f32 = 236.;
26pub const CALENDAR_PANE_TAG: &str = "shell/islands/calendar/picker";
27pub const MINI_MONTH_TAG: &str = "shell/islands/calendar/picker/mini-month";
12const ROW_HEIGHT: f32 = 28.;
28const ROW_HEIGHT: f32 = 28.;
29const MINI_CELL: f32 = 30.;
30const CHECK_SIZE: f32 = 14.;
13
31
14/// Teams-like calendar list: Outlook + each connected Google calendar with show toggles.
15pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
32pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
16 let accounts = app.read(cx).calendar_accounts();
33 let state = app.read(cx);
34 let accounts = state.calendar_accounts();
35 let prefs = &state.calendar_prefs;
17 let mut column = v_flex()
36 let mut column = v_flex()
18 .debug_selector(|| "shell/islands/calendar/picker".into())
37 .debug_selector(|| CALENDAR_PANE_TAG.into())
19 .w(px(PICKER_WIDTH))
38 .w(px(PICKER_WIDTH))
20 .flex_none()
39 .flex_none()
21 .h_full()
40 .h_full()
@@ -27,76 +46,293 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
27 .gap(px(4.))
46 .gap(px(4.))
28 .child(
47 .child(
29 div()
48 div()
30 .text_size(px(11.))
49 .text_size(px(16.))
31 .font_weight(FontWeight::SEMIBOLD)
50 .font_weight(FontWeight::BOLD)
32 .text_color(theme::text_muted())
51 .text_color(theme::text())
33 .mb(px(6.))
52 .pb(px(8.))
34 .child("CALENDARS"),
53 .child(tr("calendar.view.title")),
35 )
54 )
36 .child(outlook_row(app, &accounts));
55 .child(mini_month(app, state))
56 .child(add_calendar_row(app))
57 .child(outlook_group(
58 app,
59 &accounts,
60 prefs.group_collapsed(OUTLOOK_GROUP),
61 ));
37 for account in &accounts.google_accounts {
62 for account in &accounts.google_accounts {
38 column = column.child(
63 column = column.child(google_group(
39 div()
64 app,
40 .mt(px(8.))
65 &accounts,
41 .mb(px(2.))
66 account,
42 .text_size(px(11.))
67 prefs.group_collapsed(&account.id),
43 .font_weight(FontWeight::SEMIBOLD)
68 state.calendar_expanded_groups.contains(&account.id),
44 .text_color(theme::text_muted())
69 ));
45 .truncate()
46 .child(account.email.clone()),
47 );
48 for calendar in &account.calendars {
49 let toggle_app = app.clone();
50 let account_id = account.id.clone();
51 let calendar_id = calendar.id.clone();
52 let color = if calendar.primary {
53 theme::accent()
54 } else {
55 theme::text_soft()
56 };
57 column = column.child(toggle_row(
58 format!("calendar-picker-{}", calendar.id),
59 calendar.summary.clone(),
60 calendar.selected,
61 color,
62 move |cx| {
63 toggle_app.update(cx, |state, cx| {
64 state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
65 });
66 },
67 ));
68 }
69 }
70 if !accounts.has_google() {
71 column = column.child(
72 div()
73 .mt(px(8.))
74 .text_size(px(12.))
75 .text_color(theme::text_muted())
76 .child("Connect Google in Settings › Calendar"),
77 );
78 }
70 }
79 column
71 column
80}
72}
81
73
82fn outlook_row(app: &Entity<AppState>, accounts: &CalendarAccounts) -> Stateful<Div> {
74/// Mini month with its own month arrows; a click shows the span around that day.
75fn mini_month(app: &Entity<AppState>, state: &AppState) -> Div {
76 let month = state.calendar_mini_month_shown();
77 let (back, forward, pick) = (app.clone(), app.clone(), app.clone());
78 v_flex()
79 .debug_selector(|| MINI_MONTH_TAG.into())
80 .pb(px(8.))
81 .child(
82 h_flex()
83 .items_center()
84 .justify_between()
85 .pb(px(4.))
86 .child(
87 div()
88 .pl(px(4.))
89 .text_size(px(13.))
90 .font_weight(FontWeight::SEMIBOLD)
91 .text_color(theme::text())
92 .child(app_base::format::month_year_label(month)),
93 )
94 .child(
95 h_flex()
96 .child(
97 Button::new("calendar-mini-back")
98 .xsmall()
99 .ghost()
100 .icon(IconName::ChevronUp)
101 .tooltip(tr("calendar.view.previous_month_short"))
102 .on_click(move |_, _, cx| {
103 back.update(cx, |state, cx| {
104 state.move_calendar_mini_month(-1, cx)
105 })
106 }),
107 )
108 .child(
109 Button::new("calendar-mini-forward")
110 .xsmall()
111 .ghost()
112 .icon(IconName::ChevronDown)
113 .tooltip(tr("calendar.view.next_month_short"))
114 .on_click(move |_, _, cx| {
115 forward.update(cx, |state, cx| {
116 state.move_calendar_mini_month(1, cx)
117 })
118 }),
119 ),
120 ),
121 )
122 .child(mini_month_grid(
123 "calendar-mini",
124 month,
125 &state.calendar_dates(),
126 state.calendar_layout().first_day,
127 Local::now().date_naive(),
128 MINI_CELL,
129 Rc::new(move |date, _, cx| {
130 pick.update(cx, |state, cx| state.show_calendar_date(date, cx))
131 }),
132 ))
133}
134
135fn add_calendar_row(app: &Entity<AppState>) -> Stateful<Div> {
83 let app = app.clone();
136 let app = app.clone();
84 toggle_row(
137 h_flex()
85 "calendar-picker-outlook",
138 .id("calendar-add-calendar")
86 "Outlook",
139 .h(px(ROW_HEIGHT))
87 accounts.outlook_selected,
140 .flex_none()
88 theme::accent(),
141 .w_full()
142 .items_center()
143 .gap(px(8.))
144 .px(px(4.))
145 .rounded(px(6.))
146 .cursor_pointer()
147 .hover(|row| row.bg(theme::popup_hover()))
148 .text_size(px(13.))
149 .text_color(theme::accent_text())
150 .child(icon(IconName::Plus, 14., theme::accent_text()))
151 .child(tr("calendar.view.add_calendar"))
152 .on_click(move |_, _, cx| {
153 app.update(cx, |state, cx| {
154 state.open_settings(SettingsSection::Calendar, cx)
155 })
156 })
157}
158
159fn outlook_group(app: &Entity<AppState>, accounts: &CalendarAccounts, collapsed: bool) -> Div {
160 let on = accounts.outlook_selected;
161 let (toggle_group, toggle_row) = (app.clone(), app.clone());
162 let collapse = app.clone();
163 group(
164 format!("calendar-group-{OUTLOOK_GROUP}"),
165 tr("calendar.view.my_calendars"),
166 if on {
167 GroupCheck::All
168 } else {
169 GroupCheck::None
170 },
171 collapsed,
172 move |cx| toggle_group.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx)),
173 move |cx| {
174 collapse.update(cx, |state, cx| {
175 state.update_calendar_prefs(|prefs| prefs.toggle_group(OUTLOOK_GROUP), cx)
176 })
177 },
178 )
179 .when(!collapsed, |group| {
180 group.child(calendar_row(
181 "calendar-picker-outlook",
182 "Outlook".to_owned(),
183 on,
184 theme::calendar_color(0),
185 move |cx| toggle_row.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx)),
186 ))
187 })
188}
189
190fn google_group(
191 app: &Entity<AppState>,
192 accounts: &CalendarAccounts,
193 account: &GoogleAccount,
194 collapsed: bool,
195 expanded: bool,
196) -> Div {
197 let selected: Vec<bool> = account
198 .calendars
199 .iter()
200 .map(|calendar| calendar.selected)
201 .collect();
202 let primary: Vec<bool> = account
203 .calendars
204 .iter()
205 .map(|calendar| calendar.primary)
206 .collect();
207 let check = group_check(&selected);
208 let (toggle_group, collapse, expand) = (app.clone(), app.clone(), app.clone());
209 let (group_id, collapse_id, expand_id) =
210 (account.id.clone(), account.id.clone(), account.id.clone());
211 let mut body = group(
212 format!("calendar-group-{}", account.id),
213 account.email.clone(),
214 check,
215 collapsed,
89 move |cx| {
216 move |cx| {
90 app.update(cx, |state, cx| state.toggle_outlook_calendar_selected(cx));
217 toggle_group.update(cx, |state, cx| {
218 state.set_google_account_selected(&group_id, check != GroupCheck::All, cx)
219 })
91 },
220 },
221 move |cx| {
222 collapse.update(cx, |state, cx| {
223 state.update_calendar_prefs(|prefs| prefs.toggle_group(&collapse_id), cx)
224 })
225 },
226 );
227 if collapsed {
228 return body;
229 }
230 for index in listed_calendars(&selected, &primary, expanded) {
231 let calendar = &account.calendars[index];
232 let toggle = app.clone();
233 let (account_id, calendar_id) = (account.id.clone(), calendar.id.clone());
234 let color = google_calendar_index(accounts, &account.id, &calendar.id)
235 .map_or_else(theme::accent, theme::calendar_color);
236 body = body.child(calendar_row(
237 format!("calendar-picker-{}-{}", account.id, calendar.id),
238 calendar.summary.clone(),
239 calendar.selected,
240 color,
241 move |cx| {
242 toggle.update(cx, |state, cx| {
243 state.toggle_google_calendar_selected(&account_id, &calendar_id, cx)
244 });
245 },
246 ));
247 }
248 if offers_show_all(account.calendars.len()) {
249 body = body.child(
250 div()
251 .id(SharedString::from(format!(
252 "calendar-show-all-{}",
253 account.id
254 )))
255 .pl(px(28.))
256 .h(px(ROW_HEIGHT))
257 .flex_none()
258 .flex()
259 .items_center()
260 .cursor_pointer()
261 .text_size(px(12.))
262 .text_color(theme::accent_text())
263 .child(if expanded {
264 tr("calendar.view.show_fewer")
265 } else {
266 tr("calendar.view.show_all")
267 })
268 .on_click(move |_, _, cx| {
269 expand.update(cx, |state, cx| {
270 state.toggle_calendar_group_expanded(&expand_id, cx)
271 })
272 }),
273 );
274 }
275 body
276}
277
278/// Group header: chevron to collapse, a check box for the whole group, the title.
279fn group(
280 id: String,
281 title: String,
282 check: GroupCheck,
283 collapsed: bool,
284 toggle: impl Fn(&mut App) + 'static,
285 collapse: impl Fn(&mut App) + 'static,
286) -> Div {
287 v_flex().w_full().pt(px(6.)).child(
288 h_flex()
289 .h(px(ROW_HEIGHT))
290 .flex_none()
291 .w_full()
292 .items_center()
293 .gap(px(6.))
294 .child(
295 div()
296 .id(SharedString::from(format!("{id}-chevron")))
297 .flex_none()
298 .cursor_pointer()
299 .child(icon(
300 if collapsed {
301 IconName::ChevronRight
302 } else {
303 IconName::ChevronDown
304 },
305 14.,
306 theme::text_muted(),
307 ))
308 .on_click(move |_, _, cx| collapse(cx)),
309 )
310 .child(
311 div()
312 .id(SharedString::from(format!("{id}-check")))
313 .flex_none()
314 .cursor_pointer()
315 .child(check_box(check, theme::accent()))
316 .on_click(move |_, _, cx| toggle(cx)),
317 )
318 .child(
319 div()
320 .flex_1()
321 .min_w_0()
322 .truncate()
323 .text_size(px(13.))
324 .font_weight(FontWeight::SEMIBOLD)
325 .text_color(theme::text())
326 .child(title),
327 ),
92 )
328 )
93}
329}
94
330
95fn toggle_row(
331fn calendar_row(
96 id: impl Into<ElementId>,
332 id: impl Into<ElementId>,
97 label: impl Into<SharedString>,
333 label: String,
98 on: bool,
334 on: bool,
99 swatch: Hsla,
335 color: Hsla,
100 on_click: impl Fn(&mut App) + 'static,
336 on_click: impl Fn(&mut App) + 'static,
101) -> Stateful<Div> {
337) -> Stateful<Div> {
102 h_flex()
338 h_flex()
@@ -106,25 +342,20 @@ fn toggle_row(
106 .w_full()
342 .w_full()
107 .items_center()
343 .items_center()
108 .gap(px(8.))
344 .gap(px(8.))
345 .pl(px(24.))
346 .pr(px(4.))
109 .rounded(px(6.))
347 .rounded(px(6.))
110 .px(px(4.))
111 .cursor_pointer()
348 .cursor_pointer()
112 .hover(|row| row.bg(theme::popup_hover()))
349 .hover(|row| row.bg(theme::popup_hover()))
113 .on_click(move |_, _, cx| on_click(cx))
350 .on_click(move |_, _, cx| on_click(cx))
114 .child(
351 .child(check_box(
115 div()
352 if on {
116 .size(px(14.))
353 GroupCheck::All
117 .flex_none()
354 } else {
118 .rounded(px(3.))
355 GroupCheck::None
119 .bg(if on { swatch } else { theme::border() })
356 },
120 .when(on, |box_| {
357 color,
121 box_.flex().items_center().justify_center().child(icon(
358 ))
122 IconName::Check,
123 10.,
124 theme::text(),
125 ))
126 }),
127 )
128 .child(
359 .child(
129 div()
360 div()
130 .flex_1()
361 .flex_1()
@@ -132,6 +363,33 @@ fn toggle_row(
132 .truncate()
363 .truncate()
133 .text_size(px(13.))
364 .text_size(px(13.))
134 .text_color(theme::text())
365 .text_color(theme::text())
135 .child(label.into()),
366 .child(label),
136 )
367 )
137}
368}
369
370/// Check box in the calendar's colour: filled with a tick when on, a dash when partly on.
371fn check_box(check: GroupCheck, color: Hsla) -> Div {
372 div()
373 .size(px(CHECK_SIZE))
374 .flex_none()
375 .flex()
376 .items_center()
377 .justify_center()
378 .rounded(px(3.))
379 .map(|check_box| match check {
380 GroupCheck::All => {
381 check_box
382 .bg(color)
383 .child(icon(IconName::Check, 10., theme::on_accent()))
384 }
385 GroupCheck::Some => check_box.bg(color.opacity(0.5)).child(
386 div()
387 .w(px(8.))
388 .h(px(2.))
389 .rounded_full()
390 .bg(theme::on_accent()),
391 ),
392 // Lines stay soft: an empty box is a light fill of the calendar colour.
393 GroupCheck::None => check_box.bg(color.opacity(0.22)),
394 })
395}
crates/app/src/views/calendar_view.rs +373 −131
@@ -1,8 +1,8 @@
1 1 use std::time::Duration;
2 2
3 use app_base::format::{self, clock_format};
3 use app_base::format::{self, WeekdayWidth, clock_format, weekday_name};
4 4 use chatsvc::{CalendarEvent, ResponseType, join_info_text};
5 use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
5 use chrono::{DateTime, Datelike, Local, NaiveDate, Offset, Timelike, Utc};
6 6 use gpui_kit::assets::IconName;
7 7 use gpui_kit::component::Sizable as _;
8 8 use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -22,26 +22,49 @@ use super::rsvp_menu::rsvp_menu;
22 22 use super::scroll_edge::scroll_offset;
23 23 use crate::app_state::AppState;
24 24 use crate::call::calendar_now::{
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION, hour_height,
26 now_scroll_offset_y, offset_differs, shows_hour_grid, work_start_scroll_offset_y,
27 27 };
28 use crate::call::week::CalendarLoadFailure;
28 29 use crate::call::week_grid::{
29 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 CalendarSpan, EventLook, WeekBlock, WeekDay, WeekLayout, calendar_index, event_look,
31 hour_label, month_shown, week_days,
30 32 };
31 33 use crate::i18n::tr;
32 34 use crate::theme;
35 use crate::views::widgets::icon;
33 36
34 const HOUR_HEIGHT: f32 = 120.;
35 const QUARTERS_PER_HOUR: usize = 4;
36 const QUARTER_LINE_OPACITY: f32 = 0.45;
37 37 const GUTTER_WIDTH: f32 = 50.;
38 38 const HEADER_HEIGHT: f32 = 52.;
39 39 const DAY_HEADER_HEIGHT: f32 = 56.;
40 40 const ALL_DAY_HEIGHT: f32 = 26.;
41 41 const BLOCK_GAP: f32 = 2.;
42 const CANCELED_PREFIX: &str = "Canceled: ";
43 const COPY_JOIN_INFO: &str = "Copy join info";
44 const COMPACT_HEADER_WIDTH: f32 = 960.;
42 const MINOR_LINE_OPACITY: f32 = 0.45;
43 const OFF_HOURS_OPACITY: f32 = 0.85;
44 const NOW_ELSEWHERE_OPACITY: f32 = 0.4;
45 pub const CALENDAR_HEADER_TAG: &str = "shell/islands/calendar/header";
46 pub const CALENDAR_DAY_HEADERS_TAG: &str = "shell/islands/calendar/day-headers";
47 pub const CALENDAR_NEW_MEETING_TAG: &str = "shell/islands/calendar/header/new-meeting";
48 pub const COMPACT_HEADER_WIDTH: f32 = 960.;
49 /// Header widths below which button labels give way to icons (German labels are longest).
50 const SECONDARY_LABELS_WIDTH: f32 = 1080.;
51 const PRIMARY_LABELS_WIDTH: f32 = 780.;
52
53 /// Which header buttons keep their text at a given header width.
54 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55 pub struct HeaderLabels {
56 /// Today, view and New meeting.
57 pub primary: bool,
58 /// Join with an ID and Meet now.
59 pub secondary: bool,
60 }
61
62 pub fn header_labels(header_width: f32) -> HeaderLabels {
63 HeaderLabels {
64 primary: header_width >= PRIMARY_LABELS_WIDTH,
65 secondary: header_width >= SECONDARY_LABELS_WIDTH,
66 }
67 }
45 68 const BUSY_FILL_OPACITY: f32 = 0.28;
46 69 const FREE_FILL_OPACITY: f32 = 0.12;
47 70 const STATUS_BAR_WIDTH: f32 = 4.;
@@ -61,6 +84,9 @@ pub struct CalendarView {
61 84 last_programmatic_offset: f32,
62 85 skip_manual_check: bool,
63 86 clock_running: bool,
87 /// Row height of one hour and minor lines per hour, from the time scale.
88 hour_height: f32,
89 steps_per_hour: usize,
64 90 _observation: Subscription,
65 91 _agent_observation: Option<Subscription>,
66 92 }
@@ -78,6 +104,8 @@ impl CalendarView {
78 104 last_programmatic_offset: 0.,
79 105 skip_manual_check: false,
80 106 clock_running: false,
107 hour_height: hour_height(Default::default()),
108 steps_per_hour: 2,
81 109 _observation: observation,
82 110 _agent_observation: agent_observation,
83 111 }
@@ -92,26 +120,41 @@ impl CalendarView {
92 120 let offset = now_scroll_offset_y(
93 121 local.hour(),
94 122 local.minute(),
95 HOUR_HEIGHT,
123 self.hour_height,
96 124 Self::grid_viewport_height(window),
97 125 NOW_BIAS_FRACTION,
98 126 );
127 self.set_programmatic_offset(offset);
128 }
129
130 /// A range without today opens at work start instead of midnight.
131 fn align_scroll_to_work_start(&mut self, work_start_minute: i64, window: &Window) {
132 let offset = work_start_scroll_offset_y(
133 work_start_minute,
134 self.hour_height,
135 Self::grid_viewport_height(window),
136 );
137 self.set_programmatic_offset(offset);
138 }
139
140 fn set_programmatic_offset(&mut self, offset: f32) {
99 141 self.scroll.set_offset(point(px(0.), px(offset)));
100 142 self.last_programmatic_offset = offset;
101 143 self.skip_manual_check = true;
102 144 }
103 145
104 146 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
105 let (scroll_to_now, span, today_visible) = {
147 let (scroll_to_now, span, today_visible, work_start) = {
106 148 let state = self.state.read(cx);
107 let start = state.calendar_start();
108 let today = Local::now().date_naive();
109 let today_visible = start <= today
110 && today < start + chrono::Duration::days(state.calendar_week.span.days());
149 let today_visible = state.calendar_shows_today();
150 let prefs = &state.calendar_prefs;
151 self.hour_height = hour_height(prefs.time_scale);
152 self.steps_per_hour = prefs.time_scale.steps_per_hour() as usize;
111 153 (
112 154 state.calendar_scroll_to_now,
113 155 state.calendar_week.span,
114 156 today_visible,
157 prefs.work_hours.minute_range().0,
115 158 )
116 159 };
117 160 if !shows_hour_grid(span) {
@@ -121,7 +164,12 @@ impl CalendarView {
121 164 self.ensure_clock(cx);
122 165 if scroll_to_now != self.seen_scroll_to_now {
123 166 self.seen_scroll_to_now = scroll_to_now;
124 self.follow_now.request_align();
167 if today_visible {
168 self.follow_now.request_align();
169 } else {
170 self.align_scroll_to_work_start(work_start, window);
171 return;
172 }
125 173 }
126 174 if self.skip_manual_check {
127 175 self.skip_manual_check = false;
@@ -180,33 +228,60 @@ impl CalendarView {
180 228 cx.notify();
181 229 }
182 230
183 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
231 fn header(
232 &self,
233 start: NaiveDate,
234 span: CalendarSpan,
235 dates: &[NaiveDate],
236 layout: &WeekLayout,
237 compact: bool,
238 labels: HeaderLabels,
239 ) -> impl IntoElement {
184 240 let span_state = self.state.clone();
185 let label = |text: &'static str| (!compact).then_some(text);
241 let label = |key: &'static str| labels.primary.then(|| tr(key));
242 let secondary = |key: &'static str| labels.secondary.then(|| tr(key));
186 243 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
187 244 let (join_state, meet_state, new_state) =
188 245 (self.state.clone(), self.state.clone(), self.state.clone());
246 let pane_state = self.state.clone();
247 let (back_tip, forward_tip) = match span {
248 CalendarSpan::Day => ("calendar.view.previous_day", "calendar.view.next_day"),
249 CalendarSpan::Month => ("calendar.view.previous_month", "calendar.view.next_month"),
250 _ => ("calendar.view.previous_week", "calendar.view.next_week"),
251 };
189 252 h_flex()
253 .debug_selector(|| CALENDAR_HEADER_TAG.into())
190 254 .h(px(HEADER_HEIGHT))
191 255 .flex_none()
192 256 .items_center()
193 257 .gap(px(8.))
194 258 .px(px(16.))
195 .child(
196 div()
197 .flex_none()
198 .text_size(px(16.))
199 .font_weight(FontWeight::BOLD)
200 .mr(px(8.))
201 .child("Calendar"),
202 )
259 .when(!compact, |header| {
260 header.child(
261 Button::new("calendar-pane-toggle")
262 .small()
263 .ghost()
264 .icon(IconName::PanelLeft)
265 .tooltip(tr("calendar.view.toggle_pane"))
266 .on_click(move |_, _, cx| {
267 pane_state.update(cx, |state, cx| {
268 state.update_calendar_prefs(
269 |prefs| prefs.pane_hidden = !prefs.pane_hidden,
270 cx,
271 )
272 })
273 }),
274 )
275 })
203 276 .child(
204 277 Button::new("calendar-today")
205 278 .small()
206 279 .outline()
207 280 .icon(IconName::Calendar)
208 .when_some(label("Today"), |button, text| button.label(text))
209 .tooltip("Today")
281 .when_some(label("calendar.view.today"), |button, text| {
282 button.label(text)
283 })
284 .tooltip(tr("calendar.view.today"))
210 285 .on_click(move |_, _, cx| {
211 286 today.update(cx, |state, cx| state.calendar_to_today(cx))
212 287 }),
@@ -216,11 +291,7 @@ impl CalendarView {
216 291 .small()
217 292 .ghost()
218 293 .icon(IconName::ChevronLeft)
219 .tooltip(match span {
220 CalendarSpan::Day => "Go to previous day",
221 CalendarSpan::Month => "Go to previous month",
222 _ => "Go to previous week",
223 })
294 .tooltip(tr(back_tip))
224 295 .on_click(move |_, _, cx| {
225 296 back.update(cx, |state, cx| state.shift_calendar_week(-1, cx))
226 297 }),
@@ -230,20 +301,16 @@ impl CalendarView {
230 301 .small()
231 302 .ghost()
232 303 .icon(IconName::ChevronRight)
233 .tooltip(match span {
234 CalendarSpan::Day => "Go to next day",
235 CalendarSpan::Month => "Go to next month",
236 _ => "Go to next week",
237 })
304 .tooltip(tr(forward_tip))
238 305 .on_click(move |_, _, cx| {
239 306 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
240 307 }),
241 308 )
242 309 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
243 310 &self.state,
244 span.title(start),
245 start,
246 span.days(),
311 span.title(start, layout),
312 dates.to_vec(),
313 layout.first_day,
247 314 if span == CalendarSpan::Month {
248 315 month_shown(start)
249 316 } else {
@@ -254,7 +321,8 @@ impl CalendarView {
254 321 Button::new("calendar-span")
255 322 .small()
256 323 .ghost()
257 .label(span.label())
324 .icon(IconName::LayoutGrid)
325 .when(labels.primary, |button| button.label(span.label()))
258 326 .dropdown_caret(true)
259 327 .dropdown_menu(move |menu, _, _| {
260 328 CalendarSpan::ALL.iter().fold(menu, |menu, &choice| {
@@ -276,8 +344,10 @@ impl CalendarView {
276 344 .small()
277 345 .outline()
278 346 .icon(IconName::Hash)
279 .when_some(label("Join with an ID"), |button, text| button.label(text))
280 .tooltip("Join with an ID")
347 .when_some(secondary("calendar.view.join_with_id"), |button, text| {
348 button.label(text)
349 })
350 .tooltip(tr("calendar.view.join_with_id"))
281 351 .on_click(move |_, window, cx| {
282 352 open_join_with_id(join_state.clone(), window, cx)
283 353 }),
@@ -287,25 +357,32 @@ impl CalendarView {
287 357 .small()
288 358 .outline()
289 359 .icon(IconName::Video)
290 .when_some(label("Meet now"), |button, text| button.label(text))
291 .tooltip("Meet now")
360 .when_some(secondary("calendar.view.meet_now"), |button, text| {
361 button.label(text)
362 })
363 .tooltip(tr("calendar.view.meet_now"))
292 364 .on_click(move |_, _, cx| {
293 365 meet_state.update(cx, |state, cx| state.start_meet_now(cx))
294 366 }),
295 367 )
296 368 .child(
297 369 Button::new("calendar-new-meeting")
370 .debug_selector(|| CALENDAR_NEW_MEETING_TAG.into())
298 371 .small()
299 372 .primary()
300 373 .icon(IconName::Plus)
301 .when_some(label("New meeting"), |button, text| button.label(text))
302 .tooltip("New meeting")
374 .when_some(label("calendar.view.new_meeting"), |button, text| {
375 button.label(text)
376 })
377 .tooltip(tr("calendar.view.new_meeting"))
303 378 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
304 379 )
305 380 }
306 381
382 /// Day number above the full weekday name; today in the accent colour with its bar.
307 383 fn day_headers(&self, days: &[WeekDay], today: NaiveDate) -> impl IntoElement {
308 384 h_flex()
385 .debug_selector(|| CALENDAR_DAY_HEADERS_TAG.into())
309 386 .h(px(DAY_HEADER_HEIGHT))
310 387 .flex_none()
311 388 .border_b_1()
@@ -313,10 +390,10 @@ impl CalendarView {
313 390 .child(div().w(px(GUTTER_WIDTH)).flex_none())
314 391 .children(days.iter().map(|day| {
315 392 let is_today = day.date == today;
316 let color = if is_today {
317 theme::accent_text()
393 let (number_color, name_color) = if is_today {
394 (theme::accent_text(), theme::accent_text())
318 395 } else {
319 theme::text_soft()
396 (theme::text(), theme::text_soft())
320 397 };
321 398 v_flex()
322 399 .relative()
@@ -342,14 +419,16 @@ impl CalendarView {
342 419 div()
343 420 .text_size(px(20.))
344 421 .line_height(px(24.))
345 .text_color(color)
422 .text_color(number_color)
423 .when(is_today, |number| number.font_weight(FontWeight::SEMIBOLD))
346 424 .child(format::calendar_day_number(day.date)),
347 425 )
348 426 .child(
349 427 div()
350 428 .text_size(px(12.))
351 .text_color(color)
352 .child(day.date.format("%a").to_string()),
429 .text_color(name_color)
430 .truncate()
431 .child(weekday_name(day.date.weekday(), WeekdayWidth::Full)),
353 432 )
354 433 }))
355 434 }
@@ -358,6 +437,7 @@ impl CalendarView {
358 437 &self,
359 438 days: &[WeekDay],
360 439 events: &[CalendarEvent],
440 colors: &[Hsla],
361 441 send_response: bool,
362 442 ) -> Option<Div> {
363 443 if days.iter().all(|day| day.all_day.is_empty()) {
@@ -379,6 +459,7 @@ impl CalendarView {
379 459 .border_color(theme::border())
380 460 .children(day.all_day.iter().map(|&index| {
381 461 let event = events[index].clone();
462 let color = colors[index];
382 463 let open_state = self.state.clone();
383 464 let (menu_state, menu_event) = (self.state.clone(), event.clone());
384 465 // Day-qualified id: multi-day all-day chips share object_id.
@@ -391,8 +472,8 @@ impl CalendarView {
391 472 .px(px(6.))
392 473 .flex()
393 474 .items_center()
394 .rounded(px(4.))
395 .bg(event_fill(event_look(&event)))
475 .rounded(px(6.))
476 .bg(event_fill(event_look(&event), color))
396 477 .text_size(px(12.))
397 478 .truncate()
398 479 .cursor_pointer()
@@ -417,21 +498,22 @@ impl CalendarView {
417 498 &self,
418 499 block: &WeekBlock,
419 500 event: &CalendarEvent,
501 color: Hsla,
420 502 day: NaiveDate,
421 503 send_response: bool,
422 504 ) -> impl IntoElement {
423 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
424 let height = ((block.end_minute - block.start_minute) as f32 / 60. * HOUR_HEIGHT
505 let top = block.start_minute as f32 / 60. * self.hour_height;
506 let height = ((block.end_minute - block.start_minute) as f32 / 60. * self.hour_height
425 507 - BLOCK_GAP)
426 508 .max(14.);
427 509 let width = 1. / block.lanes as f32;
428 510 let compact = height < 36.;
429 511 let small = height < SMALL_TITLE_HEIGHT;
430 512 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);
513 let title_line = if small { 14. } else { 16. };
514 let pad_y = if compact { 1. } else { 3. };
515 // Title and organizer flow as one text; tall blocks wrap it over more lines.
516 let lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
435 517 let look = event_look(event);
436 518 // Join on the block whenever a Teams link exists (same as detail dialog).
437 519 // Skip on tiny blocks — the button would crush the title.
@@ -465,13 +547,13 @@ impl CalendarView {
465 547 .size_full()
466 548 .items_start()
467 549 .overflow_hidden()
468 .rounded(px(4.))
469 .bg(event_fill(look))
550 .rounded(px(6.))
551 .bg(event_fill(look, color))
470 552 .when(event.cancelled, |block| block.opacity(0.6))
471 553 .cursor_pointer()
472 .children(status_bar(look))
554 .children(status_bar(look, color))
473 555 .child(
474 v_flex()
556 div()
475 557 .flex_1()
476 558 .min_w_0()
477 559 .pl(px(5.))
@@ -479,28 +561,20 @@ impl CalendarView {
479 561 .h_full()
480 562 .py(px(pad_y))
481 563 .overflow_hidden()
482 .when(compact, |body| body.justify_center())
483 .child(
484 div()
485 .text_size(px(title_size))
486 .line_height(px(title_line))
487 .font_weight(FontWeight::SEMIBOLD)
488 .text_color(title_color)
489 .when(compact, |title| title.truncate())
490 .when(!compact, |title| title.line_clamp(title_lines))
491 .child(event_title(event)),
492 )
493 .when(!compact && title_lines > 2, |body| {
494 body.children(event.organizer_name.clone().map(|organizer| {
495 div()
496 .text_size(px(12.))
497 .line_height(px(16.))
498 .text_color(detail_color)
499 .truncate()
500 .child(organizer)
501 }))
502 }),
564 .text_size(px(title_size))
565 .line_height(px(title_line))
566 .text_color(detail_color)
567 .line_clamp(lines)
568 .text_ellipsis()
569 .child(title_and_organizer(event, title_color)),
503 570 )
571 .when(event.series, |block| {
572 block.child(div().flex_none().pt(px(pad_y + 1.)).pr(px(4.)).child(icon(
573 IconName::Repeat,
574 12.,
575 detail_color,
576 )))
577 })
504 578 .when(can_join, |block| {
505 579 block.child(
506 580 div().flex_none().pr(px(4.)).pt(px(3.)).child(
@@ -533,21 +607,30 @@ impl CalendarView {
533 607 })
534 608 }
535 609
610 #[allow(clippy::too_many_arguments)]
536 611 fn grid(
537 612 &self,
538 613 days: &[WeekDay],
539 614 events: &[CalendarEvent],
615 colors: &[Hsla],
616 layout: &WeekLayout,
617 work_minutes: (i64, i64),
540 618 today: NaiveDate,
541 619 now: DateTime<Utc>,
542 620 send_response: bool,
543 621 cx: &mut Context<Self>,
544 622 ) -> impl IntoElement {
545 let total_height = 24. * HOUR_HEIGHT;
623 let row = self.hour_height;
624 let steps = self.steps_per_hour;
625 let total_height = 24. * row;
546 626 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
547 627 let now_minute = {
548 628 let local = now.with_timezone(&Local);
549 629 local.hour() * 60 + local.minute()
550 630 };
631 let now_top = now_minute as f32 / 60. * row;
632 let today_shown = days.iter().any(|day| day.date == today);
633 let minute_y = |minute: i64| minute as f32 / 60. * row;
551 634 div()
552 635 .id("calendar-grid")
553 636 .flex_1()
@@ -565,18 +648,38 @@ impl CalendarView {
565 648 .flex_none()
566 649 .children((0..24).map(|hour| {
567 650 div()
568 .h(px(HOUR_HEIGHT))
569 .pt(px(4.))
651 .h(px(row))
652 .pt(px(2.))
653 .pr(px(8.))
570 654 .flex()
571 .justify_center()
572 .text_size(px(12.))
573 .text_color(theme::text_soft())
655 .justify_end()
656 .text_size(px(11.))
657 .text_color(theme::text_muted())
574 658 .when(hour > 0, |label| {
575 659 label.child(hour_label(hour, twelve_hour))
576 660 })
577 661 })),
578 662 )
579 663 .children(days.iter().map(|day| {
664 let work_day = layout.is_work_day(day.date.weekday());
665 let (work_start, work_end) = work_minutes;
666 let shade = |top: f32, height: f32| {
667 div()
668 .absolute()
669 .top(px(top))
670 .left_0()
671 .right_0()
672 .h(px(height))
673 .bg(theme::background().opacity(OFF_HOURS_OPACITY))
674 };
675 let shading = if work_day {
676 vec![
677 shade(0., minute_y(work_start)),
678 shade(minute_y(work_end), total_height - minute_y(work_end)),
679 ]
680 } else {
681 vec![shade(0., total_height)]
682 };
580 683 div()
581 684 .relative()
582 685 .flex_1()
@@ -584,31 +687,41 @@ impl CalendarView {
584 687 .h_full()
585 688 .border_l_1()
586 689 .border_color(theme::border())
587 .children((1..24 * QUARTERS_PER_HOUR).map(|quarter| {
690 .children(shading)
691 .children((1..24 * steps).map(|step| {
588 692 let line = div()
589 693 .absolute()
590 .top(
591 px(quarter as f32 * HOUR_HEIGHT / QUARTERS_PER_HOUR as f32),
592 )
694 .top(px(step as f32 * row / steps as f32))
593 695 .left_0()
594 .right_0();
595 if quarter % QUARTERS_PER_HOUR == 0 {
596 line.h(px(1.)).bg(theme::border())
696 .right_0()
697 .h(px(1.));
698 if step % steps == 0 {
699 line.bg(theme::border())
597 700 } else {
598 line.h(px(1.))
599 .bg(theme::border().opacity(QUARTER_LINE_OPACITY))
701 line.bg(theme::border().opacity(MINOR_LINE_OPACITY))
600 702 }
601 703 }))
602 704 .children(day.blocks.iter().map(|block| {
603 705 self.event_block(
604 706 block,
605 707 &events[block.event_index],
708 colors[block.event_index],
606 709 day.date,
607 710 send_response,
608 711 )
609 712 }))
713 .when(today_shown && day.date != today, |column| {
714 column.child(
715 div()
716 .absolute()
717 .top(px(now_top))
718 .left_0()
719 .right_0()
720 .h(px(1.))
721 .bg(theme::accent().opacity(NOW_ELSEWHERE_OPACITY)),
722 )
723 })
610 724 .when(day.date == today, |column| {
611 let now_top = now_minute as f32 / 60. * HOUR_HEIGHT;
612 725 column
613 726 .child(
614 727 div()
@@ -634,6 +747,66 @@ impl CalendarView {
634 747 }
635 748 }
636 749
750 /// Loading line and one notice per failed source, under the calendar header.
751 fn load_notices(
752 state: &Entity<AppState>,
753 failures: &[CalendarLoadFailure],
754 loading: bool,
755 ) -> Vec<Div> {
756 let mut rows = Vec::new();
757 if loading {
758 rows.push(
759 h_flex()
760 .flex_none()
761 .px(px(16.))
762 .pb(px(6.))
763 .text_size(px(12.))
764 .text_color(theme::text_muted())
765 .child(tr("calendar.view.loading")),
766 );
767 }
768 for failure in failures {
769 let retry = state.clone();
770 let mut args = std::collections::HashMap::new();
771 args.insert("source".to_owned(), failure.source.label().to_owned());
772 rows.push(
773 h_flex()
774 .flex_none()
775 .mx(px(16.))
776 .mb(px(6.))
777 .px(px(12.))
778 .py(px(6.))
779 .gap(px(12.))
780 .items_center()
781 .rounded(px(6.))
782 .bg(theme::red_tint())
783 .text_size(px(13.))
784 .text_color(theme::text())
785 .child(
786 div()
787 .flex_1()
788 .min_w_0()
789 .truncate()
790 .child(crate::i18n::tr_args("calendar.view.source_failed", &args)),
791 )
792 .child(
793 Button::new(SharedString::from(format!(
794 "calendar-retry-{}",
795 failure.source.label()
796 )))
797 .xsmall()
798 .outline()
799 .label(tr("common.retry"))
800 .tooltip(failure.message.clone())
801 .on_click(move |_, _, cx| {
802 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
803 }),
804 ),
805 );
806 }
807 rows
808 }
809
637 810 fn event_menu(
638 811 menu: PopupMenu,
639 812 state: &Entity<AppState>,
@@ -647,18 +820,20 @@ fn event_menu(
647 820 .filter(|_| event.online && !event.cancelled)
648 821 {
649 822 let (join_state, subject) = (state.clone(), event.subject.clone());
650 menu = menu.item(PopupMenuItem::new("Join").icon(IconName::Video).on_click(
651 move |_, _, cx| {
652 join_state.update(cx, |state, cx| {
653 state.join_calendar_meeting(Some(&join_url), &subject, cx)
654 })
655 },
656 ));
823 menu = menu.item(
824 PopupMenuItem::new(tr("common.join"))
825 .icon(IconName::Video)
826 .on_click(move |_, _, cx| {
827 join_state.update(cx, |state, cx| {
828 state.join_calendar_meeting(Some(&join_url), &subject, cx)
829 })
830 }),
831 );
657 832 }
658 833 if let Some(join_url) = event.join_url.as_deref().filter(|_| event.online) {
659 834 let info = join_info_text(join_url, event.dial_in.as_ref());
660 835 menu = menu.item(
661 PopupMenuItem::new(COPY_JOIN_INFO)
836 PopupMenuItem::new(tr("calendar.view.copy_join_info"))
662 837 .icon(IconName::Copy)
663 838 .on_click(move |_, _, cx| {
664 839 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
@@ -668,7 +843,7 @@ fn event_menu(
668 843 if let Some(thread_id) = event.thread_id.clone() {
669 844 let chat_state = state.clone();
670 845 menu = menu.item(
671 PopupMenuItem::new("Chat with participants")
846 PopupMenuItem::new(tr("calendar.view.chat_with_participants"))
672 847 .icon(IconName::MessageSquare)
673 848 .on_click(move |_, _, cx| {
674 849 chat_state.update(cx, |state, cx| {
@@ -689,31 +864,49 @@ fn event_menu(
689 864 )
690 865 }
691 866
692 fn event_fill(look: EventLook) -> Hsla {
867 fn event_fill(look: EventLook, color: Hsla) -> Hsla {
693 868 match look {
694 EventLook::Busy => theme::accent().opacity(BUSY_FILL_OPACITY),
695 EventLook::Free | EventLook::Tentative => theme::accent().opacity(FREE_FILL_OPACITY),
869 EventLook::Busy => color.opacity(BUSY_FILL_OPACITY),
870 EventLook::Free | EventLook::Tentative => color.opacity(FREE_FILL_OPACITY),
696 871 }
697 872 }
698 873
699 fn status_bar(look: EventLook) -> Option<Div> {
874 fn status_bar(look: EventLook, color: Hsla) -> Option<Div> {
700 875 let bar = div().flex_none().w(px(STATUS_BAR_WIDTH)).h_full();
701 876 match look {
702 EventLook::Busy => Some(bar.bg(theme::accent())),
877 EventLook::Busy => Some(bar.bg(color)),
703 878 EventLook::Tentative => Some(
704 bar.bg(theme::accent().opacity(BUSY_FILL_OPACITY)).child(
705 div()
706 .size_full()
707 .bg(pattern_slash(theme::accent(), HATCH_STRIPE, HATCH_GAP)),
708 ),
879 bar.bg(color.opacity(BUSY_FILL_OPACITY))
880 .child(
881 div()
882 .size_full()
883 .bg(pattern_slash(color, HATCH_STRIPE, HATCH_GAP)),
884 ),
709 885 ),
710 886 EventLook::Free => None,
711 887 }
712 888 }
713 889
890 /// "Daily Standup Zulal Fouque": bold title, organizer right after it on the same line.
891 fn title_and_organizer(event: &CalendarEvent, title_color: Hsla) -> StyledText {
892 let title = event_title(event);
893 let text = match event.organizer_name.as_deref() {
894 Some(organizer) if !organizer.is_empty() => format!("{title} {organizer}"),
895 _ => title.clone(),
896 };
897 StyledText::new(text).with_highlights([(
898 0..title.len(),
899 HighlightStyle {
900 color: Some(title_color),
901 font_weight: Some(FontWeight::SEMIBOLD),
902 ..Default::default()
903 },
904 )])
905 }
906
714 907 fn event_title(event: &CalendarEvent) -> String {
715 908 let subject = if event.cancelled {
716 format!("{CANCELED_PREFIX}{}", event.subject)
909 format!("{}{}", tr("calendar.peek.canceled_prefix"), event.subject)
717 910 } else {
718 911 event.subject.clone()
719 912 };
@@ -744,18 +937,39 @@ fn source_label(event: &CalendarEvent) -> String {
744 937
745 938 impl Render for CalendarView {
746 939 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
747 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
940 let window_width = f32::from(window.viewport_size().width);
941 let compact = window_width < COMPACT_HEADER_WIDTH;
748 942 self.sync_follow_from_state(window, cx);
749 943 let state = self.state.read(cx);
750 944 let start = state.calendar_start();
751 945 let events = state.calendar_week.events.clone();
752 946 let send_response = state.rsvp_send_response;
947 let failures = state.calendar_week.failures.clone();
948 let loading = state.calendar_week.loading && events.is_empty();
753 949 let offset = Local::now().offset().fix();
754 950 let span = state.calendar_week.span;
755 let days = week_days(&events, start, span.days(), offset);
951 let layout = state.calendar_layout();
952 let dates = state.calendar_dates();
953 let days = week_days(&events, &dates, offset);
756 954 let today = Local::now().date_naive();
757 955 let now = Utc::now();
758 let show_picker = !compact;
956 let accounts = state.calendar_accounts();
957 let colors: Vec<Hsla> = events
958 .iter()
959 .map(|event| theme::calendar_color(calendar_index(event, &accounts)))
960 .collect();
961 let work_minutes = state.calendar_prefs.work_hours.minute_range();
962 let show_picker = !compact && !state.calendar_prefs.pane_hidden;
963 // Width left for the header: window minus rail, island gaps and the pane.
964 let header_width = window_width
965 - app_ui_kit::layout::RAIL_WIDTH
966 - 2. * app_ui_kit::layout::ISLAND_GAP
967 - if show_picker {
968 calendar_picker::PICKER_WIDTH
969 } else {
970 0.
971 };
972 let labels = header_labels(header_width);
759 973 h_flex()
760 974 .debug_selector(|| "shell/islands/calendar".into())
761 975 .flex_1()
@@ -773,7 +987,8 @@ impl Render for CalendarView {
773 987 .flex_1()
774 988 .min_w_0()
775 989 .h_full()
776 .child(self.header(start, span, compact))
990 .child(self.header(start, span, &dates, &layout, compact, labels))
991 .children(load_notices(&self.state, &failures, loading))
777 992 .children(meeting_proposal_cards(cx))
778 993 .map(|calendar| {
779 994 if span == CalendarSpan::Month {
@@ -782,16 +997,43 @@ impl Render for CalendarView {
782 997 start,
783 998 &days,
784 999 &events,
1000 &colors,
785 1001 today,
786 1002 offset,
1003 layout.weekdays(),
787 1004 ))
788 1005 } else {
789 1006 calendar
790 1007 .child(self.day_headers(&days, today))
791 .children(self.all_day_row(&days, &events, send_response))
792 .child(self.grid(&days, &events, today, now, send_response, cx))
1008 .children(self.all_day_row(&days, &events, &colors, send_response))
1009 .child(self.grid(
1010 &days,
1011 &events,
1012 &colors,
1013 &layout,
1014 work_minutes,
1015 today,
1016 now,
1017 send_response,
1018 cx,
1019 ))
793 1020 }
794 1021 }),
795 1022 )
796 1023 }
797 1024 }
1025
1026 #[cfg(test)]
1027 mod tests {
1028 use super::header_labels;
1029
1030 #[test]
1031 fn header_buttons_drop_their_text_as_the_header_narrows() {
1032 let wide = header_labels(1300.);
1033 assert!(wide.primary && wide.secondary);
1034 let middle = header_labels(900.);
1035 assert!(middle.primary && !middle.secondary);
1036 let narrow = header_labels(600.);
1037 assert!(!narrow.primary && !narrow.secondary);
1038 }
1039 }
@@ -1,8 +1,8 @@
1use std::time::Duration;
1use std::time::Duration;
2
2
3use app_base::format::{self, clock_format};
3use app_base::format::{self, WeekdayWidth, clock_format, weekday_name};
4use chatsvc::{CalendarEvent, ResponseType, join_info_text};
4use chatsvc::{CalendarEvent, ResponseType, join_info_text};
5use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
5use chrono::{DateTime, Datelike, Local, NaiveDate, Offset, Timelike, Utc};
6use gpui_kit::assets::IconName;
6use gpui_kit::assets::IconName;
7use gpui_kit::component::Sizable as _;
7use gpui_kit::component::Sizable as _;
8use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -22,26 +22,49 @@ use super::rsvp_menu::rsvp_menu;
22use super::scroll_edge::scroll_offset;
22use super::scroll_edge::scroll_offset;
23use crate::app_state::AppState;
23use crate::app_state::AppState;
24use crate::call::calendar_now::{
24use crate::call::calendar_now::{
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION, hour_height,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
26 now_scroll_offset_y, offset_differs, shows_hour_grid, work_start_scroll_offset_y,
27};
27};
28use crate::call::week::CalendarLoadFailure;
28use crate::call::week_grid::{
29use crate::call::week_grid::{
29 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
30 CalendarSpan, EventLook, WeekBlock, WeekDay, WeekLayout, calendar_index, event_look,
31 hour_label, month_shown, week_days,
30};
32};
31use crate::i18n::tr;
33use crate::i18n::tr;
32use crate::theme;
34use crate::theme;
35use crate::views::widgets::icon;
33
36
34const HOUR_HEIGHT: f32 = 120.;
35const QUARTERS_PER_HOUR: usize = 4;
36const QUARTER_LINE_OPACITY: f32 = 0.45;
37const GUTTER_WIDTH: f32 = 50.;
37const GUTTER_WIDTH: f32 = 50.;
38const HEADER_HEIGHT: f32 = 52.;
38const HEADER_HEIGHT: f32 = 52.;
39const DAY_HEADER_HEIGHT: f32 = 56.;
39const DAY_HEADER_HEIGHT: f32 = 56.;
40const ALL_DAY_HEIGHT: f32 = 26.;
40const ALL_DAY_HEIGHT: f32 = 26.;
41const BLOCK_GAP: f32 = 2.;
41const BLOCK_GAP: f32 = 2.;
42const CANCELED_PREFIX: &str = "Canceled: ";
42const MINOR_LINE_OPACITY: f32 = 0.45;
43const COPY_JOIN_INFO: &str = "Copy join info";
43const OFF_HOURS_OPACITY: f32 = 0.85;
44const COMPACT_HEADER_WIDTH: f32 = 960.;
44const NOW_ELSEWHERE_OPACITY: f32 = 0.4;
45pub const CALENDAR_HEADER_TAG: &str = "shell/islands/calendar/header";
46pub const CALENDAR_DAY_HEADERS_TAG: &str = "shell/islands/calendar/day-headers";
47pub const CALENDAR_NEW_MEETING_TAG: &str = "shell/islands/calendar/header/new-meeting";
48pub const COMPACT_HEADER_WIDTH: f32 = 960.;
49/// Header widths below which button labels give way to icons (German labels are longest).
50const SECONDARY_LABELS_WIDTH: f32 = 1080.;
51const PRIMARY_LABELS_WIDTH: f32 = 780.;
52
53/// Which header buttons keep their text at a given header width.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct HeaderLabels {
56 /// Today, view and New meeting.
57 pub primary: bool,
58 /// Join with an ID and Meet now.
59 pub secondary: bool,
60}
61
62pub fn header_labels(header_width: f32) -> HeaderLabels {
63 HeaderLabels {
64 primary: header_width >= PRIMARY_LABELS_WIDTH,
65 secondary: header_width >= SECONDARY_LABELS_WIDTH,
66 }
67}
45const BUSY_FILL_OPACITY: f32 = 0.28;
68const BUSY_FILL_OPACITY: f32 = 0.28;
46const FREE_FILL_OPACITY: f32 = 0.12;
69const FREE_FILL_OPACITY: f32 = 0.12;
47const STATUS_BAR_WIDTH: f32 = 4.;
70const STATUS_BAR_WIDTH: f32 = 4.;
@@ -61,6 +84,9 @@ pub struct CalendarView {
61 last_programmatic_offset: f32,
84 last_programmatic_offset: f32,
62 skip_manual_check: bool,
85 skip_manual_check: bool,
63 clock_running: bool,
86 clock_running: bool,
87 /// Row height of one hour and minor lines per hour, from the time scale.
88 hour_height: f32,
89 steps_per_hour: usize,
64 _observation: Subscription,
90 _observation: Subscription,
65 _agent_observation: Option<Subscription>,
91 _agent_observation: Option<Subscription>,
66}
92}
@@ -78,6 +104,8 @@ impl CalendarView {
78 last_programmatic_offset: 0.,
104 last_programmatic_offset: 0.,
79 skip_manual_check: false,
105 skip_manual_check: false,
80 clock_running: false,
106 clock_running: false,
107 hour_height: hour_height(Default::default()),
108 steps_per_hour: 2,
81 _observation: observation,
109 _observation: observation,
82 _agent_observation: agent_observation,
110 _agent_observation: agent_observation,
83 }
111 }
@@ -92,26 +120,41 @@ impl CalendarView {
92 let offset = now_scroll_offset_y(
120 let offset = now_scroll_offset_y(
93 local.hour(),
121 local.hour(),
94 local.minute(),
122 local.minute(),
95 HOUR_HEIGHT,
123 self.hour_height,
96 Self::grid_viewport_height(window),
124 Self::grid_viewport_height(window),
97 NOW_BIAS_FRACTION,
125 NOW_BIAS_FRACTION,
98 );
126 );
127 self.set_programmatic_offset(offset);
128 }
129
130 /// A range without today opens at work start instead of midnight.
131 fn align_scroll_to_work_start(&mut self, work_start_minute: i64, window: &Window) {
132 let offset = work_start_scroll_offset_y(
133 work_start_minute,
134 self.hour_height,
135 Self::grid_viewport_height(window),
136 );
137 self.set_programmatic_offset(offset);
138 }
139
140 fn set_programmatic_offset(&mut self, offset: f32) {
99 self.scroll.set_offset(point(px(0.), px(offset)));
141 self.scroll.set_offset(point(px(0.), px(offset)));
100 self.last_programmatic_offset = offset;
142 self.last_programmatic_offset = offset;
101 self.skip_manual_check = true;
143 self.skip_manual_check = true;
102 }
144 }
103
145
104 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
146 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
105 let (scroll_to_now, span, today_visible) = {
147 let (scroll_to_now, span, today_visible, work_start) = {
106 let state = self.state.read(cx);
148 let state = self.state.read(cx);
107 let start = state.calendar_start();
149 let today_visible = state.calendar_shows_today();
108 let today = Local::now().date_naive();
150 let prefs = &state.calendar_prefs;
109 let today_visible = start <= today
151 self.hour_height = hour_height(prefs.time_scale);
110 && today < start + chrono::Duration::days(state.calendar_week.span.days());
152 self.steps_per_hour = prefs.time_scale.steps_per_hour() as usize;
111 (
153 (
112 state.calendar_scroll_to_now,
154 state.calendar_scroll_to_now,
113 state.calendar_week.span,
155 state.calendar_week.span,
114 today_visible,
156 today_visible,
157 prefs.work_hours.minute_range().0,
115 )
158 )
116 };
159 };
117 if !shows_hour_grid(span) {
160 if !shows_hour_grid(span) {
@@ -121,7 +164,12 @@ impl CalendarView {
121 self.ensure_clock(cx);
164 self.ensure_clock(cx);
122 if scroll_to_now != self.seen_scroll_to_now {
165 if scroll_to_now != self.seen_scroll_to_now {
123 self.seen_scroll_to_now = scroll_to_now;
166 self.seen_scroll_to_now = scroll_to_now;
124 self.follow_now.request_align();
167 if today_visible {
168 self.follow_now.request_align();
169 } else {
170 self.align_scroll_to_work_start(work_start, window);
171 return;
172 }
125 }
173 }
126 if self.skip_manual_check {
174 if self.skip_manual_check {
127 self.skip_manual_check = false;
175 self.skip_manual_check = false;
@@ -180,33 +228,60 @@ impl CalendarView {
180 cx.notify();
228 cx.notify();
181 }
229 }
182
230
183 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
231 fn header(
232 &self,
233 start: NaiveDate,
234 span: CalendarSpan,
235 dates: &[NaiveDate],
236 layout: &WeekLayout,
237 compact: bool,
238 labels: HeaderLabels,
239 ) -> impl IntoElement {
184 let span_state = self.state.clone();
240 let span_state = self.state.clone();
185 let label = |text: &'static str| (!compact).then_some(text);
241 let label = |key: &'static str| labels.primary.then(|| tr(key));
242 let secondary = |key: &'static str| labels.secondary.then(|| tr(key));
186 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
243 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
187 let (join_state, meet_state, new_state) =
244 let (join_state, meet_state, new_state) =
188 (self.state.clone(), self.state.clone(), self.state.clone());
245 (self.state.clone(), self.state.clone(), self.state.clone());
246 let pane_state = self.state.clone();
247 let (back_tip, forward_tip) = match span {
248 CalendarSpan::Day => ("calendar.view.previous_day", "calendar.view.next_day"),
249 CalendarSpan::Month => ("calendar.view.previous_month", "calendar.view.next_month"),
250 _ => ("calendar.view.previous_week", "calendar.view.next_week"),
251 };
189 h_flex()
252 h_flex()
253 .debug_selector(|| CALENDAR_HEADER_TAG.into())
190 .h(px(HEADER_HEIGHT))
254 .h(px(HEADER_HEIGHT))
191 .flex_none()
255 .flex_none()
192 .items_center()
256 .items_center()
193 .gap(px(8.))
257 .gap(px(8.))
194 .px(px(16.))
258 .px(px(16.))
195 .child(
259 .when(!compact, |header| {
196 div()
260 header.child(
197 .flex_none()
261 Button::new("calendar-pane-toggle")
198 .text_size(px(16.))
262 .small()
199 .font_weight(FontWeight::BOLD)
263 .ghost()
200 .mr(px(8.))
264 .icon(IconName::PanelLeft)
201 .child("Calendar"),
265 .tooltip(tr("calendar.view.toggle_pane"))
202 )
266 .on_click(move |_, _, cx| {
267 pane_state.update(cx, |state, cx| {
268 state.update_calendar_prefs(
269 |prefs| prefs.pane_hidden = !prefs.pane_hidden,
270 cx,
271 )
272 })
273 }),
274 )
275 })
203 .child(
276 .child(
204 Button::new("calendar-today")
277 Button::new("calendar-today")
205 .small()
278 .small()
206 .outline()
279 .outline()
207 .icon(IconName::Calendar)
280 .icon(IconName::Calendar)
208 .when_some(label("Today"), |button, text| button.label(text))
281 .when_some(label("calendar.view.today"), |button, text| {
209 .tooltip("Today")
282 button.label(text)
283 })
284 .tooltip(tr("calendar.view.today"))
210 .on_click(move |_, _, cx| {
285 .on_click(move |_, _, cx| {
211 today.update(cx, |state, cx| state.calendar_to_today(cx))
286 today.update(cx, |state, cx| state.calendar_to_today(cx))
212 }),
287 }),
@@ -216,11 +291,7 @@ impl CalendarView {
216 .small()
291 .small()
217 .ghost()
292 .ghost()
218 .icon(IconName::ChevronLeft)
293 .icon(IconName::ChevronLeft)
219 .tooltip(match span {
294 .tooltip(tr(back_tip))
220 CalendarSpan::Day => "Go to previous day",
221 CalendarSpan::Month => "Go to previous month",
222 _ => "Go to previous week",
223 })
224 .on_click(move |_, _, cx| {
295 .on_click(move |_, _, cx| {
225 back.update(cx, |state, cx| state.shift_calendar_week(-1, cx))
296 back.update(cx, |state, cx| state.shift_calendar_week(-1, cx))
226 }),
297 }),
@@ -230,20 +301,16 @@ impl CalendarView {
230 .small()
301 .small()
231 .ghost()
302 .ghost()
232 .icon(IconName::ChevronRight)
303 .icon(IconName::ChevronRight)
233 .tooltip(match span {
304 .tooltip(tr(forward_tip))
234 CalendarSpan::Day => "Go to next day",
235 CalendarSpan::Month => "Go to next month",
236 _ => "Go to next week",
237 })
238 .on_click(move |_, _, cx| {
305 .on_click(move |_, _, cx| {
239 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
306 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
240 }),
307 }),
241 )
308 )
242 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
309 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
243 &self.state,
310 &self.state,
244 span.title(start),
311 span.title(start, layout),
245 start,
312 dates.to_vec(),
246 span.days(),
313 layout.first_day,
247 if span == CalendarSpan::Month {
314 if span == CalendarSpan::Month {
248 month_shown(start)
315 month_shown(start)
249 } else {
316 } else {
@@ -254,7 +321,8 @@ impl CalendarView {
254 Button::new("calendar-span")
321 Button::new("calendar-span")
255 .small()
322 .small()
256 .ghost()
323 .ghost()
257 .label(span.label())
324 .icon(IconName::LayoutGrid)
325 .when(labels.primary, |button| button.label(span.label()))
258 .dropdown_caret(true)
326 .dropdown_caret(true)
259 .dropdown_menu(move |menu, _, _| {
327 .dropdown_menu(move |menu, _, _| {
260 CalendarSpan::ALL.iter().fold(menu, |menu, &choice| {
328 CalendarSpan::ALL.iter().fold(menu, |menu, &choice| {
@@ -276,8 +344,10 @@ impl CalendarView {
276 .small()
344 .small()
277 .outline()
345 .outline()
278 .icon(IconName::Hash)
346 .icon(IconName::Hash)
279 .when_some(label("Join with an ID"), |button, text| button.label(text))
347 .when_some(secondary("calendar.view.join_with_id"), |button, text| {
280 .tooltip("Join with an ID")
348 button.label(text)
349 })
350 .tooltip(tr("calendar.view.join_with_id"))
281 .on_click(move |_, window, cx| {
351 .on_click(move |_, window, cx| {
282 open_join_with_id(join_state.clone(), window, cx)
352 open_join_with_id(join_state.clone(), window, cx)
283 }),
353 }),
@@ -287,25 +357,32 @@ impl CalendarView {
287 .small()
357 .small()
288 .outline()
358 .outline()
289 .icon(IconName::Video)
359 .icon(IconName::Video)
290 .when_some(label("Meet now"), |button, text| button.label(text))
360 .when_some(secondary("calendar.view.meet_now"), |button, text| {
291 .tooltip("Meet now")
361 button.label(text)
362 })
363 .tooltip(tr("calendar.view.meet_now"))
292 .on_click(move |_, _, cx| {
364 .on_click(move |_, _, cx| {
293 meet_state.update(cx, |state, cx| state.start_meet_now(cx))
365 meet_state.update(cx, |state, cx| state.start_meet_now(cx))
294 }),
366 }),
295 )
367 )
296 .child(
368 .child(
297 Button::new("calendar-new-meeting")
369 Button::new("calendar-new-meeting")
370 .debug_selector(|| CALENDAR_NEW_MEETING_TAG.into())
298 .small()
371 .small()
299 .primary()
372 .primary()
300 .icon(IconName::Plus)
373 .icon(IconName::Plus)
301 .when_some(label("New meeting"), |button, text| button.label(text))
374 .when_some(label("calendar.view.new_meeting"), |button, text| {
302 .tooltip("New meeting")
375 button.label(text)
376 })
377 .tooltip(tr("calendar.view.new_meeting"))
303 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
378 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
304 )
379 )
305 }
380 }
306
381
382 /// Day number above the full weekday name; today in the accent colour with its bar.
307 fn day_headers(&self, days: &[WeekDay], today: NaiveDate) -> impl IntoElement {
383 fn day_headers(&self, days: &[WeekDay], today: NaiveDate) -> impl IntoElement {
308 h_flex()
384 h_flex()
385 .debug_selector(|| CALENDAR_DAY_HEADERS_TAG.into())
309 .h(px(DAY_HEADER_HEIGHT))
386 .h(px(DAY_HEADER_HEIGHT))
310 .flex_none()
387 .flex_none()
311 .border_b_1()
388 .border_b_1()
@@ -313,10 +390,10 @@ impl CalendarView {
313 .child(div().w(px(GUTTER_WIDTH)).flex_none())
390 .child(div().w(px(GUTTER_WIDTH)).flex_none())
314 .children(days.iter().map(|day| {
391 .children(days.iter().map(|day| {
315 let is_today = day.date == today;
392 let is_today = day.date == today;
316 let color = if is_today {
393 let (number_color, name_color) = if is_today {
317 theme::accent_text()
394 (theme::accent_text(), theme::accent_text())
318 } else {
395 } else {
319 theme::text_soft()
396 (theme::text(), theme::text_soft())
320 };
397 };
321 v_flex()
398 v_flex()
322 .relative()
399 .relative()
@@ -342,14 +419,16 @@ impl CalendarView {
342 div()
419 div()
343 .text_size(px(20.))
420 .text_size(px(20.))
344 .line_height(px(24.))
421 .line_height(px(24.))
345 .text_color(color)
422 .text_color(number_color)
423 .when(is_today, |number| number.font_weight(FontWeight::SEMIBOLD))
346 .child(format::calendar_day_number(day.date)),
424 .child(format::calendar_day_number(day.date)),
347 )
425 )
348 .child(
426 .child(
349 div()
427 div()
350 .text_size(px(12.))
428 .text_size(px(12.))
351 .text_color(color)
429 .text_color(name_color)
352 .child(day.date.format("%a").to_string()),
430 .truncate()
431 .child(weekday_name(day.date.weekday(), WeekdayWidth::Full)),
353 )
432 )
354 }))
433 }))
355 }
434 }
@@ -358,6 +437,7 @@ impl CalendarView {
358 &self,
437 &self,
359 days: &[WeekDay],
438 days: &[WeekDay],
360 events: &[CalendarEvent],
439 events: &[CalendarEvent],
440 colors: &[Hsla],
361 send_response: bool,
441 send_response: bool,
362 ) -> Option<Div> {
442 ) -> Option<Div> {
363 if days.iter().all(|day| day.all_day.is_empty()) {
443 if days.iter().all(|day| day.all_day.is_empty()) {
@@ -379,6 +459,7 @@ impl CalendarView {
379 .border_color(theme::border())
459 .border_color(theme::border())
380 .children(day.all_day.iter().map(|&index| {
460 .children(day.all_day.iter().map(|&index| {
381 let event = events[index].clone();
461 let event = events[index].clone();
462 let color = colors[index];
382 let open_state = self.state.clone();
463 let open_state = self.state.clone();
383 let (menu_state, menu_event) = (self.state.clone(), event.clone());
464 let (menu_state, menu_event) = (self.state.clone(), event.clone());
384 // Day-qualified id: multi-day all-day chips share object_id.
465 // Day-qualified id: multi-day all-day chips share object_id.
@@ -391,8 +472,8 @@ impl CalendarView {
391 .px(px(6.))
472 .px(px(6.))
392 .flex()
473 .flex()
393 .items_center()
474 .items_center()
394 .rounded(px(4.))
475 .rounded(px(6.))
395 .bg(event_fill(event_look(&event)))
476 .bg(event_fill(event_look(&event), color))
396 .text_size(px(12.))
477 .text_size(px(12.))
397 .truncate()
478 .truncate()
398 .cursor_pointer()
479 .cursor_pointer()
@@ -417,21 +498,22 @@ impl CalendarView {
417 &self,
498 &self,
418 block: &WeekBlock,
499 block: &WeekBlock,
419 event: &CalendarEvent,
500 event: &CalendarEvent,
501 color: Hsla,
420 day: NaiveDate,
502 day: NaiveDate,
421 send_response: bool,
503 send_response: bool,
422 ) -> impl IntoElement {
504 ) -> impl IntoElement {
423 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
505 let top = block.start_minute as f32 / 60. * self.hour_height;
424 let height = ((block.end_minute - block.start_minute) as f32 / 60. * HOUR_HEIGHT
506 let height = ((block.end_minute - block.start_minute) as f32 / 60. * self.hour_height
425 - BLOCK_GAP)
507 - BLOCK_GAP)
426 .max(14.);
508 .max(14.);
427 let width = 1. / block.lanes as f32;
509 let width = 1. / block.lanes as f32;
428 let compact = height < 36.;
510 let compact = height < 36.;
429 let small = height < SMALL_TITLE_HEIGHT;
511 let small = height < SMALL_TITLE_HEIGHT;
430 let title_size = if small { 10. } else { 12. };
512 let title_size = if small { 10. } else { 12. };
431 let title_line = if small { 14. } else { 18. };
513 let title_line = if small { 14. } else { 16. };
432 let pad_y = if compact { 1. } else { 4. };
514 let pad_y = if compact { 1. } else { 3. };
433 // Fill the block: long titles use the free height instead of clamping to 2 lines.
515 // Title and organizer flow as one text; tall blocks wrap it over more lines.
434 let title_lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
516 let lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
435 let look = event_look(event);
517 let look = event_look(event);
436 // Join on the block whenever a Teams link exists (same as detail dialog).
518 // Join on the block whenever a Teams link exists (same as detail dialog).
437 // Skip on tiny blocks — the button would crush the title.
519 // Skip on tiny blocks — the button would crush the title.
@@ -465,13 +547,13 @@ impl CalendarView {
465 .size_full()
547 .size_full()
466 .items_start()
548 .items_start()
467 .overflow_hidden()
549 .overflow_hidden()
468 .rounded(px(4.))
550 .rounded(px(6.))
469 .bg(event_fill(look))
551 .bg(event_fill(look, color))
470 .when(event.cancelled, |block| block.opacity(0.6))
552 .when(event.cancelled, |block| block.opacity(0.6))
471 .cursor_pointer()
553 .cursor_pointer()
472 .children(status_bar(look))
554 .children(status_bar(look, color))
473 .child(
555 .child(
474 v_flex()
556 div()
475 .flex_1()
557 .flex_1()
476 .min_w_0()
558 .min_w_0()
477 .pl(px(5.))
559 .pl(px(5.))
@@ -479,28 +561,20 @@ impl CalendarView {
479 .h_full()
561 .h_full()
480 .py(px(pad_y))
562 .py(px(pad_y))
481 .overflow_hidden()
563 .overflow_hidden()
482 .when(compact, |body| body.justify_center())
564 .text_size(px(title_size))
483 .child(
565 .line_height(px(title_line))
484 div()
566 .text_color(detail_color)
485 .text_size(px(title_size))
567 .line_clamp(lines)
486 .line_height(px(title_line))
568 .text_ellipsis()
487 .font_weight(FontWeight::SEMIBOLD)
569 .child(title_and_organizer(event, title_color)),
488 .text_color(title_color)
489 .when(compact, |title| title.truncate())
490 .when(!compact, |title| title.line_clamp(title_lines))
491 .child(event_title(event)),
492 )
493 .when(!compact && title_lines > 2, |body| {
494 body.children(event.organizer_name.clone().map(|organizer| {
495 div()
496 .text_size(px(12.))
497 .line_height(px(16.))
498 .text_color(detail_color)
499 .truncate()
500 .child(organizer)
501 }))
502 }),
503 )
570 )
571 .when(event.series, |block| {
572 block.child(div().flex_none().pt(px(pad_y + 1.)).pr(px(4.)).child(icon(
573 IconName::Repeat,
574 12.,
575 detail_color,
576 )))
577 })
504 .when(can_join, |block| {
578 .when(can_join, |block| {
505 block.child(
579 block.child(
506 div().flex_none().pr(px(4.)).pt(px(3.)).child(
580 div().flex_none().pr(px(4.)).pt(px(3.)).child(
@@ -533,21 +607,30 @@ impl CalendarView {
533 })
607 })
534 }
608 }
535
609
610 #[allow(clippy::too_many_arguments)]
536 fn grid(
611 fn grid(
537 &self,
612 &self,
538 days: &[WeekDay],
613 days: &[WeekDay],
539 events: &[CalendarEvent],
614 events: &[CalendarEvent],
615 colors: &[Hsla],
616 layout: &WeekLayout,
617 work_minutes: (i64, i64),
540 today: NaiveDate,
618 today: NaiveDate,
541 now: DateTime<Utc>,
619 now: DateTime<Utc>,
542 send_response: bool,
620 send_response: bool,
543 cx: &mut Context<Self>,
621 cx: &mut Context<Self>,
544 ) -> impl IntoElement {
622 ) -> impl IntoElement {
545 let total_height = 24. * HOUR_HEIGHT;
623 let row = self.hour_height;
624 let steps = self.steps_per_hour;
625 let total_height = 24. * row;
546 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
626 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
547 let now_minute = {
627 let now_minute = {
548 let local = now.with_timezone(&Local);
628 let local = now.with_timezone(&Local);
549 local.hour() * 60 + local.minute()
629 local.hour() * 60 + local.minute()
550 };
630 };
631 let now_top = now_minute as f32 / 60. * row;
632 let today_shown = days.iter().any(|day| day.date == today);
633 let minute_y = |minute: i64| minute as f32 / 60. * row;
551 div()
634 div()
552 .id("calendar-grid")
635 .id("calendar-grid")
553 .flex_1()
636 .flex_1()
@@ -565,18 +648,38 @@ impl CalendarView {
565 .flex_none()
648 .flex_none()
566 .children((0..24).map(|hour| {
649 .children((0..24).map(|hour| {
567 div()
650 div()
568 .h(px(HOUR_HEIGHT))
651 .h(px(row))
569 .pt(px(4.))
652 .pt(px(2.))
653 .pr(px(8.))
570 .flex()
654 .flex()
571 .justify_center()
655 .justify_end()
572 .text_size(px(12.))
656 .text_size(px(11.))
573 .text_color(theme::text_soft())
657 .text_color(theme::text_muted())
574 .when(hour > 0, |label| {
658 .when(hour > 0, |label| {
575 label.child(hour_label(hour, twelve_hour))
659 label.child(hour_label(hour, twelve_hour))
576 })
660 })
577 })),
661 })),
578 )
662 )
579 .children(days.iter().map(|day| {
663 .children(days.iter().map(|day| {
664 let work_day = layout.is_work_day(day.date.weekday());
665 let (work_start, work_end) = work_minutes;
666 let shade = |top: f32, height: f32| {
667 div()
668 .absolute()
669 .top(px(top))
670 .left_0()
671 .right_0()
672 .h(px(height))
673 .bg(theme::background().opacity(OFF_HOURS_OPACITY))
674 };
675 let shading = if work_day {
676 vec![
677 shade(0., minute_y(work_start)),
678 shade(minute_y(work_end), total_height - minute_y(work_end)),
679 ]
680 } else {
681 vec![shade(0., total_height)]
682 };
580 div()
683 div()
581 .relative()
684 .relative()
582 .flex_1()
685 .flex_1()
@@ -584,31 +687,41 @@ impl CalendarView {
584 .h_full()
687 .h_full()
585 .border_l_1()
688 .border_l_1()
586 .border_color(theme::border())
689 .border_color(theme::border())
587 .children((1..24 * QUARTERS_PER_HOUR).map(|quarter| {
690 .children(shading)
691 .children((1..24 * steps).map(|step| {
588 let line = div()
692 let line = div()
589 .absolute()
693 .absolute()
590 .top(
694 .top(px(step as f32 * row / steps as f32))
591 px(quarter as f32 * HOUR_HEIGHT / QUARTERS_PER_HOUR as f32),
592 )
593 .left_0()
695 .left_0()
594 .right_0();
696 .right_0()
595 if quarter % QUARTERS_PER_HOUR == 0 {
697 .h(px(1.));
596 line.h(px(1.)).bg(theme::border())
698 if step % steps == 0 {
699 line.bg(theme::border())
597 } else {
700 } else {
598 line.h(px(1.))
701 line.bg(theme::border().opacity(MINOR_LINE_OPACITY))
599 .bg(theme::border().opacity(QUARTER_LINE_OPACITY))
600 }
702 }
601 }))
703 }))
602 .children(day.blocks.iter().map(|block| {
704 .children(day.blocks.iter().map(|block| {
603 self.event_block(
705 self.event_block(
604 block,
706 block,
605 &events[block.event_index],
707 &events[block.event_index],
708 colors[block.event_index],
606 day.date,
709 day.date,
607 send_response,
710 send_response,
608 )
711 )
609 }))
712 }))
713 .when(today_shown && day.date != today, |column| {
714 column.child(
715 div()
716 .absolute()
717 .top(px(now_top))
718 .left_0()
719 .right_0()
720 .h(px(1.))
721 .bg(theme::accent().opacity(NOW_ELSEWHERE_OPACITY)),
722 )
723 })
610 .when(day.date == today, |column| {
724 .when(day.date == today, |column| {
611 let now_top = now_minute as f32 / 60. * HOUR_HEIGHT;
612 column
725 column
613 .child(
726 .child(
614 div()
727 div()
@@ -634,6 +747,66 @@ impl CalendarView {
634 }
747 }
635}
748}
636
749
750/// Loading line and one notice per failed source, under the calendar header.
751fn load_notices(
752 state: &Entity<AppState>,
753 failures: &[CalendarLoadFailure],
754 loading: bool,
755) -> Vec<Div> {
756 let mut rows = Vec::new();
757 if loading {
758 rows.push(
759 h_flex()
760 .flex_none()
761 .px(px(16.))
762 .pb(px(6.))
763 .text_size(px(12.))
764 .text_color(theme::text_muted())
765 .child(tr("calendar.view.loading")),
766 );
767 }
768 for failure in failures {
769 let retry = state.clone();
770 let mut args = std::collections::HashMap::new();
771 args.insert("source".to_owned(), failure.source.label().to_owned());
772 rows.push(
773 h_flex()
774 .flex_none()
775 .mx(px(16.))
776 .mb(px(6.))
777 .px(px(12.))
778 .py(px(6.))
779 .gap(px(12.))
780 .items_center()
781 .rounded(px(6.))
782 .bg(theme::red_tint())
783 .text_size(px(13.))
784 .text_color(theme::text())
785 .child(
786 div()
787 .flex_1()
788 .min_w_0()
789 .truncate()
790 .child(crate::i18n::tr_args("calendar.view.source_failed", &args)),
791 )
792 .child(
793 Button::new(SharedString::from(format!(
794 "calendar-retry-{}",
795 failure.source.label()
796 )))
797 .xsmall()
798 .outline()
799 .label(tr("common.retry"))
800 .tooltip(failure.message.clone())
801 .on_click(move |_, _, cx| {
802 retry.update(cx, |state, cx| state.retry_calendar_week(cx))
803 }),
804 ),
805 );
806 }
807 rows
808}
809
637fn event_menu(
810fn event_menu(
638 menu: PopupMenu,
811 menu: PopupMenu,
639 state: &Entity<AppState>,
812 state: &Entity<AppState>,
@@ -647,18 +820,20 @@ fn event_menu(
647 .filter(|_| event.online && !event.cancelled)
820 .filter(|_| event.online && !event.cancelled)
648 {
821 {
649 let (join_state, subject) = (state.clone(), event.subject.clone());
822 let (join_state, subject) = (state.clone(), event.subject.clone());
650 menu = menu.item(PopupMenuItem::new("Join").icon(IconName::Video).on_click(
823 menu = menu.item(
651 move |_, _, cx| {
824 PopupMenuItem::new(tr("common.join"))
652 join_state.update(cx, |state, cx| {
825 .icon(IconName::Video)
653 state.join_calendar_meeting(Some(&join_url), &subject, cx)
826 .on_click(move |_, _, cx| {
654 })
827 join_state.update(cx, |state, cx| {
655 },
828 state.join_calendar_meeting(Some(&join_url), &subject, cx)
656 ));
829 })
830 }),
831 );
657 }
832 }
658 if let Some(join_url) = event.join_url.as_deref().filter(|_| event.online) {
833 if let Some(join_url) = event.join_url.as_deref().filter(|_| event.online) {
659 let info = join_info_text(join_url, event.dial_in.as_ref());
834 let info = join_info_text(join_url, event.dial_in.as_ref());
660 menu = menu.item(
835 menu = menu.item(
661 PopupMenuItem::new(COPY_JOIN_INFO)
836 PopupMenuItem::new(tr("calendar.view.copy_join_info"))
662 .icon(IconName::Copy)
837 .icon(IconName::Copy)
663 .on_click(move |_, _, cx| {
838 .on_click(move |_, _, cx| {
664 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
839 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
@@ -668,7 +843,7 @@ fn event_menu(
668 if let Some(thread_id) = event.thread_id.clone() {
843 if let Some(thread_id) = event.thread_id.clone() {
669 let chat_state = state.clone();
844 let chat_state = state.clone();
670 menu = menu.item(
845 menu = menu.item(
671 PopupMenuItem::new("Chat with participants")
846 PopupMenuItem::new(tr("calendar.view.chat_with_participants"))
672 .icon(IconName::MessageSquare)
847 .icon(IconName::MessageSquare)
673 .on_click(move |_, _, cx| {
848 .on_click(move |_, _, cx| {
674 chat_state.update(cx, |state, cx| {
849 chat_state.update(cx, |state, cx| {
@@ -689,31 +864,49 @@ fn event_menu(
689 )
864 )
690}
865}
691
866
692fn event_fill(look: EventLook) -> Hsla {
867fn event_fill(look: EventLook, color: Hsla) -> Hsla {
693 match look {
868 match look {
694 EventLook::Busy => theme::accent().opacity(BUSY_FILL_OPACITY),
869 EventLook::Busy => color.opacity(BUSY_FILL_OPACITY),
695 EventLook::Free | EventLook::Tentative => theme::accent().opacity(FREE_FILL_OPACITY),
870 EventLook::Free | EventLook::Tentative => color.opacity(FREE_FILL_OPACITY),
696 }
871 }
697}
872}
698
873
699fn status_bar(look: EventLook) -> Option<Div> {
874fn status_bar(look: EventLook, color: Hsla) -> Option<Div> {
700 let bar = div().flex_none().w(px(STATUS_BAR_WIDTH)).h_full();
875 let bar = div().flex_none().w(px(STATUS_BAR_WIDTH)).h_full();
701 match look {
876 match look {
702 EventLook::Busy => Some(bar.bg(theme::accent())),
877 EventLook::Busy => Some(bar.bg(color)),
703 EventLook::Tentative => Some(
878 EventLook::Tentative => Some(
704 bar.bg(theme::accent().opacity(BUSY_FILL_OPACITY)).child(
879 bar.bg(color.opacity(BUSY_FILL_OPACITY))
705 div()
880 .child(
706 .size_full()
881 div()
707 .bg(pattern_slash(theme::accent(), HATCH_STRIPE, HATCH_GAP)),
882 .size_full()
708 ),
883 .bg(pattern_slash(color, HATCH_STRIPE, HATCH_GAP)),
884 ),
709 ),
885 ),
710 EventLook::Free => None,
886 EventLook::Free => None,
711 }
887 }
712}
888}
713
889
890/// "Daily Standup Zulal Fouque": bold title, organizer right after it on the same line.
891fn title_and_organizer(event: &CalendarEvent, title_color: Hsla) -> StyledText {
892 let title = event_title(event);
893 let text = match event.organizer_name.as_deref() {
894 Some(organizer) if !organizer.is_empty() => format!("{title} {organizer}"),
895 _ => title.clone(),
896 };
897 StyledText::new(text).with_highlights([(
898 0..title.len(),
899 HighlightStyle {
900 color: Some(title_color),
901 font_weight: Some(FontWeight::SEMIBOLD),
902 ..Default::default()
903 },
904 )])
905}
906
714fn event_title(event: &CalendarEvent) -> String {
907fn event_title(event: &CalendarEvent) -> String {
715 let subject = if event.cancelled {
908 let subject = if event.cancelled {
716 format!("{CANCELED_PREFIX}{}", event.subject)
909 format!("{}{}", tr("calendar.peek.canceled_prefix"), event.subject)
717 } else {
910 } else {
718 event.subject.clone()
911 event.subject.clone()
719 };
912 };
@@ -744,18 +937,39 @@ fn source_label(event: &CalendarEvent) -> String {
744
937
745impl Render for CalendarView {
938impl Render for CalendarView {
746 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
939 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
747 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
940 let window_width = f32::from(window.viewport_size().width);
941 let compact = window_width < COMPACT_HEADER_WIDTH;
748 self.sync_follow_from_state(window, cx);
942 self.sync_follow_from_state(window, cx);
749 let state = self.state.read(cx);
943 let state = self.state.read(cx);
750 let start = state.calendar_start();
944 let start = state.calendar_start();
751 let events = state.calendar_week.events.clone();
945 let events = state.calendar_week.events.clone();
752 let send_response = state.rsvp_send_response;
946 let send_response = state.rsvp_send_response;
947 let failures = state.calendar_week.failures.clone();
948 let loading = state.calendar_week.loading && events.is_empty();
753 let offset = Local::now().offset().fix();
949 let offset = Local::now().offset().fix();
754 let span = state.calendar_week.span;
950 let span = state.calendar_week.span;
755 let days = week_days(&events, start, span.days(), offset);
951 let layout = state.calendar_layout();
952 let dates = state.calendar_dates();
953 let days = week_days(&events, &dates, offset);
756 let today = Local::now().date_naive();
954 let today = Local::now().date_naive();
757 let now = Utc::now();
955 let now = Utc::now();
758 let show_picker = !compact;
956 let accounts = state.calendar_accounts();
957 let colors: Vec<Hsla> = events
958 .iter()
959 .map(|event| theme::calendar_color(calendar_index(event, &accounts)))
960 .collect();
961 let work_minutes = state.calendar_prefs.work_hours.minute_range();
962 let show_picker = !compact && !state.calendar_prefs.pane_hidden;
963 // Width left for the header: window minus rail, island gaps and the pane.
964 let header_width = window_width
965 - app_ui_kit::layout::RAIL_WIDTH
966 - 2. * app_ui_kit::layout::ISLAND_GAP
967 - if show_picker {
968 calendar_picker::PICKER_WIDTH
969 } else {
970 0.
971 };
972 let labels = header_labels(header_width);
759 h_flex()
973 h_flex()
760 .debug_selector(|| "shell/islands/calendar".into())
974 .debug_selector(|| "shell/islands/calendar".into())
761 .flex_1()
975 .flex_1()
@@ -773,7 +987,8 @@ impl Render for CalendarView {
773 .flex_1()
987 .flex_1()
774 .min_w_0()
988 .min_w_0()
775 .h_full()
989 .h_full()
776 .child(self.header(start, span, compact))
990 .child(self.header(start, span, &dates, &layout, compact, labels))
991 .children(load_notices(&self.state, &failures, loading))
777 .children(meeting_proposal_cards(cx))
992 .children(meeting_proposal_cards(cx))
778 .map(|calendar| {
993 .map(|calendar| {
779 if span == CalendarSpan::Month {
994 if span == CalendarSpan::Month {
@@ -782,16 +997,43 @@ impl Render for CalendarView {
782 start,
997 start,
783 &days,
998 &days,
784 &events,
999 &events,
1000 &colors,
785 today,
1001 today,
786 offset,
1002 offset,
1003 layout.weekdays(),
787 ))
1004 ))
788 } else {
1005 } else {
789 calendar
1006 calendar
790 .child(self.day_headers(&days, today))
1007 .child(self.day_headers(&days, today))
791 .children(self.all_day_row(&days, &events, send_response))
1008 .children(self.all_day_row(&days, &events, &colors, send_response))
792 .child(self.grid(&days, &events, today, now, send_response, cx))
1009 .child(self.grid(
1010 &days,
1011 &events,
1012 &colors,
1013 &layout,
1014 work_minutes,
1015 today,
1016 now,
1017 send_response,
1018 cx,
1019 ))
793 }
1020 }
794 }),
1021 }),
795 )
1022 )
796 }
1023 }
797}
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028 use super::header_labels;
1029
1030 #[test]
1031 fn header_buttons_drop_their_text_as_the_header_narrows() {
1032 let wide = header_labels(1300.);
1033 assert!(wide.primary && wide.secondary);
1034 let middle = header_labels(900.);
1035 assert!(middle.primary && !middle.secondary);
1036 let narrow = header_labels(600.);
1037 assert!(!narrow.primary && !narrow.secondary);
1038 }
1039}
crates/app/src/views/mod.rs +1 −0
@@ -8,6 +8,7 @@ pub mod attachments;
8 8 pub mod avatar;
9 9 pub mod calendar_date_picker;
10 10 pub mod calendar_event_dialog;
11 pub mod calendar_mini_month;
11 12 pub mod calendar_month;
12 13 pub mod calendar_picker;
13 14 pub mod calendar_view;
@@ -8,6 +8,7 @@ pub mod attachments;
8pub mod avatar;
8pub mod avatar;
9pub mod calendar_date_picker;
9pub mod calendar_date_picker;
10pub mod calendar_event_dialog;
10pub mod calendar_event_dialog;
11pub mod calendar_mini_month;
11pub mod calendar_month;
12pub mod calendar_month;
12pub mod calendar_picker;
13pub mod calendar_picker;
13pub mod calendar_view;
14pub mod calendar_view;
crates/app/src/views/sidebar.rs +3 −0
@@ -530,6 +530,9 @@ impl SidebarView {
530 530 let changed = self.tab != tab;
531 531 self.tab = tab;
532 532 if changed {
533 if tab != SidebarTab::Calendar {
534 self.state.update(cx, |state, _| state.close_calendar());
535 }
533 536 self.restore_last_view(tab, cx);
534 537 cx.emit(SidebarEvent::TabChanged);
535 538 }
@@ -530,6 +530,9 @@ impl SidebarView {
530 let changed = self.tab != tab;
530 let changed = self.tab != tab;
531 self.tab = tab;
531 self.tab = tab;
532 if changed {
532 if changed {
533 if tab != SidebarTab::Calendar {
534 self.state.update(cx, |state, _| state.close_calendar());
535 }
533 self.restore_last_view(tab, cx);
536 self.restore_last_view(tab, cx);
534 cx.emit(SidebarEvent::TabChanged);
537 cx.emit(SidebarEvent::TabChanged);
535 }
538 }
crates/graph/src/lib.rs +2 −0
@@ -4,6 +4,7 @@ mod content;
4 4 mod error;
5 5 mod files;
6 6 mod library;
7 mod mailbox;
7 8 mod models;
8 9 mod outgoing;
9 10 mod page;
@@ -23,6 +24,7 @@ pub use files::{
23 24 percent_done, share_id,
24 25 };
25 26 pub use library::DriveEntry;
27 pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
26 28 pub use models::{
27 29 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
28 30 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
@@ -4,6 +4,7 @@ mod content;
4mod error;
4mod error;
5mod files;
5mod files;
6mod library;
6mod library;
7mod mailbox;
7mod models;
8mod models;
8mod outgoing;
9mod outgoing;
9mod page;
10mod page;
@@ -23,6 +24,7 @@ pub use files::{
23 percent_done, share_id,
24 percent_done, share_id,
24};
25};
25pub use library::DriveEntry;
26pub use library::DriveEntry;
27pub use mailbox::{MailboxWorkingHours, parse_working_hours, working_hours_body};
26pub use models::{
28pub use models::{
27 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
29 Attachment, Body, Channel, Chat, ChatViewpoint, Identity, Member, Mention, Message,
28 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
30 OnlineMeetingInfo, Photo, Presence, Reaction, Sender, Tag, Team, UNKNOWN_USER_NAME, User,
crates/graph/src/mailbox.rs added +173 −0
@@ -0,0 +1,173 @@
1 //! Outlook mailbox working hours (`/me/mailboxSettings`), the setting Teams and
2 //! Outlook read for work days and hours.
3 //!
4 //! `MailboxSettings.Read` is not granted to the Teams client; `ReadWrite` is.
5
6 use chrono::{NaiveTime, Weekday};
7 use serde_json::{Value, json};
8 use session::{Method, Scope};
9
10 use crate::client::Graph;
11 use crate::error::{Error, Result};
12 use crate::urls;
13
14 const MAILBOX_SCOPE: &str = "MailboxSettings.ReadWrite";
15 const TIME_FORMAT: &str = "%H:%M:%S%.f";
16
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct MailboxWorkingHours {
19 pub days: Vec<Weekday>,
20 pub start: NaiveTime,
21 pub end: NaiveTime,
22 /// Windows or IANA name as the mailbox stores it; written back unchanged.
23 pub time_zone: Option<String>,
24 /// Mailbox language (`en-CH`); Outlook derives the first day of week from it.
25 pub locale: Option<String>,
26 }
27
28 impl Graph {
29 pub async fn working_hours(&self) -> Result<MailboxWorkingHours> {
30 let url = urls::mailbox_settings();
31 let body = self.get(&url, &Scope::graph(MAILBOX_SCOPE)).await?;
32 parse_working_hours(&body)
33 .ok_or_else(|| Error::from(session::Error::api(200, &url, body.clone())))
34 }
35
36 pub async fn set_working_hours(&self, hours: &MailboxWorkingHours) -> Result<()> {
37 self.session()
38 .request(
39 Method::Patch,
40 &urls::mailbox_settings(),
41 &Scope::graph(MAILBOX_SCOPE),
42 Some(working_hours_body(hours)),
43 )
44 .await?;
45 Ok(())
46 }
47 }
48
49 pub fn parse_working_hours(body: &Value) -> Option<MailboxWorkingHours> {
50 let hours = body.get("workingHours")?;
51 let days = hours
52 .get("daysOfWeek")?
53 .as_array()?
54 .iter()
55 .filter_map(Value::as_str)
56 .filter_map(|day| day.parse::<Weekday>().ok())
57 .collect();
58 let time = |key: &str| {
59 let text = hours.get(key)?.as_str()?;
60 NaiveTime::parse_from_str(text, TIME_FORMAT)
61 .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M"))
62 .ok()
63 };
64 Some(MailboxWorkingHours {
65 days,
66 start: time("startTime")?,
67 end: time("endTime")?,
68 time_zone: hours
69 .pointer("/timeZone/name")
70 .and_then(Value::as_str)
71 .map(str::to_owned),
72 locale: body
73 .pointer("/language/locale")
74 .and_then(Value::as_str)
75 .filter(|locale| !locale.is_empty())
76 .map(str::to_owned),
77 })
78 }
79
80 pub fn working_hours_body(hours: &MailboxWorkingHours) -> Value {
81 let mut working = json!({
82 "daysOfWeek": hours.days.iter().map(|day| day_name(*day)).collect::<Vec<_>>(),
83 "startTime": graph_time(hours.start),
84 "endTime": graph_time(hours.end),
85 });
86 if let Some(name) = &hours.time_zone {
87 working["timeZone"] = json!({ "name": name });
88 }
89 json!({ "workingHours": working })
90 }
91
92 /// Graph writes seven fraction digits; working hours never carry fractions.
93 fn graph_time(time: NaiveTime) -> String {
94 format!("{}.0000000", time.format("%H:%M:%S"))
95 }
96
97 fn day_name(day: Weekday) -> &'static str {
98 match day {
99 Weekday::Mon => "monday",
100 Weekday::Tue => "tuesday",
101 Weekday::Wed => "wednesday",
102 Weekday::Thu => "thursday",
103 Weekday::Fri => "friday",
104 Weekday::Sat => "saturday",
105 Weekday::Sun => "sunday",
106 }
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use super::*;
112
113 fn captured() -> Value {
114 // Shape of GET /me/mailboxSettings as returned on 2026-11-15.
115 json!({
116 "timeFormat": "HH:mm",
117 "dateFormat": "d MMM yyyy",
118 "language": {"locale": "en-CH", "displayName": "English (Switzerland)"},
119 "workingHours": {
120 "daysOfWeek": ["monday", "tuesday", "wednesday", "thursday", "friday"],
121 "startTime": "08:00:00.0000000",
122 "endTime": "17:00:00.0000000",
123 "timeZone": {"name": "W. Europe Standard Time"}
124 }
125 })
126 }
127
128 #[test]
129 fn mailbox_working_hours_parse() {
130 let hours = parse_working_hours(&captured()).unwrap();
131 assert_eq!(
132 hours.days,
133 [
134 Weekday::Mon,
135 Weekday::Tue,
136 Weekday::Wed,
137 Weekday::Thu,
138 Weekday::Fri
139 ]
140 );
141 assert_eq!(hours.start, NaiveTime::from_hms_opt(8, 0, 0).unwrap());
142 assert_eq!(hours.end, NaiveTime::from_hms_opt(17, 0, 0).unwrap());
143 assert_eq!(hours.time_zone.as_deref(), Some("W. Europe Standard Time"));
144 assert_eq!(hours.locale.as_deref(), Some("en-CH"));
145 }
146
147 #[test]
148 fn mailbox_working_hours_body_round_trips() {
149 let mut hours = parse_working_hours(&captured()).unwrap();
150 hours.days.retain(|day| *day != Weekday::Fri);
151 hours.start = NaiveTime::from_hms_opt(7, 30, 0).unwrap();
152 let body = working_hours_body(&hours);
153 assert_eq!(
154 body["workingHours"]["daysOfWeek"],
155 json!(["monday", "tuesday", "wednesday", "thursday"])
156 );
157 assert_eq!(body["workingHours"]["startTime"], "07:30:00.0000000");
158 assert_eq!(
159 body["workingHours"]["timeZone"]["name"],
160 "W. Europe Standard Time"
161 );
162 let parsed = parse_working_hours(&body).unwrap();
163 assert_eq!(
164 (parsed.days, parsed.start, parsed.end),
165 (hours.days, hours.start, hours.end)
166 );
167 }
168
169 #[test]
170 fn mailbox_without_working_hours_is_none() {
171 assert!(parse_working_hours(&json!({"timeFormat": "HH:mm"})).is_none());
172 }
173 }
@@ -0,0 +1,173 @@
1//! Outlook mailbox working hours (`/me/mailboxSettings`), the setting Teams and
2//! Outlook read for work days and hours.
3//!
4//! `MailboxSettings.Read` is not granted to the Teams client; `ReadWrite` is.
5
6use chrono::{NaiveTime, Weekday};
7use serde_json::{Value, json};
8use session::{Method, Scope};
9
10use crate::client::Graph;
11use crate::error::{Error, Result};
12use crate::urls;
13
14const MAILBOX_SCOPE: &str = "MailboxSettings.ReadWrite";
15const TIME_FORMAT: &str = "%H:%M:%S%.f";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MailboxWorkingHours {
19 pub days: Vec<Weekday>,
20 pub start: NaiveTime,
21 pub end: NaiveTime,
22 /// Windows or IANA name as the mailbox stores it; written back unchanged.
23 pub time_zone: Option<String>,
24 /// Mailbox language (`en-CH`); Outlook derives the first day of week from it.
25 pub locale: Option<String>,
26}
27
28impl Graph {
29 pub async fn working_hours(&self) -> Result<MailboxWorkingHours> {
30 let url = urls::mailbox_settings();
31 let body = self.get(&url, &Scope::graph(MAILBOX_SCOPE)).await?;
32 parse_working_hours(&body)
33 .ok_or_else(|| Error::from(session::Error::api(200, &url, body.clone())))
34 }
35
36 pub async fn set_working_hours(&self, hours: &MailboxWorkingHours) -> Result<()> {
37 self.session()
38 .request(
39 Method::Patch,
40 &urls::mailbox_settings(),
41 &Scope::graph(MAILBOX_SCOPE),
42 Some(working_hours_body(hours)),
43 )
44 .await?;
45 Ok(())
46 }
47}
48
49pub fn parse_working_hours(body: &Value) -> Option<MailboxWorkingHours> {
50 let hours = body.get("workingHours")?;
51 let days = hours
52 .get("daysOfWeek")?
53 .as_array()?
54 .iter()
55 .filter_map(Value::as_str)
56 .filter_map(|day| day.parse::<Weekday>().ok())
57 .collect();
58 let time = |key: &str| {
59 let text = hours.get(key)?.as_str()?;
60 NaiveTime::parse_from_str(text, TIME_FORMAT)
61 .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M"))
62 .ok()
63 };
64 Some(MailboxWorkingHours {
65 days,
66 start: time("startTime")?,
67 end: time("endTime")?,
68 time_zone: hours
69 .pointer("/timeZone/name")
70 .and_then(Value::as_str)
71 .map(str::to_owned),
72 locale: body
73 .pointer("/language/locale")
74 .and_then(Value::as_str)
75 .filter(|locale| !locale.is_empty())
76 .map(str::to_owned),
77 })
78}
79
80pub fn working_hours_body(hours: &MailboxWorkingHours) -> Value {
81 let mut working = json!({
82 "daysOfWeek": hours.days.iter().map(|day| day_name(*day)).collect::<Vec<_>>(),
83 "startTime": graph_time(hours.start),
84 "endTime": graph_time(hours.end),
85 });
86 if let Some(name) = &hours.time_zone {
87 working["timeZone"] = json!({ "name": name });
88 }
89 json!({ "workingHours": working })
90}
91
92/// Graph writes seven fraction digits; working hours never carry fractions.
93fn graph_time(time: NaiveTime) -> String {
94 format!("{}.0000000", time.format("%H:%M:%S"))
95}
96
97fn day_name(day: Weekday) -> &'static str {
98 match day {
99 Weekday::Mon => "monday",
100 Weekday::Tue => "tuesday",
101 Weekday::Wed => "wednesday",
102 Weekday::Thu => "thursday",
103 Weekday::Fri => "friday",
104 Weekday::Sat => "saturday",
105 Weekday::Sun => "sunday",
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 fn captured() -> Value {
114 // Shape of GET /me/mailboxSettings as returned on 2026-11-15.
115 json!({
116 "timeFormat": "HH:mm",
117 "dateFormat": "d MMM yyyy",
118 "language": {"locale": "en-CH", "displayName": "English (Switzerland)"},
119 "workingHours": {
120 "daysOfWeek": ["monday", "tuesday", "wednesday", "thursday", "friday"],
121 "startTime": "08:00:00.0000000",
122 "endTime": "17:00:00.0000000",
123 "timeZone": {"name": "W. Europe Standard Time"}
124 }
125 })
126 }
127
128 #[test]
129 fn mailbox_working_hours_parse() {
130 let hours = parse_working_hours(&captured()).unwrap();
131 assert_eq!(
132 hours.days,
133 [
134 Weekday::Mon,
135 Weekday::Tue,
136 Weekday::Wed,
137 Weekday::Thu,
138 Weekday::Fri
139 ]
140 );
141 assert_eq!(hours.start, NaiveTime::from_hms_opt(8, 0, 0).unwrap());
142 assert_eq!(hours.end, NaiveTime::from_hms_opt(17, 0, 0).unwrap());
143 assert_eq!(hours.time_zone.as_deref(), Some("W. Europe Standard Time"));
144 assert_eq!(hours.locale.as_deref(), Some("en-CH"));
145 }
146
147 #[test]
148 fn mailbox_working_hours_body_round_trips() {
149 let mut hours = parse_working_hours(&captured()).unwrap();
150 hours.days.retain(|day| *day != Weekday::Fri);
151 hours.start = NaiveTime::from_hms_opt(7, 30, 0).unwrap();
152 let body = working_hours_body(&hours);
153 assert_eq!(
154 body["workingHours"]["daysOfWeek"],
155 json!(["monday", "tuesday", "wednesday", "thursday"])
156 );
157 assert_eq!(body["workingHours"]["startTime"], "07:30:00.0000000");
158 assert_eq!(
159 body["workingHours"]["timeZone"]["name"],
160 "W. Europe Standard Time"
161 );
162 let parsed = parse_working_hours(&body).unwrap();
163 assert_eq!(
164 (parsed.days, parsed.start, parsed.end),
165 (hours.days, hours.start, hours.end)
166 );
167 }
168
169 #[test]
170 fn mailbox_without_working_hours_is_none() {
171 assert!(parse_working_hours(&json!({"timeFormat": "HH:mm"})).is_none());
172 }
173}
crates/graph/src/urls.rs +4 −0
@@ -62,6 +62,10 @@ pub fn user_direct_reports(user_id: &str) -> String {
62 62 )
63 63 }
64 64
65 pub fn mailbox_settings() -> String {
66 format!("{GRAPH}/v1.0/me/mailboxSettings")
67 }
68
65 69 pub fn get_schedule() -> String {
66 70 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67 71 }
@@ -62,6 +62,10 @@ pub fn user_direct_reports(user_id: &str) -> String {
62 )
62 )
63}
63}
64
64
65pub fn mailbox_settings() -> String {
66 format!("{GRAPH}/v1.0/me/mailboxSettings")
67}
68
65pub fn get_schedule() -> String {
69pub fn get_schedule() -> String {
66 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
70 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
67}
71}
crates/store/src/calendar_accounts.rs +55 −0
@@ -178,6 +178,28 @@ pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Res
178 178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179 179 }
180 180
181 /// Save Google tokens refreshed during a fetch without touching anything else.
182 ///
183 /// A fetch works on a copy of the accounts it read before it started. Saving that copy
184 /// back would undo a calendar toggle the user made meanwhile, so only tokens are merged
185 /// into the accounts as they are stored now.
186 pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
187 let mut current = load_calendar_accounts(store);
188 let mut changed = false;
189 for account in &mut current.google_accounts {
190 if let Some(fresh) = fetched.google_account(&account.id)
191 && fresh.tokens != account.tokens
192 {
193 account.tokens = fresh.tokens.clone();
194 changed = true;
195 }
196 }
197 if changed {
198 save_calendar_accounts(store, &current)?;
199 }
200 Ok(())
201 }
202
181 203 #[cfg(test)]
182 204 mod tests {
183 205 use super::*;
@@ -239,4 +261,37 @@ mod tests {
239 261 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240 262 assert!(accounts.write_targets.is_empty());
241 263 }
264
265 #[test]
266 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 let directory = tempdir().unwrap();
268 let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
269 let mut stored = CalendarAccounts::default();
270 stored.google_accounts.push(GoogleAccount {
271 id: "g1".into(),
272 email: "me@example.com".into(),
273 calendars: vec![GoogleCalendarInfo {
274 id: "work".into(),
275 summary: "Work".into(),
276 selected: true,
277 primary: false,
278 }],
279 tokens: GoogleTokenSet::default(),
280 });
281 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 let mut fetched = load_calendar_accounts(&store);
284 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 stored.google_accounts[0].calendars[0].selected = false;
287 stored.outlook_selected = false;
288 save_calendar_accounts(&store, &stored).unwrap();
289
290 merge_google_tokens(&store, &fetched).unwrap();
291
292 let merged = load_calendar_accounts(&store);
293 assert!(!merged.outlook_selected);
294 assert!(!merged.google_accounts[0].calendars[0].selected);
295 assert_eq!(merged.google_accounts[0].tokens.access_token, "fresh");
296 }
242 297 }
@@ -178,6 +178,28 @@ pub fn save_calendar_accounts(store: &Store, accounts: &CalendarAccounts) -> Res
178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
178 store.set_meta(CALENDAR_ACCOUNTS_KEY, &accounts.to_json())
179}
179}
180
180
181/// Save Google tokens refreshed during a fetch without touching anything else.
182///
183/// A fetch works on a copy of the accounts it read before it started. Saving that copy
184/// back would undo a calendar toggle the user made meanwhile, so only tokens are merged
185/// into the accounts as they are stored now.
186pub fn merge_google_tokens(store: &Store, fetched: &CalendarAccounts) -> Result<()> {
187 let mut current = load_calendar_accounts(store);
188 let mut changed = false;
189 for account in &mut current.google_accounts {
190 if let Some(fresh) = fetched.google_account(&account.id)
191 && fresh.tokens != account.tokens
192 {
193 account.tokens = fresh.tokens.clone();
194 changed = true;
195 }
196 }
197 if changed {
198 save_calendar_accounts(store, &current)?;
199 }
200 Ok(())
201}
202
181#[cfg(test)]
203#[cfg(test)]
182mod tests {
204mod tests {
183 use super::*;
205 use super::*;
@@ -239,4 +261,37 @@ mod tests {
239 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
261 assert_eq!(accounts.home.provider, CalendarProvider::Outlook);
240 assert!(accounts.write_targets.is_empty());
262 assert!(accounts.write_targets.is_empty());
241 }
263 }
264
265 #[test]
266 fn token_merge_keeps_a_toggle_made_during_the_fetch() {
267 let directory = tempdir().unwrap();
268 let store = Store::open(&directory.path().join("db.sqlite")).unwrap();
269 let mut stored = CalendarAccounts::default();
270 stored.google_accounts.push(GoogleAccount {
271 id: "g1".into(),
272 email: "me@example.com".into(),
273 calendars: vec![GoogleCalendarInfo {
274 id: "work".into(),
275 summary: "Work".into(),
276 selected: true,
277 primary: false,
278 }],
279 tokens: GoogleTokenSet::default(),
280 });
281 save_calendar_accounts(&store, &stored).unwrap();
282 // The fetch starts from this copy and refreshes the token.
283 let mut fetched = load_calendar_accounts(&store);
284 fetched.google_accounts[0].tokens.access_token = "fresh".into();
285 // Meanwhile the user turns the calendar off and Outlook off.
286 stored.google_accounts[0].calendars[0].selected = false;
287 stored.outlook_selected = false;
288 save_calendar_accounts(&store, &stored).unwrap();
289
290 merge_google_tokens(&store, &fetched).unwrap();
291
292 let merged = load_calendar_accounts(&store);
293 assert!(!merged.outlook_selected);
294 assert!(!merged.google_accounts[0].calendars[0].selected);
295 assert_eq!(merged.google_accounts[0].tokens.access_token, "fresh");
296 }
242}
297}
crates/store/src/lib.rs +2 −1
@@ -27,7 +27,8 @@ mod time;
27 27
28 28 pub use calendar_accounts::{
29 29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, save_calendar_accounts,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
31 save_calendar_accounts,
31 32 };
32 33 pub use error::{Error, Result};
33 34 pub use image_files::ImageFileCache;
@@ -27,7 +27,8 @@ mod time;
27
27
28pub use calendar_accounts::{
28pub use calendar_accounts::{
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
29 CALENDAR_ACCOUNTS_KEY, CalendarAccounts, CalendarProvider, CalendarRef, GoogleAccount,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, save_calendar_accounts,
30 GoogleCalendarInfo, GoogleTokenSet, load_calendar_accounts, merge_google_tokens,
31 save_calendar_accounts,
31};
32};
32pub use error::{Error, Result};
33pub use error::{Error, Result};
33pub use image_files::ImageFileCache;
34pub use image_files::ImageFileCache;
docs/decisions/0015-linux-desktop-toasts-use-freedesktop-notifications.md +1 −1
@@ -1,5 +1,5 @@
1 1 ---
2 status: proposed
2 status: accepted
3 3 date: 2026-11-14
4 4 ---
5 5
@@ -1,5 +1,5 @@
1---
1---
2status: proposed
2status: accepted
3date: 2026-11-14
3date: 2026-11-14
4---
4---
5
5
docs/decisions/0016-calendar-week-start-and-time-scale-stay-local.md added +33 −0
@@ -0,0 +1,33 @@
1 ---
2 status: accepted
3 date: 2026-11-15
4 ---
5
6 # ADR 0016: Calendar work hours go to the mailbox, week start and time scale stay local
7
8 ## Context
9
10 `GUARDRAILS.md` says settings Teams knows are saved where Teams saves them. The calendar view settings come from two places in Teams:
11
12 - Work days and work hours are the Outlook mailbox working hours. Graph exposes them as `/me/mailboxSettings`. The Teams client token is granted `MailboxSettings.ReadWrite` but not `MailboxSettings.Read`. A live read returned HTTP 200 on 2026-11-15.
13 - First day of week and the time scale are Outlook web (OWA) user options. Graph has no endpoint for them. The new Teams calendar reads them through the OWA options service.
14
15 The options were:
16
17 - write everything locally;
18 - reach the OWA options service from the fork;
19 - split by what Graph can reach.
20
21 ## Decision
22
23 - Work days and hours are read from and written to the mailbox working hours through Graph. A local copy is only a cache for the grid.
24 - First day of week defaults to the region of the mailbox language (`language.locale` in the mailbox settings), which is where Outlook takes the OWA default from. The regional format is the fallback. A local override can change it.
25 - The time scale is a local setting. Its default, 30 minutes, matches Teams.
26 - Default view and the last used span are fork settings and stay local.
27
28 ## Consequences
29
30 - Changing work hours in the app changes them in Outlook and Teams too, and the other way round after the next read.
31 - A first-day or time-scale change in Outlook web does not reach the app, and an app change does not reach Outlook. This deviation is named in the change's commit.
32 - If the fork adopts the OWA options service later, first day and time scale move there, and this record is superseded.
33 - OpenSpec `calendar-view-settings` owns the observable behaviour.
@@ -0,0 +1,33 @@
1---
2status: accepted
3date: 2026-11-15
4---
5
6# ADR 0016: Calendar work hours go to the mailbox, week start and time scale stay local
7
8## Context
9
10`GUARDRAILS.md` says settings Teams knows are saved where Teams saves them. The calendar view settings come from two places in Teams:
11
12- Work days and work hours are the Outlook mailbox working hours. Graph exposes them as `/me/mailboxSettings`. The Teams client token is granted `MailboxSettings.ReadWrite` but not `MailboxSettings.Read`. A live read returned HTTP 200 on 2026-11-15.
13- First day of week and the time scale are Outlook web (OWA) user options. Graph has no endpoint for them. The new Teams calendar reads them through the OWA options service.
14
15The options were:
16
17- write everything locally;
18- reach the OWA options service from the fork;
19- split by what Graph can reach.
20
21## Decision
22
23- Work days and hours are read from and written to the mailbox working hours through Graph. A local copy is only a cache for the grid.
24- First day of week defaults to the region of the mailbox language (`language.locale` in the mailbox settings), which is where Outlook takes the OWA default from. The regional format is the fallback. A local override can change it.
25- The time scale is a local setting. Its default, 30 minutes, matches Teams.
26- Default view and the last used span are fork settings and stay local.
27
28## Consequences
29
30- Changing work hours in the app changes them in Outlook and Teams too, and the other way round after the next read.
31- A first-day or time-scale change in Outlook web does not reach the app, and an app change does not reach Outlook. This deviation is named in the change's commit.
32- If the fork adopts the OWA options service later, first day and time scale move there, and this record is superseded.
33- OpenSpec `calendar-view-settings` owns the observable behaviour.
docs/decisions/README.md +2 −1
@@ -31,5 +31,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
31 31 | [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
32 32 | [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33 33 | [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
34 | [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
34 35
35 Records `0001` to `0014` are the decisions already shipped. `0015` stays `proposed` until the Linux desktop-notifications change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
36 Records `0001` to `0016` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -31,5 +31,6 @@ Statuses: `proposed`, `accepted`, `superseded`.
31| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
31| [0013](0013-local-diagnostic-data-and-upstream-issues.md) | Local diagnostic data layout and upstream issues |
32| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
32| [0014](0014-linux-installs-and-updates-itself.md) | The Linux binary installs and updates itself |
33| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
33| [0015](0015-linux-desktop-toasts-use-freedesktop-notifications.md) | Linux desktop toasts use freedesktop Notifications |
34| [0016](0016-calendar-week-start-and-time-scale-stay-local.md) | Calendar work hours go to the mailbox, week start and time scale stay local |
34
35
35Records `0001` to `0014` are the decisions already shipped. `0015` stays `proposed` until the Linux desktop-notifications change merges. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
36Records `0001` to `0016` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
docs/design/islands/SPEC.md +1 −0
@@ -85,6 +85,7 @@ Core roles (non-exhaustive; prefer an existing role over inventing a hex):
85 85 | `accent`, `accent_text`, `accent_soft`, `accent_strong`, `on_accent` | Primary actions and links |
86 86 | `bubble_own` / `bubble_other` | Message bubbles |
87 87 | `green`, `red`, `amber`, … | Status semantics already defined on the palette |
88 | `accent`, then `avatar_palette` | Calendar colours: Outlook takes `accent`, every further calendar in the calendar list the next palette colour (`theme::calendar_color`) |
88 89
89 90 Shades: Dark (default), Light, High contrast. Schemes: Rusty Teams and Teams (`SCHEMES` in `schemes.rs`). Changing a hex belongs in the palette / scheme tables, not in a view.
90 91
@@ -85,6 +85,7 @@ Core roles (non-exhaustive; prefer an existing role over inventing a hex):
85| `accent`, `accent_text`, `accent_soft`, `accent_strong`, `on_accent` | Primary actions and links |
85| `accent`, `accent_text`, `accent_soft`, `accent_strong`, `on_accent` | Primary actions and links |
86| `bubble_own` / `bubble_other` | Message bubbles |
86| `bubble_own` / `bubble_other` | Message bubbles |
87| `green`, `red`, `amber`, … | Status semantics already defined on the palette |
87| `green`, `red`, `amber`, … | Status semantics already defined on the palette |
88| `accent`, then `avatar_palette` | Calendar colours: Outlook takes `accent`, every further calendar in the calendar list the next palette colour (`theme::calendar_color`) |
88
89
89Shades: Dark (default), Light, High contrast. Schemes: Rusty Teams and Teams (`SCHEMES` in `schemes.rs`). Changing a hex belongs in the palette / scheme tables, not in a view.
90Shades: Dark (default), Light, High contrast. Schemes: Rusty Teams and Teams (`SCHEMES` in `schemes.rs`). Changing a hex belongs in the palette / scheme tables, not in a view.
90
91