BlueGit

ict rusty-teams

Files

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

composer.rs

eba4ad94 History
composer.rs 60.2 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::path::PathBuf;
4use std::sync::Arc;
5use std::time::Duration;
6
7use gpui_kit::assets::IconName;
8use gpui_kit::component::{
9 h_flex,
10 input::{
11 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
12 MoveUp, Textarea, TextareaState,
13 },
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use teams_core::{
20 FileReference, HostedImage, MentionCandidate, MentionInput, MessageExtras, UploadedFile,
21};
22
23use super::attachment_tray::{
24 AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,
25 UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,
26 prepare_pasted_image, read_attachment, render_tray,
27};
28use super::avatar::{person_avatar, square_avatar};
29use super::emoji_popup::{self, EmojiPopup};
30use super::widgets::{icon, symbol};
31use crate::app_state::AppState;
32use crate::emoji;
33use crate::runtime;
34use crate::theme;
35
36const MIN_ROWS: usize = 1;
37const MAX_ROWS: usize = 8;
38const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
39const MENTION_LIMIT: usize = 8;
40const MENTION_QUERY_MAX_CHARS: usize = 32;
41const MENTION_QUERY_MAX_WORDS: usize = 3;
42const POPUP_WIDTH: f32 = 380.;
43const POPUP_ROW_HEIGHT: f32 = 44.;
44const DEMO_UPLOAD_STEPS: u8 = 10;
45const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
46const DEMO_FAILURE_STEP: u8 = 6;
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ReplyPreview {
50 pub message_id: String,
51 pub author: String,
52 pub excerpt: String,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct EditPreview {
57 pub message_id: String,
58 pub excerpt: String,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Outgoing {
63 pub text: String,
64 pub mentions: Vec<MentionInput>,
65 pub reply: Option<ReplyPreview>,
66 pub edit: Option<EditPreview>,
67 pub images: Vec<OutgoingImage>,
68 pub files: Vec<OutgoingFile>,
69}
70
71impl Outgoing {
72 pub fn has_attachments(&self) -> bool {
73 !self.images.is_empty() || !self.files.is_empty()
74 }
75
76 pub fn extras(&self) -> MessageExtras {
77 MessageExtras {
78 kept: Vec::new(),
79 images: self
80 .images
81 .iter()
82 .map(|outgoing| HostedImage {
83 content_type: outgoing.image.format.mime_type().to_owned(),
84 bytes: Arc::new(outgoing.image.bytes.clone()),
85 })
86 .collect(),
87 files: self
88 .files
89 .iter()
90 .map(|file| file.reference.clone())
91 .collect(),
92 }
93 }
94}
95
96enum UploadEvent {
97 Progress(u8),
98 Uploaded(UploadedFile),
99 Finished(UploadResult),
100}
101
102enum UploadHandle {
103 Network(tokio::task::AbortHandle),
104 Demo(Task<()>),
105}
106
107impl UploadHandle {
108 fn cancel(self) {
109 match self {
110 UploadHandle::Network(handle) => handle.abort(),
111 UploadHandle::Demo(task) => drop(task),
112 }
113 }
114}
115
116pub enum ComposerEvent {
117 Submit(Box<Outgoing>),
118 EditLast,
119}
120
121struct MentionPopup {
122 range: Range<usize>,
123 query: String,
124 candidates: Vec<MentionCandidate>,
125 highlighted: usize,
126}
127
128struct Conversion {
129 value: String,
130 cursor: usize,
131 range: Range<usize>,
132 original: String,
133}
134
135pub struct Composer {
136 app: Entity<AppState>,
137 input: Entity<TextareaState>,
138 conversation_id: Option<String>,
139 reply: Option<ReplyPreview>,
140 editing: Option<EditPreview>,
141 mention_inputs: HashMap<String, MentionInput>,
142 mention_counter: usize,
143 popup: Option<MentionPopup>,
144 lookup: Option<Task<()>>,
145 emoji_popup: Option<EmojiPopup>,
146 emoji_dismissed_at: Option<usize>,
147 recent_emoji: emoji::Recent,
148 conversion: Option<Conversion>,
149 undone_value: Option<String>,
150 previous_value: String,
151 tray: AttachmentTray,
152 uploads: HashMap<u64, UploadHandle>,
153 demo_failed: HashSet<u64>,
154 carry_images_into: Option<String>,
155 _subscription: Subscription,
156}
157
158impl EventEmitter<ComposerEvent> for Composer {}
159
160pub fn is_plain_enter(event: &InputEvent) -> bool {
161 matches!(event, InputEvent::PressEnter { shift: false, .. })
162}
163
164/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
165pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
166 match event {
167 InputEvent::PressEnter { shift: false, .. } => {
168 let trimmed = value.trim();
169 (!trimmed.is_empty()).then(|| trimmed.to_owned())
170 }
171 _ => None,
172 }
173}
174
175pub fn active_mention(
176 text: &str,
177 cursor: usize,
178 tokens: &[Range<usize>],
179) -> Option<(Range<usize>, String)> {
180 if cursor > text.len() || !text.is_char_boundary(cursor) {
181 return None;
182 }
183 let before = &text[..cursor];
184 let at = before.rfind('@')?;
185 if before[..at]
186 .chars()
187 .next_back()
188 .is_some_and(|previous| !previous.is_whitespace())
189 {
190 return None;
191 }
192 let query = &before[at + 1..];
193 let rejected = query.contains('\n')
194 || query.starts_with(char::is_whitespace)
195 || query.ends_with(char::is_whitespace)
196 || query.chars().count() > MENTION_QUERY_MAX_CHARS
197 || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS
198 || tokens
199 .iter()
200 .any(|token| token.start < cursor && at < token.end);
201 (!rejected).then(|| (at..cursor, query.to_owned()))
202}
203
204fn candidate_subtitle(candidate: &MentionCandidate) -> String {
205 match candidate {
206 MentionCandidate::Person(person) => person
207 .job_title
208 .clone()
209 .filter(|title| !title.trim().is_empty())
210 .or_else(|| person.mail.clone())
211 .unwrap_or_default(),
212 MentionCandidate::Channel { .. } => "Channel".to_owned(),
213 MentionCandidate::Team { .. } => "Team".to_owned(),
214 }
215}
216
217fn candidate_key(candidate: &MentionCandidate) -> &str {
218 match candidate {
219 MentionCandidate::Person(person) => &person.user_id,
220 MentionCandidate::Channel { channel_id, .. } => channel_id,
221 MentionCandidate::Team { team_id, .. } => team_id,
222 }
223}
224
225impl Composer {
226 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
227 let input = cx.new(|cx| {
228 TextareaState::new(window, cx)
229 .auto_grow(MIN_ROWS, MAX_ROWS)
230 .submit_on_enter(true)
231 .placeholder("Type a message")
232 });
233 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
234 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
235 Composer {
236 app,
237 input,
238 conversation_id: None,
239 reply: None,
240 editing: None,
241 mention_inputs: HashMap::new(),
242 mention_counter: 0,
243 popup: None,
244 lookup: None,
245 emoji_popup: None,
246 emoji_dismissed_at: None,
247 recent_emoji,
248 conversion: None,
249 undone_value: None,
250 previous_value: String::new(),
251 tray: AttachmentTray::default(),
252 uploads: HashMap::new(),
253 demo_failed: HashSet::new(),
254 carry_images_into: None,
255 _subscription: subscription,
256 }
257 }
258
259 fn on_input_event(
260 &mut self,
261 input: &Entity<TextareaState>,
262 event: &InputEvent,
263 window: &mut Window,
264 cx: &mut Context<Self>,
265 ) {
266 cx.notify();
267 if matches!(event, InputEvent::Change) {
268 self.convert_typed(window, cx);
269 self.update_emoji(cx);
270 self.update_mention(cx);
271 }
272 let value = input.read(cx).value();
273 if submitted_text(event, &value).is_some()
274 || (is_plain_enter(event) && !self.tray.is_empty())
275 {
276 self.submit_current(window, cx);
277 }
278 }
279
280 fn update_mention(&mut self, cx: &mut Context<Self>) {
281 let state = self.input.read(cx);
282 let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect();
283 let found = active_mention(&state.value(), state.cursor(), &tokens);
284 let Some((range, query)) = found else {
285 self.close_mention_popup();
286 return;
287 };
288 let unchanged = self
289 .popup
290 .as_ref()
291 .is_some_and(|popup| popup.query == query && popup.range == range);
292 if unchanged {
293 return;
294 }
295 let previous = self.popup.take();
296 self.popup = Some(MentionPopup {
297 range,
298 query: query.clone(),
299 candidates: previous.map(|popup| popup.candidates).unwrap_or_default(),
300 highlighted: 0,
301 });
302 self.request_candidates(query, cx);
303 }
304
305 fn close_popup(&mut self) {
306 self.close_mention_popup();
307 self.emoji_popup = None;
308 }
309
310 fn close_mention_popup(&mut self) {
311 self.popup = None;
312 self.lookup = None;
313 }
314
315 fn convert_typed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316 let state = self.input.read(cx);
317 let (value, cursor) = (state.value().to_string(), state.cursor());
318 let previous = std::mem::replace(&mut self.previous_value, value.clone());
319 let found = match emoji::typed_char(&previous, &value, cursor) {
320 Some(':') => emoji::closing_code(&value, cursor)
321 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
322 Some(' ') => emoji::smiley_before_space(&value, cursor),
323 _ => None,
324 };
325 let Some((range, glyph)) = found else {
326 return;
327 };
328 let original = value[range.clone()].to_owned();
329 let cursor = self.replace_text(range.clone(), glyph, cursor, window, cx);
330 self.previous_value = self.input.read(cx).value().to_string();
331 self.conversion = Some(Conversion {
332 value: self.previous_value.clone(),
333 cursor,
334 range: range.start..range.start + glyph.len(),
335 original,
336 });
337 self.remember_emoji(glyph, cx);
338 }
339
340 /// Returns the cursor, kept at the same spot relative to the text after `range`.
341 fn replace_text(
342 &mut self,
343 range: Range<usize>,
344 text: &str,
345 cursor: usize,
346 window: &mut Window,
347 cx: &mut Context<Self>,
348 ) -> usize {
349 let cursor = cursor + text.len() - range.len();
350 self.input.update(cx, |state, cx| {
351 state.set_selected_range(range, cx);
352 state.replace(text.to_owned(), window, cx);
353 state.set_selected_range(cursor..cursor, cx);
354 });
355 cursor
356 }
357
358 fn undo_conversion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
359 let state = self.input.read(cx);
360 let unchanged = self.conversion.as_ref().is_some_and(|conversion| {
361 conversion.value == state.value().as_ref() && conversion.cursor == state.cursor()
362 });
363 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
364 return false;
365 };
366 self.replace_text(
367 conversion.range,
368 &conversion.original,
369 conversion.cursor,
370 window,
371 cx,
372 );
373 self.undone_value = Some(self.input.read(cx).value().to_string());
374 self.update_emoji(cx);
375 true
376 }
377
378 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
379 self.recent_emoji.push(glyph);
380 self.recent_emoji.save(&self.app.read(cx).store);
381 }
382
383 fn update_emoji(&mut self, cx: &mut Context<Self>) {
384 let state = self.input.read(cx);
385 let found = emoji::active_query(&state.value(), state.cursor());
386 if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
387 self.emoji_dismissed_at = None;
388 }
389 let found = found.filter(|_| self.emoji_dismissed_at.is_none());
390 let Some((range, query)) = found else {
391 self.emoji_popup = None;
392 return;
393 };
394 let unchanged = self
395 .emoji_popup
396 .as_ref()
397 .is_some_and(|popup| popup.query == query && popup.range == range);
398 if unchanged {
399 return;
400 }
401 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
402 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
403 }
404
405 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
406 let Some(popup) = self.emoji_popup.take() else {
407 return;
408 };
409 let Some(glyph) = popup.selected().map(|found| found.glyph) else {
410 return;
411 };
412 let cursor = popup.range.end;
413 self.replace_text(popup.range, glyph, cursor, window, cx);
414 self.remember_emoji(glyph, cx);
415 cx.notify();
416 }
417
418 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
419 let Some(conversation_id) = self.conversation_id.clone() else {
420 return;
421 };
422 let (demo, engine) = {
423 let state = self.app.read(cx);
424 (state.mode.demo, state.engine.clone())
425 };
426 if demo {
427 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
428 self.apply_candidates(&query, candidates, cx);
429 return;
430 }
431 let Some(engine) = engine else {
432 return;
433 };
434 self.lookup = Some(cx.spawn(async move |this, cx| {
435 cx.background_executor().timer(MENTION_DEBOUNCE).await;
436 let task_query = query.clone();
437 let receiver = runtime::spawn(async move {
438 engine
439 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
440 .await
441 });
442 if let Ok(Ok(candidates)) = receiver.await {
443 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
444 .ok();
445 }
446 }));
447 }
448
449 fn apply_candidates(
450 &mut self,
451 query: &str,
452 candidates: Vec<MentionCandidate>,
453 cx: &mut Context<Self>,
454 ) {
455 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
456 return;
457 };
458 popup.candidates = candidates;
459 popup.highlighted = 0;
460 cx.notify();
461 }
462
463 fn popup_is_open(&self) -> bool {
464 self.emoji_popup.is_some()
465 || self
466 .popup
467 .as_ref()
468 .is_some_and(|popup| !popup.candidates.is_empty())
469 }
470
471 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
472 if let Some(popup) = self.emoji_popup.as_mut() {
473 popup.move_highlight(delta);
474 cx.notify();
475 } else if let Some(popup) = self.popup.as_mut() {
476 let last = popup.candidates.len().saturating_sub(1) as isize;
477 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
478 cx.notify();
479 }
480 }
481
482 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
483 if self.emoji_popup.is_some() {
484 self.accept_emoji(window, cx);
485 } else {
486 self.accept_mention(window, cx);
487 }
488 }
489
490 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
491 let Some(popup) = self.popup.take() else {
492 return;
493 };
494 self.lookup = None;
495 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
496 return;
497 };
498 self.mention_counter += 1;
499 let token_id = format!(
500 "mention-{}-{}",
501 self.mention_counter,
502 candidate_key(candidate)
503 );
504 let label = format!("@{}", candidate.display_name());
505 self.mention_inputs
506 .insert(token_id.clone(), candidate.to_mention());
507 self.input.update(cx, |state, cx| {
508 let token = InlineToken::new(token_id, label);
509 if state
510 .replace_range_with_token(popup.range, token, window, cx)
511 .is_ok()
512 {
513 state.insert(" ", window, cx);
514 }
515 });
516 self.close_popup();
517 cx.notify();
518 }
519
520 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
521 let text = text.to_owned();
522 self.input
523 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
524 }
525
526 pub fn set_conversation(
527 &mut self,
528 conversation_id: &str,
529 name: &str,
530 window: &mut Window,
531 cx: &mut Context<Self>,
532 ) {
533 self.set_placeholder(&format!("Message {name}"), window, cx);
534 if self.conversation_id.as_deref() != Some(conversation_id) {
535 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
536 self.conversation_id = Some(conversation_id.to_owned());
537 self.cancel_uploads();
538 let dropped = if carry {
539 self.tray.keep_images_only()
540 } else {
541 self.tray.clear()
542 };
543 self.discard_uploaded(dropped, cx);
544 self.reply = None;
545 if self.editing.take().is_some() {
546 self.input
547 .update(cx, |state, cx| state.set_value("", window, cx));
548 }
549 self.mention_inputs.clear();
550 self.close_popup();
551 cx.notify();
552 }
553 }
554
555 /// The draft's images follow the user into this chat; any other switch clears the tray.
556 pub fn carry_images_into(&mut self, conversation_id: String) {
557 self.carry_images_into = Some(conversation_id);
558 }
559
560 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
561 discard_uploaded(self.app.read(cx).engine.clone(), files);
562 }
563
564 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
565 self.reply = reply;
566 if self.reply.is_some() {
567 self.editing = None;
568 }
569 cx.notify();
570 }
571
572 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
573 self.restore(&draft, window, cx);
574 self.focus(window, cx);
575 }
576
577 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
578 self.editing = None;
579 self.set_text("", window, cx);
580 }
581
582 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
583 let state = self.input.read(cx);
584 let mut text = state.value().trim().to_owned();
585 if !self.can_send(cx) {
586 return None;
587 }
588 let attachments_apply = self.editing.is_none();
589 if self.undone_value.as_deref() != Some(state.value().as_ref())
590 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
591 {
592 text.replace_range(range, glyph);
593 }
594 let mentions = state
595 .tokens()
596 .iter()
597 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
598 .cloned()
599 .collect();
600 Some(Outgoing {
601 text,
602 mentions,
603 reply: self.reply.clone(),
604 edit: self.editing.clone(),
605 images: if attachments_apply {
606 self.tray.outgoing_images()
607 } else {
608 Vec::new()
609 },
610 files: if attachments_apply {
611 self.tray.outgoing_files()
612 } else {
613 Vec::new()
614 },
615 })
616 }
617
618 fn can_send(&self, cx: &App) -> bool {
619 let has_text = !self.input.read(cx).value().trim().is_empty();
620 if self.editing.is_some() {
621 return has_text;
622 }
623 (has_text || !self.tray.is_empty()) && !self.tray.blocks_send()
624 }
625
626 pub fn is_editing(&self) -> bool {
627 self.editing.is_some()
628 }
629
630 fn files_allowed(&self) -> bool {
631 self.conversation_id
632 .as_deref()
633 .is_some_and(|conversation_id| !conversation_id.is_empty())
634 }
635
636 fn cancel_uploads(&mut self) {
637 for (_, handle) in self.uploads.drain() {
638 handle.cancel();
639 }
640 }
641
642 pub fn open_picker(&mut self, cx: &mut Context<Self>) {
643 if self.editing.is_some() {
644 return;
645 }
646 let receiver = cx.prompt_for_paths(PathPromptOptions {
647 files: true,
648 directories: false,
649 multiple: true,
650 prompt: None,
651 });
652 cx.spawn(async move |this, cx| {
653 if let Ok(Ok(Some(paths))) = receiver.await {
654 this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();
655 }
656 })
657 .detach();
658 }
659
660 pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
661 if self.editing.is_some() || paths.is_empty() {
662 return;
663 }
664 let ids = self.tray.add_pending(&names_of(&paths));
665 for (id, path) in ids.into_iter().zip(paths) {
666 cx.spawn(async move |this, cx| {
667 let loaded = cx
668 .background_executor()
669 .spawn(async move { read_attachment(&path) })
670 .await;
671 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
672 .ok();
673 })
674 .detach();
675 }
676 cx.notify();
677 }
678
679 fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {
680 let ids = self.tray.add_pending(&[pasted_image_name()]);
681 cx.notify();
682 let Some(&id) = ids.first() else {
683 return;
684 };
685 cx.spawn(async move |this, cx| {
686 let loaded = cx
687 .background_executor()
688 .spawn(async move { prepare_pasted_image(pasted) })
689 .await;
690 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
691 .ok();
692 })
693 .detach();
694 }
695
696 fn paste(&mut self, item: &ClipboardItem, cx: &mut Context<Self>) -> bool {
697 if self.editing.is_some() {
698 return false;
699 }
700 match paste_action(item) {
701 PasteAction::Text => false,
702 PasteAction::Files(paths) => {
703 self.add_paths(paths, cx);
704 true
705 }
706 PasteAction::Image(pasted) => {
707 self.add_pasted_image(pasted, cx);
708 true
709 }
710 }
711 }
712
713 fn finish_reading(
714 &mut self,
715 id: u64,
716 loaded: Result<LoadedFile, String>,
717 cx: &mut Context<Self>,
718 ) {
719 match loaded {
720 Ok(loaded) => {
721 let files_allowed = self.files_allowed();
722 if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {
723 self.start_upload(job, cx);
724 }
725 }
726 Err(message) => self.tray.fail_reading(id, message),
727 }
728 cx.notify();
729 }
730
731 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
732 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
733 self.tray.finish_upload(job.id, UploadResult::Failed);
734 return;
735 };
736 let state = self.app.read(cx);
737 let (demo, engine) = (state.mode.demo, state.engine.clone());
738 if demo {
739 self.simulate_upload(job, cx);
740 return;
741 }
742 let Some(engine) = engine else {
743 self.tray.finish_upload(job.id, UploadResult::Failed);
744 return;
745 };
746 let id = job.id;
747 let (event_sender, mut event_receiver) =
748 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
749 let finished_sender = event_sender.clone();
750 let (_, handle) = runtime::spawn_abortable(async move {
751 let result = async {
752 let uploaded = match job.kind {
753 JobKind::Upload => {
754 let progress_sender = event_sender.clone();
755 let uploaded = engine
756 .upload_attachment_file(
757 &conversation_id,
758 &job.name,
759 &job.bytes,
760 move |percent| {
761 let _ = progress_sender.send(UploadEvent::Progress(percent));
762 },
763 )
764 .await;
765 match uploaded {
766 Ok(uploaded) => {
767 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
768 uploaded
769 }
770 Err(_) => return UploadResult::Failed,
771 }
772 }
773 JobKind::Share(uploaded) => uploaded,
774 };
775 let Some(reference) = uploaded.reference() else {
776 return UploadResult::Failed;
777 };
778 match engine.share_attachment(&conversation_id, &uploaded).await {
779 Ok(()) => UploadResult::Done(DoneFile {
780 reference,
781 uploaded: Some(uploaded),
782 }),
783 Err(_) => UploadResult::ShareFailed(uploaded),
784 }
785 }
786 .await;
787 let _ = finished_sender.send(UploadEvent::Finished(result));
788 });
789 self.uploads.insert(id, UploadHandle::Network(handle));
790 cx.spawn(async move |this, cx| {
791 while let Some(event) = event_receiver.recv().await {
792 let updated = this.update(cx, |this, cx| {
793 let orphan = match event {
794 UploadEvent::Progress(percent) => {
795 this.tray.set_progress(id, percent);
796 None
797 }
798 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
799 UploadEvent::Finished(result) => this.finish_upload(id, result),
800 };
801 this.discard_uploaded(orphan.into_iter().collect(), cx);
802 cx.notify();
803 });
804 if updated.is_err() {
805 break;
806 }
807 }
808 })
809 .detach();
810 }
811
812 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
813 let id = job.id;
814 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
815 let task = cx.spawn(async move |this, cx| {
816 for step in 1..=DEMO_UPLOAD_STEPS {
817 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
818 if fails && step == DEMO_FAILURE_STEP {
819 this.update(cx, |this, cx| {
820 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
821 })
822 .ok();
823 return;
824 }
825 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
826 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
827 .ok();
828 }
829 let reference = FileReference {
830 attachment_id: format!("demo-attachment-{id}"),
831 content_url: format!("https://demo.invalid/files/{}", job.name),
832 name: job.name,
833 };
834 let done = DoneFile {
835 reference,
836 uploaded: None,
837 };
838 this.update(cx, |this, cx| {
839 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
840 })
841 .ok();
842 });
843 self.uploads.insert(id, UploadHandle::Demo(task));
844 }
845
846 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
847 self.tray.set_progress(id, percent);
848 cx.notify();
849 }
850
851 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
852 self.uploads.remove(&id);
853 self.tray.finish_upload(id, result)
854 }
855
856 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
857 self.finish_upload(id, result);
858 cx.notify();
859 }
860
861 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
862 if let Some(handle) = self.uploads.remove(&id) {
863 handle.cancel();
864 }
865 let uploaded = self.tray.remove(id);
866 self.discard_uploaded(uploaded.into_iter().collect(), cx);
867 cx.notify();
868 }
869
870 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
871 if let Some(job) = self.tray.retry(id) {
872 self.start_upload(job, cx);
873 }
874 cx.notify();
875 }
876
877 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
878 let Some(outgoing) = self.outgoing(cx) else {
879 return;
880 };
881 self.input
882 .update(cx, |state, cx| state.set_value("", window, cx));
883 self.mention_inputs.clear();
884 if self.editing.is_none() {
885 self.tray.clear();
886 }
887 self.reply = None;
888 self.editing = None;
889 self.close_popup();
890 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
891 cx.notify();
892 }
893
894 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
895 self.mention_inputs.clear();
896 let mut content = InputContent::new(outgoing.text.clone());
897 let mut cursor = 0;
898 for mention in &outgoing.mentions {
899 let needle = format!("@{}", mention.text);
900 let Some(offset) = outgoing.text[cursor..].find(&needle) else {
901 continue;
902 };
903 let range = cursor + offset..cursor + offset + needle.len();
904 self.mention_counter += 1;
905 let token_id = format!("mention-{}", self.mention_counter);
906 let token = InlineToken::new(token_id.clone(), needle);
907 if let Ok(next) = content.clone().with_token(range.clone(), token) {
908 content = next;
909 self.mention_inputs.insert(token_id, mention.clone());
910 cursor = range.end;
911 }
912 }
913 let end = outgoing.text.len();
914 self.input.update(cx, |state, cx| {
915 state.set_value(content, window, cx);
916 state.set_selected_range(end..end, cx);
917 });
918 self.reply = outgoing.reply.clone();
919 self.editing = outgoing.edit.clone();
920 if outgoing.edit.is_none() {
921 self.cancel_uploads();
922 self.tray.restore(&outgoing.images, &outgoing.files);
923 }
924 self.close_popup();
925 cx.notify();
926 }
927
928 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
929 let text = text.to_owned();
930 let end = text.len();
931 self.input.update(cx, |state, cx| {
932 state.set_value(text, window, cx);
933 state.set_selected_range(end..end, cx);
934 });
935 self.mention_inputs.clear();
936 self.update_emoji(cx);
937 self.update_mention(cx);
938 cx.notify();
939 }
940
941 pub fn is_empty(&self, cx: &App) -> bool {
942 self.input.read(cx).value().trim().is_empty() && self.tray.is_empty()
943 }
944
945 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
946 self.input.update(cx, |state, cx| state.focus(window, cx));
947 }
948
949 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
950 let popup = self
951 .popup
952 .as_ref()
953 .filter(|popup| !popup.candidates.is_empty())?;
954 let directory = &self.app.read(cx).directory;
955 let rows = popup
956 .candidates
957 .iter()
958 .enumerate()
959 .map(|(index, candidate)| {
960 let name = candidate.display_name().to_owned();
961 let avatar = match candidate {
962 MentionCandidate::Person(person) => {
963 person_avatar(directory, Some(&person.user_id), &name, 28.)
964 }
965 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
966 };
967 let subtitle = candidate_subtitle(candidate);
968 h_flex()
969 .id(ElementId::Name(format!("mention-row-{index}").into()))
970 .mx(px(6.))
971 .px(px(6.))
972 .h(px(POPUP_ROW_HEIGHT))
973 .gap(px(10.))
974 .items_center()
975 .rounded(px(6.))
976 .cursor_pointer()
977 .when(index == popup.highlighted, |row| {
978 row.bg(theme::surface_raised())
979 })
980 .hover(|row| row.bg(theme::row_hover()))
981 .child(avatar)
982 .child(
983 v_flex()
984 .flex_1()
985 .min_w_0()
986 .child(
987 div()
988 .truncate()
989 .text_size(px(13.5))
990 .text_color(theme::text())
991 .child(name),
992 )
993 .when(!subtitle.is_empty(), |column| {
994 column.child(
995 div()
996 .truncate()
997 .text_size(px(12.))
998 .text_color(theme::text_muted())
999 .child(subtitle),
1000 )
1001 }),
1002 )
1003 .on_click(cx.listener(move |this, _, window, cx| {
1004 if let Some(popup) = this.popup.as_mut() {
1005 popup.highlighted = index;
1006 }
1007 this.accept_mention(window, cx);
1008 }))
1009 });
1010 Some(
1011 v_flex()
1012 .id("mention-popup")
1013 .absolute()
1014 .bottom(relative(1.))
1015 .left_0()
1016 .mb(px(6.))
1017 .w(px(POPUP_WIDTH))
1018 .py(px(6.))
1019 .rounded(px(10.))
1020 .border_1()
1021 .border_color(theme::border_strong())
1022 .bg(theme::surface())
1023 .shadow_lg()
1024 .occlude()
1025 .children(rows)
1026 .into_any_element(),
1027 )
1028 }
1029
1030 fn render_emoji_popup(
1031 &self,
1032 window: &mut Window,
1033 cx: &mut Context<Self>,
1034 ) -> Option<AnyElement> {
1035 let popup = self.emoji_popup.as_ref()?;
1036 let colon = popup.range.start..popup.range.start + 1;
1037 let anchor = self
1038 .input
1039 .read(cx)
1040 .range_to_bounds(&colon)
1041 .map(|bounds| bounds.origin);
1042 if anchor.is_none() {
1043 window.request_animation_frame();
1044 }
1045 let composer = cx.entity().downgrade();
1046 Some(emoji_popup::render(
1047 popup,
1048 anchor,
1049 move |index, window, cx| {
1050 composer
1051 .update(cx, |this, cx| {
1052 if let Some(popup) = this.emoji_popup.as_mut() {
1053 popup.highlighted = index;
1054 }
1055 this.accept_emoji(window, cx);
1056 })
1057 .ok();
1058 },
1059 ))
1060 }
1061
1062 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1063 let edit = self.editing.as_ref()?;
1064 Some(
1065 h_flex()
1066 .w_full()
1067 .mb(px(6.))
1068 .gap(px(10.))
1069 .items_center()
1070 .pl(px(10.))
1071 .pr(px(4.))
1072 .py(px(6.))
1073 .rounded(px(8.))
1074 .bg(theme::surface())
1075 .border_1()
1076 .border_color(theme::border())
1077 .child(icon(IconName::Pencil, 14., theme::accent_text()))
1078 .child(
1079 v_flex()
1080 .flex_1()
1081 .min_w_0()
1082 .child(
1083 div()
1084 .truncate()
1085 .text_size(px(12.))
1086 .font_weight(FontWeight::SEMIBOLD)
1087 .text_color(theme::accent_text())
1088 .child("Editing message"),
1089 )
1090 .child(
1091 div()
1092 .truncate()
1093 .text_size(px(12.))
1094 .text_color(theme::text_muted())
1095 .child(edit.excerpt.clone()),
1096 ),
1097 )
1098 .child(
1099 div()
1100 .id("edit-close")
1101 .size(px(24.))
1102 .flex()
1103 .items_center()
1104 .justify_center()
1105 .rounded(px(6.))
1106 .cursor_pointer()
1107 .hover(|button| button.bg(theme::row_hover()))
1108 .child(icon(IconName::Close, 14., theme::text_muted()))
1109 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
1110 ),
1111 )
1112 }
1113
1114 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1115 let reply = self.reply.as_ref()?;
1116 Some(
1117 h_flex()
1118 .w_full()
1119 .mb(px(6.))
1120 .gap(px(10.))
1121 .items_center()
1122 .pl(px(10.))
1123 .pr(px(4.))
1124 .py(px(6.))
1125 .rounded(px(8.))
1126 .bg(theme::surface())
1127 .border_1()
1128 .border_color(theme::border())
1129 .child(icon(IconName::Undo2, 14., theme::accent_text()))
1130 .child(
1131 v_flex()
1132 .flex_1()
1133 .min_w_0()
1134 .child(
1135 div()
1136 .truncate()
1137 .text_size(px(12.))
1138 .font_weight(FontWeight::SEMIBOLD)
1139 .text_color(theme::accent_text())
1140 .child(format!("Replying to {}", reply.author)),
1141 )
1142 .child(
1143 div()
1144 .truncate()
1145 .text_size(px(12.))
1146 .text_color(theme::text_muted())
1147 .child(reply.excerpt.clone()),
1148 ),
1149 )
1150 .child(
1151 div()
1152 .id("reply-close")
1153 .size(px(24.))
1154 .flex()
1155 .items_center()
1156 .justify_center()
1157 .rounded(px(6.))
1158 .cursor_pointer()
1159 .hover(|button| button.bg(theme::row_hover()))
1160 .child(icon(IconName::Close, 14., theme::text_muted()))
1161 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
1162 ),
1163 )
1164 }
1165}
1166
1167impl Render for Composer {
1168 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1169 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
1170 let can_send = self.can_send(cx);
1171 let can_attach = self.editing.is_none();
1172 let send = div()
1173 .id("composer-send")
1174 .size(px(32.))
1175 .flex_none()
1176 .flex()
1177 .items_center()
1178 .justify_center()
1179 .rounded(px(8.))
1180 .child(symbol("keyboard_return", 20., white()))
1181 .when(!can_send, |button| button.opacity(0.4))
1182 .when(can_send, |button| {
1183 button
1184 .cursor_pointer()
1185 .hover(|button| button.bg(white().opacity(0.1)))
1186 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
1187 });
1188 let attach = can_attach.then(|| {
1189 div()
1190 .id("composer-attach")
1191 .size(px(32.))
1192 .flex_none()
1193 .flex()
1194 .items_center()
1195 .justify_center()
1196 .rounded(px(8.))
1197 .cursor_pointer()
1198 .hover(|button| button.bg(theme::row_hover()))
1199 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
1200 .child(symbol("attach_file", 20., theme::text_muted()))
1201 .on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))
1202 });
1203 let composer = cx.weak_entity();
1204 let input = Textarea::new(&self.input)
1205 .appearance(false)
1206 .bordered(false)
1207 .on_paste(move |item, _, cx| {
1208 composer
1209 .update(cx, |this, cx| this.paste(item, cx))
1210 .unwrap_or(false)
1211 })
1212 .token(|context, _, _| {
1213 div()
1214 .h(context.line_height())
1215 .px(px(5.))
1216 .rounded(px(5.))
1217 .bg(if context.is_selected() {
1218 theme::accent().opacity(0.4)
1219 } else {
1220 theme::mention_background(false)
1221 })
1222 .text_color(theme::mention_text())
1223 .font_weight(FontWeight::SEMIBOLD)
1224 .child(context.token().label().clone())
1225 });
1226 let tray = can_attach
1227 .then(|| {
1228 render_tray(
1229 &self.tray,
1230 Self::remove_attachment,
1231 Self::retry_attachment,
1232 cx,
1233 )
1234 })
1235 .flatten();
1236 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
1237 div()
1238 .w_full()
1239 .mb(px(6.))
1240 .text_size(px(12.))
1241 .text_color(theme::amber())
1242 .child(notice.to_owned())
1243 });
1244 v_flex()
1245 .w_full()
1246 .flex_none()
1247 .px(px(24.))
1248 .pt(px(8.))
1249 .pb(px(12.))
1250 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
1251 if this.popup_is_open() {
1252 this.move_highlight(-1, cx);
1253 cx.stop_propagation();
1254 } else if this.editing.is_none() && this.is_empty(cx) {
1255 cx.emit(ComposerEvent::EditLast);
1256 cx.stop_propagation();
1257 }
1258 }))
1259 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
1260 if this.popup_is_open() {
1261 this.move_highlight(1, cx);
1262 cx.stop_propagation();
1263 }
1264 }))
1265 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
1266 if this.popup_is_open() {
1267 this.accept_popup(window, cx);
1268 cx.stop_propagation();
1269 }
1270 }))
1271 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
1272 if this.popup_is_open() {
1273 this.accept_popup(window, cx);
1274 cx.stop_propagation();
1275 }
1276 }))
1277 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
1278 if this.undo_conversion(window, cx) {
1279 cx.stop_propagation();
1280 }
1281 }))
1282 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
1283 if let Some(popup) = &this.emoji_popup {
1284 this.emoji_dismissed_at = Some(popup.range.start);
1285 }
1286 if this.popup.is_some() || this.emoji_popup.is_some() {
1287 this.close_popup();
1288 cx.notify();
1289 cx.stop_propagation();
1290 } else if this.editing.is_some() {
1291 this.cancel_edit(window, cx);
1292 cx.stop_propagation();
1293 }
1294 }))
1295 .children(notice)
1296 .children(self.render_reply_strip(cx))
1297 .children(self.render_edit_strip(cx))
1298 .child(
1299 div()
1300 .relative()
1301 .w_full()
1302 .children(self.render_popup(cx))
1303 .children(self.render_emoji_popup(window, cx))
1304 .child(
1305 v_flex()
1306 .w_full()
1307 .rounded(px(10.))
1308 .bg(theme::surface())
1309 .border_1()
1310 .border_color(if focused {
1311 theme::accent()
1312 } else {
1313 theme::border_strong()
1314 })
1315 .children(tray)
1316 .child(
1317 h_flex()
1318 .w_full()
1319 .items_end()
1320 .gap(px(6.))
1321 .py(px(6.))
1322 .pl(px(if can_attach { 6. } else { 12. }))
1323 .pr(px(6.))
1324 .children(attach)
1325 .child(div().flex_1().min_w_0().child(input))
1326 .child(send),
1327 ),
1328 ),
1329 )
1330 }
1331}
1332
1333#[cfg(test)]
1334mod tests {
1335 use super::{active_mention, submitted_text};
1336 use gpui_kit::component::input::InputEvent;
1337
1338 fn press(shift: bool) -> InputEvent {
1339 InputEvent::PressEnter {
1340 secondary: false,
1341 shift,
1342 }
1343 }
1344
1345 #[test]
1346 fn enter_sends_trimmed_text() {
1347 assert_eq!(
1348 submitted_text(&press(false), " hello \n"),
1349 Some("hello".into())
1350 );
1351 }
1352
1353 #[test]
1354 fn shift_enter_never_sends() {
1355 assert_eq!(submitted_text(&press(true), "hello"), None);
1356 }
1357
1358 #[test]
1359 fn blank_text_never_sends() {
1360 assert_eq!(submitted_text(&press(false), " \n "), None);
1361 }
1362
1363 #[test]
1364 fn other_events_never_send() {
1365 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
1366 }
1367
1368 #[test]
1369 fn at_sign_opens_a_mention_query() {
1370 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
1371 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
1372 }
1373
1374 #[test]
1375 fn names_with_a_space_keep_the_query_open() {
1376 assert_eq!(
1377 active_mention("@Mara Lin", 9, &[]),
1378 Some((0..9, "Mara Lin".into()))
1379 );
1380 }
1381
1382 #[test]
1383 fn mail_addresses_and_closed_queries_do_not_open() {
1384 assert_eq!(active_mention("a@b", 3, &[]), None);
1385 assert_eq!(active_mention("@Mara ", 6, &[]), None);
1386 assert_eq!(active_mention("@ x", 3, &[]), None);
1387 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
1388 }
1389
1390 #[test]
1391 fn text_inside_a_token_does_not_reopen() {
1392 let token = 0..15;
1393 assert_eq!(
1394 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
1395 None
1396 );
1397 assert_eq!(
1398 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
1399 Some((16..19, "Pr".into()))
1400 );
1401 }
1402
1403 #[test]
1404 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
1405 use std::sync::Arc;
1406
1407 use gpui_kit::{Image, ImageFormat};
1408 use teams_core::FileKind;
1409
1410 use super::{Outgoing, OutgoingFile, OutgoingImage};
1411
1412 let outgoing = Outgoing {
1413 text: String::new(),
1414 mentions: Vec::new(),
1415 reply: None,
1416 edit: None,
1417 images: vec![OutgoingImage {
1418 name: "pasted-image.png".into(),
1419 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
1420 dimensions: Some((1, 1)),
1421 }],
1422 files: vec![OutgoingFile {
1423 name: "plan.pdf".into(),
1424 size: 9,
1425 kind: FileKind::Pdf,
1426 uploaded: None,
1427 reference: teams_core::FileReference {
1428 attachment_id: "guid".into(),
1429 content_url: "https://files.example/plan.pdf".into(),
1430 name: "plan.pdf".into(),
1431 },
1432 }],
1433 };
1434 let extras = outgoing.extras();
1435 assert_eq!(extras.images[0].content_type, "image/png");
1436 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
1437 assert_eq!(extras.files[0].attachment_id, "guid");
1438 assert!(outgoing.has_attachments());
1439 }
1440
1441 #[test]
1442 fn enter_sends_attachments_even_without_text() {
1443 assert!(super::is_plain_enter(&press(false)));
1444 assert!(!super::is_plain_enter(&press(true)));
1445 assert!(!super::is_plain_enter(&InputEvent::Change));
1446 }
1447
1448 mod keys {
1449 use std::sync::Arc;
1450
1451 use gpui_kit::test::TestWindowExt as _;
1452 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
1453 use store::Store;
1454
1455 use super::super::Composer;
1456 use crate::app_state::{AppState, Mode};
1457
1458 #[gpui_kit::test]
1459 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
1460 cx.update(gpui_kit::init);
1461 let store = Arc::new(Store::open_in_memory().unwrap());
1462 let mode = Mode {
1463 demo: true,
1464 read_only: false,
1465 demo_sync: None,
1466 };
1467 let (handle, composer) = cx.update(|cx| {
1468 let app = cx.new(|_| AppState::new(store, mode));
1469 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1470 cx.new(|cx| Composer::new(app, window, cx))
1471 })
1472 .unwrap()
1473 });
1474 let value = cx
1475 .update_window(handle, |_, window, cx| {
1476 composer.update(cx, |composer, cx| composer.focus(window, cx));
1477 window.render_frame(cx);
1478 window.input("first line", cx);
1479 window.press("shift-enter", cx);
1480 window.input("second line", cx);
1481 window.press("ctrl-a", cx);
1482 window.input("X", cx);
1483 composer.read(cx).input.read(cx).value()
1484 })
1485 .unwrap();
1486 assert_eq!(value, "X");
1487 }
1488
1489 #[gpui_kit::test]
1490 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
1491 cx.update(gpui_kit::init);
1492 let store = Arc::new(Store::open_in_memory().unwrap());
1493 let mode = Mode {
1494 demo: true,
1495 read_only: false,
1496 demo_sync: None,
1497 };
1498 let (handle, composer) = cx.update(|cx| {
1499 let app = cx.new(|_| AppState::new(store, mode));
1500 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1501 cx.new(|cx| Composer::new(app, window, cx))
1502 })
1503 .unwrap()
1504 });
1505 let directory = tempfile::tempdir().unwrap();
1506 let path = directory.path().join("plan.pdf");
1507 std::fs::write(&path, b"%PDF-1.7").unwrap();
1508 cx.update_window(handle, |_, window, cx| {
1509 composer.update(cx, |composer, cx| {
1510 composer.set_conversation("demo-chat", "Demo", window, cx);
1511 composer.add_paths(vec![path], cx);
1512 });
1513 })
1514 .unwrap();
1515 cx.run_until_parked();
1516 cx.update(|cx| {
1517 let composer = composer.read(cx);
1518 assert!(composer.tray.blocks_send());
1519 assert!(!composer.can_send(cx));
1520 });
1521 cx.executor()
1522 .advance_clock(std::time::Duration::from_secs(3));
1523 cx.run_until_parked();
1524 cx.update(|cx| {
1525 let composer = composer.read(cx);
1526 assert!(composer.can_send(cx));
1527 let outgoing = composer
1528 .outgoing(cx)
1529 .expect("an attachment alone is a message");
1530 assert_eq!(outgoing.text, "");
1531 assert_eq!(outgoing.files.len(), 1);
1532 assert_eq!(outgoing.files[0].name, "plan.pdf");
1533 });
1534 }
1535
1536 #[gpui_kit::test]
1537 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
1538 cx.update(gpui_kit::init);
1539 let store = Arc::new(Store::open_in_memory().unwrap());
1540 let mode = Mode {
1541 demo: true,
1542 read_only: false,
1543 demo_sync: None,
1544 };
1545 let (handle, composer) = cx.update(|cx| {
1546 let app = cx.new(|_| AppState::new(store, mode));
1547 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1548 cx.new(|cx| Composer::new(app, window, cx))
1549 })
1550 .unwrap()
1551 });
1552 let directory = tempfile::tempdir().unwrap();
1553 let path = directory.path().join("plan.pdf");
1554 std::fs::write(&path, b"%PDF-1.7").unwrap();
1555 cx.update_window(handle, |_, window, cx| {
1556 composer.update(cx, |composer, cx| {
1557 composer.set_conversation("demo-chat", "Demo", window, cx);
1558 composer.add_paths(vec![path], cx);
1559 });
1560 })
1561 .unwrap();
1562 cx.run_until_parked();
1563 cx.update_window(handle, |_, window, cx| {
1564 composer.update(cx, |composer, cx| {
1565 composer.set_conversation("other-chat", "Other", window, cx)
1566 });
1567 })
1568 .unwrap();
1569 cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));
1570 }
1571
1572 fn demo_composer(
1573 cx: &mut TestAppContext,
1574 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
1575 cx.update(gpui_kit::init);
1576 let store = Arc::new(Store::open_in_memory().unwrap());
1577 let mode = Mode {
1578 demo: true,
1579 read_only: false,
1580 demo_sync: None,
1581 };
1582 let (handle, composer) = cx.update(|cx| {
1583 let app = cx.new(|_| AppState::new(store, mode));
1584 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
1585 cx.new(|cx| Composer::new(app, window, cx))
1586 })
1587 .unwrap()
1588 });
1589 (handle, composer)
1590 }
1591
1592 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
1593 let path = directory.join("dot.png");
1594 image::RgbaImage::new(2, 2).save(&path).unwrap();
1595 path
1596 }
1597
1598 #[gpui_kit::test]
1599 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
1600 use super::super::{EditPreview, Outgoing};
1601
1602 let (handle, composer) = demo_composer(cx);
1603 let directory = tempfile::tempdir().unwrap();
1604 let path = directory.path().join("plan.pdf");
1605 std::fs::write(&path, b"%PDF-1.7").unwrap();
1606 cx.update_window(handle, |_, window, cx| {
1607 composer.update(cx, |composer, cx| {
1608 composer.set_conversation("demo-chat", "Demo", window, cx);
1609 composer.add_paths(vec![path], cx);
1610 });
1611 })
1612 .unwrap();
1613 cx.run_until_parked();
1614 cx.executor()
1615 .advance_clock(std::time::Duration::from_secs(3));
1616 cx.run_until_parked();
1617 cx.update_window(handle, |_, window, cx| {
1618 composer.update(cx, |composer, cx| {
1619 let draft = Outgoing {
1620 text: "old".into(),
1621 mentions: Vec::new(),
1622 reply: None,
1623 edit: Some(EditPreview {
1624 message_id: "m1".into(),
1625 excerpt: "old".into(),
1626 }),
1627 images: Vec::new(),
1628 files: Vec::new(),
1629 };
1630 composer.begin_edit(draft, window, cx);
1631 });
1632 })
1633 .unwrap();
1634 cx.update(|cx| {
1635 let composer = composer.read(cx);
1636 assert_eq!(composer.tray.items().len(), 1);
1637 let outgoing = composer.outgoing(cx).unwrap();
1638 assert!(outgoing.files.is_empty());
1639 assert_eq!(outgoing.text, "old");
1640 });
1641 cx.update_window(handle, |_, window, cx| {
1642 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
1643 })
1644 .unwrap();
1645 cx.update(|cx| {
1646 let composer = composer.read(cx);
1647 assert_eq!(composer.tray.items().len(), 1);
1648 assert!(composer.can_send(cx));
1649 });
1650 }
1651
1652 #[gpui_kit::test]
1653 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
1654 let (handle, composer) = demo_composer(cx);
1655 let directory = tempfile::tempdir().unwrap();
1656 let path = small_png(directory.path());
1657 for (carry, chosen, expected) in [
1658 (Some("chat-a"), "chat-a", 1),
1659 (None, "chat-b", 0),
1660 (Some("chat-a"), "chat-b", 0),
1661 ] {
1662 cx.update_window(handle, |_, window, cx| {
1663 composer.update(cx, |composer, cx| {
1664 composer.set_conversation("", "", window, cx);
1665 composer.add_paths(vec![path.clone()], cx);
1666 });
1667 })
1668 .unwrap();
1669 cx.run_until_parked();
1670 cx.update_window(handle, |_, window, cx| {
1671 composer.update(cx, |composer, cx| {
1672 if let Some(chat) = carry {
1673 composer.carry_images_into(chat.to_owned());
1674 }
1675 composer.set_conversation(chosen, "Chat", window, cx);
1676 });
1677 })
1678 .unwrap();
1679 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
1680 }
1681 }
1682
1683 #[gpui_kit::test]
1684 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
1685 cx: &mut TestAppContext,
1686 ) {
1687 let (handle, composer) = demo_composer(cx);
1688 let directory = tempfile::tempdir().unwrap();
1689 let png = small_png(directory.path());
1690 let pdf = directory.path().join("plan.pdf");
1691 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
1692 cx.update_window(handle, |_, window, cx| {
1693 composer.update(cx, |composer, cx| {
1694 composer.set_conversation("bob-chat", "Bob", window, cx);
1695 composer.add_paths(vec![png, pdf], cx);
1696 });
1697 })
1698 .unwrap();
1699 cx.run_until_parked();
1700 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
1701 cx.update_window(handle, |_, window, cx| {
1702 composer.update(cx, |composer, cx| {
1703 composer.carry_images_into(String::new());
1704 composer.set_conversation("", "", window, cx);
1705 });
1706 })
1707 .unwrap();
1708 cx.update(|cx| {
1709 let composer = composer.read(cx);
1710 assert_eq!(composer.tray.items().len(), 1);
1711 assert_eq!(composer.tray.items()[0].name, "dot.png");
1712 assert!(!composer.files_allowed());
1713 });
1714 }
1715 }
1716}