BlueGit

ict rusty-teams

Files

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

transfer_picker.rs

transfer_picker.rs 12.0 KiB Download Raw
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 input::{Input, InputEvent, InputState},
7 v_flex,
8};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11
12use super::avatar::person_avatar;
13use super::switcher::clamp_highlight;
14use super::widgets::icon;
15use crate::i18n::tr;
16use crate::app_state::AppState;
17use crate::call::TransferCandidate;
18use crate::fuzzy;
19use crate::theme::{self, ElevatedSurface as _};
20
21const MAX_RESULTS: usize = 6;
22const CARD_WIDTH: f32 = 440.;
23const CARD_RADIUS: f32 = 12.;
24const CARD_PADDING: f32 = 16.;
25const SECTION_GAP: f32 = 12.;
26const BACKDROP_OPACITY: f32 = 0.55;
27const ROW_HEIGHT: f32 = 44.;
28const AVATAR_SIZE: f32 = 28.;
29const FIELD_HEIGHT: f32 = 36.;
30const CLOSE_SIZE: f32 = 28.;
31const DISABLED_OPACITY: f32 = 0.4;
32
33pub fn visible_candidates(
34 candidates: &[(String, TransferCandidate)],
35 query: &str,
36) -> Vec<TransferCandidate> {
37 fuzzy::rank(query, candidates, MAX_RESULTS)
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PickerMode {
42 Transfer,
43 Invite,
44}
45
46pub struct TransferPicker {
47 app: Entity<AppState>,
48 mode: PickerMode,
49 candidates: Vec<(String, TransferCandidate)>,
50 search: Entity<InputState>,
51 results: Vec<TransferCandidate>,
52 highlighted: usize,
53 target: Option<TransferCandidate>,
54 _subscription: Subscription,
55}
56
57impl TransferPicker {
58 pub fn new(
59 app: Entity<AppState>,
60 candidates: Vec<TransferCandidate>,
61 mode: PickerMode,
62 window: &mut Window,
63 cx: &mut Context<Self>,
64 ) -> Self {
65 let candidates: Vec<(String, TransferCandidate)> = candidates
66 .into_iter()
67 .map(|candidate| (candidate.name.clone(), candidate))
68 .collect();
69 let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));
70 let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
71 search.update(cx, |input, cx| input.focus(window, cx));
72 let results = visible_candidates(&candidates, "");
73 TransferPicker {
74 app,
75 mode,
76 candidates,
77 search,
78 results,
79 highlighted: 0,
80 target: None,
81 _subscription: subscription,
82 }
83 }
84
85 pub fn choose(&mut self, candidate: TransferCandidate) {
86 self.target = Some(candidate);
87 }
88
89 fn on_search_event(
90 &mut self,
91 input: &Entity<InputState>,
92 event: &InputEvent,
93 _: &mut Window,
94 cx: &mut Context<Self>,
95 ) {
96 match event {
97 InputEvent::Change => {
98 let query = input.read(cx).value().to_string();
99 self.results = visible_candidates(&self.candidates, &query);
100 self.highlighted = 0;
101 cx.notify();
102 }
103 InputEvent::PressEnter { .. } => {
104 if let Some(candidate) = self.results.get(self.highlighted).cloned() {
105 self.target = Some(candidate);
106 cx.notify();
107 }
108 }
109 _ => {}
110 }
111 }
112
113 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
114 match event.keystroke.key.as_str() {
115 "escape" => self.close(cx),
116 "down" => {
117 self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());
118 cx.notify();
119 }
120 "up" => {
121 self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());
122 cx.notify();
123 }
124 _ => {}
125 }
126 }
127
128 fn close(&self, cx: &mut Context<Self>) {
129 self.app
130 .update(cx, |state, cx| state.close_transfer_picker(cx));
131 }
132
133 fn list(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
134 let directory = &self.app.read(cx).directory;
135 let rows: Vec<AnyElement> = self
136 .results
137 .iter()
138 .enumerate()
139 .map(|(index, candidate)| {
140 let chosen = self.target.as_ref() == Some(candidate);
141 let picked = candidate.clone();
142 h_flex()
143 .id(ElementId::Name(format!("transfer-target-{index}").into()))
144 .h(px(ROW_HEIGHT))
145 .flex_none()
146 .px(px(8.))
147 .gap(px(10.))
148 .items_center()
149 .rounded(px(6.))
150 .cursor_pointer()
151 .when(
152 chosen || (self.target.is_none() && index == self.highlighted),
153 |row| row.bg(theme::surface_raised()),
154 )
155 .hover(|row| row.bg(theme::row_hover()))
156 .child(person_avatar(
157 directory,
158 candidate.user_id.as_deref(),
159 &candidate.name,
160 AVATAR_SIZE,
161 ))
162 .child(
163 div()
164 .flex_1()
165 .min_w_0()
166 .truncate()
167 .text_size(px(14.))
168 .child(candidate.name.clone()),
169 )
170 .when(chosen, |row| {
171 row.child(icon(IconName::Check, 16., theme::accent_text()))
172 })
173 .on_click(cx.listener(move |this, _, _, cx| {
174 this.choose(picked.clone());
175 cx.notify();
176 }))
177 .into_any_element()
178 })
179 .collect();
180 v_flex()
181 .id("transfer-targets")
182 .w_full()
183 .max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))
184 .overflow_y_scrollbar()
185 .children(rows)
186 }
187
188 fn action(
189 &self,
190 id: &'static str,
191 label: &'static str,
192 primary: bool,
193 run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>),
194 ) -> AnyElement {
195 let button = Button::new(id).label(label);
196 let button = if primary { button } else { button.ghost() };
197 let Some(target) = self.target.clone() else {
198 return button.opacity(DISABLED_OPACITY).into_any_element();
199 };
200 let app = self.app.clone();
201 button
202 .on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx)))
203 .into_any_element()
204 }
205}
206
207impl Render for TransferPicker {
208 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
209 let field = h_flex()
210 .w_full()
211 .h(px(FIELD_HEIGHT))
212 .px(px(10.))
213 .gap(px(8.))
214 .items_center()
215 .rounded(px(6.))
216 .bg(theme::surface())
217 .border_1()
218 .border_color(theme::border())
219 .child(icon(IconName::Search, 14., theme::text_muted()))
220 .child(
221 div()
222 .flex_1()
223 .child(Input::new(&self.search).appearance(false).bordered(false)),
224 );
225 let actions = h_flex()
226 .w_full()
227 .justify_end()
228 .gap(px(8.))
229 .child(
230 Button::new("transfer-cancel")
231 .ghost()
232 .label(tr("common.cancel"))
233 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
234 )
235 .children(match self.mode {
236 PickerMode::Transfer => vec![
237 self.action("transfer-consult", "Consult first", false, AppState::start_consult),
238 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
239 ],
240 PickerMode::Invite => {
241 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
242 }
243 });
244 div()
245 .id("transfer-layer")
246 .absolute()
247 .top_0()
248 .left_0()
249 .size_full()
250 .flex()
251 .items_center()
252 .justify_center()
253 .child(
254 div()
255 .id("transfer-backdrop")
256 .absolute()
257 .top_0()
258 .left_0()
259 .size_full()
260 .bg(black().opacity(BACKDROP_OPACITY))
261 .occlude()
262 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
263 )
264 .child(
265 v_flex()
266 .id("transfer-card")
267 .w(px(CARD_WIDTH))
268 .max_w(relative(1.))
269 .p(px(CARD_PADDING))
270 .gap(px(SECTION_GAP))
271 .rounded(px(CARD_RADIUS))
272 .dialog_surface()
273 .text_color(theme::text())
274 .occlude()
275 .on_key_down(cx.listener(Self::on_key_down))
276 .child(
277 h_flex()
278 .w_full()
279 .items_center()
280 .gap(px(SECTION_GAP))
281 .child(
282 div()
283 .flex_1()
284 .text_size(px(15.))
285 .font_weight(FontWeight::SEMIBOLD)
286 .child(match self.mode {
287 PickerMode::Transfer => "Transfer call",
288 PickerMode::Invite => "Invite people",
289 }),
290 )
291 .child(
292 div()
293 .id("transfer-close")
294 .size(px(CLOSE_SIZE))
295 .flex_none()
296 .flex()
297 .items_center()
298 .justify_center()
299 .rounded_full()
300 .cursor_pointer()
301 .hover(|button| button.bg(theme::row_hover()))
302 .on_click(cx.listener(|this, _, _, cx| this.close(cx)))
303 .child(icon(IconName::X, 16., theme::text_muted())),
304 ),
305 )
306 .child(field)
307 .child(self.list(cx))
308 .child(actions),
309 )
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::{MAX_RESULTS, visible_candidates};
316 use crate::call::TransferCandidate;
317
318 fn candidate(name: &str) -> (String, TransferCandidate) {
319 (
320 name.to_owned(),
321 TransferCandidate {
322 mri: format!("8:orgid:{name}"),
323 name: name.to_owned(),
324 user_id: Some(name.to_owned()),
325 chat_id: format!("19:{name}"),
326 },
327 )
328 }
329
330 #[test]
331 fn the_search_ranks_people_by_name() {
332 let people = vec![
333 candidate("Ana Weiss"),
334 candidate("Bo Brandt"),
335 candidate("Anja Vogel"),
336 ];
337 let found: Vec<String> = visible_candidates(&people, "anj")
338 .into_iter()
339 .map(|person| person.name)
340 .collect();
341 assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));
342 assert_eq!(visible_candidates(&people, "").len(), 3);
343 assert!(visible_candidates(&people, "zzz").is_empty());
344 }
345
346 #[test]
347 fn the_list_is_capped() {
348 let people: Vec<(String, TransferCandidate)> = (0..20)
349 .map(|index| candidate(&format!("Person {index}")))
350 .collect();
351 assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);
352 }
353}