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::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::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("transfer-consult", "Consult first", false, AppState::start_consult),
237 self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind),
238 ],
239 PickerMode::Invite => {
240 vec![self.action("transfer-invite", "Invite", true, AppState::invite_call_person)]
241 }
242 });
243 div()
244 .id("transfer-layer")
245 .absolute()
246 .top_0()
247 .left_0()
248 .size_full()
249 .flex()
250 .items_center()
251 .justify_center()
252 .child(
253 div()
254 .id("transfer-backdrop")
255 .absolute()
256 .top_0()
257 .left_0()
258 .size_full()
259 .bg(black().opacity(BACKDROP_OPACITY))
260 .occlude()
261 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
262 )
263 .child(
264 v_flex()
265 .id("transfer-card")
266 .w(px(CARD_WIDTH))
267 .max_w(relative(1.))
268 .p(px(CARD_PADDING))
269 .gap(px(SECTION_GAP))
270 .rounded(px(CARD_RADIUS))
271 .dialog_surface()
272 .text_color(theme::text())
273 .occlude()
274 .on_key_down(cx.listener(Self::on_key_down))
275 .child(
276 h_flex()
277 .w_full()
278 .items_center()
279 .gap(px(SECTION_GAP))
280 .child(
281 div()
282 .flex_1()
283 .text_size(px(15.))
284 .font_weight(FontWeight::SEMIBOLD)
285 .child(match self.mode {
286 PickerMode::Transfer => "Transfer call",
287 PickerMode::Invite => "Invite people",
288 }),
289 )
290 .child(
291 div()
292 .id("transfer-close")
293 .size(px(CLOSE_SIZE))
294 .flex_none()
295 .flex()
296 .items_center()
297 .justify_center()
298 .rounded_full()
299 .cursor_pointer()
300 .hover(|button| button.bg(theme::row_hover()))
301 .on_click(cx.listener(|this, _, _, cx| this.close(cx)))
302 .child(icon(IconName::X, 16., theme::text_muted())),
303 ),
304 )
305 .child(field)
306 .child(self.list(cx))
307 .child(actions),
308 )
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::{MAX_RESULTS, visible_candidates};
315 use crate::call::TransferCandidate;
316
317 fn candidate(name: &str) -> (String, TransferCandidate) {
318 (
319 name.to_owned(),
320 TransferCandidate {
321 mri: format!("8:orgid:{name}"),
322 name: name.to_owned(),
323 user_id: Some(name.to_owned()),
324 chat_id: format!("19:{name}"),
325 },
326 )
327 }
328
329 #[test]
330 fn the_search_ranks_people_by_name() {
331 let people = vec![
332 candidate("Ana Weiss"),
333 candidate("Bo Brandt"),
334 candidate("Anja Vogel"),
335 ];
336 let found: Vec<String> = visible_candidates(&people, "anj")
337 .into_iter()
338 .map(|person| person.name)
339 .collect();
340 assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));
341 assert_eq!(visible_candidates(&people, "").len(), 3);
342 assert!(visible_candidates(&people, "zzz").is_empty());
343 }
344
345 #[test]
346 fn the_list_is_capped() {
347 let people: Vec<(String, TransferCandidate)> = (0..20)
348 .map(|index| candidate(&format!("Person {index}")))
349 .collect();
350 assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);
351 }
352}