BlueGit

ict rusty-teams

Files

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

transfer_picker.rs

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