BlueGit

ict rusty-teams

Files

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

transfer_picker.rs

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