BlueGit

ict rusty-teams

Files

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

forward_dialog.rs

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