BlueGit

ict rusty-teams

Files

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

calendar_view.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
calendar_view.rs 27.9 KiB Download Raw
1use std::time::Duration;
2
3use app_base::format::{self, clock_format};
4use chatsvc::{CalendarEvent, ResponseType, join_info_text};
5use chrono::{DateTime, 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_month::month_grid;
16use super::join_dialog::open_join_with_id;
17use super::meeting_proposal_card::meeting_proposal_cards;
18use super::new_meeting_dialog::open_new_meeting;
19use super::rsvp_menu::rsvp_menu;
20use super::scroll_edge::scroll_offset;
21use crate::app_state::AppState;
22use crate::call::calendar_now::{
23 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
24 now_scroll_offset_y, offset_differs, shows_hour_grid,
25};
26use crate::call::join_available;
27use crate::call::week_grid::{
28 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
29};
30use crate::theme;
31
32const HOUR_HEIGHT: f32 = 120.;
33const QUARTERS_PER_HOUR: usize = 4;
34const QUARTER_LINE_OPACITY: f32 = 0.45;
35const GUTTER_WIDTH: f32 = 50.;
36const HEADER_HEIGHT: f32 = 52.;
37const DAY_HEADER_HEIGHT: f32 = 56.;
38const ALL_DAY_HEIGHT: f32 = 26.;
39const BLOCK_GAP: f32 = 2.;
40const CANCELED_PREFIX: &str = "Canceled: ";
41const COPY_JOIN_INFO: &str = "Copy join info";
42const COMPACT_HEADER_WIDTH: f32 = 960.;
43const BUSY_FILL_OPACITY: f32 = 0.28;
44const FREE_FILL_OPACITY: f32 = 0.12;
45const STATUS_BAR_WIDTH: f32 = 4.;
46const HATCH_STRIPE: f32 = 1.5;
47const HATCH_GAP: f32 = 2.5;
48const SMALL_TITLE_HEIGHT: f32 = 20.;
49const TODAY_MARK_HEIGHT: f32 = 3.;
50const NOW_DOT_SIZE: f32 = 8.;
51const CLOCK_TICK: Duration = Duration::from_secs(30);
52const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;
53
54pub struct CalendarView {
55 state: Entity<AppState>,
56 scroll: ScrollHandle,
57 follow_now: FollowNow,
58 seen_scroll_to_now: u64,
59 last_programmatic_offset: f32,
60 skip_manual_check: bool,
61 clock_running: bool,
62 _observation: Subscription,
63 _agent_observation: Option<Subscription>,
64}
65
66impl CalendarView {
67 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
68 let observation = cx.observe(&state, |_, _, cx| cx.notify());
69 let agent_observation =
70 crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
71 CalendarView {
72 state,
73 scroll: ScrollHandle::new(),
74 follow_now: FollowNow { active: true },
75 seen_scroll_to_now: 0,
76 last_programmatic_offset: 0.,
77 skip_manual_check: false,
78 clock_running: false,
79 _observation: observation,
80 _agent_observation: agent_observation,
81 }
82 }
83
84 fn grid_viewport_height(window: &Window) -> f32 {
85 (f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)
86 }
87
88 fn align_scroll_to_now(&mut self, window: &Window) {
89 let local = Local::now();
90 let offset = now_scroll_offset_y(
91 local.hour(),
92 local.minute(),
93 HOUR_HEIGHT,
94 Self::grid_viewport_height(window),
95 NOW_BIAS_FRACTION,
96 );
97 self.scroll.set_offset(point(px(0.), px(offset)));
98 self.last_programmatic_offset = offset;
99 self.skip_manual_check = true;
100 }
101
102 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
103 let (scroll_to_now, span, today_visible) = {
104 let state = self.state.read(cx);
105 let start = state.calendar_start();
106 let today = Local::now().date_naive();
107 let today_visible = start <= today
108 && today < start + chrono::Duration::days(state.calendar_week.span.days());
109 (
110 state.calendar_scroll_to_now,
111 state.calendar_week.span,
112 today_visible,
113 )
114 };
115 if !shows_hour_grid(span) {
116 self.stop_clock();
117 return;
118 }
119 self.ensure_clock(cx);
120 if scroll_to_now != self.seen_scroll_to_now {
121 self.seen_scroll_to_now = scroll_to_now;
122 self.follow_now.request_align();
123 }
124 if self.skip_manual_check {
125 self.skip_manual_check = false;
126 } else if self.follow_now.active
127 && offset_differs(
128 f32::from(scroll_offset(&self.scroll).y),
129 self.last_programmatic_offset,
130 MANUAL_SCROLL_EPSILON,
131 )
132 {
133 self.follow_now.note_manual_scroll();
134 }
135 if self.follow_now.should_follow(today_visible) {
136 self.align_scroll_to_now(window);
137 }
138 }
139
140 fn ensure_clock(&mut self, cx: &mut Context<Self>) {
141 if self.clock_running {
142 return;
143 }
144 self.clock_running = true;
145 cx.spawn(async move |this, cx| {
146 loop {
147 cx.background_executor().timer(CLOCK_TICK).await;
148 let keep = this
149 .update(cx, |view, cx| {
150 let span = view.state.read(cx).calendar_week.span;
151 if !shows_hour_grid(span) {
152 view.clock_running = false;
153 return false;
154 }
155 cx.notify();
156 true
157 })
158 .unwrap_or(false);
159 if !keep {
160 break;
161 }
162 }
163 })
164 .detach();
165 }
166
167 fn stop_clock(&mut self) {
168 self.clock_running = false;
169 }
170
171 fn on_grid_scroll_wheel(
172 &mut self,
173 _event: &ScrollWheelEvent,
174 _window: &mut Window,
175 cx: &mut Context<Self>,
176 ) {
177 self.follow_now.note_manual_scroll();
178 cx.notify();
179 }
180
181 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
182 let span_state = self.state.clone();
183 let label = |text: &'static str| (!compact).then_some(text);
184 let (today, back, forward) = (self.state.clone(), self.state.clone(), self.state.clone());
185 let (join_state, meet_state, new_state) =
186 (self.state.clone(), self.state.clone(), self.state.clone());
187 h_flex()
188 .h(px(HEADER_HEIGHT))
189 .flex_none()
190 .items_center()
191 .gap(px(8.))
192 .px(px(16.))
193 .child(
194 div()
195 .flex_none()
196 .text_size(px(16.))
197 .font_weight(FontWeight::BOLD)
198 .mr(px(8.))
199 .child("Calendar"),
200 )
201 .child(
202 Button::new("calendar-today")
203 .small()
204 .outline()
205 .icon(IconName::Calendar)
206 .when_some(label("Today"), |button, text| button.label(text))
207 .tooltip("Today")
208 .on_click(move |_, _, cx| {
209 today.update(cx, |state, cx| state.calendar_to_today(cx))
210 }),
211 )
212 .child(
213 Button::new("calendar-back")
214 .small()
215 .ghost()
216 .icon(IconName::ChevronLeft)
217 .tooltip(match span {
218 CalendarSpan::Day => "Go to previous day",
219 CalendarSpan::Month => "Go to previous month",
220 _ => "Go to previous week",
221 })
222 .on_click(move |_, _, cx| {
223 back.update(cx, |state, cx| state.shift_calendar_week(-1, cx))
224 }),
225 )
226 .child(
227 Button::new("calendar-forward")
228 .small()
229 .ghost()
230 .icon(IconName::ChevronRight)
231 .tooltip(match span {
232 CalendarSpan::Day => "Go to next day",
233 CalendarSpan::Month => "Go to next month",
234 _ => "Go to next week",
235 })
236 .on_click(move |_, _, cx| {
237 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
238 }),
239 )
240 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
241 &self.state,
242 span.title(start),
243 start,
244 span.days(),
245 if span == CalendarSpan::Month {
246 month_shown(start)
247 } else {
248 start
249 },
250 )))
251 .child(
252 Button::new("calendar-span")
253 .small()
254 .ghost()
255 .label(span.label())
256 .dropdown_caret(true)
257 .dropdown_menu(move |menu, _, _| {
258 CalendarSpan::ALL.iter().fold(menu, |menu, &choice| {
259 let state = span_state.clone();
260 menu.item(
261 PopupMenuItem::new(choice.label())
262 .checked(choice == span)
263 .on_click(move |_, _, cx| {
264 state.update(cx, |state, cx| {
265 state.set_calendar_span(choice, cx)
266 })
267 }),
268 )
269 })
270 }),
271 )
272 .child(
273 Button::new("calendar-join-id")
274 .small()
275 .outline()
276 .icon(IconName::Hash)
277 .when_some(label("Join with an ID"), |button, text| button.label(text))
278 .tooltip("Join with an ID")
279 .on_click(move |_, window, cx| {
280 open_join_with_id(join_state.clone(), window, cx)
281 }),
282 )
283 .child(
284 Button::new("calendar-meet-now")
285 .small()
286 .outline()
287 .icon(IconName::Video)
288 .when_some(label("Meet now"), |button, text| button.label(text))
289 .tooltip("Meet now")
290 .on_click(move |_, _, cx| {
291 meet_state.update(cx, |state, cx| state.start_meet_now(cx))
292 }),
293 )
294 .child(
295 Button::new("calendar-new-meeting")
296 .small()
297 .primary()
298 .icon(IconName::Plus)
299 .when_some(label("New meeting"), |button, text| button.label(text))
300 .tooltip("New meeting")
301 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
302 )
303 }
304
305 fn day_headers(&self, days: &[WeekDay], today: NaiveDate) -> impl IntoElement {
306 h_flex()
307 .h(px(DAY_HEADER_HEIGHT))
308 .flex_none()
309 .border_b_1()
310 .border_color(theme::border())
311 .child(div().w(px(GUTTER_WIDTH)).flex_none())
312 .children(days.iter().map(|day| {
313 let is_today = day.date == today;
314 let color = if is_today {
315 theme::accent_text()
316 } else {
317 theme::text_soft()
318 };
319 v_flex()
320 .relative()
321 .flex_1()
322 .min_w_0()
323 .h_full()
324 .justify_center()
325 .px(px(12.))
326 .border_l_1()
327 .border_color(theme::border())
328 .when(is_today, |header| {
329 header.child(
330 div()
331 .absolute()
332 .top_0()
333 .left_0()
334 .right_0()
335 .h(px(TODAY_MARK_HEIGHT))
336 .bg(theme::accent()),
337 )
338 })
339 .child(
340 div()
341 .text_size(px(20.))
342 .line_height(px(24.))
343 .text_color(color)
344 .child(format::calendar_day_number(day.date)),
345 )
346 .child(
347 div()
348 .text_size(px(12.))
349 .text_color(color)
350 .child(day.date.format("%a").to_string()),
351 )
352 }))
353 }
354
355 fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {
356 if days.iter().all(|day| day.all_day.is_empty()) {
357 return None;
358 }
359 Some(
360 h_flex()
361 .flex_none()
362 .border_b_1()
363 .border_color(theme::border())
364 .child(div().w(px(GUTTER_WIDTH)).flex_none())
365 .children(days.iter().map(|day| {
366 v_flex()
367 .flex_1()
368 .min_w_0()
369 .gap(px(BLOCK_GAP))
370 .p(px(BLOCK_GAP))
371 .border_l_1()
372 .border_color(theme::border())
373 .children(day.all_day.iter().map(|&index| {
374 div()
375 .h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
376 .px(px(6.))
377 .flex()
378 .items_center()
379 .rounded(px(4.))
380 .bg(event_fill(event_look(&events[index])))
381 .text_size(px(12.))
382 .truncate()
383 .child(event_title(&events[index]))
384 }))
385 })),
386 )
387 }
388
389 fn event_block(
390 &self,
391 block: &WeekBlock,
392 event: &CalendarEvent,
393 now: DateTime<Utc>,
394 send_response: bool,
395 ) -> impl IntoElement {
396 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
397 let height = ((block.end_minute - block.start_minute) as f32 / 60. * HOUR_HEIGHT
398 - BLOCK_GAP)
399 .max(14.);
400 let width = 1. / block.lanes as f32;
401 let compact = height < 36.;
402 let small = height < SMALL_TITLE_HEIGHT;
403 let look = event_look(event);
404 let can_join = event.online
405 && !event.cancelled
406 && event.join_url.is_some()
407 && join_available(event.start, event.end, now);
408 let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());
409 let (menu_state, menu_event) = (self.state.clone(), event.clone());
410 let (join_state, join_url, subject) = (
411 self.state.clone(),
412 event.join_url.clone(),
413 event.subject.clone(),
414 );
415 let (title_color, detail_color) = match look {
416 EventLook::Busy => (theme::text(), theme::text_soft()),
417 EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
418 };
419 div()
420 .id(SharedString::from(format!(
421 "calendar-event-{}",
422 event.object_id
423 )))
424 .absolute()
425 .top(px(top))
426 .h(px(height))
427 .left(relative(width * block.lane as f32))
428 .w(relative(width))
429 .px(px(BLOCK_GAP))
430 .child(
431 h_flex()
432 .size_full()
433 .items_start()
434 .overflow_hidden()
435 .rounded(px(4.))
436 .bg(event_fill(look))
437 .when(event.cancelled, |block| block.opacity(0.6))
438 .cursor_pointer()
439 .children(status_bar(look))
440 .child(
441 v_flex()
442 .flex_1()
443 .min_w_0()
444 .pl(px(5.))
445 .pr(px(4.))
446 .h_full()
447 .py(px(if compact { 1. } else { 4. }))
448 .when(compact, |body| body.justify_center())
449 .child(
450 div()
451 .text_size(px(if small { 10. } else { 12. }))
452 .line_height(px(if small { 13. } else { 16. }))
453 .font_weight(FontWeight::SEMIBOLD)
454 .text_color(title_color)
455 .when(compact, |title| title.truncate())
456 .when(!compact, |title| title.line_clamp(2))
457 .child(event_title(event)),
458 )
459 .when(!compact, |body| {
460 body.children(event.organizer_name.clone().map(|organizer| {
461 div()
462 .text_size(px(12.))
463 .line_height(px(16.))
464 .text_color(detail_color)
465 .truncate()
466 .child(organizer)
467 }))
468 }),
469 )
470 .when(can_join, |block| {
471 block.child(
472 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
473 Button::new(SharedString::from(format!(
474 "calendar-join-{}",
475 event.object_id
476 )))
477 .xsmall()
478 .primary()
479 .label("Join")
480 .on_click(move |_, _, cx| {
481 cx.stop_propagation();
482 join_state.update(cx, |state, cx| {
483 state.join_calendar_meeting(
484 join_url.as_deref(),
485 &subject,
486 cx,
487 )
488 });
489 }),
490 ),
491 )
492 }),
493 )
494 .on_click(move |_, _, cx| {
495 open_state.update(cx, |state, cx| {
496 state.open_meeting_chat(thread_id.as_deref(), cx)
497 });
498 })
499 .context_menu(move |menu, _, _| {
500 event_menu(menu, &menu_state, &menu_event, send_response)
501 })
502 }
503
504 fn grid(
505 &self,
506 days: &[WeekDay],
507 events: &[CalendarEvent],
508 today: NaiveDate,
509 now: DateTime<Utc>,
510 send_response: bool,
511 cx: &mut Context<Self>,
512 ) -> impl IntoElement {
513 let total_height = 24. * HOUR_HEIGHT;
514 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
515 let now_minute = {
516 let local = now.with_timezone(&Local);
517 local.hour() * 60 + local.minute()
518 };
519 div()
520 .id("calendar-grid")
521 .flex_1()
522 .min_h_0()
523 .overflow_y_scroll()
524 .track_scroll(&self.scroll)
525 .on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))
526 .child(
527 h_flex()
528 .h(px(total_height))
529 .w_full()
530 .child(
531 v_flex()
532 .w(px(GUTTER_WIDTH))
533 .flex_none()
534 .children((0..24).map(|hour| {
535 div()
536 .h(px(HOUR_HEIGHT))
537 .pt(px(4.))
538 .flex()
539 .justify_center()
540 .text_size(px(12.))
541 .text_color(theme::text_soft())
542 .when(hour > 0, |label| {
543 label.child(hour_label(hour, twelve_hour))
544 })
545 })),
546 )
547 .children(days.iter().map(|day| {
548 div()
549 .relative()
550 .flex_1()
551 .min_w_0()
552 .h_full()
553 .border_l_1()
554 .border_color(theme::border())
555 .children((1..24 * QUARTERS_PER_HOUR).map(|quarter| {
556 let line = div()
557 .absolute()
558 .top(
559 px(quarter as f32 * HOUR_HEIGHT / QUARTERS_PER_HOUR as f32),
560 )
561 .left_0()
562 .right_0();
563 if quarter % QUARTERS_PER_HOUR == 0 {
564 line.h(px(1.)).bg(theme::border())
565 } else {
566 line.h(px(1.))
567 .bg(theme::border().opacity(QUARTER_LINE_OPACITY))
568 }
569 }))
570 .children(day.blocks.iter().map(|block| {
571 self.event_block(
572 block,
573 &events[block.event_index],
574 now,
575 send_response,
576 )
577 }))
578 .when(day.date == today, |column| {
579 let now_top = now_minute as f32 / 60. * HOUR_HEIGHT;
580 column
581 .child(
582 div()
583 .absolute()
584 .top(px(now_top - 1.))
585 .left_0()
586 .right_0()
587 .h(px(2.))
588 .bg(theme::accent()),
589 )
590 .child(
591 div()
592 .absolute()
593 .top(px(now_top - NOW_DOT_SIZE / 2.))
594 .left_0()
595 .size(px(NOW_DOT_SIZE))
596 .rounded_full()
597 .bg(theme::accent()),
598 )
599 })
600 })),
601 )
602 }
603}
604
605fn event_menu(
606 menu: PopupMenu,
607 state: &Entity<AppState>,
608 event: &CalendarEvent,
609 send_response: bool,
610) -> PopupMenu {
611 let mut menu = menu;
612 if let Some(join_url) = event
613 .join_url
614 .clone()
615 .filter(|_| event.online && !event.cancelled)
616 {
617 let (join_state, subject) = (state.clone(), event.subject.clone());
618 menu = menu.item(PopupMenuItem::new("Join").icon(IconName::Video).on_click(
619 move |_, _, cx| {
620 join_state.update(cx, |state, cx| {
621 state.join_calendar_meeting(Some(&join_url), &subject, cx)
622 })
623 },
624 ));
625 }
626 if let Some(join_url) = event.join_url.as_deref().filter(|_| event.online) {
627 let info = join_info_text(join_url, event.dial_in.as_ref());
628 menu = menu.item(
629 PopupMenuItem::new(COPY_JOIN_INFO)
630 .icon(IconName::Copy)
631 .on_click(move |_, _, cx| {
632 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
633 }),
634 );
635 }
636 if let Some(thread_id) = event.thread_id.clone() {
637 let chat_state = state.clone();
638 menu = menu.item(
639 PopupMenuItem::new("Chat with participants")
640 .icon(IconName::MessageSquare)
641 .on_click(move |_, _, cx| {
642 chat_state.update(cx, |state, cx| {
643 state.open_meeting_chat(Some(&thread_id), cx)
644 })
645 }),
646 );
647 }
648 if event.response == ResponseType::Organizer || event.organizer_name.is_none() {
649 return menu;
650 }
651 rsvp_menu(
652 menu.separator(),
653 state,
654 &event.object_id,
655 event.response,
656 send_response,
657 )
658}
659
660fn event_fill(look: EventLook) -> Hsla {
661 match look {
662 EventLook::Busy => theme::accent().opacity(BUSY_FILL_OPACITY),
663 EventLook::Free | EventLook::Tentative => theme::accent().opacity(FREE_FILL_OPACITY),
664 }
665}
666
667fn status_bar(look: EventLook) -> Option<Div> {
668 let bar = div().flex_none().w(px(STATUS_BAR_WIDTH)).h_full();
669 match look {
670 EventLook::Busy => Some(bar.bg(theme::accent())),
671 EventLook::Tentative => Some(
672 bar.bg(theme::accent().opacity(BUSY_FILL_OPACITY)).child(
673 div()
674 .size_full()
675 .bg(pattern_slash(theme::accent(), HATCH_STRIPE, HATCH_GAP)),
676 ),
677 ),
678 EventLook::Free => None,
679 }
680}
681
682fn event_title(event: &CalendarEvent) -> String {
683 if event.cancelled {
684 format!("{CANCELED_PREFIX}{}", event.subject)
685 } else {
686 event.subject.clone()
687 }
688}
689
690impl Render for CalendarView {
691 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
692 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
693 self.sync_follow_from_state(window, cx);
694 let state = self.state.read(cx);
695 let start = state.calendar_start();
696 let events = state.calendar_week.events.clone();
697 let send_response = state.rsvp_send_response;
698 let offset = Local::now().offset().fix();
699 let span = state.calendar_week.span;
700 let days = week_days(&events, start, span.days(), offset);
701 let today = Local::now().date_naive();
702 let now = Utc::now();
703 v_flex()
704 .debug_selector(|| "shell/islands/calendar".into())
705 .flex_1()
706 .w_full()
707 .min_w_0()
708 .h_full()
709 .rounded(px(10.))
710 .bg(theme::surface())
711 .overflow_hidden()
712 .child(self.header(start, span, compact))
713 .children(meeting_proposal_cards(cx))
714 .map(|calendar| {
715 if span == CalendarSpan::Month {
716 calendar.child(month_grid(
717 &self.state,
718 start,
719 &days,
720 &events,
721 today,
722 offset,
723 ))
724 } else {
725 calendar
726 .child(self.day_headers(&days, today))
727 .children(self.all_day_row(&days, &events))
728 .child(self.grid(&days, &events, today, now, send_response, cx))
729 }
730 })
731 }
732}