BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / calendar_view.rs

calendar_view.rs

calendar_view.rs 51.9 KiB Download Raw
1use std::time::Duration;
2
3use app_base::format::{self, WeekdayWidth, clock_format, weekday_name};
4use chatsvc::{CalendarEvent, ResponseType, join_info_text};
5use chrono::{DateTime, Datelike, FixedOffset, Local, NaiveDate, Offset, Timelike, Utc};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::Sizable as _;
8use gpui_kit::component::button::{Button, ButtonVariants as _};
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::calendar_date_picker::date_picker_button;
15use super::calendar_event_dialog::open_calendar_event;
16use super::calendar_month::month_grid;
17use super::calendar_picker;
18use super::join_dialog::open_join_with_id;
19use super::meeting_proposal_card::meeting_proposal_cards;
20use super::new_meeting_dialog::{open_new_meeting, open_new_meeting_at};
21use super::rsvp_menu::rsvp_menu;
22use super::scroll_edge::scroll_offset;
23use crate::app_state::AppState;
24use crate::call::calendar_now::{
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};
28use crate::call::schedule::DEFAULT_LENGTH_MINUTES;
29use crate::call::slot_select::{SlotSelection, minute_at};
30use crate::call::week::CalendarLoadFailure;
31use crate::call::week_grid::{
32 CalendarSpan, EventLook, WeekBlock, WeekDay, WeekLayout, calendar_index, event_look,
33 hour_label, month_shown, week_days,
34};
35use crate::i18n::tr;
36use crate::theme;
37use crate::views::widgets::icon;
38
39const GUTTER_WIDTH: f32 = 50.;
40const HEADER_HEIGHT: f32 = 52.;
41const DAY_HEADER_HEIGHT: f32 = 56.;
42const ALL_DAY_HEIGHT: f32 = 26.;
43const BLOCK_GAP: f32 = 2.;
44const MINOR_LINE_OPACITY: f32 = 0.45;
45const OFF_HOURS_OPACITY: f32 = 0.85;
46const NOW_ELSEWHERE_OPACITY: f32 = 0.4;
47pub const CALENDAR_HEADER_TAG: &str = "shell/islands/calendar/header";
48pub const CALENDAR_DAY_HEADERS_TAG: &str = "shell/islands/calendar/day-headers";
49pub const CALENDAR_NEW_MEETING_TAG: &str = "shell/islands/calendar/header/new-meeting";
50pub const COMPACT_HEADER_WIDTH: f32 = 960.;
51/// Header widths below which button labels give way to icons (German labels are longest).
52const SECONDARY_LABELS_WIDTH: f32 = 1080.;
53const PRIMARY_LABELS_WIDTH: f32 = 780.;
54
55/// Which header buttons keep their text at a given header width.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct HeaderLabels {
58 /// Today, view and New meeting.
59 pub primary: bool,
60 /// Join with an ID and Meet now.
61 pub secondary: bool,
62}
63
64pub fn header_labels(header_width: f32) -> HeaderLabels {
65 HeaderLabels {
66 primary: header_width >= PRIMARY_LABELS_WIDTH,
67 secondary: header_width >= SECONDARY_LABELS_WIDTH,
68 }
69}
70const BUSY_FILL_OPACITY: f32 = 0.28;
71const FREE_FILL_OPACITY: f32 = 0.12;
72const STATUS_BAR_WIDTH: f32 = 4.;
73const HATCH_STRIPE: f32 = 1.5;
74const HATCH_GAP: f32 = 2.5;
75const SMALL_TITLE_HEIGHT: f32 = 20.;
76const TODAY_MARK_HEIGHT: f32 = 3.;
77const NOW_DOT_SIZE: f32 = 8.;
78const CLOCK_TICK: Duration = Duration::from_secs(30);
79const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;
80const SELECTION_FILL_OPACITY: f32 = 0.24;
81/// Height below which the picked block drops its time label.
82const SELECTION_LABEL_HEIGHT: f32 = 18.;
83
84/// A left press on an empty slot that is still held; the block grows from `anchor`.
85#[derive(Debug, Clone, Copy)]
86struct SlotDrag {
87 date: NaiveDate,
88 anchor: i64,
89}
90
91pub struct CalendarView {
92 state: Entity<AppState>,
93 scroll: ScrollHandle,
94 follow_now: FollowNow,
95 seen_scroll_to_now: u64,
96 last_programmatic_offset: f32,
97 skip_manual_check: bool,
98 clock_running: bool,
99 /// Row height of one hour and minor lines per hour, from the time scale.
100 hour_height: f32,
101 steps_per_hour: usize,
102 /// Block of empty slots picked on the hour grid for a new meeting.
103 slot_selection: Option<SlotSelection>,
104 slot_drag: Option<SlotDrag>,
105 /// Focus for the hour grid, so Escape can drop the picked block.
106 grid_focus: FocusHandle,
107 _observation: Subscription,
108 _agent_observation: Option<Subscription>,
109}
110
111impl CalendarView {
112 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
113 let observation = cx.observe(&state, |_, _, cx| cx.notify());
114 let agent_observation =
115 crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
116 CalendarView {
117 state,
118 scroll: ScrollHandle::new(),
119 follow_now: FollowNow { active: true },
120 seen_scroll_to_now: 0,
121 last_programmatic_offset: 0.,
122 skip_manual_check: false,
123 clock_running: false,
124 hour_height: hour_height(Default::default()),
125 steps_per_hour: 2,
126 slot_selection: None,
127 slot_drag: None,
128 grid_focus: cx.focus_handle(),
129 _observation: observation,
130 _agent_observation: agent_observation,
131 }
132 }
133
134 fn grid_viewport_height(window: &Window) -> f32 {
135 (f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)
136 }
137
138 fn align_scroll_to_now(&mut self, window: &Window) {
139 let local = Local::now();
140 let offset = now_scroll_offset_y(
141 local.hour(),
142 local.minute(),
143 self.hour_height,
144 Self::grid_viewport_height(window),
145 NOW_BIAS_FRACTION,
146 );
147 self.set_programmatic_offset(offset);
148 }
149
150 /// A range without today opens at work start instead of midnight.
151 fn align_scroll_to_work_start(&mut self, work_start_minute: i64, window: &Window) {
152 let offset = work_start_scroll_offset_y(
153 work_start_minute,
154 self.hour_height,
155 Self::grid_viewport_height(window),
156 );
157 self.set_programmatic_offset(offset);
158 }
159
160 fn set_programmatic_offset(&mut self, offset: f32) {
161 self.scroll.set_offset(point(px(0.), px(offset)));
162 self.last_programmatic_offset = offset;
163 self.skip_manual_check = true;
164 }
165
166 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
167 let (scroll_to_now, span, today_visible, work_start) = {
168 let state = self.state.read(cx);
169 let today_visible = state.calendar_shows_today();
170 let prefs = &state.calendar_prefs;
171 self.hour_height = hour_height(prefs.time_scale);
172 self.steps_per_hour = prefs.time_scale.steps_per_hour() as usize;
173 (
174 state.calendar_scroll_to_now,
175 state.calendar_week.span,
176 today_visible,
177 prefs.work_hours.minute_range().0,
178 )
179 };
180 if !shows_hour_grid(span) {
181 self.stop_clock();
182 return;
183 }
184 self.ensure_clock(cx);
185 if scroll_to_now != self.seen_scroll_to_now {
186 self.seen_scroll_to_now = scroll_to_now;
187 if today_visible {
188 self.follow_now.request_align();
189 } else {
190 self.align_scroll_to_work_start(work_start, window);
191 return;
192 }
193 }
194 if self.skip_manual_check {
195 self.skip_manual_check = false;
196 } else if self.follow_now.active
197 && offset_differs(
198 f32::from(scroll_offset(&self.scroll).y),
199 self.last_programmatic_offset,
200 MANUAL_SCROLL_EPSILON,
201 )
202 {
203 self.follow_now.note_manual_scroll();
204 }
205 if self.follow_now.should_follow(today_visible) {
206 self.align_scroll_to_now(window);
207 }
208 }
209
210 fn ensure_clock(&mut self, cx: &mut Context<Self>) {
211 if self.clock_running {
212 return;
213 }
214 self.clock_running = true;
215 cx.spawn(async move |this, cx| {
216 loop {
217 cx.background_executor().timer(CLOCK_TICK).await;
218 let keep = this
219 .update(cx, |view, cx| {
220 let span = view.state.read(cx).calendar_week.span;
221 if !shows_hour_grid(span) {
222 view.clock_running = false;
223 return false;
224 }
225 cx.notify();
226 true
227 })
228 .unwrap_or(false);
229 if !keep {
230 break;
231 }
232 }
233 })
234 .detach();
235 }
236
237 fn stop_clock(&mut self) {
238 self.clock_running = false;
239 }
240
241 fn on_grid_scroll_wheel(
242 &mut self,
243 _event: &ScrollWheelEvent,
244 window: &mut Window,
245 cx: &mut Context<Self>,
246 ) {
247 self.follow_now.note_manual_scroll();
248 if self.slot_drag.is_some() {
249 // A wheel turn moves the grid under a still pointer; follow it once the
250 // new offset is in.
251 cx.on_next_frame(window, |view, window, cx| {
252 view.drag_slot_to(window.mouse_position(), cx)
253 });
254 }
255 cx.notify();
256 }
257
258 fn step_minutes(&self) -> i64 {
259 60 / self.steps_per_hour.max(1) as i64
260 }
261
262 /// Grid step under a window position; the day's columns scroll together, so the
263 /// scroll container's top plus its offset is where midnight sits.
264 fn minute_at_position(&self, position: Point<Pixels>) -> i64 {
265 let content_top =
266 f32::from(self.scroll.bounds().top()) + f32::from(scroll_offset(&self.scroll).y);
267 minute_at(
268 f32::from(position.y) - content_top,
269 self.hour_height,
270 self.step_minutes(),
271 )
272 }
273
274 fn one_slot(&self, date: NaiveDate, position: Point<Pixels>) -> SlotSelection {
275 let minute = self.minute_at_position(position);
276 SlotSelection::between(date, minute, minute, self.step_minutes())
277 }
278
279 /// Left press on an empty slot: start picking a block, or a double click opens
280 /// New meeting at that slot with the default meeting length, as Teams does.
281 fn press_slot(
282 &mut self,
283 date: NaiveDate,
284 event: &MouseDownEvent,
285 window: &mut Window,
286 cx: &mut Context<Self>,
287 ) {
288 let slot = self.one_slot(date, event.position);
289 if event.click_count >= 2 {
290 self.clear_slot_selection(cx);
291 let meeting =
292 SlotSelection::starting_at(date, slot.start_minute, DEFAULT_LENGTH_MINUTES);
293 open_meeting_for(self.state.clone(), meeting, window, cx);
294 return;
295 }
296 self.slot_drag = Some(SlotDrag {
297 date,
298 anchor: slot.start_minute,
299 });
300 self.slot_selection = Some(slot);
301 cx.notify();
302 }
303
304 fn drag_slot_to(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
305 let Some(drag) = self.slot_drag else {
306 return;
307 };
308 let minute = self.minute_at_position(position);
309 let selection = SlotSelection::between(drag.date, drag.anchor, minute, self.step_minutes());
310 if self.slot_selection != Some(selection) {
311 self.slot_selection = Some(selection);
312 cx.notify();
313 }
314 }
315
316 fn end_slot_drag(&mut self, cx: &mut Context<Self>) {
317 if self.slot_drag.take().is_some() {
318 cx.notify();
319 }
320 }
321
322 /// Right press on an empty slot: keep the picked block when the press is inside
323 /// it, otherwise pick just that slot, so the menu always has a block to use.
324 fn right_press_slot(
325 &mut self,
326 date: NaiveDate,
327 event: &MouseDownEvent,
328 cx: &mut Context<Self>,
329 ) {
330 self.slot_drag = None;
331 let minute = self.minute_at_position(event.position);
332 if !self
333 .slot_selection
334 .is_some_and(|selection| selection.contains(date, minute))
335 {
336 self.slot_selection = Some(self.one_slot(date, event.position));
337 }
338 cx.notify();
339 }
340
341 fn clear_slot_selection(&mut self, cx: &mut Context<Self>) {
342 self.slot_drag = None;
343 if self.slot_selection.take().is_some() {
344 cx.notify();
345 }
346 }
347
348 /// While a block is being picked, follow the pointer outside the grid and over
349 /// meetings too. Releases are caught on the grid itself (see `grid`), whose
350 /// listeners already exist when the press lands.
351 fn slot_drag_listener(&self, cx: &Context<Self>) -> impl IntoElement {
352 let view = cx.entity().downgrade();
353 canvas(
354 |_, _, _| {},
355 move |_, _, window, _| {
356 let moved = view.clone();
357 window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {
358 if !phase.bubble() {
359 return;
360 }
361 let held = event.pressed_button == Some(MouseButton::Left);
362 moved
363 .update(cx, |view, cx| {
364 if held {
365 view.drag_slot_to(event.position, cx);
366 } else {
367 view.end_slot_drag(cx);
368 }
369 })
370 .ok();
371 });
372 },
373 )
374 .absolute()
375 .size_full()
376 }
377
378 /// Invisible layer under a day's meetings that takes presses on empty slots.
379 fn slot_layer(&self, date: NaiveDate, cx: &Context<Self>) -> impl IntoElement {
380 let (menu_view, menu_state) = (cx.entity().downgrade(), self.state.clone());
381 div()
382 .id(SharedString::from(format!("calendar-slots-{date}")))
383 .absolute()
384 .top_0()
385 .left_0()
386 .size_full()
387 // Capture runs before the context menu notes which element to give focus
388 // back to, so Escape reaches the grid after the menu closes.
389 .capture_any_mouse_down(cx.listener(|view, _: &MouseDownEvent, window, cx| {
390 window.focus(&view.grid_focus, cx)
391 }))
392 .on_mouse_down(
393 MouseButton::Left,
394 cx.listener(move |view, event: &MouseDownEvent, window, cx| {
395 view.press_slot(date, event, window, cx)
396 }),
397 )
398 .on_mouse_down(
399 MouseButton::Right,
400 cx.listener(move |view, event: &MouseDownEvent, _, cx| {
401 view.right_press_slot(date, event, cx)
402 }),
403 )
404 .context_menu(move |menu, _, _| {
405 let (view, state) = (menu_view.clone(), menu_state.clone());
406 menu.item(
407 PopupMenuItem::new(tr("calendar.view.new_meeting"))
408 .icon(IconName::Plus)
409 .on_click(move |_, window, cx| {
410 let picked = view
411 .update(cx, |view, cx| {
412 let picked = view.slot_selection;
413 view.clear_slot_selection(cx);
414 picked
415 })
416 .ok()
417 .flatten();
418 match picked {
419 Some(picked) => open_meeting_for(state.clone(), picked, window, cx),
420 None => open_new_meeting(state.clone(), window, cx),
421 }
422 }),
423 )
424 })
425 }
426
427 /// The picked block: an accent fill and bar, with its times when there is room.
428 fn selection_block(&self, selection: &SlotSelection) -> Div {
429 let row = self.hour_height;
430 let top = selection.start_minute as f32 / 60. * row;
431 let height = (selection.end_minute - selection.start_minute) as f32 / 60. * row;
432 // The times New meeting will open with, so the label and the form agree.
433 let label = selection
434 .form_times(grid_offset(), &Local)
435 .label(clock_format());
436 div()
437 .absolute()
438 .top(px(top))
439 .h(px(height))
440 .left_0()
441 .right_0()
442 .px(px(BLOCK_GAP))
443 .child(
444 h_flex()
445 .size_full()
446 .items_start()
447 .overflow_hidden()
448 .rounded(px(6.))
449 .bg(theme::accent().opacity(SELECTION_FILL_OPACITY))
450 .child(
451 div()
452 .flex_none()
453 .w(px(STATUS_BAR_WIDTH))
454 .h_full()
455 .bg(theme::accent()),
456 )
457 .child(
458 div()
459 .flex_1()
460 .min_w_0()
461 .pl(px(5.))
462 .pr(px(4.))
463 .text_size(px(11.))
464 .line_height(px(16.))
465 .text_color(theme::accent_text())
466 .truncate()
467 .when(height >= SELECTION_LABEL_HEIGHT, |text| text.child(label)),
468 ),
469 )
470 }
471
472 fn header(
473 &self,
474 start: NaiveDate,
475 span: CalendarSpan,
476 dates: &[NaiveDate],
477 layout: &WeekLayout,
478 compact: bool,
479 labels: HeaderLabels,
480 ) -> impl IntoElement {
481 let span_state = self.state.clone();
482 let label = |key: &'static str| labels.primary.then(|| tr(key));
483 let secondary = |key: &'static str| labels.secondary.then(|| tr(key));
484 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
485 let (join_state, meet_state, new_state) =
486 (self.state.clone(), self.state.clone(), self.state.clone());
487 let pane_state = self.state.clone();
488 let (back_tip, forward_tip) = match span {
489 CalendarSpan::Day => ("calendar.view.previous_day", "calendar.view.next_day"),
490 CalendarSpan::Month => ("calendar.view.previous_month", "calendar.view.next_month"),
491 _ => ("calendar.view.previous_week", "calendar.view.next_week"),
492 };
493 h_flex()
494 .debug_selector(|| CALENDAR_HEADER_TAG.into())
495 .h(px(HEADER_HEIGHT))
496 .flex_none()
497 .items_center()
498 .gap(px(8.))
499 .px(px(16.))
500 .when(!compact, |header| {
501 header.child(
502 Button::new("calendar-pane-toggle")
503 .small()
504 .ghost()
505 .icon(IconName::PanelLeft)
506 .tooltip(tr("calendar.view.toggle_pane"))
507 .on_click(move |_, _, cx| {
508 pane_state.update(cx, |state, cx| {
509 state.update_calendar_prefs(
510 |prefs| prefs.pane_hidden = !prefs.pane_hidden,
511 cx,
512 )
513 })
514 }),
515 )
516 })
517 .child(
518 Button::new("calendar-today")
519 .small()
520 .outline()
521 .icon(IconName::Calendar)
522 .when_some(label("calendar.view.today"), |button, text| {
523 button.label(text)
524 })
525 .tooltip(tr("calendar.view.today"))
526 .on_click(move |_, _, cx| {
527 today.update(cx, |state, cx| state.calendar_to_today(cx))
528 }),
529 )
530 .child(
531 Button::new("calendar-back")
532 .small()
533 .ghost()
534 .icon(IconName::ChevronLeft)
535 .tooltip(tr(back_tip))
536 .on_click(move |_, _, cx| {
537 back.update(cx, |state, cx| state.shift_calendar_week(-1, cx))
538 }),
539 )
540 .child(
541 Button::new("calendar-forward")
542 .small()
543 .ghost()
544 .icon(IconName::ChevronRight)
545 .tooltip(tr(forward_tip))
546 .on_click(move |_, _, cx| {
547 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
548 }),
549 )
550 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
551 &self.state,
552 span.title(start, layout),
553 dates.to_vec(),
554 layout.first_day,
555 if span == CalendarSpan::Month {
556 month_shown(start)
557 } else {
558 start
559 },
560 )))
561 .child(
562 Button::new("calendar-span")
563 .small()
564 .ghost()
565 .icon(IconName::LayoutGrid)
566 .when(labels.primary, |button| button.label(span.label()))
567 .dropdown_caret(true)
568 .dropdown_menu(move |menu, _, _| {
569 CalendarSpan::ALL.iter().fold(menu, |menu, &choice| {
570 let state = span_state.clone();
571 menu.item(
572 PopupMenuItem::new(choice.label())
573 .checked(choice == span)
574 .on_click(move |_, _, cx| {
575 state.update(cx, |state, cx| {
576 state.set_calendar_span(choice, cx)
577 })
578 }),
579 )
580 })
581 }),
582 )
583 .child(
584 Button::new("calendar-join-id")
585 .small()
586 .outline()
587 .icon(IconName::Hash)
588 .when_some(secondary("calendar.view.join_with_id"), |button, text| {
589 button.label(text)
590 })
591 .tooltip(tr("calendar.view.join_with_id"))
592 .on_click(move |_, window, cx| {
593 open_join_with_id(join_state.clone(), window, cx)
594 }),
595 )
596 .child(
597 Button::new("calendar-meet-now")
598 .small()
599 .outline()
600 .icon(IconName::Video)
601 .when_some(secondary("calendar.view.meet_now"), |button, text| {
602 button.label(text)
603 })
604 .tooltip(tr("calendar.view.meet_now"))
605 .on_click(move |_, _, cx| {
606 meet_state.update(cx, |state, cx| state.start_meet_now(cx))
607 }),
608 )
609 .child(
610 Button::new("calendar-new-meeting")
611 .debug_selector(|| CALENDAR_NEW_MEETING_TAG.into())
612 .small()
613 .primary()
614 .icon(IconName::Plus)
615 .when_some(label("calendar.view.new_meeting"), |button, text| {
616 button.label(text)
617 })
618 .tooltip(tr("calendar.view.new_meeting"))
619 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
620 )
621 }
622
623 /// Day number above the full weekday name; today in the accent colour with its bar.
624 fn day_headers(&self, days: &[WeekDay], today: NaiveDate) -> impl IntoElement {
625 h_flex()
626 .debug_selector(|| CALENDAR_DAY_HEADERS_TAG.into())
627 .h(px(DAY_HEADER_HEIGHT))
628 .flex_none()
629 .border_b_1()
630 .border_color(theme::border())
631 .child(div().w(px(GUTTER_WIDTH)).flex_none())
632 .children(days.iter().map(|day| {
633 let is_today = day.date == today;
634 let (number_color, name_color) = if is_today {
635 (theme::accent_text(), theme::accent_text())
636 } else {
637 (theme::text(), theme::text_soft())
638 };
639 v_flex()
640 .relative()
641 .flex_1()
642 .min_w_0()
643 .h_full()
644 .justify_center()
645 .px(px(12.))
646 .border_l_1()
647 .border_color(theme::border())
648 .when(is_today, |header| {
649 header.child(
650 div()
651 .absolute()
652 .top_0()
653 .left_0()
654 .right_0()
655 .h(px(TODAY_MARK_HEIGHT))
656 .bg(theme::accent()),
657 )
658 })
659 .child(
660 div()
661 .text_size(px(20.))
662 .line_height(px(24.))
663 .text_color(number_color)
664 .when(is_today, |number| number.font_weight(FontWeight::SEMIBOLD))
665 .child(format::calendar_day_number(day.date)),
666 )
667 .child(
668 div()
669 .text_size(px(12.))
670 .text_color(name_color)
671 .truncate()
672 .child(weekday_name(day.date.weekday(), WeekdayWidth::Full)),
673 )
674 }))
675 }
676
677 fn all_day_row(
678 &self,
679 days: &[WeekDay],
680 events: &[CalendarEvent],
681 colors: &[Hsla],
682 send_response: bool,
683 ) -> Option<Div> {
684 if days.iter().all(|day| day.all_day.is_empty()) {
685 return None;
686 }
687 Some(
688 h_flex()
689 .flex_none()
690 .border_b_1()
691 .border_color(theme::border())
692 .child(div().w(px(GUTTER_WIDTH)).flex_none())
693 .children(days.iter().map(|day| {
694 v_flex()
695 .flex_1()
696 .min_w_0()
697 .gap(px(BLOCK_GAP))
698 .p(px(BLOCK_GAP))
699 .border_l_1()
700 .border_color(theme::border())
701 .children(day.all_day.iter().map(|&index| {
702 let event = events[index].clone();
703 let color = colors[index];
704 let open_state = self.state.clone();
705 let (menu_state, menu_event) = (self.state.clone(), event.clone());
706 // Day-qualified id: multi-day all-day chips share object_id.
707 div()
708 .id(SharedString::from(format!(
709 "calendar-all-day-{}-{}",
710 event.object_id, day.date
711 )))
712 .h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
713 .px(px(6.))
714 .flex()
715 .items_center()
716 .rounded(px(6.))
717 .bg(event_fill(event_look(&event), color))
718 .text_size(px(12.))
719 .truncate()
720 .cursor_pointer()
721 .child(event_title(&event))
722 .on_click(move |_, window, cx| {
723 open_calendar_event(
724 open_state.clone(),
725 event.clone(),
726 window,
727 cx,
728 );
729 })
730 .context_menu(move |menu, _, _| {
731 event_menu(menu, &menu_state, &menu_event, send_response)
732 })
733 }))
734 })),
735 )
736 }
737
738 fn event_block(
739 &self,
740 block: &WeekBlock,
741 event: &CalendarEvent,
742 color: Hsla,
743 day: NaiveDate,
744 send_response: bool,
745 ) -> impl IntoElement {
746 let top = block.start_minute as f32 / 60. * self.hour_height;
747 let height = ((block.end_minute - block.start_minute) as f32 / 60. * self.hour_height
748 - BLOCK_GAP)
749 .max(14.);
750 let width = 1. / block.lanes as f32;
751 let compact = height < 36.;
752 let small = height < SMALL_TITLE_HEIGHT;
753 let title_size = if small { 10. } else { 12. };
754 let title_line = if small { 14. } else { 16. };
755 let pad_y = if compact { 1. } else { 3. };
756 // Title and organizer flow as one text; tall blocks wrap it over more lines.
757 let lines = (((height - pad_y * 2.) / title_line).floor() as usize).clamp(1, 8);
758 let look = event_look(event);
759 // Join on the block whenever a Teams link exists (same as detail dialog).
760 // Skip on tiny blocks — the button would crush the title.
761 let can_join = !compact && event.online && !event.cancelled && event.join_url.is_some();
762 let open_state = self.state.clone();
763 let open_event = event.clone();
764 let (menu_state, menu_event) = (self.state.clone(), event.clone());
765 let (join_state, join_url, subject) = (
766 self.state.clone(),
767 event.join_url.clone(),
768 event.subject.clone(),
769 );
770 let (title_color, detail_color) = match look {
771 EventLook::Busy => (theme::text(), theme::text_soft()),
772 EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
773 };
774 // Day-qualified id: overnight / multi-day spans reuse object_id per column.
775 div()
776 .id(SharedString::from(format!(
777 "calendar-event-{}-{}",
778 event.object_id, day
779 )))
780 // Presses on a meeting must not reach the empty-slot layer under it.
781 .block_mouse_except_scroll()
782 .absolute()
783 .top(px(top))
784 .h(px(height))
785 .left(relative(width * block.lane as f32))
786 .w(relative(width))
787 .px(px(BLOCK_GAP))
788 .child(
789 h_flex()
790 .size_full()
791 .items_start()
792 .overflow_hidden()
793 .rounded(px(6.))
794 .bg(event_fill(look, color))
795 .when(event.cancelled, |block| block.opacity(0.6))
796 .cursor_pointer()
797 .children(status_bar(look, color))
798 .child(
799 div()
800 .flex_1()
801 .min_w_0()
802 .pl(px(5.))
803 .pr(px(4.))
804 .h_full()
805 .py(px(pad_y))
806 .overflow_hidden()
807 .text_size(px(title_size))
808 .line_height(px(title_line))
809 .text_color(detail_color)
810 .line_clamp(lines)
811 .text_ellipsis()
812 .child(title_and_organizer(event, title_color)),
813 )
814 .when(event.series, |block| {
815 block.child(div().flex_none().pt(px(pad_y + 1.)).pr(px(4.)).child(icon(
816 IconName::Repeat,
817 12.,
818 detail_color,
819 )))
820 })
821 .when(can_join, |block| {
822 block.child(
823 div().flex_none().pr(px(4.)).pt(px(3.)).child(
824 Button::new(SharedString::from(format!(
825 "calendar-join-{}-{}",
826 event.object_id, day
827 )))
828 .xsmall()
829 .primary()
830 .label(tr("common.join"))
831 .on_click(move |_, _, cx| {
832 cx.stop_propagation();
833 join_state.update(cx, |state, cx| {
834 state.join_calendar_meeting(
835 join_url.as_deref(),
836 &subject,
837 cx,
838 )
839 });
840 }),
841 ),
842 )
843 }),
844 )
845 .on_click(move |_, window, cx| {
846 open_calendar_event(open_state.clone(), open_event.clone(), window, cx);
847 })
848 .context_menu(move |menu, _, _| {
849 event_menu(menu, &menu_state, &menu_event, send_response)
850 })
851 }
852
853 #[allow(clippy::too_many_arguments)]
854 fn grid(
855 &self,
856 days: &[WeekDay],
857 events: &[CalendarEvent],
858 colors: &[Hsla],
859 layout: &WeekLayout,
860 work_minutes: (i64, i64),
861 today: NaiveDate,
862 now: DateTime<Utc>,
863 send_response: bool,
864 cx: &mut Context<Self>,
865 ) -> impl IntoElement {
866 let row = self.hour_height;
867 let steps = self.steps_per_hour;
868 let total_height = 24. * row;
869 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
870 let now_minute = {
871 let local = now.with_timezone(&Local);
872 local.hour() * 60 + local.minute()
873 };
874 let now_top = now_minute as f32 / 60. * row;
875 let today_shown = days.iter().any(|day| day.date == today);
876 let minute_y = |minute: i64| minute as f32 / 60. * row;
877 let selection = self.slot_selection;
878 let dragging = self.slot_drag.is_some();
879 div()
880 .id("calendar-grid")
881 .flex_1()
882 .min_h_0()
883 .overflow_y_scroll()
884 .track_scroll(&self.scroll)
885 .track_focus(&self.grid_focus)
886 .on_key_down(cx.listener(|view, event: &KeyDownEvent, _, cx| {
887 if event.keystroke.key == "escape" && view.slot_selection.is_some() {
888 view.clear_slot_selection(cx);
889 cx.stop_propagation();
890 }
891 }))
892 .on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))
893 // Inside the grid, or outside it and over meetings (whose hitboxes block
894 // the grid's): either way a left release ends the drag.
895 .on_mouse_up(
896 MouseButton::Left,
897 cx.listener(|view, _: &MouseUpEvent, _, cx| view.end_slot_drag(cx)),
898 )
899 .on_mouse_up_out(
900 MouseButton::Left,
901 cx.listener(|view, _: &MouseUpEvent, _, cx| view.end_slot_drag(cx)),
902 )
903 .when(dragging, |grid| grid.child(self.slot_drag_listener(cx)))
904 .child(
905 h_flex()
906 .h(px(total_height))
907 .w_full()
908 .child(
909 v_flex()
910 .w(px(GUTTER_WIDTH))
911 .flex_none()
912 .children((0..24).map(|hour| {
913 div()
914 .h(px(row))
915 .pt(px(2.))
916 .pr(px(8.))
917 .flex()
918 .justify_end()
919 .text_size(px(11.))
920 .text_color(theme::text_muted())
921 .when(hour > 0, |label| {
922 label.child(hour_label(hour, twelve_hour))
923 })
924 })),
925 )
926 .children(days.iter().map(|day| {
927 let work_day = layout.is_work_day(day.date.weekday());
928 let (work_start, work_end) = work_minutes;
929 let shade = |top: f32, height: f32| {
930 div()
931 .absolute()
932 .top(px(top))
933 .left_0()
934 .right_0()
935 .h(px(height))
936 .bg(theme::background().opacity(OFF_HOURS_OPACITY))
937 };
938 let shading = if work_day {
939 vec![
940 shade(0., minute_y(work_start)),
941 shade(minute_y(work_end), total_height - minute_y(work_end)),
942 ]
943 } else {
944 vec![shade(0., total_height)]
945 };
946 div()
947 .relative()
948 .flex_1()
949 .min_w_0()
950 .h_full()
951 .border_l_1()
952 .border_color(theme::border())
953 .child(self.slot_layer(day.date, cx))
954 .children(shading)
955 .children((1..24 * steps).map(|step| {
956 let line = div()
957 .absolute()
958 .top(px(step as f32 * row / steps as f32))
959 .left_0()
960 .right_0()
961 .h(px(1.));
962 if step % steps == 0 {
963 line.bg(theme::border())
964 } else {
965 line.bg(theme::border().opacity(MINOR_LINE_OPACITY))
966 }
967 }))
968 .children(
969 selection
970 .filter(|selection| selection.date == day.date)
971 .map(|selection| self.selection_block(&selection)),
972 )
973 .children(day.blocks.iter().map(|block| {
974 self.event_block(
975 block,
976 &events[block.event_index],
977 colors[block.event_index],
978 day.date,
979 send_response,
980 )
981 }))
982 .when(today_shown && day.date != today, |column| {
983 column.child(
984 div()
985 .absolute()
986 .top(px(now_top))
987 .left_0()
988 .right_0()
989 .h(px(1.))
990 .bg(theme::accent().opacity(NOW_ELSEWHERE_OPACITY)),
991 )
992 })
993 .when(day.date == today, |column| {
994 column
995 .child(
996 div()
997 .absolute()
998 .top(px(now_top - 1.))
999 .left_0()
1000 .right_0()
1001 .h(px(2.))
1002 .bg(theme::accent()),
1003 )
1004 .child(
1005 div()
1006 .absolute()
1007 .top(px(now_top - NOW_DOT_SIZE / 2.))
1008 .left_0()
1009 .size(px(NOW_DOT_SIZE))
1010 .rounded_full()
1011 .bg(theme::accent()),
1012 )
1013 })
1014 })),
1015 )
1016 }
1017}
1018
1019/// The one UTC offset the hour grid lays every shown day out with.
1020fn grid_offset() -> FixedOffset {
1021 Local::now().offset().fix()
1022}
1023
1024/// New meeting for a block picked on the grid.
1025fn open_meeting_for(
1026 state: Entity<AppState>,
1027 picked: SlotSelection,
1028 window: &mut Window,
1029 cx: &mut App,
1030) {
1031 let form = picked.form_times(grid_offset(), &Local);
1032 open_new_meeting_at(state, form.date, form.start, form.end, window, cx);
1033}
1034
1035/// Loading line and one notice per failed source, under the calendar header.
1036fn load_notices(
1037 state: &Entity<AppState>,
1038 failures: &[CalendarLoadFailure],
1039 loading: bool,
1040) -> Vec<Div> {
1041 let mut rows = Vec::new();
1042 if loading {
1043 rows.push(
1044 h_flex()
1045 .flex_none()
1046 .px(px(16.))
1047 .pb(px(6.))
1048 .text_size(px(12.))
1049 .text_color(theme::text_muted())
1050 .child(tr("calendar.view.loading")),
1051 );
1052 }
1053 for failure in failures {
1054 let action = state.clone();
1055 let sign_in = failure.sign_in;
1056 let mut args = std::collections::HashMap::new();
1057 args.insert("source".to_owned(), failure.source.label().to_owned());
1058 let label = if sign_in {
1059 tr("auth.sign_in")
1060 } else {
1061 tr("common.retry")
1062 };
1063 rows.push(
1064 h_flex()
1065 .flex_none()
1066 .mx(px(16.))
1067 .mb(px(6.))
1068 .px(px(12.))
1069 .py(px(6.))
1070 .gap(px(12.))
1071 .items_center()
1072 .rounded(px(6.))
1073 .bg(theme::red_tint())
1074 .text_size(px(13.))
1075 .text_color(theme::text())
1076 .child(
1077 div()
1078 .flex_1()
1079 .min_w_0()
1080 .truncate()
1081 .child(crate::i18n::tr_args("calendar.view.source_failed", &args)),
1082 )
1083 .child(
1084 Button::new(SharedString::from(format!(
1085 "calendar-retry-{}",
1086 failure.source.label()
1087 )))
1088 .xsmall()
1089 .outline()
1090 .label(label)
1091 .tooltip(failure.message.clone())
1092 .on_click(move |_, _, cx| {
1093 action.update(cx, |state, cx| {
1094 if sign_in {
1095 state.connect_google_calendar(cx);
1096 } else {
1097 state.retry_calendar_week(cx);
1098 }
1099 })
1100 }),
1101 ),
1102 );
1103 }
1104 rows
1105}
1106
1107fn event_menu(
1108 menu: PopupMenu,
1109 state: &Entity<AppState>,
1110 event: &CalendarEvent,
1111 send_response: bool,
1112) -> PopupMenu {
1113 let mut menu = menu;
1114 if let Some(join_url) = event
1115 .join_url
1116 .clone()
1117 .filter(|_| event.online && !event.cancelled)
1118 {
1119 let (join_state, subject) = (state.clone(), event.subject.clone());
1120 menu = menu.item(
1121 PopupMenuItem::new(tr("common.join"))
1122 .icon(IconName::Video)
1123 .on_click(move |_, _, cx| {
1124 join_state.update(cx, |state, cx| {
1125 state.join_calendar_meeting(Some(&join_url), &subject, cx)
1126 })
1127 }),
1128 );
1129 }
1130 if let Some(join_url) = event.join_url.as_deref().filter(|_| event.online) {
1131 let info = join_info_text(join_url, event.dial_in.as_ref());
1132 menu = menu.item(
1133 PopupMenuItem::new(tr("calendar.view.copy_join_info"))
1134 .icon(IconName::Copy)
1135 .on_click(move |_, _, cx| {
1136 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
1137 }),
1138 );
1139 }
1140 if let Some(thread_id) = event.thread_id.clone() {
1141 let chat_state = state.clone();
1142 menu = menu.item(
1143 PopupMenuItem::new(tr("calendar.view.chat_with_participants"))
1144 .icon(IconName::MessageSquare)
1145 .on_click(move |_, _, cx| {
1146 chat_state.update(cx, |state, cx| {
1147 state.open_meeting_chat(Some(&thread_id), cx)
1148 })
1149 }),
1150 );
1151 }
1152 if event.response == ResponseType::Organizer || event.organizer_name.is_none() {
1153 return menu;
1154 }
1155 rsvp_menu(
1156 menu.separator(),
1157 state,
1158 &event.object_id,
1159 event.response,
1160 send_response,
1161 )
1162}
1163
1164fn event_fill(look: EventLook, color: Hsla) -> Hsla {
1165 match look {
1166 EventLook::Busy => color.opacity(BUSY_FILL_OPACITY),
1167 EventLook::Free | EventLook::Tentative => color.opacity(FREE_FILL_OPACITY),
1168 }
1169}
1170
1171fn status_bar(look: EventLook, color: Hsla) -> Option<Div> {
1172 let bar = div().flex_none().w(px(STATUS_BAR_WIDTH)).h_full();
1173 match look {
1174 EventLook::Busy => Some(bar.bg(color)),
1175 EventLook::Tentative => Some(
1176 bar.bg(color.opacity(BUSY_FILL_OPACITY))
1177 .child(
1178 div()
1179 .size_full()
1180 .bg(pattern_slash(color, HATCH_STRIPE, HATCH_GAP)),
1181 ),
1182 ),
1183 EventLook::Free => None,
1184 }
1185}
1186
1187/// "Daily Standup Zulal Fouque": bold title, organizer right after it on the same line.
1188fn title_and_organizer(event: &CalendarEvent, title_color: Hsla) -> StyledText {
1189 let title = event_title(event);
1190 let text = match event.organizer_name.as_deref() {
1191 Some(organizer) if !organizer.is_empty() => format!("{title} {organizer}"),
1192 _ => title.clone(),
1193 };
1194 StyledText::new(text).with_highlights([(
1195 0..title.len(),
1196 HighlightStyle {
1197 color: Some(title_color),
1198 font_weight: Some(FontWeight::SEMIBOLD),
1199 ..Default::default()
1200 },
1201 )])
1202}
1203
1204fn event_title(event: &CalendarEvent) -> String {
1205 let subject = if event.cancelled {
1206 format!("{}{}", tr("calendar.peek.canceled_prefix"), event.subject)
1207 } else {
1208 event.subject.clone()
1209 };
1210 let label = source_label(event);
1211 if label.is_empty() {
1212 subject
1213 } else {
1214 format!("{subject} · {label}")
1215 }
1216}
1217
1218fn source_label(event: &CalendarEvent) -> String {
1219 let mut sources = event.sources.clone();
1220 if sources.is_empty() {
1221 sources.push(event.source);
1222 }
1223 sources.sort_by_key(|source| source.label());
1224 sources.dedup();
1225 if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
1226 return String::new();
1227 }
1228 sources
1229 .iter()
1230 .map(|source| source.label())
1231 .collect::<Vec<_>>()
1232 .join("+")
1233}
1234
1235impl Render for CalendarView {
1236 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1237 let window_width = f32::from(window.viewport_size().width);
1238 let compact = window_width < COMPACT_HEADER_WIDTH;
1239 self.sync_follow_from_state(window, cx);
1240 let state = self.state.read(cx);
1241 let start = state.calendar_start();
1242 let events = state.calendar_week.events.clone();
1243 let send_response = state.rsvp_send_response;
1244 let failures = state.calendar_week.failures.clone();
1245 let loading = state.calendar_week.loading && events.is_empty();
1246 let offset = grid_offset();
1247 let span = state.calendar_week.span;
1248 let layout = state.calendar_layout();
1249 let dates = state.calendar_dates();
1250 let days = week_days(&events, &dates, offset);
1251 // A picked block goes away once its day scrolls out of view or Month shows.
1252 if self.slot_selection.is_some_and(|picked| {
1253 span == CalendarSpan::Month || !picked.fits(&dates, self.step_minutes())
1254 }) {
1255 self.slot_selection = None;
1256 self.slot_drag = None;
1257 }
1258 let today = Local::now().date_naive();
1259 let now = Utc::now();
1260 let accounts = state.calendar_accounts();
1261 let colors: Vec<Hsla> = events
1262 .iter()
1263 .map(|event| theme::calendar_color(calendar_index(event, &accounts)))
1264 .collect();
1265 let work_minutes = state.calendar_prefs.work_hours.minute_range();
1266 let show_picker = !compact && !state.calendar_prefs.pane_hidden;
1267 // Width left for the header: window minus rail, island gaps and the pane.
1268 let header_width = window_width
1269 - app_ui_kit::layout::RAIL_WIDTH
1270 - 2. * app_ui_kit::layout::ISLAND_GAP
1271 - if show_picker {
1272 calendar_picker::PICKER_WIDTH
1273 } else {
1274 0.
1275 };
1276 let labels = header_labels(header_width);
1277 h_flex()
1278 .debug_selector(|| "shell/islands/calendar".into())
1279 .flex_1()
1280 .w_full()
1281 .min_w_0()
1282 .h_full()
1283 .rounded(px(10.))
1284 .bg(theme::surface())
1285 .overflow_hidden()
1286 .when(show_picker, |row| {
1287 row.child(calendar_picker::render(&self.state, cx))
1288 })
1289 .child(
1290 v_flex()
1291 .flex_1()
1292 .min_w_0()
1293 .h_full()
1294 .child(self.header(start, span, &dates, &layout, compact, labels))
1295 .children(load_notices(&self.state, &failures, loading))
1296 .children(meeting_proposal_cards(cx))
1297 .map(|calendar| {
1298 if span == CalendarSpan::Month {
1299 calendar.child(month_grid(
1300 &self.state,
1301 start,
1302 &days,
1303 &events,
1304 &colors,
1305 today,
1306 offset,
1307 layout.weekdays(),
1308 ))
1309 } else {
1310 calendar
1311 .child(self.day_headers(&days, today))
1312 .children(self.all_day_row(&days, &events, &colors, send_response))
1313 .child(self.grid(
1314 &days,
1315 &events,
1316 &colors,
1317 &layout,
1318 work_minutes,
1319 today,
1320 now,
1321 send_response,
1322 cx,
1323 ))
1324 }
1325 }),
1326 )
1327 }
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332 use super::header_labels;
1333
1334 #[test]
1335 fn header_buttons_drop_their_text_as_the_header_narrows() {
1336 let wide = header_labels(1300.);
1337 assert!(wide.primary && wide.secondary);
1338 let middle = header_labels(900.);
1339 assert!(middle.primary && !middle.secondary);
1340 let narrow = header_labels(600.);
1341 assert!(!narrow.primary && !narrow.secondary);
1342 }
1343}