BlueGit

ict rusty-teams

Files

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

forward_dialog.rs

forward_dialog.rs 19.1 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;
19
20const MAX_RESULTS: usize = 8;
21const CARD_WIDTH: f32 = 480.;
22const CARD_RADIUS: f32 = 12.;
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::row_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::surface())
261 .border_1()
262 .border_color(theme::border());
263 match &self.target {
264 Some(target) => field
265 .child(
266 div()
267 .flex_1()
268 .min_w_0()
269 .truncate()
270 .text_size(px(13.))
271 .child(format!("To: {}", target.title)),
272 )
273 .child(
274 div()
275 .id("forward-clear-target")
276 .size(px(20.))
277 .flex_none()
278 .flex()
279 .items_center()
280 .justify_center()
281 .rounded(px(4.))
282 .cursor_pointer()
283 .hover(|button| button.bg(theme::row_hover()))
284 .on_click(cx.listener(|this, _, window, cx| this.clear_target(window, cx)))
285 .child(icon(IconName::X, 14., theme::text_muted())),
286 )
287 .into_any_element(),
288 None => field
289 .child(icon(IconName::Search, 14., theme::text_muted()))
290 .child(
291 div()
292 .flex_1()
293 .child(Input::new(&self.search).appearance(false).bordered(false)),
294 )
295 .into_any_element(),
296 }
297 }
298
299 fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {
300 let directory = &self.app.read(cx).directory;
301 let selected_id = self
302 .target
303 .as_ref()
304 .map(|target| target.selection.conversation_id().to_owned());
305 let rows: Vec<AnyElement> = self
306 .results
307 .iter()
308 .enumerate()
309 .map(|(index, candidate)| {
310 let chosen = selected_id.as_deref() == Some(candidate.selection.conversation_id());
311 let highlighted = self.target.is_none() && index == self.highlighted;
312 h_flex()
313 .id(ElementId::Name(format!("forward-target-{index}").into()))
314 .h(px(ROW_HEIGHT))
315 .flex_none()
316 .px(px(8.))
317 .gap(px(10.))
318 .items_center()
319 .rounded(px(6.))
320 .cursor_pointer()
321 .when(highlighted || chosen, |row| row.bg(theme::surface_raised()))
322 .hover(|row| row.bg(theme::row_hover()))
323 .child(candidate_avatar(
324 directory,
325 &candidate.avatar,
326 AVATAR_SIZE,
327 theme::background(),
328 ))
329 .child(
330 v_flex()
331 .flex_1()
332 .min_w_0()
333 .child(
334 div()
335 .truncate()
336 .text_size(px(14.))
337 .text_color(theme::text())
338 .child(candidate.title.clone()),
339 )
340 .child(
341 div()
342 .truncate()
343 .text_size(px(12.))
344 .text_color(theme::text_muted())
345 .child(candidate.subtitle.clone()),
346 ),
347 )
348 .when(chosen, |row| {
349 row.child(icon(IconName::Check, 16., theme::accent_text()))
350 })
351 .on_click(
352 cx.listener(move |this, _, window, cx| this.choose(index, window, cx)),
353 )
354 .into_any_element()
355 })
356 .collect();
357 v_flex()
358 .id("forward-targets")
359 .w_full()
360 .max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))
361 .overflow_y_scroll()
362 .children(rows)
363 }
364
365 fn send_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {
366 let button = h_flex()
367 .id("forward-send")
368 .h(px(BUTTON_HEIGHT))
369 .px(px(16.))
370 .gap(px(6.))
371 .items_center()
372 .rounded(px(6.))
373 .bg(theme::accent())
374 .text_color(theme::on_accent())
375 .text_size(px(13.))
376 .font_weight(FontWeight::SEMIBOLD)
377 .when(self.sending, |button| {
378 button.child(icon(IconName::Loader, 14., theme::on_accent()))
379 })
380 .child("Forward");
381 if enabled {
382 button
383 .cursor_pointer()
384 .hover(|button| button.bg(theme::accent_text()))
385 .on_click(cx.listener(|this, _, _, cx| this.send(cx)))
386 } else {
387 button.opacity(DISABLED_OPACITY)
388 }
389 }
390
391 fn preview(&self) -> Div {
392 let text = match self.source.text.trim() {
393 "" => EMPTY_PREVIEW.to_owned(),
394 text => text.to_owned(),
395 };
396 v_flex()
397 .w_full()
398 .px(px(10.))
399 .py(px(6.))
400 .gap(px(2.))
401 .border_l(px(3.))
402 .border_color(theme::accent())
403 .rounded_r(px(4.))
404 .bg(theme::quote_fill())
405 .child(
406 h_flex()
407 .gap(px(8.))
408 .items_baseline()
409 .child(
410 div()
411 .text_size(px(12.))
412 .font_weight(FontWeight::SEMIBOLD)
413 .text_color(theme::text_soft())
414 .child(self.source.author.clone()),
415 )
416 .child(
417 div()
418 .text_size(px(11.))
419 .text_color(theme::text_muted())
420 .child(self.source.time.clone()),
421 ),
422 )
423 .child(
424 div()
425 .line_clamp(PREVIEW_LINES)
426 .text_size(px(12.5))
427 .text_color(theme::text_muted())
428 .child(text),
429 )
430 }
431}
432
433impl Render for ForwardDialog {
434 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
435 let enabled = can_forward(self.target.as_ref(), self.sending);
436 div()
437 .id("forward-layer")
438 .absolute()
439 .top_0()
440 .left_0()
441 .size_full()
442 .flex()
443 .items_center()
444 .justify_center()
445 .child(
446 div()
447 .id("forward-backdrop")
448 .absolute()
449 .top_0()
450 .left_0()
451 .size_full()
452 .bg(black().opacity(BACKDROP_OPACITY))
453 .occlude()
454 .on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close))),
455 )
456 .child(
457 v_flex()
458 .id("forward-card")
459 .w(px(CARD_WIDTH))
460 .max_w(relative(1.))
461 .max_h(relative(1.))
462 .m(px(CARD_MARGIN))
463 .p(px(CARD_PADDING))
464 .gap(px(SECTION_GAP))
465 .rounded(px(CARD_RADIUS))
466 .bg(theme::background())
467 .border_1()
468 .border_color(theme::border_strong())
469 .text_color(theme::text())
470 .shadow_lg()
471 .occlude()
472 .on_key_down(cx.listener(Self::on_key_down))
473 .child(self.header(cx))
474 .child(self.target_field(cx))
475 .child(self.list(cx))
476 .child(self.preview())
477 .child(Input::new(&self.comment))
478 .children(self.error.clone().map(|error| {
479 div()
480 .text_size(px(12.))
481 .text_color(theme::red_tint())
482 .child(error)
483 }))
484 .child(
485 h_flex()
486 .w_full()
487 .justify_end()
488 .gap(px(8.))
489 .child(
490 Button::new("forward-cancel")
491 .ghost()
492 .label("Cancel")
493 .on_click(cx.listener(|_, _, _, cx| {
494 cx.emit(ForwardDialogEvent::Close)
495 })),
496 )
497 .child(self.send_button(enabled, cx)),
498 ),
499 )
500 }
501}
502
503#[cfg(test)]
504mod tests {
505 use super::{MAX_RESULTS, can_forward, visible_candidates};
506 use crate::app_state::Selection;
507 use crate::views::switcher::{Candidate, CandidateAvatar};
508
509 fn candidates(titles: &[&str]) -> Vec<(String, Candidate)> {
510 titles
511 .iter()
512 .map(|title| {
513 (
514 (*title).to_owned(),
515 Candidate {
516 title: (*title).to_owned(),
517 subtitle: "Chat".to_owned(),
518 avatar: CandidateAvatar::Team {
519 name: (*title).to_owned(),
520 key: (*title).to_owned(),
521 },
522 selection: Selection::Chat(format!("id-{title}")),
523 },
524 )
525 })
526 .collect()
527 }
528
529 fn titles(found: &[Candidate]) -> Vec<&str> {
530 found
531 .iter()
532 .map(|candidate| candidate.title.as_str())
533 .collect()
534 }
535
536 #[test]
537 fn empty_query_keeps_the_recent_order_and_caps_the_list() {
538 let many: Vec<String> = (0..12).map(|number| format!("Chat {number:02}")).collect();
539 let names: Vec<&str> = many.iter().map(String::as_str).collect();
540 let found = visible_candidates(&candidates(&names), "");
541 assert_eq!(found.len(), MAX_RESULTS);
542 assert_eq!(titles(&found)[0], "Chat 00");
543 assert_eq!(titles(&found)[7], "Chat 07");
544 }
545
546 #[test]
547 fn a_query_keeps_only_matching_targets() {
548 let found = visible_candidates(&candidates(&["Release", "Mara", "Atlas"]), "rel");
549 assert_eq!(titles(&found), vec!["Release"]);
550 assert!(visible_candidates(&candidates(&["Release"]), "zzz").is_empty());
551 }
552
553 #[test]
554 fn forwarding_needs_a_target_and_no_send_in_flight() {
555 let all = candidates(&["Release"]);
556 let target = &all[0].1;
557 assert!(!can_forward(None, false));
558 assert!(can_forward(Some(target), false));
559 assert!(!can_forward(Some(target), true));
560 }
561}