BlueGit

ict rusty-teams

Files

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

profile_card.rs

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