BlueGit

ict rusty-teams

Files

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

forward_dialog.rs

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