BlueGit

ict rusty-teams

Files

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

forward_dialog.rs

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