BlueGit

ict rusty-teams

Files

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

profile_card.rs

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