BlueGit

ict rusty-teams

Files

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

forward_dialog.rs

forward_dialog.rs 19.0 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::switcher::{Candidate, candidate_avatar, clamp_highlight};
12use super::widgets::{icon, symbol};
13use crate::app_state::{AppState, Selection};
14use crate::fuzzy;
15use crate::message_actions::ForwardSource;
16use crate::notice::short_error;
17use crate::runtime;
18use crate::theme::{self, ElevatedSurface as _};
19
20const MAX_RESULTS: usize = 8;
21const CARD_WIDTH: f32 = 480.;
22const CARD_RADIUS: f32 = 10.;
23const CARD_PADDING: f32 = 16.;
24const CARD_MARGIN: f32 = 32.;
25const SECTION_GAP: f32 = 12.;
26const BACKDROP_OPACITY: f32 = 0.55;
27const ROW_HEIGHT: f32 = 40.;
28const AVATAR_SIZE: f32 = 28.;
29const PREVIEW_LINES: usize = 4;
30const CLOSE_SIZE: f32 = 28.;
31const FIELD_HEIGHT: f32 = 36.;
32const BUTTON_HEIGHT: f32 = 32.;
33const DISABLED_OPACITY: f32 = 0.4;
34const EMPTY_PREVIEW: &str = "Attachment";
35
36pub enum ForwardDialogEvent {
37 Close,
38 Sent { target: Selection, title: String },
39}
40
41pub struct ForwardDialog {
42 app: Entity<AppState>,
43 source: ForwardSource,
44 candidates: Vec<(String, Candidate)>,
45 search: Entity<InputState>,
46 comment: Entity<InputState>,
47 results: Vec<Candidate>,
48 highlighted: usize,
49 target: Option<Candidate>,
50 sending: bool,
51 error: Option<String>,
52 _subscriptions: [Subscription; 2],
53}
54
55impl EventEmitter<ForwardDialogEvent> for ForwardDialog {}
56
57pub fn visible_candidates(candidates: &[(String, Candidate)], query: &str) -> Vec<Candidate> {
58 fuzzy::rank(query, candidates, MAX_RESULTS)
59}
60
61pub fn can_forward(target: Option<&Candidate>, sending: bool) -> bool {
62 target.is_some() && !sending
63}
64
65impl ForwardDialog {
66 pub fn new(
67 app: Entity<AppState>,
68 source: ForwardSource,
69 candidates: Vec<(String, Candidate)>,
70 window: &mut Window,
71 cx: &mut Context<Self>,
72 ) -> Self {
73 let search =
74 cx.new(|cx| InputState::new(window, cx).placeholder("Search chats and channels"));
75 let comment =
76 cx.new(|cx| InputState::new(window, cx).placeholder("Add a message (optional)"));
77 let subscriptions = [
78 cx.subscribe_in(&search, window, Self::on_search_event),
79 cx.subscribe_in(&comment, window, Self::on_comment_event),
80 ];
81 search.update(cx, |input, cx| input.focus(window, cx));
82 let results = visible_candidates(&candidates, "");
83 ForwardDialog {
84 app,
85 source,
86 candidates,
87 search,
88 comment,
89 results,
90 highlighted: 0,
91 target: None,
92 sending: false,
93 error: None,
94 _subscriptions: subscriptions,
95 }
96 }
97
98 fn on_search_event(
99 &mut self,
100 input: &Entity<InputState>,
101 event: &InputEvent,
102 window: &mut Window,
103 cx: &mut Context<Self>,
104 ) {
105 match event {
106 InputEvent::Change => {
107 let query = input.read(cx).value().to_string();
108 self.results = visible_candidates(&self.candidates, &query);
109 self.highlighted = 0;
110 cx.notify();
111 }
112 InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),
113 _ => {}
114 }
115 }
116
117 fn on_comment_event(
118 &mut self,
119 _: &Entity<InputState>,
120 event: &InputEvent,
121 _: &mut Window,
122 cx: &mut Context<Self>,
123 ) {
124 if matches!(event, InputEvent::PressEnter { .. }) {
125 self.send(cx);
126 }
127 }
128
129 fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
130 let Some(candidate) = self.results.get(index).cloned() else {
131 return;
132 };
133 self.highlighted = index;
134 self.target = Some(candidate);
135 self.error = None;
136 self.comment.update(cx, |input, cx| input.focus(window, cx));
137 cx.notify();
138 }
139
140 fn clear_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {
141 self.target = None;
142 self.error = None;
143 self.search.update(cx, |input, cx| input.focus(window, cx));
144 cx.notify();
145 }
146
147 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
148 match event.keystroke.key.as_str() {
149 "escape" => cx.emit(ForwardDialogEvent::Close),
150 "down" if self.target.is_none() => {
151 self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());
152 cx.notify();
153 }
154 "up" if self.target.is_none() => {
155 self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());
156 cx.notify();
157 }
158 _ => {}
159 }
160 }
161
162 fn send(&mut self, cx: &mut Context<Self>) {
163 let Some(target) = self.target.clone().filter(|_| !self.sending) else {
164 return;
165 };
166 let comment = self.comment.read(cx).value().trim().to_owned();
167 let state = self.app.read(cx);
168 if state.mode.read_only {
169 self.error = Some("Read-only mode: message not forwarded".to_owned());
170 cx.notify();
171 return;
172 }
173 let sent = ForwardDialogEvent::Sent {
174 target: target.selection.clone(),
175 title: target.title.clone(),
176 };
177 let Some(engine) = state.engine.clone() else {
178 if state.mode.demo {
179 let source = self.source.clone();
180 self.app.update(cx, |state, cx| {
181 state.forward_locally(&source, &target.selection, &comment, cx)
182 });
183 cx.emit(sent);
184 } else {
185 self.error = Some("Not connected".to_owned());
186 cx.notify();
187 }
188 return;
189 };
190 self.sending = true;
191 self.error = None;
192 let source = self.source.clone();
193 let target_id = target.selection.conversation_id().to_owned();
194 let receiver = runtime::spawn(async move {
195 engine
196 .forward_messages(
197 &source.conversation_id,
198 &target_id,
199 &[source.message_id],
200 &comment,
201 )
202 .await
203 });
204 cx.spawn(async move |this, cx| {
205 let outcome = match receiver.await {
206 Ok(Ok(_)) => Ok(()),
207 Ok(Err(error)) => Err(short_error(&error)),
208 Err(_) => Err("cancelled".to_owned()),
209 };
210 this.update(cx, |this, cx| {
211 this.sending = false;
212 match outcome {
213 Ok(()) => cx.emit(sent),
214 Err(reason) => this.error = Some(reason),
215 }
216 cx.notify();
217 })
218 .ok();
219 })
220 .detach();
221 cx.notify();
222 }
223
224 fn header(&self, cx: &mut Context<Self>) -> Div {
225 h_flex()
226 .w_full()
227 .items_center()
228 .gap(px(SECTION_GAP))
229 .child(
230 div()
231 .flex_1()
232 .text_size(px(15.))
233 .font_weight(FontWeight::SEMIBOLD)
234 .child("Forward message"),
235 )
236 .child(
237 div()
238 .id("forward-close")
239 .size(px(CLOSE_SIZE))
240 .flex_none()
241 .flex()
242 .items_center()
243 .justify_center()
244 .rounded_full()
245 .cursor_pointer()
246 .hover(|button| button.bg(theme::popup_hover()))
247 .on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close)))
248 .child(symbol("close", 16., theme::text_muted())),
249 )
250 }
251
252 fn target_field(&self, cx: &mut Context<Self>) -> AnyElement {
253 let field = h_flex()
254 .w_full()
255 .h(px(FIELD_HEIGHT))
256 .px(px(10.))
257 .gap(px(8.))
258 .items_center()
259 .rounded(px(6.))
260 .bg(theme::popup_hover());
261 match &self.target {
262 Some(target) => field
263 .child(
264 div()
265 .flex_1()
266 .min_w_0()
267 .truncate()
268 .text_size(px(13.))
269 .child(format!("To: {}", target.title)),
270 )
271 .child(
272 div()
273 .id("forward-clear-target")
274 .size(px(20.))
275 .flex_none()
276 .flex()
277 .items_center()
278 .justify_center()
279 .rounded(px(4.))
280 .cursor_pointer()
281 .hover(|button| button.bg(theme::popup_hover()))
282 .on_click(cx.listener(|this, _, window, cx| this.clear_target(window, cx)))
283 .child(icon(IconName::X, 14., theme::text_muted())),
284 )
285 .into_any_element(),
286 None => field
287 .child(icon(IconName::Search, 14., theme::text_muted()))
288 .child(
289 div()
290 .flex_1()
291 .child(Input::new(&self.search).appearance(false).bordered(false)),
292 )
293 .into_any_element(),
294 }
295 }
296
297 fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {
298 let directory = &self.app.read(cx).directory;
299 let selected_id = self
300 .target
301 .as_ref()
302 .map(|target| target.selection.conversation_id().to_owned());
303 let rows: Vec<AnyElement> = self
304 .results
305 .iter()
306 .enumerate()
307 .map(|(index, candidate)| {
308 let chosen = selected_id.as_deref() == Some(candidate.selection.conversation_id());
309 let highlighted = self.target.is_none() && index == self.highlighted;
310 h_flex()
311 .id(ElementId::Name(format!("forward-target-{index}").into()))
312 .h(px(ROW_HEIGHT))
313 .flex_none()
314 .px(px(8.))
315 .gap(px(10.))
316 .items_center()
317 .rounded(px(6.))
318 .cursor_pointer()
319 .when(highlighted || chosen, |row| row.bg(theme::popup_hover()))
320 .hover(|row| row.bg(theme::popup_hover()))
321 .child(candidate_avatar(
322 directory,
323 &candidate.avatar,
324 AVATAR_SIZE,
325 theme::popup(),
326 ))
327 .child(
328 v_flex()
329 .flex_1()
330 .min_w_0()
331 .child(
332 div()
333 .truncate()
334 .text_size(px(14.))
335 .text_color(theme::text())
336 .child(candidate.title.clone()),
337 )
338 .child(
339 div()
340 .truncate()
341 .text_size(px(12.))
342 .text_color(theme::text_muted())
343 .child(candidate.subtitle.clone()),
344 ),
345 )
346 .when(chosen, |row| {
347 row.child(icon(IconName::Check, 16., theme::accent_text()))
348 })
349 .on_click(
350 cx.listener(move |this, _, window, cx| this.choose(index, window, cx)),
351 )
352 .into_any_element()
353 })
354 .collect();
355 v_flex()
356 .id("forward-targets")
357 .w_full()
358 .max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))
359 .overflow_y_scroll()
360 .children(rows)
361 }
362
363 fn send_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {
364 let button = h_flex()
365 .id("forward-send")
366 .h(px(BUTTON_HEIGHT))
367 .px(px(16.))
368 .gap(px(6.))
369 .items_center()
370 .rounded(px(6.))
371 .bg(theme::accent())
372 .text_color(theme::on_accent())
373 .text_size(px(13.))
374 .font_weight(FontWeight::SEMIBOLD)
375 .when(self.sending, |button| {
376 button.child(icon(IconName::Loader, 14., theme::on_accent()))
377 })
378 .child("Forward");
379 if enabled {
380 button
381 .cursor_pointer()
382 .hover(|button| button.bg(theme::accent_text()))
383 .on_click(cx.listener(|this, _, _, cx| this.send(cx)))
384 } else {
385 button.opacity(DISABLED_OPACITY)
386 }
387 }
388
389 fn preview(&self) -> Div {
390 let text = match self.source.text.trim() {
391 "" => EMPTY_PREVIEW.to_owned(),
392 text => text.to_owned(),
393 };
394 v_flex()
395 .w_full()
396 .px(px(10.))
397 .py(px(6.))
398 .gap(px(2.))
399 .border_l(px(3.))
400 .border_color(theme::accent())
401 .rounded_r(px(4.))
402 .bg(theme::quote_fill())
403 .child(
404 h_flex()
405 .gap(px(8.))
406 .items_baseline()
407 .child(
408 div()
409 .text_size(px(12.))
410 .font_weight(FontWeight::SEMIBOLD)
411 .text_color(theme::text_soft())
412 .child(self.source.author.clone()),
413 )
414 .child(
415 div()
416 .text_size(px(11.))
417 .text_color(theme::text_muted())
418 .child(self.source.time.clone()),
419 ),
420 )
421 .child(
422 div()
423 .line_clamp(PREVIEW_LINES)
424 .text_size(px(12.5))
425 .text_color(theme::text_muted())
426 .child(text),
427 )
428 }
429}
430
431impl Render for ForwardDialog {
432 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
433 let enabled = can_forward(self.target.as_ref(), self.sending);
434 div()
435 .id("forward-layer")
436 .absolute()
437 .top_0()
438 .left_0()
439 .size_full()
440 .flex()
441 .items_center()
442 .justify_center()
443 .child(
444 div()
445 .id("forward-backdrop")
446 .absolute()
447 .top_0()
448 .left_0()
449 .size_full()
450 .bg(black().opacity(BACKDROP_OPACITY))
451 .occlude()
452 .on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close))),
453 )
454 .child(
455 v_flex()
456 .id("forward-card")
457 .w(px(CARD_WIDTH))
458 .max_w(relative(1.))
459 .max_h(relative(1.))
460 .m(px(CARD_MARGIN))
461 .p(px(CARD_PADDING))
462 .gap(px(SECTION_GAP))
463 .rounded(px(CARD_RADIUS))
464 .dialog_surface()
465 .text_color(theme::text())
466 .occlude()
467 .on_key_down(cx.listener(Self::on_key_down))
468 .child(self.header(cx))
469 .child(self.target_field(cx))
470 .child(self.list(cx))
471 .child(self.preview())
472 .child(Input::new(&self.comment))
473 .children(self.error.clone().map(|error| {
474 div()
475 .text_size(px(12.))
476 .text_color(theme::red_tint())
477 .child(error)
478 }))
479 .child(
480 h_flex()
481 .w_full()
482 .justify_end()
483 .gap(px(8.))
484 .child(
485 Button::new("forward-cancel")
486 .ghost()
487 .label("Cancel")
488 .on_click(cx.listener(|_, _, _, cx| {
489 cx.emit(ForwardDialogEvent::Close)
490 })),
491 )
492 .child(self.send_button(enabled, cx)),
493 ),
494 )
495 }
496}
497
498#[cfg(test)]
499mod tests {
500 use super::{MAX_RESULTS, can_forward, visible_candidates};
501 use crate::app_state::Selection;
502 use crate::views::switcher::{Candidate, CandidateAvatar};
503
504 fn candidates(titles: &[&str]) -> Vec<(String, Candidate)> {
505 titles
506 .iter()
507 .map(|title| {
508 (
509 (*title).to_owned(),
510 Candidate {
511 title: (*title).to_owned(),
512 subtitle: "Chat".to_owned(),
513 avatar: CandidateAvatar::Team {
514 name: (*title).to_owned(),
515 key: (*title).to_owned(),
516 },
517 selection: Selection::Chat(format!("id-{title}")),
518 },
519 )
520 })
521 .collect()
522 }
523
524 fn titles(found: &[Candidate]) -> Vec<&str> {
525 found
526 .iter()
527 .map(|candidate| candidate.title.as_str())
528 .collect()
529 }
530
531 #[test]
532 fn empty_query_keeps_the_recent_order_and_caps_the_list() {
533 let many: Vec<String> = (0..12).map(|number| format!("Chat {number:02}")).collect();
534 let names: Vec<&str> = many.iter().map(String::as_str).collect();
535 let found = visible_candidates(&candidates(&names), "");
536 assert_eq!(found.len(), MAX_RESULTS);
537 assert_eq!(titles(&found)[0], "Chat 00");
538 assert_eq!(titles(&found)[7], "Chat 07");
539 }
540
541 #[test]
542 fn a_query_keeps_only_matching_targets() {
543 let found = visible_candidates(&candidates(&["Release", "Mara", "Atlas"]), "rel");
544 assert_eq!(titles(&found), vec!["Release"]);
545 assert!(visible_candidates(&candidates(&["Release"]), "zzz").is_empty());
546 }
547
548 #[test]
549 fn forwarding_needs_a_target_and_no_send_in_flight() {
550 let all = candidates(&["Release"]);
551 let target = &all[0].1;
552 assert!(!can_forward(None, false));
553 assert!(can_forward(Some(target), false));
554 assert!(!can_forward(Some(target), true));
555 }
556}