BlueGit

ict rusty-teams

Files

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

profile_card.rs

profile_card.rs 25.3 KiB Download Raw
1use std::sync::Arc;
2
3use chrono::Utc;
4use gpui_kit::assets::IconName;
5use gpui_kit::base::GlobalState;
6use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10
11use super::avatar::{person_avatar, with_presence};
12use super::new_chat::Pick;
13use super::new_meeting_dialog::open_new_meeting_with;
14use super::widgets::icon;
15use crate::app_state::{AppHandle, AppState};
16use crate::data::{Presence, PresenceKind, presence_kind_of};
17use crate::people::resolve_names;
18use crate::profile_model::{
19 ContactKind, ContactRow, StatusBox, contact_rows, has_organization, local_time_label,
20 mailto_url, status_box, status_line, work_location_label,
21};
22use crate::theme::{self, ElevatedSurface as _};
23
24const CARD_WIDTH: f32 = 340.;
25const CARD_RADIUS: f32 = 10.;
26const CARD_PADDING: f32 = 16.;
27const CARD_GAP: f32 = 12.;
28const CARD_MARGIN: f32 = 8.;
29const CLICK_OFFSET: f32 = 4.;
30const PHOTO_SIZE: f32 = 56.;
31const PERSON_ROW_AVATAR: f32 = 22.;
32const STATUS_LINES: usize = 3;
33const REPORTS_MAX_HEIGHT: f32 = 168.;
34const ACTION_HEIGHT: f32 = 30.;
35const SKELETON_HEIGHT: f32 = 10.;
36const SCHEDULE_MEETING: &str = "Schedule meeting";
37const EMAIL: &str = "Email";
38const COPY_EMAIL: &str = "Copy email";
39
40pub enum ProfileCardEvent {
41 Close,
42}
43
44pub struct ProfileCard {
45 app: Entity<AppState>,
46 user_id: String,
47 history: Vec<String>,
48 anchor: Point<Pixels>,
49 contact_open: bool,
50 organization_open: bool,
51 reports_open: bool,
52 focus_handle: FocusHandle,
53 _observation: Subscription,
54}
55
56impl EventEmitter<ProfileCardEvent> for ProfileCard {}
57
58pub fn open_profile(user_id: &str, position: Point<Pixels>, cx: &mut App) {
59 let Some(handle) = cx.try_global::<AppHandle>() else {
60 return;
61 };
62 let (app, user_id) = (handle.0.clone(), user_id.to_owned());
63 app.update(cx, |state, cx| {
64 state.open_profile_card(&user_id, position, cx)
65 });
66}
67
68/// `true` when the link was a profile link and has been handled.
69pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bool {
70 match url.strip_prefix(PROFILE_LINK_PREFIX) {
71 Some(user_id) => {
72 open_profile(user_id, position, cx);
73 true
74 }
75 None => false,
76 }
77}
78
79pub fn opens_profile(element: Stateful<Div>, user_id: Option<&str>) -> Stateful<Div> {
80 match user_id {
81 Some(user_id) => {
82 let user_id = user_id.to_owned();
83 element.cursor_pointer().on_click(move |event, _, cx| {
84 cx.stop_propagation();
85 open_profile(&user_id, event.position(), cx)
86 })
87 }
88 None => element,
89 }
90}
91
92impl ProfileCard {
93 pub fn new(
94 app: Entity<AppState>,
95 user_id: String,
96 anchor: Point<Pixels>,
97 window: &mut Window,
98 cx: &mut Context<Self>,
99 ) -> Self {
100 let focus_handle = cx.focus_handle();
101 window.focus(&focus_handle, cx);
102 let observation = cx.observe(&app, |_, _, cx| cx.notify());
103 ProfileCard {
104 app,
105 user_id,
106 history: Vec::new(),
107 anchor,
108 contact_open: true,
109 organization_open: true,
110 reports_open: false,
111 focus_handle,
112 _observation: observation,
113 }
114 }
115
116 pub fn move_to(&mut self, user_id: String, anchor: Point<Pixels>, cx: &mut Context<Self>) {
117 self.history.clear();
118 self.anchor = anchor;
119 self.show(user_id, false, cx);
120 }
121
122 fn show(&mut self, user_id: String, remember: bool, cx: &mut Context<Self>) {
123 if remember {
124 self.history
125 .push(std::mem::replace(&mut self.user_id, user_id));
126 } else {
127 self.user_id = user_id;
128 }
129 self.reports_open = false;
130 let id = self.user_id.clone();
131 self.app.update(cx, |state, cx| {
132 state.request_profile(&id, false, cx);
133 state.request_avatars(vec![id.clone()], cx);
134 });
135 cx.notify();
136 }
137
138 fn go_back(&mut self, cx: &mut Context<Self>) {
139 if let Some(previous) = self.history.pop() {
140 self.show(previous, false, cx);
141 }
142 }
143
144 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
145 if event.keystroke.key == "escape" {
146 cx.emit(ProfileCardEvent::Close);
147 }
148 }
149
150 fn display_name(&self, profile: Option<&PersonProfile>, cx: &App) -> String {
151 profile
152 .and_then(|profile| profile.display_name.clone())
153 .or_else(|| {
154 resolve_names(self.app.read(cx), std::slice::from_ref(&self.user_id))
155 .remove(&self.user_id)
156 })
157 .unwrap_or_else(|| "Unknown person".to_owned())
158 }
159
160 fn presence(&self, profile: Option<&PersonProfile>, cx: &App) -> Presence {
161 let directory = self.app.read(cx).directory.presence_of(&self.user_id);
162 match (directory, profile.and_then(|profile| profile.availability)) {
163 (Presence::Live(kind), _) if kind != PresenceKind::Unknown => directory,
164 (_, Some(availability)) => Presence::Live(presence_kind_of(availability)),
165 _ => directory,
166 }
167 }
168
169 fn header(&self, profile: Option<&PersonProfile>, failed: bool, cx: &App) -> Div {
170 let name = self.display_name(profile, cx);
171 let presence = self.presence(profile, cx);
172 let directory = &self.app.read(cx).directory;
173 let photo = with_presence(
174 person_avatar(directory, Some(&self.user_id), &name, PHOTO_SIZE),
175 presence,
176 PHOTO_SIZE,
177 theme::surface_raised(),
178 );
179 let availability = directory.status_label(&self.user_id, presence);
180 let local_time = profile.and_then(|profile| local_time_label(profile, Utc::now()));
181 let subline = status_line(availability, local_time.as_deref());
182 let details = v_flex()
183 .gap(px(1.))
184 .children(profile.into_iter().flat_map(|profile| {
185 [&profile.job_title, &profile.department]
186 .into_iter()
187 .flatten()
188 .filter(|text| !text.trim().is_empty())
189 .map(|text| muted_line(text.clone()))
190 .collect::<Vec<_>>()
191 }));
192 let work_location = profile
193 .and_then(|profile| profile.work_location)
194 .map(|location| {
195 let glyph = match location.kind {
196 WorkLocationKind::Office => IconName::Building2,
197 WorkLocationKind::Remote => IconName::House,
198 };
199 h_flex()
200 .gap(px(5.))
201 .items_center()
202 .child(icon(glyph, 13., theme::text_muted()))
203 .child(muted_line(work_location_label(location).to_owned()))
204 });
205 let loading = profile.is_none() && !failed;
206 h_flex().gap(px(12.)).items_center().child(photo).child(
207 v_flex()
208 .flex_1()
209 .min_w_0()
210 .gap(px(2.))
211 .child(
212 div()
213 .truncate()
214 .text_size(px(15.))
215 .font_weight(FontWeight::SEMIBOLD)
216 .text_color(theme::text())
217 .child(name),
218 )
219 .when(!subline.is_empty(), |column| {
220 column.child(muted_line(subline))
221 })
222 .children(work_location)
223 .child(details)
224 .when(loading, |column| column.child(skeleton(0.6))),
225 )
226 }
227
228 fn status_box(&self, status: &StatusBox) -> AnyElement {
229 let (background, foreground) = if status.out_of_office {
230 (theme::amber().opacity(0.12), theme::amber())
231 } else {
232 (theme::surface(), theme::text_soft())
233 };
234 let full_text = status.text.clone();
235 div()
236 .id("profile-status")
237 .w_full()
238 .px(px(10.))
239 .py(px(8.))
240 .rounded(px(6.))
241 .bg(background)
242 .text_color(foreground)
243 .text_size(px(12.))
244 .line_height(relative(1.4))
245 .child(
246 div()
247 .line_clamp(STATUS_LINES)
248 .text_ellipsis()
249 .child(status.text.clone()),
250 )
251 .tooltip(move |window, cx| Tooltip::new(full_text.clone()).build(window, cx))
252 .into_any_element()
253 }
254
255 fn actions(&self, email: Option<String>, cx: &mut Context<Self>) -> Div {
256 let is_me = self
257 .app
258 .read(cx)
259 .directory
260 .me
261 .as_ref()
262 .is_some_and(|me| me.user_id == self.user_id);
263 let profile = self
264 .app
265 .read(cx)
266 .profiles
267 .get(&self.user_id)
268 .and_then(|entry| entry.profile.clone());
269 let name = self.display_name(profile.as_deref(), cx);
270 let user_id = self.user_id.clone();
271 let (mail_email, copy_email) = (email.clone(), email.clone());
272 let invitee = Pick {
273 user_id: user_id.clone(),
274 name: name.clone(),
275 mail: email,
276 };
277 let chat_id = user_id.clone();
278 let (video_id, audio_id) = (user_id.clone(), user_id.clone());
279 h_flex()
280 .gap(px(8.))
281 .when(!is_me, |row| {
282 row.child(
283 action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
284 cx.listener(move |this, _, _, cx| {
285 let user_id = chat_id.clone();
286 this.app
287 .update(cx, |state, cx| state.open_chat_with(&user_id, cx));
288 cx.emit(ProfileCardEvent::Close);
289 }),
290 ),
291 )
292 .child(
293 icon_action(
294 "profile-video-call",
295 IconName::Video,
296 video_call_tooltip(&name),
297 )
298 .on_click(cx.listener(move |this, _, _, cx| {
299 let user_id = video_id.clone();
300 this.app
301 .update(cx, |state, cx| state.call_person(&user_id, true, cx));
302 cx.emit(ProfileCardEvent::Close);
303 })),
304 )
305 .child(
306 icon_action(
307 "profile-audio-call",
308 IconName::Phone,
309 audio_call_tooltip(&name),
310 )
311 .on_click(cx.listener(move |this, _, _, cx| {
312 let user_id = audio_id.clone();
313 this.app
314 .update(cx, |state, cx| state.call_person(&user_id, false, cx));
315 cx.emit(ProfileCardEvent::Close);
316 })),
317 )
318 .child(
319 icon_action(
320 "profile-schedule-meeting",
321 IconName::Calendar,
322 SCHEDULE_MEETING.to_owned(),
323 )
324 .on_click(cx.listener(move |this, _, window, cx| {
325 open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);
326 cx.emit(ProfileCardEvent::Close);
327 })),
328 )
329 })
330 .when_some(mail_email, |row, address| {
331 row.child(
332 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
333 cx.listener(move |_, _, _, cx| {
334 cx.open_url(&mailto_url(&address));
335 cx.emit(ProfileCardEvent::Close);
336 }),
337 ),
338 )
339 })
340 .when_some(copy_email, |row, address| {
341 row.child(
342 icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())
343 .on_click(cx.listener(move |this, _, _, cx| {
344 this.app
345 .update(cx, |state, cx| state.copy_profile_email(&address, cx));
346 cx.emit(ProfileCardEvent::Close);
347 })),
348 )
349 })
350 }
351
352 fn section_header(
353 &self,
354 id: &'static str,
355 label: &'static str,
356 open: bool,
357 cx: &mut Context<Self>,
358 ) -> Stateful<Div> {
359 h_flex()
360 .id(id)
361 .gap(px(4.))
362 .items_center()
363 .cursor_pointer()
364 .text_size(px(12.))
365 .font_weight(FontWeight::SEMIBOLD)
366 .text_color(theme::text_muted())
367 .child(icon(
368 if open {
369 IconName::ChevronDown
370 } else {
371 IconName::ChevronRight
372 },
373 14.,
374 theme::text_muted(),
375 ))
376 .child(label)
377 .on_click(cx.listener(move |this, _, _, cx| {
378 match id {
379 "profile-contact-header" => this.contact_open = !this.contact_open,
380 _ => this.organization_open = !this.organization_open,
381 }
382 cx.notify();
383 }))
384 }
385
386 fn contact_section(&self, rows: Vec<ContactRow>, cx: &mut Context<Self>) -> Div {
387 let open = self.contact_open;
388 v_flex()
389 .gap(px(6.))
390 .child(self.section_header("profile-contact-header", "Contact", open, cx))
391 .when(open, |section| {
392 section.children(rows.into_iter().map(contact_row))
393 })
394 }
395
396 fn person_row(
397 &self,
398 id: String,
399 person: &OrgPerson,
400 caption: Option<&'static str>,
401 cx: &mut Context<Self>,
402 ) -> Stateful<Div> {
403 let name = person.display_name.clone().unwrap_or_default();
404 let subtitle = caption
405 .map(str::to_owned)
406 .or_else(|| person.job_title.clone())
407 .filter(|text| !text.is_empty());
408 let target = person.id.clone();
409 let directory = &self.app.read(cx).directory;
410 h_flex()
411 .id(ElementId::Name(id.into()))
412 .gap(px(8.))
413 .px(px(4.))
414 .py(px(3.))
415 .items_center()
416 .rounded(px(6.))
417 .cursor_pointer()
418 .hover(|row| row.bg(theme::row_hover()))
419 .child(person_avatar(
420 directory,
421 Some(&person.id),
422 &name,
423 PERSON_ROW_AVATAR,
424 ))
425 .child(
426 div()
427 .truncate()
428 .text_size(px(12.5))
429 .text_color(theme::text())
430 .child(name),
431 )
432 .children(
433 subtitle.map(|text| div().flex_1().min_w_0().truncate().child(muted_text(text))),
434 )
435 .on_click(cx.listener(move |this, _, _, cx| this.show(target.clone(), true, cx)))
436 }
437
438 fn organization_section(&self, profile: &PersonProfile, cx: &mut Context<Self>) -> Div {
439 let open = self.organization_open;
440 let mut section = v_flex().gap(px(4.)).child(self.section_header(
441 "profile-organization-header",
442 "Organization",
443 open,
444 cx,
445 ));
446 if !open {
447 return section;
448 }
449 if let Some(manager) = &profile.manager {
450 section = section.child(self.person_row(
451 "profile-manager".to_owned(),
452 manager,
453 Some("Manager"),
454 cx,
455 ));
456 }
457 let count = profile.direct_reports.len();
458 if count > 0 {
459 let label = match count {
460 1 => "1 direct report".to_owned(),
461 count => format!("{count} direct reports"),
462 };
463 let reports_open = self.reports_open;
464 section = section.child(
465 h_flex()
466 .id("profile-reports-toggle")
467 .gap(px(4.))
468 .px(px(4.))
469 .py(px(3.))
470 .items_center()
471 .cursor_pointer()
472 .text_size(px(12.5))
473 .text_color(theme::text_soft())
474 .child(label)
475 .child(icon(
476 if reports_open {
477 IconName::ChevronDown
478 } else {
479 IconName::ChevronRight
480 },
481 14.,
482 theme::text_muted(),
483 ))
484 .on_click(cx.listener(|this, _, _, cx| {
485 this.reports_open = !this.reports_open;
486 cx.notify();
487 })),
488 );
489 if reports_open {
490 let rows: Vec<Stateful<Div>> = profile
491 .direct_reports
492 .iter()
493 .enumerate()
494 .map(|(index, person)| {
495 self.person_row(format!("profile-report-{index}"), person, None, cx)
496 })
497 .collect();
498 section = section.child(
499 v_flex()
500 .id("profile-reports")
501 .max_h(px(REPORTS_MAX_HEIGHT))
502 .overflow_y_scroll()
503 .children(rows),
504 );
505 }
506 }
507 section
508 }
509
510 fn loading_sections(&self) -> Div {
511 v_flex()
512 .gap(px(8.))
513 .child(skeleton(1.))
514 .child(skeleton(0.8))
515 .child(skeleton(0.5))
516 }
517
518 fn failure(&self, cx: &mut Context<Self>) -> Div {
519 h_flex()
520 .gap(px(6.))
521 .text_size(px(12.))
522 .text_color(theme::red_soft())
523 .child("Profile details could not be loaded.")
524 .child(
525 div()
526 .id("profile-retry")
527 .cursor_pointer()
528 .underline()
529 .text_color(theme::red_tint())
530 .child("Retry")
531 .on_click(cx.listener(|this, _, _, cx| {
532 let id = this.user_id.clone();
533 this.app
534 .update(cx, |state, cx| state.request_profile(&id, true, cx));
535 })),
536 )
537 }
538
539 fn body(&self, entry_state: EntryState, cx: &mut Context<Self>) -> Vec<AnyElement> {
540 let EntryState { profile, failed } = entry_state;
541 let mut parts: Vec<AnyElement> = Vec::new();
542 let Some(profile) = profile else {
543 parts.push(self.actions(None, cx).into_any_element());
544 parts.push(if failed {
545 self.failure(cx).into_any_element()
546 } else {
547 self.loading_sections().into_any_element()
548 });
549 return parts;
550 };
551 if let Some(status) = status_box(&profile) {
552 parts.push(self.status_box(&status));
553 }
554 parts.push(self.actions(profile.email.clone(), cx).into_any_element());
555 let rows = contact_rows(&profile);
556 if !rows.is_empty() {
557 parts.push(self.contact_section(rows, cx).into_any_element());
558 }
559 if has_organization(&profile) {
560 parts.push(self.organization_section(&profile, cx).into_any_element());
561 }
562 if failed {
563 parts.push(self.failure(cx).into_any_element());
564 }
565 parts
566 }
567}
568
569struct EntryState {
570 profile: Option<Arc<PersonProfile>>,
571 failed: bool,
572}
573
574fn muted_text(text: String) -> Div {
575 div()
576 .text_size(px(12.))
577 .text_color(theme::text_muted())
578 .child(text)
579}
580
581fn muted_line(text: String) -> Div {
582 muted_text(text).truncate()
583}
584
585fn skeleton(width_ratio: f32) -> Div {
586 div()
587 .h(px(SKELETON_HEIGHT))
588 .w(relative(width_ratio))
589 .rounded(px(4.))
590 .bg(theme::popup_hover())
591}
592
593fn contact_row(row: ContactRow) -> Div {
594 let glyph = match row.kind {
595 ContactKind::Email => IconName::Mail,
596 ContactKind::WorkPhone => IconName::Phone,
597 ContactKind::MobilePhone => IconName::Smartphone,
598 ContactKind::Office => IconName::MapPin,
599 };
600 h_flex()
601 .gap(px(8.))
602 .px(px(4.))
603 .items_center()
604 .child(icon(glyph, 14., theme::text_muted()))
605 .child(
606 div()
607 .flex_1()
608 .min_w_0()
609 .truncate()
610 .text_size(px(12.5))
611 .text_color(theme::text())
612 .child(row.value),
613 )
614}
615
616pub fn video_call_tooltip(name: &str) -> String {
617 format!("Start a video call with {name}")
618}
619
620pub fn audio_call_tooltip(name: &str) -> String {
621 format!("Start an audio call with {name}")
622}
623
624fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {
625 div()
626 .id(id)
627 .size(px(ACTION_HEIGHT))
628 .flex()
629 .flex_none()
630 .items_center()
631 .justify_center()
632 .rounded(px(6.))
633 .cursor_pointer()
634 .bg(theme::popup_hover())
635 .hover(|button| button.opacity(0.9))
636 .child(icon(glyph, 14., theme::text_soft()))
637 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
638}
639
640fn action_button(
641 id: &'static str,
642 label: &'static str,
643 glyph: IconName,
644 filled: bool,
645) -> Stateful<Div> {
646 let (foreground, background) = if filled {
647 (theme::on_accent(), theme::accent())
648 } else {
649 (theme::text_soft(), theme::popup_hover())
650 };
651 h_flex()
652 .id(id)
653 .h(px(ACTION_HEIGHT))
654 .px(px(10.))
655 .gap(px(6.))
656 .items_center()
657 .justify_center()
658 .rounded(px(6.))
659 .cursor_pointer()
660 .bg(background)
661 .text_color(foreground)
662 .text_size(px(12.5))
663 .font_weight(FontWeight::SEMIBOLD)
664 .hover(|button| button.opacity(0.9))
665 .child(icon(glyph, 14., foreground))
666 .child(label)
667}
668
669impl Render for ProfileCard {
670 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
671 let entry_state = self
672 .app
673 .read(cx)
674 .profiles
675 .get(&self.user_id)
676 .map(|entry| EntryState {
677 profile: entry.profile.clone(),
678 failed: entry.failed,
679 })
680 .unwrap_or(EntryState {
681 profile: None,
682 failed: false,
683 });
684 let profile = entry_state.profile.clone();
685 let header = self.header(profile.as_deref(), entry_state.failed, cx);
686 let body = self.body(entry_state, cx);
687 let back = (!self.history.is_empty()).then(|| {
688 h_flex()
689 .id("profile-back")
690 .gap(px(4.))
691 .items_center()
692 .cursor_pointer()
693 .text_size(px(12.))
694 .text_color(theme::text_muted())
695 .hover(|button| button.text_color(theme::text()))
696 .child(icon(IconName::ArrowLeft, 14., theme::text_muted()))
697 .child("Back")
698 .on_click(cx.listener(|this, _, _, cx| this.go_back(cx)))
699 });
700 let card = v_flex()
701 .id("profile-card")
702 .track_focus(&self.focus_handle)
703 .w(px(CARD_WIDTH))
704 .p(px(CARD_PADDING))
705 .gap(px(CARD_GAP))
706 .rounded(px(CARD_RADIUS))
707 .flyout_surface()
708 .text_color(theme::text())
709 .occlude()
710 .on_key_down(cx.listener(Self::on_key_down))
711 .on_mouse_down(MouseButton::Left, |_, _, cx| {
712 GlobalState::suppress_text_selection(cx);
713 cx.stop_propagation();
714 })
715 .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
716 .children(back)
717 .child(header)
718 .children(body);
719 let offset = point(px(CLICK_OFFSET), px(CLICK_OFFSET));
720 div()
721 .id("profile-layer")
722 .absolute()
723 .top_0()
724 .left_0()
725 .size_full()
726 .occlude()
727 .on_mouse_down(
728 MouseButton::Left,
729 cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),
730 )
731 .on_mouse_down(
732 MouseButton::Right,
733 cx.listener(|_, _, _, cx| cx.emit(ProfileCardEvent::Close)),
734 )
735 .child(
736 deferred(
737 anchored()
738 .position(self.anchor + offset)
739 .anchor(Anchor::TopLeft)
740 .snap_to_window_with_margin(px(CARD_MARGIN))
741 .child(card),
742 )
743 .with_priority(2),
744 )
745 }
746}
747
748#[cfg(test)]
749mod tests {
750 use super::{audio_call_tooltip, video_call_tooltip};
751
752 #[test]
753 fn call_tooltips_use_the_teams_wording() {
754 assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");
755 assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");
756 }
757}