BlueGit

ict rusty-teams

Files

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

composer.rs

composer.rs 105.4 KiB Download Raw
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
3use std::ops::Range;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::sync::Arc;
7use std::time::Duration;
8
9use gpui_kit::assets::IconName;
10use gpui_kit::component::{
11 ActiveTheme as _, h_flex,
12 input::{
13 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
14 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
16 },
17 tooltip::Tooltip,
18 v_flex,
19};
20use gpui_kit::prelude::FluentBuilder as _;
21use gpui_kit::*;
22use teams_core::{
23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24 MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,
25 link_url, map_offset, reverse_edits,
26};
27
28use super::attachment_tray::{
29 AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,
30 UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,
31 prepare_pasted_image, read_attachment, render_tray,
32};
33use super::avatar::{person_avatar, square_avatar};
34use super::draft_style::draft_style;
35use super::emoji_popup::{self, EmojiPopup};
36use super::format_toolbar::{self, FormatButton};
37use super::widgets::{icon, symbol};
38use crate::app_state::AppState;
39use crate::emoji;
40use crate::runtime;
41use crate::theme;
42
43const MIN_ROWS: usize = 1;
44const MAX_ROWS: usize = 8;
45const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
46const MENTION_LIMIT: usize = 8;
47const MENTION_QUERY_MAX_CHARS: usize = 32;
48const MENTION_QUERY_MAX_WORDS: usize = 3;
49const POPUP_WIDTH: f32 = 380.;
50const POPUP_ROW_HEIGHT: f32 = 44.;
51const DEMO_UPLOAD_STEPS: u8 = 10;
52const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
53const DEMO_FAILURE_STEP: u8 = 6;
54const HISTORY_LIMIT: usize = 200;
55const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
56const KEY_CONTEXT: &str = "Composer";
57
58actions!(
59 composer,
60 [
61 ToggleBold,
62 ToggleItalic,
63 ToggleUnderline,
64 ToggleStrike,
65 ToggleCode,
66 EditLink
67 ]
68);
69
70pub fn bind_keys(cx: &mut App) {
71 cx.bind_keys([
72 KeyBinding::new("ctrl-b", ToggleBold, Some(KEY_CONTEXT)),
73 KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),
74 KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),
75 KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),
76 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
77 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
78 #[cfg(target_os = "macos")]
79 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
80 #[cfg(target_os = "macos")]
81 KeyBinding::new("cmd-i", ToggleItalic, Some(KEY_CONTEXT)),
82 #[cfg(target_os = "macos")]
83 KeyBinding::new("cmd-u", ToggleUnderline, Some(KEY_CONTEXT)),
84 #[cfg(target_os = "macos")]
85 KeyBinding::new("cmd-k", EditLink, Some(KEY_CONTEXT)),
86 ]);
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct ReplyPreview {
91 pub message_id: String,
92 pub author: String,
93 pub excerpt: String,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct EditPreview {
98 pub message_id: String,
99 pub excerpt: String,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Outgoing {
104 pub draft: Draft,
105 pub mentions: Vec<MentionInput>,
106 pub reply: Option<ReplyPreview>,
107 pub edit: Option<EditPreview>,
108 pub images: Vec<OutgoingImage>,
109 pub files: Vec<OutgoingFile>,
110}
111
112impl Outgoing {
113 /// Without list and quote markers, for previews.
114 pub fn text(&self) -> String {
115 self.draft.plain_text()
116 }
117
118 /// The body before mentions become `<at>` tags.
119 pub fn html(&self) -> String {
120 self.draft.to_html()
121 }
122
123 pub fn has_attachments(&self) -> bool {
124 !self.images.is_empty() || !self.files.is_empty()
125 }
126
127 pub fn extras(&self) -> MessageExtras {
128 MessageExtras {
129 kept: Vec::new(),
130 images: self
131 .images
132 .iter()
133 .map(|outgoing| HostedImage {
134 content_type: outgoing.image.format.mime_type().to_owned(),
135 bytes: Arc::new(outgoing.image.bytes.clone()),
136 })
137 .collect(),
138 files: self
139 .files
140 .iter()
141 .map(|file| file.reference.clone())
142 .collect(),
143 }
144 }
145}
146
147enum UploadEvent {
148 Progress(u8),
149 Uploaded(UploadedFile),
150 Finished(UploadResult),
151}
152
153enum UploadHandle {
154 Network(tokio::task::AbortHandle),
155 Demo(Task<()>),
156}
157
158impl UploadHandle {
159 fn cancel(self) {
160 match self {
161 UploadHandle::Network(handle) => handle.abort(),
162 UploadHandle::Demo(task) => drop(task),
163 }
164 }
165}
166
167pub enum ComposerEvent {
168 Submit(Box<Outgoing>),
169 EditLast,
170}
171
172struct MentionPopup {
173 range: Range<usize>,
174 query: String,
175 candidates: Vec<MentionCandidate>,
176 highlighted: usize,
177}
178
179/// An automatic edit Backspace takes back while nothing changed since.
180struct Conversion {
181 value: String,
182 cursor: usize,
183 before: Draft,
184 restore: Vec<Edit>,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188enum StepKind {
189 Typing { after_space: bool },
190 Deleting,
191 Other,
192}
193
194/// One state of the composer's own undo history: text, tokens, formatting and selection.
195struct HistoryStep {
196 draft: Draft,
197 tokens: Vec<(Range<usize>, InlineToken)>,
198 selection: Range<usize>,
199 kind: StepKind,
200}
201
202struct LinkEditor {
203 range: Range<usize>,
204 field: Entity<InputState>,
205 refused: bool,
206 _edits: Subscription,
207}
208
209type DraftDecorations = (
210 TextDecorationCollection<TextareaMode>,
211 RangeDecorationCollection<TextareaMode>,
212);
213
214pub struct Composer {
215 app: Entity<AppState>,
216 input: Entity<TextareaState>,
217 conversation_id: Option<String>,
218 reply: Option<ReplyPreview>,
219 editing: Option<EditPreview>,
220 mention_inputs: HashMap<String, MentionInput>,
221 mention_counter: usize,
222 popup: Option<MentionPopup>,
223 lookup: Option<Task<()>>,
224 emoji_popup: Option<EmojiPopup>,
225 emoji_dismissed_at: Option<usize>,
226 recent_emoji: emoji::Recent,
227 conversion: Option<Conversion>,
228 undone_value: Option<String>,
229 previous_value: String,
230 draft: Draft,
231 decorations: DraftDecorations,
232 pending_style: Option<TypingStyle>,
233 history: Vec<HistoryStep>,
234 history_index: usize,
235 pasted_markdown: Option<String>,
236 paste_hint: Option<Task<()>>,
237 copied: Option<(String, Vec<DraftLine>)>,
238 toolbar_dismissed: Option<Range<usize>>,
239 mouse_selecting: bool,
240 link_editor: Option<LinkEditor>,
241 composer_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
242 tray: AttachmentTray,
243 uploads: HashMap<u64, UploadHandle>,
244 demo_failed: HashSet<u64>,
245 carry_images_into: Option<String>,
246 _subscriptions: [Subscription; 2],
247}
248
249impl EventEmitter<ComposerEvent> for Composer {}
250
251pub fn is_plain_enter(event: &InputEvent) -> bool {
252 matches!(event, InputEvent::PressEnter { shift: false, .. })
253}
254
255/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
256pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
257 match event {
258 InputEvent::PressEnter { shift: false, .. } => {
259 let trimmed = value.trim();
260 (!trimmed.is_empty()).then(|| trimmed.to_owned())
261 }
262 _ => None,
263 }
264}
265
266pub fn active_mention(
267 text: &str,
268 cursor: usize,
269 tokens: &[Range<usize>],
270) -> Option<(Range<usize>, String)> {
271 if cursor > text.len() || !text.is_char_boundary(cursor) {
272 return None;
273 }
274 let before = &text[..cursor];
275 let at = before.rfind('@')?;
276 if before[..at]
277 .chars()
278 .next_back()
279 .is_some_and(|previous| !previous.is_whitespace())
280 {
281 return None;
282 }
283 let query = &before[at + 1..];
284 let rejected = query.contains('\n')
285 || query.starts_with(char::is_whitespace)
286 || query.ends_with(char::is_whitespace)
287 || query.chars().count() > MENTION_QUERY_MAX_CHARS
288 || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS
289 || tokens
290 .iter()
291 .any(|token| token.start < cursor && at < token.end);
292 (!rejected).then(|| (at..cursor, query.to_owned()))
293}
294
295fn candidate_subtitle(candidate: &MentionCandidate) -> String {
296 match candidate {
297 MentionCandidate::Person(person) => person
298 .job_title
299 .clone()
300 .filter(|title| !title.trim().is_empty())
301 .or_else(|| person.mail.clone())
302 .unwrap_or_default(),
303 MentionCandidate::Channel { .. } => "Channel".to_owned(),
304 MentionCandidate::Team { .. } => "Team".to_owned(),
305 }
306}
307
308fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {
309 if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {
310 return StepKind::Typing {
311 after_space: typed.is_whitespace(),
312 };
313 }
314 let removed = previous.len().saturating_sub(value.len());
315 let one_char_removed = removed > 0
316 && previous.is_char_boundary(cursor)
317 && previous
318 .get(cursor..cursor + removed)
319 .is_some_and(|gone| gone.chars().count() == 1 && gone != "\n")
320 && previous.get(..cursor) == value.get(..cursor)
321 && previous.get(cursor + removed..) == value.get(cursor..);
322 if one_char_removed {
323 StepKind::Deleting
324 } else {
325 StepKind::Other
326 }
327}
328
329fn looks_like_url(text: &str) -> bool {
330 ["https://", "http://", "www."]
331 .iter()
332 .any(|prefix| text.starts_with(prefix))
333 && !text.contains(char::is_whitespace)
334}
335
336fn candidate_key(candidate: &MentionCandidate) -> &str {
337 match candidate {
338 MentionCandidate::Person(person) => &person.user_id,
339 MentionCandidate::Channel { channel_id, .. } => channel_id,
340 MentionCandidate::Team { team_id, .. } => team_id,
341 }
342}
343
344impl Composer {
345 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
346 let input = cx.new(|cx| {
347 TextareaState::new(window, cx)
348 .auto_grow(MIN_ROWS, MAX_ROWS)
349 .submit_on_enter(true)
350 .placeholder("Type a message")
351 });
352 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
353 let observer = cx.observe(&input, |_, _, cx| cx.notify());
354 let decorations = input.update(cx, |state, cx| {
355 (
356 state.create_decorations_collection(Vec::new(), cx),
357 state.create_range_decorations_collection(Vec::new(), cx),
358 )
359 });
360 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
361 Composer {
362 app,
363 input,
364 conversation_id: None,
365 reply: None,
366 editing: None,
367 mention_inputs: HashMap::new(),
368 mention_counter: 0,
369 popup: None,
370 lookup: None,
371 emoji_popup: None,
372 emoji_dismissed_at: None,
373 recent_emoji,
374 conversion: None,
375 undone_value: None,
376 previous_value: String::new(),
377 draft: Draft::default(),
378 decorations,
379 pending_style: None,
380 history: vec![HistoryStep {
381 draft: Draft::default(),
382 tokens: Vec::new(),
383 selection: 0..0,
384 kind: StepKind::Other,
385 }],
386 history_index: 0,
387 pasted_markdown: None,
388 paste_hint: None,
389 copied: None,
390 toolbar_dismissed: None,
391 mouse_selecting: false,
392 link_editor: None,
393 composer_bounds: Rc::new(Cell::new(None)),
394 tray: AttachmentTray::default(),
395 uploads: HashMap::new(),
396 demo_failed: HashSet::new(),
397 carry_images_into: None,
398 _subscriptions: [subscription, observer],
399 }
400 }
401
402 fn on_input_event(
403 &mut self,
404 input: &Entity<TextareaState>,
405 event: &InputEvent,
406 window: &mut Window,
407 cx: &mut Context<Self>,
408 ) {
409 cx.notify();
410 if matches!(event, InputEvent::Change) {
411 self.on_change(window, cx);
412 self.update_emoji(cx);
413 self.update_mention(cx);
414 }
415 let value = input.read(cx).value();
416 if submitted_text(event, &value).is_some()
417 || (is_plain_enter(event) && !self.tray.is_empty())
418 {
419 self.submit_current(window, cx);
420 }
421 }
422
423 fn update_mention(&mut self, cx: &mut Context<Self>) {
424 let state = self.input.read(cx);
425 let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect();
426 let found = active_mention(&state.value(), state.cursor(), &tokens);
427 let Some((range, query)) = found else {
428 self.close_mention_popup();
429 return;
430 };
431 let unchanged = self
432 .popup
433 .as_ref()
434 .is_some_and(|popup| popup.query == query && popup.range == range);
435 if unchanged {
436 return;
437 }
438 let previous = self.popup.take();
439 self.popup = Some(MentionPopup {
440 range,
441 query: query.clone(),
442 candidates: previous.map(|popup| popup.candidates).unwrap_or_default(),
443 highlighted: 0,
444 });
445 self.request_candidates(query, cx);
446 }
447
448 fn close_popup(&mut self) {
449 self.close_mention_popup();
450 self.emoji_popup = None;
451 }
452
453 fn close_mention_popup(&mut self) {
454 self.popup = None;
455 self.lookup = None;
456 }
457
458 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
459 let state = self.input.read(cx);
460 let (value, input_cursor) = (state.value().to_string(), state.cursor());
461 let previous = std::mem::replace(&mut self.previous_value, value.clone());
462 if value == self.draft.text() {
463 self.refresh_style(cx);
464 return;
465 }
466 let kind = step_kind(&previous, &value, input_cursor);
467 let typing = self.pending_style.take();
468 let cursor = self.draft.apply_edit(&value, input_cursor, typing.as_ref());
469 let edits = self.draft.take_edits();
470 self.apply_to_input(edits, cursor..cursor, window, cx);
471 self.record(kind, cx);
472 if let Some(pasted) = self.pasted_markdown.take()
473 && self.convert_paste(&pasted, cursor, window, cx)
474 {
475 return;
476 }
477 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
478 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
479 return;
480 }
481 self.convert_emoji(typed, cursor, window, cx);
482 }
483
484 fn convert_markdown(
485 &mut self,
486 cursor: usize,
487 window: &mut Window,
488 cx: &mut Context<Self>,
489 ) -> bool {
490 let before = self.draft.clone();
491 let Some((cursor, style)) = self.draft.convert_typed(cursor) else {
492 self.draft.take_edits();
493 return false;
494 };
495 self.finish_conversion(before, cursor, window, cx);
496 self.pending_style = (!style.is_empty()).then_some(style);
497 true
498 }
499
500 fn convert_emoji(
501 &mut self,
502 typed: Option<char>,
503 cursor: usize,
504 window: &mut Window,
505 cx: &mut Context<Self>,
506 ) {
507 if self.draft.in_code(cursor) {
508 return;
509 }
510 let value = self.draft.text();
511 let found = match typed {
512 Some(':') => emoji::closing_code(value, cursor)
513 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
514 Some(' ') => emoji::smiley_before_space(value, cursor),
515 _ => None,
516 };
517 let Some((range, glyph)) = found else {
518 return;
519 };
520 let before = self.draft.clone();
521 self.draft.replace(range.clone(), glyph);
522 self.finish_conversion(before, cursor + glyph.len() - range.len(), window, cx);
523 self.remember_emoji(glyph, cx);
524 }
525
526 fn finish_conversion(
527 &mut self,
528 before: Draft,
529 cursor: usize,
530 window: &mut Window,
531 cx: &mut Context<Self>,
532 ) {
533 let edits = self.draft.take_edits();
534 let restore = reverse_edits(&edits, before.text());
535 self.apply_to_input(edits, cursor..cursor, window, cx);
536 self.record(StepKind::Other, cx);
537 self.conversion = Some(Conversion {
538 value: self.draft.text().to_owned(),
539 cursor,
540 before,
541 restore,
542 });
543 }
544
545 fn convert_paste(
546 &mut self,
547 pasted: &str,
548 cursor: usize,
549 window: &mut Window,
550 cx: &mut Context<Self>,
551 ) -> bool {
552 let pasted = pasted.replace("\r\n", "\n");
553 let Some(start) = cursor
554 .checked_sub(pasted.len())
555 .filter(|start| self.draft.text().get(*start..cursor) == Some(pasted.as_str()))
556 else {
557 return false;
558 };
559 let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);
560 let cursor = self.draft.insert_lines(start..cursor, &lines);
561 self.commit(Some(cursor), window, cx);
562 self.paste_hint = Some(cx.spawn(async move |this, cx| {
563 cx.background_executor().timer(PASTE_HINT_DURATION).await;
564 this.update(cx, |this, cx| {
565 this.paste_hint = None;
566 cx.notify();
567 })
568 .ok();
569 }));
570 true
571 }
572
573 /// Puts the draft's pending edits into the input, then places the selection.
574 fn commit(&mut self, cursor: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
575 let edits = self.draft.take_edits();
576 let selection = self.input.read(cx).selected_range();
577 let selection = match cursor {
578 Some(cursor) => cursor..cursor,
579 None if edits.is_empty() => selection,
580 None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),
581 };
582 self.apply_to_input(edits, selection, window, cx);
583 self.record(StepKind::Other, cx);
584 }
585
586 fn apply_to_input(
587 &mut self,
588 edits: Vec<Edit>,
589 selection: Range<usize>,
590 window: &mut Window,
591 cx: &mut Context<Self>,
592 ) {
593 self.input.update(cx, |state, cx| {
594 let edited = !edits.is_empty();
595 if edited {
596 state.apply_edits(&edits, window, cx);
597 }
598 if edited || state.selected_range() != selection {
599 state.set_selected_range(selection.clone(), cx);
600 }
601 });
602 let value = self.input.read(cx).value().to_string();
603 if value != self.draft.text() {
604 self.draft.apply_edit(&value, selection.end, None);
605 self.draft.take_edits();
606 }
607 self.previous_value = value;
608 self.refresh_style(cx);
609 }
610
611 /// Adds the current state as an undo step. Typing and deleting runs merge into one step;
612 /// a typed space ends a typing step.
613 fn record(&mut self, kind: StepKind, cx: &App) {
614 let state = self.input.read(cx);
615 let step = HistoryStep {
616 draft: self.draft.clone(),
617 tokens: state
618 .tokens()
619 .iter()
620 .map(|span| (span.range(), span.token().clone()))
621 .collect(),
622 selection: state.selected_range(),
623 kind,
624 };
625 let at_end = self.history_index + 1 == self.history.len();
626 let merges = at_end
627 && match (self.history.last().map(|last| last.kind), kind) {
628 (Some(StepKind::Typing { after_space: false }), StepKind::Typing { .. }) => true,
629 (
630 Some(StepKind::Typing { after_space: true }),
631 StepKind::Typing { after_space },
632 ) => after_space,
633 (Some(StepKind::Deleting), StepKind::Deleting) => true,
634 _ => false,
635 };
636 if merges {
637 if let Some(last) = self.history.last_mut() {
638 *last = step;
639 }
640 return;
641 }
642 self.history.truncate(self.history_index + 1);
643 self.history.push(step);
644 if self.history.len() > HISTORY_LIMIT {
645 self.history.remove(0);
646 }
647 self.history_index = self.history.len() - 1;
648 }
649
650 /// Ctrl+Z / Ctrl+Y move through the composer's own history; the input's is never used.
651 fn step_history(&mut self, back: bool, window: &mut Window, cx: &mut Context<Self>) {
652 let target = if back {
653 self.history_index.checked_sub(1)
654 } else {
655 Some(self.history_index + 1).filter(|index| *index < self.history.len())
656 };
657 let Some(target) = target else {
658 return;
659 };
660 self.history_index = target;
661 let step = &self.history[target];
662 let mut content = InputContent::new(step.draft.text().to_owned());
663 for (range, token) in &step.tokens {
664 if let Ok(next) = content.clone().with_token(range.clone(), token.clone()) {
665 content = next;
666 }
667 }
668 let (draft, selection) = (step.draft.clone(), step.selection.clone());
669 self.input.update(cx, |state, cx| {
670 state.set_value(content, window, cx);
671 state.set_selected_range(selection, cx);
672 });
673 self.previous_value = draft.text().to_owned();
674 self.draft = draft;
675 self.pending_style = None;
676 self.conversion = None;
677 self.paste_hint = None;
678 self.refresh_style(cx);
679 self.update_emoji(cx);
680 self.update_mention(cx);
681 cx.notify();
682 }
683
684 fn refresh_style(&mut self, cx: &mut Context<Self>) {
685 let style = draft_style(&self.draft, cx.theme().mono_font_family.clone());
686 let (text, ranges) = &self.decorations;
687 text.set(style.text, cx);
688 ranges.set(style.ranges, cx);
689 self.input.update(cx, |state, cx| {
690 state.set_line_indents(style.indents, cx);
691 state.set_hanging_indents(style.markers, cx);
692 });
693 }
694
695 fn load_draft(
696 &mut self,
697 draft: Draft,
698 content: InputContent,
699 window: &mut Window,
700 cx: &mut Context<Self>,
701 ) {
702 let end = draft.text().len();
703 self.input.update(cx, |state, cx| {
704 state.set_value(content, window, cx);
705 state.set_selected_range(end..end, cx);
706 });
707 self.previous_value = draft.text().to_owned();
708 self.draft = draft;
709 self.pending_style = None;
710 self.conversion = None;
711 self.pasted_markdown = None;
712 self.paste_hint = None;
713 self.link_editor = None;
714 self.toolbar_dismissed = None;
715 self.history.clear();
716 self.history_index = 0;
717 self.record(StepKind::Other, cx);
718 self.refresh_style(cx);
719 }
720
721 /// Returns the cursor, kept at the same spot relative to the text after `range`.
722 fn replace_text(
723 &mut self,
724 range: Range<usize>,
725 text: &str,
726 cursor: usize,
727 window: &mut Window,
728 cx: &mut Context<Self>,
729 ) -> usize {
730 let cursor = cursor + text.len() - range.len();
731 self.input.update(cx, |state, cx| {
732 state.set_selected_range(range, cx);
733 state.replace(text.to_owned(), window, cx);
734 state.set_selected_range(cursor..cursor, cx);
735 });
736 cursor
737 }
738
739 fn undo_conversion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
740 let state = self.input.read(cx);
741 let unchanged = self.conversion.as_ref().is_some_and(|conversion| {
742 conversion.value == state.value().as_ref() && conversion.cursor == state.cursor()
743 });
744 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
745 return false;
746 };
747 let cursor = map_offset(&conversion.restore, conversion.cursor);
748 self.draft = conversion.before;
749 self.pending_style = None;
750 self.apply_to_input(conversion.restore, cursor..cursor, window, cx);
751 self.record(StepKind::Other, cx);
752 self.undone_value = Some(self.input.read(cx).value().to_string());
753 self.update_emoji(cx);
754 true
755 }
756
757 fn selection(&self, cx: &App) -> Range<usize> {
758 self.input.read(cx).selected_range()
759 }
760
761 fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) {
762 let selection = self.selection(cx);
763 if selection.is_empty() {
764 let cursor = selection.start;
765 let mut pending = self
766 .pending_style
767 .take()
768 .filter(|pending| pending.at == cursor)
769 .unwrap_or(TypingStyle {
770 at: cursor,
771 ..TypingStyle::default()
772 });
773 pending.toggle(kind, &self.draft.style_at(cursor));
774 self.pending_style = (!pending.is_empty()).then_some(pending);
775 } else {
776 self.draft.toggle(selection, kind);
777 self.draft.take_edits();
778 self.record(StepKind::Other, cx);
779 self.refresh_style(cx);
780 }
781 cx.notify();
782 }
783
784 fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {
785 let selection = self.selection(cx);
786 self.draft.toggle_lines(selection, kind);
787 self.commit(None, window, cx);
788 cx.notify();
789 }
790
791 fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {
792 match button {
793 FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),
794 FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
795 FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),
796 FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),
797 FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),
798 FormatButton::Link => self.open_link_editor(window, cx),
799 FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),
800 FormatButton::Numbered => self.toggle_lines(LineKind::Numbered(0), window, cx),
801 FormatButton::Quote => self.toggle_lines(LineKind::Quote, window, cx),
802 }
803 }
804
805 fn format_state(&self, button: FormatButton, selection: &Range<usize>) -> FormatState {
806 let range = selection.clone();
807 match button {
808 FormatButton::Bold => self.draft.state(range, &MarkKind::Bold),
809 FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),
810 FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),
811 FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),
812 FormatButton::Code => self.draft.state(range, &MarkKind::Code),
813 FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),
814 FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),
815 FormatButton::Numbered => self.draft.line_state(range, &LineKind::Numbered(0)),
816 FormatButton::Quote => self.draft.line_state(range, &LineKind::Quote),
817 }
818 }
819
820 fn edit_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
821 if self.link_editor.is_some() {
822 return;
823 }
824 if self.draft.is_blank() && self.selection(cx).is_empty() {
825 window.dispatch_action(Box::new(super::shell::OpenSwitcher), cx);
826 return;
827 }
828 self.open_link_editor(window, cx);
829 }
830
831 fn open_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
832 let range = self.selection(cx);
833 let prefill = self
834 .draft
835 .link_in(range.clone())
836 .or_else(|| {
837 cx.read_from_clipboard()
838 .and_then(|item| item.text())
839 .map(|text| text.trim().to_owned())
840 .filter(|text| looks_like_url(text))
841 })
842 .unwrap_or_default();
843 let field = cx.new(|cx| {
844 InputState::new(window, cx)
845 .placeholder("Paste or type a link")
846 .default_value(prefill)
847 });
848 field.update(cx, |state, cx| {
849 state.focus(window, cx);
850 state.select_all(window, cx);
851 });
852 let edits = cx.subscribe(&field, |this, _, event: &InputEvent, cx| {
853 if matches!(event, InputEvent::Change)
854 && let Some(editor) = this.link_editor.as_mut()
855 {
856 editor.refused = false;
857 cx.notify();
858 }
859 });
860 self.link_editor = Some(LinkEditor {
861 range,
862 field,
863 refused: false,
864 _edits: edits,
865 });
866 cx.notify();
867 }
868
869 fn apply_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
870 let Some(editor) = self.link_editor.take() else {
871 return;
872 };
873 let typed = editor.field.read(cx).value().trim().to_owned();
874 let url = if typed.is_empty() {
875 String::new()
876 } else if let Some(url) = link_url(&typed) {
877 url
878 } else {
879 self.link_editor = Some(LinkEditor {
880 refused: true,
881 ..editor
882 });
883 cx.notify();
884 return;
885 };
886 self.focus(window, cx);
887 if editor.range.is_empty() {
888 if !url.is_empty() {
889 let end = self.draft.insert_link(editor.range.start, &url, &url);
890 self.commit(Some(end), window, cx);
891 }
892 } else {
893 self.draft.set_link(editor.range.clone(), &url);
894 self.draft.take_edits();
895 self.refresh_style(cx);
896 self.input.update(cx, |state, cx| {
897 state.set_selected_range(editor.range.clone(), cx)
898 });
899 self.record(StepKind::Other, cx);
900 self.toolbar_dismissed = Some(editor.range);
901 }
902 cx.notify();
903 }
904
905 fn close_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
906 let Some(editor) = self.link_editor.take() else {
907 return;
908 };
909 self.focus(window, cx);
910 self.input
911 .update(cx, |state, cx| state.set_selected_range(editor.range, cx));
912 cx.notify();
913 }
914
915 fn break_line(&mut self, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
916 let selection = self.selection(cx);
917 if !selection.is_empty() {
918 return false;
919 }
920 match self.draft.break_line(selection.start, shift) {
921 Some(cursor) => {
922 self.commit(Some(cursor), window, cx);
923 true
924 }
925 None => false,
926 }
927 }
928
929 fn backspace_at_start(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
930 let selection = self.selection(cx);
931 if !selection.is_empty() {
932 return false;
933 }
934 match self.draft.backspace_at_start(selection.start) {
935 Some(cursor) => {
936 self.commit(Some(cursor), window, cx);
937 true
938 }
939 None => false,
940 }
941 }
942
943 fn delete_forward(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
944 let selection = self.selection(cx);
945 if !selection.is_empty() {
946 return false;
947 }
948 match self.draft.delete_forward(selection.start) {
949 Some(cursor) => {
950 self.commit(Some(cursor), window, cx);
951 true
952 }
953 None => false,
954 }
955 }
956
957 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
958 let selection = self.selection(cx);
959 if !self.draft.indent(selection, outdent) {
960 return false;
961 }
962 self.commit(None, window, cx);
963 true
964 }
965
966 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
967 let selection = self.selection(cx);
968 if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
969 return false;
970 }
971 let text = self.draft.text()[selection.clone()].to_owned();
972 let lines = self.draft.slice(selection);
973 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
974 text.clone(),
975 lines.clone(),
976 ));
977 self.copied = Some((text, lines));
978 true
979 }
980
981 fn copied_lines(&self, item: &ClipboardItem, text: &str) -> Option<Vec<DraftLine>> {
982 item.entries()
983 .iter()
984 .find_map(|entry| match entry {
985 ClipboardEntry::String(string) if string.text() == text => {
986 string.metadata_json::<Vec<DraftLine>>()
987 }
988 _ => None,
989 })
990 .or_else(|| {
991 let normalized = text.replace("\r\n", "\n");
992 self.copied
993 .as_ref()
994 .filter(|(copied, _)| *copied == normalized)
995 .map(|(_, lines)| lines.clone())
996 })
997 }
998
999 fn toolbar_requested(&self, cx: &App) -> bool {
1000 let selection = self.selection(cx);
1001 !selection.is_empty()
1002 && !self.mouse_selecting
1003 && self.toolbar_dismissed.as_ref() != Some(&selection)
1004 && !self.popup_is_open()
1005 }
1006
1007 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
1008 self.recent_emoji.push(glyph);
1009 self.recent_emoji.save(&self.app.read(cx).store);
1010 }
1011
1012 fn update_emoji(&mut self, cx: &mut Context<Self>) {
1013 let state = self.input.read(cx);
1014 let found = emoji::active_query(&state.value(), state.cursor())
1015 .filter(|_| !self.draft.in_code(state.cursor()));
1016 if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
1017 self.emoji_dismissed_at = None;
1018 }
1019 let found = found.filter(|_| self.emoji_dismissed_at.is_none());
1020 let Some((range, query)) = found else {
1021 self.emoji_popup = None;
1022 return;
1023 };
1024 let unchanged = self
1025 .emoji_popup
1026 .as_ref()
1027 .is_some_and(|popup| popup.query == query && popup.range == range);
1028 if unchanged {
1029 return;
1030 }
1031 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1032 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1033 }
1034
1035 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1036 let Some(popup) = self.emoji_popup.take() else {
1037 return;
1038 };
1039 let Some(glyph) = popup.selected().map(|found| found.glyph) else {
1040 return;
1041 };
1042 let cursor = popup.range.end;
1043 self.replace_text(popup.range, glyph, cursor, window, cx);
1044 self.remember_emoji(glyph, cx);
1045 cx.notify();
1046 }
1047
1048 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
1049 let Some(conversation_id) = self.conversation_id.clone() else {
1050 return;
1051 };
1052 let (demo, engine) = {
1053 let state = self.app.read(cx);
1054 (state.mode.demo, state.engine.clone())
1055 };
1056 if demo {
1057 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
1058 self.apply_candidates(&query, candidates, cx);
1059 return;
1060 }
1061 let Some(engine) = engine else {
1062 return;
1063 };
1064 self.lookup = Some(cx.spawn(async move |this, cx| {
1065 cx.background_executor().timer(MENTION_DEBOUNCE).await;
1066 let task_query = query.clone();
1067 let receiver = runtime::spawn(async move {
1068 engine
1069 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
1070 .await
1071 });
1072 if let Ok(Ok(candidates)) = receiver.await {
1073 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
1074 .ok();
1075 }
1076 }));
1077 }
1078
1079 fn apply_candidates(
1080 &mut self,
1081 query: &str,
1082 candidates: Vec<MentionCandidate>,
1083 cx: &mut Context<Self>,
1084 ) {
1085 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
1086 return;
1087 };
1088 popup.candidates = candidates;
1089 popup.highlighted = 0;
1090 cx.notify();
1091 }
1092
1093 fn popup_is_open(&self) -> bool {
1094 self.emoji_popup.is_some()
1095 || self
1096 .popup
1097 .as_ref()
1098 .is_some_and(|popup| !popup.candidates.is_empty())
1099 }
1100
1101 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1102 if let Some(popup) = self.emoji_popup.as_mut() {
1103 popup.move_highlight(delta);
1104 cx.notify();
1105 } else if let Some(popup) = self.popup.as_mut() {
1106 let last = popup.candidates.len().saturating_sub(1) as isize;
1107 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
1108 cx.notify();
1109 }
1110 }
1111
1112 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1113 if self.emoji_popup.is_some() {
1114 self.accept_emoji(window, cx);
1115 } else {
1116 self.accept_mention(window, cx);
1117 }
1118 }
1119
1120 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1121 let Some(popup) = self.popup.take() else {
1122 return;
1123 };
1124 self.lookup = None;
1125 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
1126 return;
1127 };
1128 self.mention_counter += 1;
1129 let token_id = format!(
1130 "mention-{}-{}",
1131 self.mention_counter,
1132 candidate_key(candidate)
1133 );
1134 let label = format!("@{}", candidate.display_name());
1135 self.mention_inputs
1136 .insert(token_id.clone(), candidate.to_mention());
1137 self.input.update(cx, |state, cx| {
1138 let token = InlineToken::new(token_id, label);
1139 if state
1140 .replace_range_with_token(popup.range, token, window, cx)
1141 .is_ok()
1142 {
1143 state.insert(" ", window, cx);
1144 }
1145 });
1146 self.close_popup();
1147 cx.notify();
1148 }
1149
1150 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1151 let text = text.to_owned();
1152 self.input
1153 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
1154 }
1155
1156 pub fn set_conversation(
1157 &mut self,
1158 conversation_id: &str,
1159 name: &str,
1160 window: &mut Window,
1161 cx: &mut Context<Self>,
1162 ) {
1163 self.set_placeholder(&format!("Message {name}"), window, cx);
1164 if self.conversation_id.as_deref() != Some(conversation_id) {
1165 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1166 self.conversation_id = Some(conversation_id.to_owned());
1167 self.cancel_uploads();
1168 let dropped = if carry {
1169 self.tray.keep_images_only()
1170 } else {
1171 self.tray.clear()
1172 };
1173 self.discard_uploaded(dropped, cx);
1174 self.reply = None;
1175 if self.editing.take().is_some() {
1176 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1177 }
1178 self.mention_inputs.clear();
1179 self.close_popup();
1180 cx.notify();
1181 }
1182 }
1183
1184 /// The draft's images follow the user into this chat; any other switch clears the tray.
1185 pub fn carry_images_into(&mut self, conversation_id: String) {
1186 self.carry_images_into = Some(conversation_id);
1187 }
1188
1189 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
1190 discard_uploaded(self.app.read(cx).engine.clone(), files);
1191 }
1192
1193 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
1194 self.reply = reply;
1195 if self.reply.is_some() {
1196 self.editing = None;
1197 }
1198 cx.notify();
1199 }
1200
1201 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1202 self.restore(&draft, window, cx);
1203 self.focus(window, cx);
1204 }
1205
1206 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1207 self.editing = None;
1208 self.set_text("", window, cx);
1209 }
1210
1211 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1212 let state = self.input.read(cx);
1213 if !self.can_send(cx) {
1214 return None;
1215 }
1216 let mut draft = self.current_draft(cx).trimmed();
1217 let attachments_apply = self.editing.is_none();
1218 if self.undone_value.as_deref() != Some(state.value().as_ref())
1219 && let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
1220 && !draft.in_code(range.end - 1)
1221 {
1222 draft.replace(range, glyph);
1223 draft.take_edits();
1224 }
1225 let mentions = state
1226 .tokens()
1227 .iter()
1228 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1229 .cloned()
1230 .collect();
1231 Some(Outgoing {
1232 draft,
1233 mentions,
1234 reply: self.reply.clone(),
1235 edit: self.editing.clone(),
1236 images: if attachments_apply {
1237 self.tray.outgoing_images()
1238 } else {
1239 Vec::new()
1240 },
1241 files: if attachments_apply {
1242 self.tray.outgoing_files()
1243 } else {
1244 Vec::new()
1245 },
1246 })
1247 }
1248
1249 /// The draft, or the plain input text while a change is still on its way to the draft.
1250 fn current_draft(&self, cx: &App) -> Draft {
1251 let value = self.input.read(cx).value();
1252 if self.draft.text() == value.as_ref() {
1253 self.draft.clone()
1254 } else {
1255 Draft::plain(&value)
1256 }
1257 }
1258
1259 fn can_send(&self, cx: &App) -> bool {
1260 let has_text = !self.current_draft(cx).is_blank();
1261 if self.editing.is_some() {
1262 return has_text;
1263 }
1264 (has_text || !self.tray.is_empty()) && !self.tray.blocks_send()
1265 }
1266
1267 pub fn is_editing(&self) -> bool {
1268 self.editing.is_some()
1269 }
1270
1271 fn files_allowed(&self) -> bool {
1272 self.conversation_id
1273 .as_deref()
1274 .is_some_and(|conversation_id| !conversation_id.is_empty())
1275 }
1276
1277 fn cancel_uploads(&mut self) {
1278 for (_, handle) in self.uploads.drain() {
1279 handle.cancel();
1280 }
1281 }
1282
1283 pub fn open_picker(&mut self, cx: &mut Context<Self>) {
1284 if self.editing.is_some() {
1285 return;
1286 }
1287 let receiver = cx.prompt_for_paths(PathPromptOptions {
1288 files: true,
1289 directories: false,
1290 multiple: true,
1291 prompt: None,
1292 });
1293 cx.spawn(async move |this, cx| {
1294 if let Ok(Ok(Some(paths))) = receiver.await {
1295 this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();
1296 }
1297 })
1298 .detach();
1299 }
1300
1301 pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
1302 if self.editing.is_some() || paths.is_empty() {
1303 return;
1304 }
1305 let ids = self.tray.add_pending(&names_of(&paths));
1306 for (id, path) in ids.into_iter().zip(paths) {
1307 cx.spawn(async move |this, cx| {
1308 let loaded = cx
1309 .background_executor()
1310 .spawn(async move { read_attachment(&path) })
1311 .await;
1312 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
1313 .ok();
1314 })
1315 .detach();
1316 }
1317 cx.notify();
1318 }
1319
1320 fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {
1321 let ids = self.tray.add_pending(&[pasted_image_name()]);
1322 cx.notify();
1323 let Some(&id) = ids.first() else {
1324 return;
1325 };
1326 cx.spawn(async move |this, cx| {
1327 let loaded = cx
1328 .background_executor()
1329 .spawn(async move { prepare_pasted_image(pasted) })
1330 .await;
1331 this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
1332 .ok();
1333 })
1334 .detach();
1335 }
1336
1337 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1338 if self.editing.is_none() {
1339 match paste_action(item) {
1340 PasteAction::Text => {}
1341 PasteAction::Files(paths) => {
1342 self.add_paths(paths, cx);
1343 return true;
1344 }
1345 PasteAction::Image(pasted) => {
1346 self.add_pasted_image(pasted, cx);
1347 return true;
1348 }
1349 }
1350 }
1351 let Some(text) = item.text() else {
1352 return false;
1353 };
1354 if self.draft.in_code(self.selection(cx).start) {
1355 return false;
1356 }
1357 if let Some(lines) = self.copied_lines(item, &text) {
1358 let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1359 self.commit(Some(cursor), window, cx);
1360 return true;
1361 }
1362 self.pasted_markdown = has_markdown(&text).then_some(text);
1363 false
1364 }
1365
1366 fn finish_reading(
1367 &mut self,
1368 id: u64,
1369 loaded: Result<LoadedFile, String>,
1370 cx: &mut Context<Self>,
1371 ) {
1372 match loaded {
1373 Ok(loaded) => {
1374 let files_allowed = self.files_allowed();
1375 if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {
1376 self.start_upload(job, cx);
1377 }
1378 }
1379 Err(message) => self.tray.fail_reading(id, message),
1380 }
1381 cx.notify();
1382 }
1383
1384 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1385 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
1386 self.tray.finish_upload(job.id, UploadResult::Failed);
1387 return;
1388 };
1389 let state = self.app.read(cx);
1390 let (demo, engine) = (state.mode.demo, state.engine.clone());
1391 if demo {
1392 self.simulate_upload(job, cx);
1393 return;
1394 }
1395 let Some(engine) = engine else {
1396 self.tray.finish_upload(job.id, UploadResult::Failed);
1397 return;
1398 };
1399 let id = job.id;
1400 let (event_sender, mut event_receiver) =
1401 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
1402 let finished_sender = event_sender.clone();
1403 let (_, handle) = runtime::spawn_abortable(async move {
1404 let result = async {
1405 let uploaded = match job.kind {
1406 JobKind::Upload => {
1407 let progress_sender = event_sender.clone();
1408 let uploaded = engine
1409 .upload_attachment_file(
1410 &conversation_id,
1411 &job.name,
1412 &job.bytes,
1413 move |percent| {
1414 let _ = progress_sender.send(UploadEvent::Progress(percent));
1415 },
1416 )
1417 .await;
1418 match uploaded {
1419 Ok(uploaded) => {
1420 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
1421 uploaded
1422 }
1423 Err(_) => return UploadResult::Failed,
1424 }
1425 }
1426 JobKind::Share(uploaded) => uploaded,
1427 };
1428 let Some(reference) = uploaded.reference() else {
1429 return UploadResult::Failed;
1430 };
1431 match engine.share_attachment(&conversation_id, &uploaded).await {
1432 Ok(()) => UploadResult::Done(DoneFile {
1433 reference,
1434 uploaded: Some(uploaded),
1435 }),
1436 Err(_) => UploadResult::ShareFailed(uploaded),
1437 }
1438 }
1439 .await;
1440 let _ = finished_sender.send(UploadEvent::Finished(result));
1441 });
1442 self.uploads.insert(id, UploadHandle::Network(handle));
1443 cx.spawn(async move |this, cx| {
1444 while let Some(event) = event_receiver.recv().await {
1445 let updated = this.update(cx, |this, cx| {
1446 let orphan = match event {
1447 UploadEvent::Progress(percent) => {
1448 this.tray.set_progress(id, percent);
1449 None
1450 }
1451 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
1452 UploadEvent::Finished(result) => this.finish_upload(id, result),
1453 };
1454 this.discard_uploaded(orphan.into_iter().collect(), cx);
1455 cx.notify();
1456 });
1457 if updated.is_err() {
1458 break;
1459 }
1460 }
1461 })
1462 .detach();
1463 }
1464
1465 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1466 let id = job.id;
1467 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
1468 let task = cx.spawn(async move |this, cx| {
1469 for step in 1..=DEMO_UPLOAD_STEPS {
1470 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
1471 if fails && step == DEMO_FAILURE_STEP {
1472 this.update(cx, |this, cx| {
1473 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
1474 })
1475 .ok();
1476 return;
1477 }
1478 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
1479 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
1480 .ok();
1481 }
1482 let reference = FileReference {
1483 attachment_id: format!("demo-attachment-{id}"),
1484 content_url: format!("https://demo.invalid/files/{}", job.name),
1485 name: job.name,
1486 };
1487 let done = DoneFile {
1488 reference,
1489 uploaded: None,
1490 };
1491 this.update(cx, |this, cx| {
1492 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
1493 })
1494 .ok();
1495 });
1496 self.uploads.insert(id, UploadHandle::Demo(task));
1497 }
1498
1499 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
1500 self.tray.set_progress(id, percent);
1501 cx.notify();
1502 }
1503
1504 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
1505 self.uploads.remove(&id);
1506 self.tray.finish_upload(id, result)
1507 }
1508
1509 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
1510 self.finish_upload(id, result);
1511 cx.notify();
1512 }
1513
1514 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
1515 if let Some(handle) = self.uploads.remove(&id) {
1516 handle.cancel();
1517 }
1518 let uploaded = self.tray.remove(id);
1519 self.discard_uploaded(uploaded.into_iter().collect(), cx);
1520 cx.notify();
1521 }
1522
1523 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
1524 if let Some(job) = self.tray.retry(id) {
1525 self.start_upload(job, cx);
1526 }
1527 cx.notify();
1528 }
1529
1530 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1531 let Some(outgoing) = self.outgoing(cx) else {
1532 return;
1533 };
1534 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1535 self.mention_inputs.clear();
1536 if self.editing.is_none() {
1537 self.tray.clear();
1538 }
1539 self.reply = None;
1540 self.editing = None;
1541 self.close_popup();
1542 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1543 cx.notify();
1544 }
1545
1546 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1547 self.mention_inputs.clear();
1548 let text = outgoing.draft.text();
1549 let mut content = InputContent::new(text.to_owned());
1550 let mut cursor = 0;
1551 for mention in &outgoing.mentions {
1552 let needle = format!("@{}", mention.text);
1553 let Some(offset) = text[cursor..].find(&needle) else {
1554 continue;
1555 };
1556 let range = cursor + offset..cursor + offset + needle.len();
1557 self.mention_counter += 1;
1558 let token_id = format!("mention-{}", self.mention_counter);
1559 let token = InlineToken::new(token_id.clone(), needle);
1560 if let Ok(next) = content.clone().with_token(range.clone(), token) {
1561 content = next;
1562 self.mention_inputs.insert(token_id, mention.clone());
1563 cursor = range.end;
1564 }
1565 }
1566 self.load_draft(outgoing.draft.clone(), content, window, cx);
1567 self.reply = outgoing.reply.clone();
1568 self.editing = outgoing.edit.clone();
1569 if outgoing.edit.is_none() {
1570 self.cancel_uploads();
1571 self.tray.restore(&outgoing.images, &outgoing.files);
1572 }
1573 self.close_popup();
1574 cx.notify();
1575 }
1576
1577 /// Markdown in `text` arrives formatted.
1578 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1579 let draft = Draft::from_markdown(text);
1580 let content = InputContent::new(draft.text().to_owned());
1581 self.load_draft(draft, content, window, cx);
1582 self.mention_inputs.clear();
1583 self.update_emoji(cx);
1584 self.update_mention(cx);
1585 cx.notify();
1586 }
1587
1588 pub fn is_empty(&self, _: &App) -> bool {
1589 self.draft.is_blank() && self.tray.is_empty()
1590 }
1591
1592 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1593 self.input.update(cx, |state, cx| state.focus(window, cx));
1594 }
1595
1596 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1597 let popup = self
1598 .popup
1599 .as_ref()
1600 .filter(|popup| !popup.candidates.is_empty())?;
1601 let directory = &self.app.read(cx).directory;
1602 let rows = popup
1603 .candidates
1604 .iter()
1605 .enumerate()
1606 .map(|(index, candidate)| {
1607 let name = candidate.display_name().to_owned();
1608 let avatar = match candidate {
1609 MentionCandidate::Person(person) => {
1610 person_avatar(directory, Some(&person.user_id), &name, 28.)
1611 }
1612 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
1613 };
1614 let subtitle = candidate_subtitle(candidate);
1615 h_flex()
1616 .id(ElementId::Name(format!("mention-row-{index}").into()))
1617 .mx(px(6.))
1618 .px(px(6.))
1619 .h(px(POPUP_ROW_HEIGHT))
1620 .gap(px(10.))
1621 .items_center()
1622 .rounded(px(6.))
1623 .cursor_pointer()
1624 .when(index == popup.highlighted, |row| {
1625 row.bg(theme::surface_raised())
1626 })
1627 .hover(|row| row.bg(theme::row_hover()))
1628 .child(avatar)
1629 .child(
1630 v_flex()
1631 .flex_1()
1632 .min_w_0()
1633 .child(
1634 div()
1635 .truncate()
1636 .text_size(px(13.5))
1637 .text_color(theme::text())
1638 .child(name),
1639 )
1640 .when(!subtitle.is_empty(), |column| {
1641 column.child(
1642 div()
1643 .truncate()
1644 .text_size(px(12.))
1645 .text_color(theme::text_muted())
1646 .child(subtitle),
1647 )
1648 }),
1649 )
1650 .on_click(cx.listener(move |this, _, window, cx| {
1651 if let Some(popup) = this.popup.as_mut() {
1652 popup.highlighted = index;
1653 }
1654 this.accept_mention(window, cx);
1655 }))
1656 });
1657 Some(
1658 v_flex()
1659 .id("mention-popup")
1660 .absolute()
1661 .bottom(relative(1.))
1662 .left_0()
1663 .mb(px(6.))
1664 .w(px(POPUP_WIDTH))
1665 .py(px(6.))
1666 .rounded(px(10.))
1667 .border_1()
1668 .border_color(theme::border_strong())
1669 .bg(theme::surface())
1670 .shadow_lg()
1671 .occlude()
1672 .children(rows)
1673 .into_any_element(),
1674 )
1675 }
1676
1677 fn render_emoji_popup(
1678 &self,
1679 window: &mut Window,
1680 cx: &mut Context<Self>,
1681 ) -> Option<AnyElement> {
1682 let popup = self.emoji_popup.as_ref()?;
1683 let colon = popup.range.start..popup.range.start + 1;
1684 let anchor = self
1685 .input
1686 .read(cx)
1687 .range_to_bounds(&colon)
1688 .map(|bounds| bounds.origin);
1689 if anchor.is_none() {
1690 window.request_animation_frame();
1691 }
1692 let composer = cx.entity().downgrade();
1693 Some(emoji_popup::render(
1694 popup,
1695 anchor,
1696 move |index, window, cx| {
1697 composer
1698 .update(cx, |this, cx| {
1699 if let Some(popup) = this.emoji_popup.as_mut() {
1700 popup.highlighted = index;
1701 }
1702 this.accept_emoji(window, cx);
1703 })
1704 .ok();
1705 },
1706 ))
1707 }
1708
1709 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
1710 let composer = cx.entity().downgrade();
1711 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
1712 return None;
1713 }
1714 let state = self.input.read(cx);
1715 let range = self
1716 .link_editor
1717 .as_ref()
1718 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
1719 let start = state.range_to_bounds(&(range.start..range.start))?;
1720 let end = state.range_to_bounds(&(range.end..range.end))?;
1721 let input_bounds = state.input_bounds();
1722 let center_x = if start.origin.y == end.origin.y {
1723 (start.origin.x + end.origin.x) / 2.
1724 } else {
1725 input_bounds.center().x
1726 };
1727 let edges = self
1728 .composer_bounds
1729 .get()
1730 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
1731 (bounds.left(), bounds.right())
1732 });
1733 let width = match self.link_editor {
1734 Some(_) => format_toolbar::link_width(),
1735 None => format_toolbar::bar_width(),
1736 };
1737 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
1738 let element = match &self.link_editor {
1739 Some(editor) => format_toolbar::render(
1740 placement,
1741 format_toolbar::Mode::Link {
1742 field: &editor.field,
1743 refused: editor.refused,
1744 on_apply: Rc::new(move |window, cx| {
1745 composer
1746 .update(cx, |this, cx| this.apply_link(window, cx))
1747 .ok();
1748 }),
1749 },
1750 ),
1751 None => {
1752 let state_of = |button| self.format_state(button, &range);
1753 format_toolbar::render(
1754 placement,
1755 format_toolbar::Mode::Bar {
1756 state: &state_of,
1757 on_press: Rc::new(move |button, window, cx| {
1758 composer
1759 .update(cx, |this, cx| this.press_format(button, window, cx))
1760 .ok();
1761 }),
1762 },
1763 )
1764 }
1765 };
1766 Some(element)
1767 }
1768
1769 fn render_paste_hint(&self) -> Option<Div> {
1770 self.paste_hint.as_ref()?;
1771 Some(
1772 h_flex()
1773 .mt(px(6.))
1774 .gap(px(6.))
1775 .items_center()
1776 .text_size(px(12.))
1777 .text_color(theme::text_muted())
1778 .child("Formatted from Markdown")
1779 .child(
1780 div()
1781 .px(px(5.))
1782 .py(px(1.))
1783 .rounded(px(4.))
1784 .border_1()
1785 .border_color(theme::border_strong())
1786 .bg(theme::surface_raised())
1787 .text_size(px(11.))
1788 .text_color(theme::text())
1789 .child("Ctrl+Z"),
1790 )
1791 .child("plain text"),
1792 )
1793 }
1794
1795 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1796 let edit = self.editing.as_ref()?;
1797 Some(
1798 h_flex()
1799 .w_full()
1800 .mb(px(6.))
1801 .gap(px(10.))
1802 .items_center()
1803 .pl(px(10.))
1804 .pr(px(4.))
1805 .py(px(6.))
1806 .rounded(px(8.))
1807 .bg(theme::surface())
1808 .border_1()
1809 .border_color(theme::border())
1810 .child(icon(IconName::Pencil, 14., theme::accent_text()))
1811 .child(
1812 v_flex()
1813 .flex_1()
1814 .min_w_0()
1815 .child(
1816 div()
1817 .truncate()
1818 .text_size(px(12.))
1819 .font_weight(FontWeight::SEMIBOLD)
1820 .text_color(theme::accent_text())
1821 .child("Editing message"),
1822 )
1823 .child(
1824 div()
1825 .truncate()
1826 .text_size(px(12.))
1827 .text_color(theme::text_muted())
1828 .child(edit.excerpt.clone()),
1829 ),
1830 )
1831 .child(
1832 div()
1833 .id("edit-close")
1834 .size(px(24.))
1835 .flex()
1836 .items_center()
1837 .justify_center()
1838 .rounded(px(6.))
1839 .cursor_pointer()
1840 .hover(|button| button.bg(theme::row_hover()))
1841 .child(icon(IconName::Close, 14., theme::text_muted()))
1842 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
1843 ),
1844 )
1845 }
1846
1847 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1848 let reply = self.reply.as_ref()?;
1849 Some(
1850 h_flex()
1851 .w_full()
1852 .mb(px(6.))
1853 .gap(px(10.))
1854 .items_center()
1855 .pl(px(10.))
1856 .pr(px(4.))
1857 .py(px(6.))
1858 .rounded(px(8.))
1859 .bg(theme::surface())
1860 .border_1()
1861 .border_color(theme::border())
1862 .child(icon(IconName::Undo2, 14., theme::accent_text()))
1863 .child(
1864 v_flex()
1865 .flex_1()
1866 .min_w_0()
1867 .child(
1868 div()
1869 .truncate()
1870 .text_size(px(12.))
1871 .font_weight(FontWeight::SEMIBOLD)
1872 .text_color(theme::accent_text())
1873 .child(format!("Replying to {}", reply.author)),
1874 )
1875 .child(
1876 div()
1877 .truncate()
1878 .text_size(px(12.))
1879 .text_color(theme::text_muted())
1880 .child(reply.excerpt.clone()),
1881 ),
1882 )
1883 .child(
1884 div()
1885 .id("reply-close")
1886 .size(px(24.))
1887 .flex()
1888 .items_center()
1889 .justify_center()
1890 .rounded(px(6.))
1891 .cursor_pointer()
1892 .hover(|button| button.bg(theme::row_hover()))
1893 .child(icon(IconName::Close, 14., theme::text_muted()))
1894 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
1895 ),
1896 )
1897 }
1898}
1899
1900impl Render for Composer {
1901 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1902 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
1903 let can_send = self.can_send(cx);
1904 let can_attach = self.editing.is_none();
1905 let send = div()
1906 .id("composer-send")
1907 .size(px(32.))
1908 .flex_none()
1909 .flex()
1910 .items_center()
1911 .justify_center()
1912 .rounded(px(8.))
1913 .child(symbol("keyboard_return", 20., white()))
1914 .when(!can_send, |button| button.opacity(0.4))
1915 .when(can_send, |button| {
1916 button
1917 .cursor_pointer()
1918 .hover(|button| button.bg(white().opacity(0.1)))
1919 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
1920 });
1921 let attach = can_attach.then(|| {
1922 div()
1923 .id("composer-attach")
1924 .size(px(32.))
1925 .flex_none()
1926 .flex()
1927 .items_center()
1928 .justify_center()
1929 .rounded(px(8.))
1930 .cursor_pointer()
1931 .hover(|button| button.bg(theme::row_hover()))
1932 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
1933 .child(symbol("attach_file", 20., theme::text_muted()))
1934 .on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))
1935 });
1936 let composer = cx.weak_entity();
1937 let input = Textarea::new(&self.input)
1938 .appearance(false)
1939 .bordered(false)
1940 .on_paste(move |item, window, cx| {
1941 composer
1942 .update(cx, |this, cx| this.paste(item, window, cx))
1943 .unwrap_or(false)
1944 })
1945 .token(|context, _, _| {
1946 div()
1947 .h(context.line_height())
1948 .px(px(5.))
1949 .rounded(px(5.))
1950 .bg(if context.is_selected() {
1951 theme::accent().opacity(0.4)
1952 } else {
1953 theme::mention_background(false)
1954 })
1955 .text_color(theme::mention_text())
1956 .font_weight(FontWeight::SEMIBOLD)
1957 .child(context.token().label().clone())
1958 });
1959 let tray = can_attach
1960 .then(|| {
1961 render_tray(
1962 &self.tray,
1963 Self::remove_attachment,
1964 Self::retry_attachment,
1965 cx,
1966 )
1967 })
1968 .flatten();
1969 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
1970 div()
1971 .w_full()
1972 .mb(px(6.))
1973 .text_size(px(12.))
1974 .text_color(theme::amber())
1975 .child(notice.to_owned())
1976 });
1977 let composer_bounds = self.composer_bounds.clone();
1978 v_flex()
1979 .w_full()
1980 .flex_none()
1981 .px(px(24.))
1982 .pt(px(8.))
1983 .pb(px(12.))
1984 .key_context(KEY_CONTEXT)
1985 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
1986 if this.link_editor.is_none() {
1987 this.toggle_mark(MarkKind::Bold, cx);
1988 }
1989 }))
1990 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
1991 if this.link_editor.is_none() {
1992 this.toggle_mark(MarkKind::Italic, cx);
1993 }
1994 }))
1995 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
1996 if this.link_editor.is_none() {
1997 this.toggle_mark(MarkKind::Underline, cx);
1998 }
1999 }))
2000 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2001 if this.link_editor.is_none() {
2002 this.toggle_mark(MarkKind::Strike, cx);
2003 }
2004 }))
2005 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2006 if this.link_editor.is_none() {
2007 this.toggle_mark(MarkKind::Code, cx);
2008 }
2009 }))
2010 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2011 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2012 if this.link_editor.is_none() {
2013 this.step_history(true, window, cx);
2014 cx.stop_propagation();
2015 }
2016 }))
2017 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
2018 if this.link_editor.is_none() {
2019 this.step_history(false, window, cx);
2020 cx.stop_propagation();
2021 }
2022 }))
2023 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2024 if this.link_editor.is_none() && this.copy_selection(cx) {
2025 cx.stop_propagation();
2026 }
2027 }))
2028 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2029 if this.link_editor.is_none() && this.copy_selection(cx) {
2030 this.input
2031 .update(cx, |state, cx| state.replace("", window, cx));
2032 cx.stop_propagation();
2033 }
2034 }))
2035 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
2036 if this.link_editor.is_some() {
2037 } else if this.popup_is_open() {
2038 this.move_highlight(-1, cx);
2039 cx.stop_propagation();
2040 } else if this.editing.is_none() && this.is_empty(cx) {
2041 cx.emit(ComposerEvent::EditLast);
2042 cx.stop_propagation();
2043 }
2044 }))
2045 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
2046 if this.link_editor.is_none() && this.popup_is_open() {
2047 this.move_highlight(1, cx);
2048 cx.stop_propagation();
2049 }
2050 }))
2051 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2052 if this.link_editor.is_some() {
2053 this.apply_link(window, cx);
2054 cx.stop_propagation();
2055 } else if this.popup_is_open() {
2056 this.accept_popup(window, cx);
2057 cx.stop_propagation();
2058 } else if this.break_line(action.shift, window, cx) {
2059 cx.stop_propagation();
2060 }
2061 }))
2062 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2063 if this.link_editor.is_some() {
2064 } else if this.popup_is_open() {
2065 this.accept_popup(window, cx);
2066 cx.stop_propagation();
2067 } else if this.indent(false, window, cx) {
2068 cx.stop_propagation();
2069 }
2070 }))
2071 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2072 if this.link_editor.is_none() && this.indent(true, window, cx) {
2073 cx.stop_propagation();
2074 }
2075 }))
2076 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2077 if this.link_editor.is_none()
2078 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2079 {
2080 cx.stop_propagation();
2081 }
2082 }))
2083 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2084 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2085 cx.stop_propagation();
2086 }
2087 }))
2088 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2089 if this.link_editor.is_some() {
2090 this.close_link_editor(window, cx);
2091 cx.stop_propagation();
2092 return;
2093 }
2094 if this.toolbar_requested(cx) {
2095 this.toolbar_dismissed = Some(this.selection(cx));
2096 cx.notify();
2097 cx.stop_propagation();
2098 return;
2099 }
2100 if let Some(popup) = &this.emoji_popup {
2101 this.emoji_dismissed_at = Some(popup.range.start);
2102 }
2103 if this.popup.is_some() || this.emoji_popup.is_some() {
2104 this.close_popup();
2105 cx.notify();
2106 cx.stop_propagation();
2107 } else if this.editing.is_some() {
2108 this.cancel_edit(window, cx);
2109 cx.stop_propagation();
2110 }
2111 }))
2112 .children(notice)
2113 .children(self.render_reply_strip(cx))
2114 .children(self.render_edit_strip(cx))
2115 .child(
2116 div()
2117 .relative()
2118 .w_full()
2119 .children(self.render_popup(cx))
2120 .children(self.render_emoji_popup(window, cx))
2121 .children(self.render_toolbar(focused, cx))
2122 .child(
2123 v_flex()
2124 .relative()
2125 .w_full()
2126 .rounded(px(10.))
2127 .bg(theme::surface())
2128 .border_1()
2129 .border_color(if focused {
2130 theme::accent()
2131 } else {
2132 theme::border_strong()
2133 })
2134 .child(
2135 canvas(
2136 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2137 |_, _, _, _| {},
2138 )
2139 .absolute()
2140 .size_full(),
2141 )
2142 .children(tray)
2143 .child(
2144 h_flex()
2145 .w_full()
2146 .items_end()
2147 .gap(px(6.))
2148 .py(px(6.))
2149 .pl(px(if can_attach { 6. } else { 12. }))
2150 .pr(px(6.))
2151 .children(attach)
2152 .child(
2153 div()
2154 .flex_1()
2155 .min_w_0()
2156 .capture_any_mouse_down(cx.listener(
2157 |this, _: &MouseDownEvent, _, _| {
2158 this.mouse_selecting = true;
2159 this.toolbar_dismissed = None;
2160 this.link_editor = None;
2161 },
2162 ))
2163 .capture_any_mouse_up(cx.listener(
2164 |this, _: &MouseUpEvent, _, cx| {
2165 this.mouse_selecting = false;
2166 cx.notify();
2167 },
2168 ))
2169 .on_mouse_up_out(
2170 MouseButton::Left,
2171 cx.listener(|this, _, _, cx| {
2172 this.mouse_selecting = false;
2173 cx.notify();
2174 }),
2175 )
2176 .child(input),
2177 )
2178 .child(send),
2179 ),
2180 ),
2181 )
2182 .children(self.render_paste_hint())
2183 }
2184}
2185
2186#[cfg(test)]
2187mod tests {
2188 use super::{active_mention, submitted_text};
2189 use gpui_kit::component::input::InputEvent;
2190
2191 fn press(shift: bool) -> InputEvent {
2192 InputEvent::PressEnter {
2193 secondary: false,
2194 shift,
2195 }
2196 }
2197
2198 #[test]
2199 fn enter_sends_trimmed_text() {
2200 assert_eq!(
2201 submitted_text(&press(false), " hello \n"),
2202 Some("hello".into())
2203 );
2204 }
2205
2206 #[test]
2207 fn shift_enter_never_sends() {
2208 assert_eq!(submitted_text(&press(true), "hello"), None);
2209 }
2210
2211 #[test]
2212 fn blank_text_never_sends() {
2213 assert_eq!(submitted_text(&press(false), " \n "), None);
2214 }
2215
2216 #[test]
2217 fn other_events_never_send() {
2218 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
2219 }
2220
2221 #[test]
2222 fn at_sign_opens_a_mention_query() {
2223 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
2224 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
2225 }
2226
2227 #[test]
2228 fn names_with_a_space_keep_the_query_open() {
2229 assert_eq!(
2230 active_mention("@Mara Lin", 9, &[]),
2231 Some((0..9, "Mara Lin".into()))
2232 );
2233 }
2234
2235 #[test]
2236 fn mail_addresses_and_closed_queries_do_not_open() {
2237 assert_eq!(active_mention("a@b", 3, &[]), None);
2238 assert_eq!(active_mention("@Mara ", 6, &[]), None);
2239 assert_eq!(active_mention("@ x", 3, &[]), None);
2240 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
2241 }
2242
2243 #[test]
2244 fn text_inside_a_token_does_not_reopen() {
2245 let token = 0..15;
2246 assert_eq!(
2247 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
2248 None
2249 );
2250 assert_eq!(
2251 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
2252 Some((16..19, "Pr".into()))
2253 );
2254 }
2255
2256 #[test]
2257 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
2258 use std::sync::Arc;
2259
2260 use gpui_kit::{Image, ImageFormat};
2261 use teams_core::FileKind;
2262
2263 use super::{Outgoing, OutgoingFile, OutgoingImage};
2264
2265 let outgoing = Outgoing {
2266 draft: teams_core::Draft::default(),
2267 mentions: Vec::new(),
2268 reply: None,
2269 edit: None,
2270 images: vec![OutgoingImage {
2271 name: "pasted-image.png".into(),
2272 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2273 dimensions: Some((1, 1)),
2274 }],
2275 files: vec![OutgoingFile {
2276 name: "plan.pdf".into(),
2277 size: 9,
2278 kind: FileKind::Pdf,
2279 uploaded: None,
2280 reference: teams_core::FileReference {
2281 attachment_id: "guid".into(),
2282 content_url: "https://files.example/plan.pdf".into(),
2283 name: "plan.pdf".into(),
2284 },
2285 }],
2286 };
2287 let extras = outgoing.extras();
2288 assert_eq!(extras.images[0].content_type, "image/png");
2289 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
2290 assert_eq!(extras.files[0].attachment_id, "guid");
2291 assert!(outgoing.has_attachments());
2292 }
2293
2294 #[test]
2295 fn enter_sends_attachments_even_without_text() {
2296 assert!(super::is_plain_enter(&press(false)));
2297 assert!(!super::is_plain_enter(&press(true)));
2298 assert!(!super::is_plain_enter(&InputEvent::Change));
2299 }
2300
2301 mod keys {
2302 use std::sync::Arc;
2303
2304 use gpui_kit::test::TestWindowExt as _;
2305 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2306 use store::Store;
2307
2308 use super::super::Composer;
2309 use crate::app_state::{AppState, Mode};
2310
2311 #[gpui_kit::test]
2312 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
2313 cx.update(gpui_kit::init);
2314 let store = Arc::new(Store::open_in_memory().unwrap());
2315 let mode = Mode {
2316 demo: true,
2317 read_only: false,
2318 demo_sync: None,
2319 };
2320 let (handle, composer) = cx.update(|cx| {
2321 let app = cx.new(|_| AppState::new(store, mode));
2322 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2323 cx.new(|cx| Composer::new(app, window, cx))
2324 })
2325 .unwrap()
2326 });
2327 let value = cx
2328 .update_window(handle, |_, window, cx| {
2329 composer.update(cx, |composer, cx| composer.focus(window, cx));
2330 window.render_frame(cx);
2331 window.input("first line", cx);
2332 window.press("shift-enter", cx);
2333 window.input("second line", cx);
2334 window.press("ctrl-a", cx);
2335 window.input("X", cx);
2336 composer.read(cx).input.read(cx).value()
2337 })
2338 .unwrap();
2339 assert_eq!(value, "X");
2340 }
2341
2342 struct Typist<'a> {
2343 cx: &'a mut TestAppContext,
2344 handle: gpui_kit::AnyWindowHandle,
2345 composer: gpui_kit::Entity<Composer>,
2346 }
2347
2348 impl Typist<'_> {
2349 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
2350 self.cx
2351 .update_window(self.handle, |_, window, cx| action(window, cx))
2352 .unwrap();
2353 self.cx.run_until_parked();
2354 }
2355
2356 fn type_text(&mut self, text: &str) {
2357 for character in text.chars() {
2358 self.act(|window, cx| window.input(&character.to_string(), cx));
2359 }
2360 }
2361
2362 fn press(&mut self, keys: &str) {
2363 for key in keys.split(' ') {
2364 self.act(|window, cx| window.press(key, cx));
2365 }
2366 }
2367
2368 fn value(&mut self) -> String {
2369 let composer = self.composer.clone();
2370 self.cx
2371 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
2372 }
2373
2374 fn draft(&mut self) -> teams_core::Draft {
2375 let composer = self.composer.clone();
2376 self.cx.update(|cx| composer.read(cx).draft.clone())
2377 }
2378
2379 fn outgoing(&mut self) -> super::super::Outgoing {
2380 let composer = self.composer.clone();
2381 self.cx
2382 .update(|cx| composer.read(cx).outgoing(cx))
2383 .expect("text to send")
2384 }
2385 }
2386
2387 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
2388 let (handle, composer) = demo_composer(cx);
2389 cx.update(super::super::bind_keys);
2390 let mut typist = Typist {
2391 cx,
2392 handle,
2393 composer: composer.clone(),
2394 };
2395 typist.act(|window, cx| {
2396 composer.update(cx, |composer, cx| composer.focus(window, cx));
2397 window.render_frame(cx);
2398 });
2399 typist
2400 }
2401
2402 #[gpui_kit::test]
2403 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
2404 use teams_core::{FormatState, MarkKind};
2405
2406 let mut typist = typist(cx);
2407 typist.type_text("a **bold**");
2408 assert_eq!(typist.value(), "a bold");
2409 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
2410 typist.press("backspace");
2411 assert_eq!(typist.value(), "a **bold**");
2412 assert!(typist.draft().marks().is_empty());
2413 let composer = typist.composer.clone();
2414 assert_eq!(
2415 typist
2416 .cx
2417 .update(|cx| composer.read(cx).input.read(cx).cursor()),
2418 10
2419 );
2420 typist.press("backspace");
2421 typist.type_text("* x");
2422 assert_eq!(typist.value(), "a bold x");
2423 assert_eq!(
2424 typist.draft().state(6..8, &MarkKind::Bold),
2425 FormatState::Off
2426 );
2427 }
2428
2429 #[gpui_kit::test]
2430 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
2431 let mut typist = typist(cx);
2432 typist.type_text("1. one");
2433 typist.press("enter");
2434 typist.type_text("two");
2435 assert_eq!(typist.value(), "1. one\n2. two");
2436 typist.press("enter enter");
2437 assert_eq!(typist.value(), "1. one\n2. two\n");
2438 typist.type_text("after");
2439 typist.press("enter");
2440 assert_eq!(typist.value(), "");
2441 }
2442
2443 #[gpui_kit::test]
2444 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
2445 let mut typist = typist(cx);
2446 typist.type_text("- a");
2447 typist.press("enter tab");
2448 typist.type_text("b");
2449 assert_eq!(typist.value(), "• a\n◦ b");
2450 typist.press("shift-tab");
2451 assert_eq!(typist.value(), "• a\n• b");
2452 }
2453
2454 #[gpui_kit::test]
2455 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
2456 use teams_core::{FormatState, MarkKind};
2457
2458 let mut typist = typist(cx);
2459 typist.type_text("hello");
2460 typist.press("shift-left shift-left ctrl-b");
2461 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2462 assert_eq!(
2463 typist.draft().state(0..5, &MarkKind::Bold),
2464 FormatState::Mixed
2465 );
2466 typist.press("ctrl-b");
2467 assert!(typist.draft().marks().is_empty());
2468 typist.press("end ctrl-i");
2469 typist.type_text("!");
2470 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
2471 }
2472
2473 #[gpui_kit::test]
2474 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
2475 let mut typist = typist(cx);
2476 typist
2477 .cx
2478 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2479 "**hi** there".to_owned(),
2480 ));
2481 typist.press("ctrl-v");
2482 assert_eq!(typist.value(), "hi there");
2483 let composer = typist.composer.clone();
2484 assert!(
2485 typist
2486 .cx
2487 .update(|cx| composer.read(cx).paste_hint.is_some())
2488 );
2489 typist.press("ctrl-z");
2490 assert_eq!(typist.value(), "**hi** there");
2491 assert!(typist.draft().marks().is_empty());
2492 }
2493
2494 #[gpui_kit::test]
2495 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
2496 use teams_core::{FormatState, MarkKind};
2497
2498 let mut typist = typist(cx);
2499 typist.type_text("`code` ");
2500 typist.press("ctrl-a ctrl-c end ctrl-v");
2501 assert_eq!(typist.value(), "code code ");
2502 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
2503 }
2504
2505 #[gpui_kit::test]
2506 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
2507 use teams_core::{FormatState, MarkKind};
2508
2509 let mut typist = typist(cx);
2510 typist.type_text("~~old~~");
2511 typist.press("ctrl-a");
2512 typist.type_text("new");
2513 typist.press("ctrl-z ctrl-z");
2514 assert_eq!(typist.value(), "old");
2515 assert_eq!(
2516 typist.draft().state(0..3, &MarkKind::Strike),
2517 FormatState::On
2518 );
2519 }
2520
2521 #[gpui_kit::test]
2522 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
2523 let mut typist = typist(cx);
2524 typist.type_text("see docs");
2525 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
2526 let composer = typist.composer.clone();
2527 assert!(
2528 typist
2529 .cx
2530 .update(|cx| composer.read(cx).link_editor.is_some())
2531 );
2532 typist.type_text("example.com");
2533 typist.press("enter");
2534 assert!(
2535 typist
2536 .cx
2537 .update(|cx| composer.read(cx).link_editor.is_none())
2538 );
2539 assert_eq!(
2540 typist.outgoing().html(),
2541 "see <a href=\"https://example.com\">docs</a>"
2542 );
2543 }
2544
2545 #[gpui_kit::test]
2546 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
2547 use teams_core::{FormatState, MarkKind};
2548
2549 let mut typist = typist(cx);
2550 typist.type_text("hello");
2551 typist.press("shift-left shift-left ctrl-b");
2552 typist.press("ctrl-z");
2553 assert_eq!(typist.value(), "hello");
2554 assert!(typist.draft().marks().is_empty());
2555 typist.press("ctrl-y");
2556 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2557 }
2558
2559 #[gpui_kit::test]
2560 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
2561 use teams_core::{FormatState, MarkKind};
2562
2563 let mut typist = typist(cx);
2564 typist.type_text("hello");
2565 typist.press("shift-left shift-left ctrl-b end");
2566 typist.type_text(" x");
2567 typist.press("backspace backspace");
2568 assert_eq!(typist.value(), "hello");
2569 typist.press("ctrl-z");
2570 assert_ne!(typist.value(), "hello");
2571 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2572 }
2573
2574 #[gpui_kit::test]
2575 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
2576 let mut typist = typist(cx);
2577 typist.type_text("```");
2578 typist.press("enter");
2579 typist.type_text("a");
2580 typist.press("enter");
2581 typist.type_text("b");
2582 typist.press("up end delete");
2583 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
2584 }
2585
2586 #[gpui_kit::test]
2587 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
2588 let mut typist = typist(cx);
2589 typist.type_text("```");
2590 typist.press("enter");
2591 typist.type_text(" x");
2592 typist.press("ctrl-a ctrl-c");
2593 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
2594 assert_eq!(text.as_deref(), Some(" x"));
2595 }
2596
2597 #[gpui_kit::test]
2598 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
2599 let mut typist = typist(cx);
2600 typist.type_text("docs");
2601 typist.press("ctrl-a ctrl-k");
2602 typist.type_text("javascript:alert(1)");
2603 typist.press("enter");
2604 let composer = typist.composer.clone();
2605 assert!(typist.cx.update(|cx| {
2606 composer
2607 .read(cx)
2608 .link_editor
2609 .as_ref()
2610 .is_some_and(|editor| editor.refused)
2611 }));
2612 assert!(typist.draft().marks().is_empty());
2613 typist.type_text("x");
2614 assert!(typist.cx.update(|cx| {
2615 composer
2616 .read(cx)
2617 .link_editor
2618 .as_ref()
2619 .is_some_and(|editor| !editor.refused)
2620 }));
2621 }
2622
2623 #[gpui_kit::test]
2624 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
2625 use teams_core::{FormatState, LineKind, MarkKind};
2626
2627 let mut typist = typist(cx);
2628 typist.type_text("hello");
2629 typist.press("ctrl-a ctrl-b");
2630 let composer = typist.composer.clone();
2631 typist.act(|window, cx| {
2632 composer.update(cx, |composer, cx| {
2633 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
2634 })
2635 });
2636 assert_eq!(typist.value(), "• hello");
2637 typist.press("ctrl-z");
2638 assert_eq!(typist.value(), "hello");
2639 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
2640 typist.press("ctrl-z");
2641 assert!(typist.draft().marks().is_empty());
2642 assert_eq!(typist.draft().lines(), [LineKind::Text]);
2643 }
2644
2645 #[gpui_kit::test]
2646 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
2647 use teams_core::{FormatState, MarkKind};
2648
2649 let mut typist = typist(cx);
2650 typist.type_text("hello");
2651 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
2652 assert_eq!(typist.value(), "");
2653 typist.press("ctrl-y");
2654 assert_eq!(typist.value(), "hello");
2655 assert!(typist.draft().marks().is_empty());
2656 typist.press("ctrl-y");
2657 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
2658 }
2659
2660 #[gpui_kit::test]
2661 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
2662 let mut typist = typist(cx);
2663 typist.press("ctrl-z");
2664 typist.type_text("**a**");
2665 assert_eq!(typist.value(), "a");
2666 }
2667
2668 #[gpui_kit::test]
2669 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
2670 let mut typist = typist(cx);
2671 typist.type_text("```");
2672 typist.press("enter");
2673 typist.type_text(":) ");
2674 typist
2675 .cx
2676 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
2677 typist.press("ctrl-v");
2678 assert_eq!(typist.value(), ":) **x**");
2679 let composer = typist.composer.clone();
2680 assert!(
2681 typist
2682 .cx
2683 .update(|cx| composer.read(cx).paste_hint.is_none())
2684 );
2685 let outgoing = typist.outgoing();
2686 assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
2687 }
2688
2689 #[gpui_kit::test]
2690 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
2691 let mut typist = typist(cx);
2692 typist.type_text("> quoted");
2693 typist.press("shift-enter");
2694 typist.type_text("more");
2695 let outgoing = typist.outgoing();
2696 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
2697 assert_eq!(outgoing.text(), "quoted\nmore");
2698 }
2699
2700 #[gpui_kit::test]
2701 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
2702 cx.update(gpui_kit::init);
2703 let store = Arc::new(Store::open_in_memory().unwrap());
2704 let mode = Mode {
2705 demo: true,
2706 read_only: false,
2707 demo_sync: None,
2708 };
2709 let (handle, composer) = cx.update(|cx| {
2710 let app = cx.new(|_| AppState::new(store, mode));
2711 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2712 cx.new(|cx| Composer::new(app, window, cx))
2713 })
2714 .unwrap()
2715 });
2716 let directory = tempfile::tempdir().unwrap();
2717 let path = directory.path().join("plan.pdf");
2718 std::fs::write(&path, b"%PDF-1.7").unwrap();
2719 cx.update_window(handle, |_, window, cx| {
2720 composer.update(cx, |composer, cx| {
2721 composer.set_conversation("demo-chat", "Demo", window, cx);
2722 composer.add_paths(vec![path], cx);
2723 });
2724 })
2725 .unwrap();
2726 cx.run_until_parked();
2727 cx.update(|cx| {
2728 let composer = composer.read(cx);
2729 assert!(composer.tray.blocks_send());
2730 assert!(!composer.can_send(cx));
2731 });
2732 cx.executor()
2733 .advance_clock(std::time::Duration::from_secs(3));
2734 cx.run_until_parked();
2735 cx.update(|cx| {
2736 let composer = composer.read(cx);
2737 assert!(composer.can_send(cx));
2738 let outgoing = composer
2739 .outgoing(cx)
2740 .expect("an attachment alone is a message");
2741 assert_eq!(outgoing.text(), "");
2742 assert_eq!(outgoing.files.len(), 1);
2743 assert_eq!(outgoing.files[0].name, "plan.pdf");
2744 });
2745 }
2746
2747 #[gpui_kit::test]
2748 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
2749 cx.update(gpui_kit::init);
2750 let store = Arc::new(Store::open_in_memory().unwrap());
2751 let mode = Mode {
2752 demo: true,
2753 read_only: false,
2754 demo_sync: None,
2755 };
2756 let (handle, composer) = cx.update(|cx| {
2757 let app = cx.new(|_| AppState::new(store, mode));
2758 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2759 cx.new(|cx| Composer::new(app, window, cx))
2760 })
2761 .unwrap()
2762 });
2763 let directory = tempfile::tempdir().unwrap();
2764 let path = directory.path().join("plan.pdf");
2765 std::fs::write(&path, b"%PDF-1.7").unwrap();
2766 cx.update_window(handle, |_, window, cx| {
2767 composer.update(cx, |composer, cx| {
2768 composer.set_conversation("demo-chat", "Demo", window, cx);
2769 composer.add_paths(vec![path], cx);
2770 });
2771 })
2772 .unwrap();
2773 cx.run_until_parked();
2774 cx.update_window(handle, |_, window, cx| {
2775 composer.update(cx, |composer, cx| {
2776 composer.set_conversation("other-chat", "Other", window, cx)
2777 });
2778 })
2779 .unwrap();
2780 cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));
2781 }
2782
2783 fn demo_composer(
2784 cx: &mut TestAppContext,
2785 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
2786 cx.update(gpui_kit::init);
2787 let store = Arc::new(Store::open_in_memory().unwrap());
2788 let mode = Mode {
2789 demo: true,
2790 read_only: false,
2791 demo_sync: None,
2792 };
2793 let (handle, composer) = cx.update(|cx| {
2794 let app = cx.new(|_| AppState::new(store, mode));
2795 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2796 cx.new(|cx| Composer::new(app, window, cx))
2797 })
2798 .unwrap()
2799 });
2800 (handle, composer)
2801 }
2802
2803 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
2804 let path = directory.join("dot.png");
2805 image::RgbaImage::new(2, 2).save(&path).unwrap();
2806 path
2807 }
2808
2809 #[gpui_kit::test]
2810 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
2811 use super::super::{EditPreview, Outgoing};
2812
2813 let (handle, composer) = demo_composer(cx);
2814 let directory = tempfile::tempdir().unwrap();
2815 let path = directory.path().join("plan.pdf");
2816 std::fs::write(&path, b"%PDF-1.7").unwrap();
2817 cx.update_window(handle, |_, window, cx| {
2818 composer.update(cx, |composer, cx| {
2819 composer.set_conversation("demo-chat", "Demo", window, cx);
2820 composer.add_paths(vec![path], cx);
2821 });
2822 })
2823 .unwrap();
2824 cx.run_until_parked();
2825 cx.executor()
2826 .advance_clock(std::time::Duration::from_secs(3));
2827 cx.run_until_parked();
2828 cx.update_window(handle, |_, window, cx| {
2829 composer.update(cx, |composer, cx| {
2830 let draft = Outgoing {
2831 draft: teams_core::Draft::plain("old"),
2832 mentions: Vec::new(),
2833 reply: None,
2834 edit: Some(EditPreview {
2835 message_id: "m1".into(),
2836 excerpt: "old".into(),
2837 }),
2838 images: Vec::new(),
2839 files: Vec::new(),
2840 };
2841 composer.begin_edit(draft, window, cx);
2842 });
2843 })
2844 .unwrap();
2845 cx.update(|cx| {
2846 let composer = composer.read(cx);
2847 assert_eq!(composer.tray.items().len(), 1);
2848 let outgoing = composer.outgoing(cx).unwrap();
2849 assert!(outgoing.files.is_empty());
2850 assert_eq!(outgoing.text(), "old");
2851 });
2852 cx.update_window(handle, |_, window, cx| {
2853 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
2854 })
2855 .unwrap();
2856 cx.update(|cx| {
2857 let composer = composer.read(cx);
2858 assert_eq!(composer.tray.items().len(), 1);
2859 assert!(composer.can_send(cx));
2860 });
2861 }
2862
2863 #[gpui_kit::test]
2864 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
2865 let (handle, composer) = demo_composer(cx);
2866 let directory = tempfile::tempdir().unwrap();
2867 let path = small_png(directory.path());
2868 for (carry, chosen, expected) in [
2869 (Some("chat-a"), "chat-a", 1),
2870 (None, "chat-b", 0),
2871 (Some("chat-a"), "chat-b", 0),
2872 ] {
2873 cx.update_window(handle, |_, window, cx| {
2874 composer.update(cx, |composer, cx| {
2875 composer.set_conversation("", "", window, cx);
2876 composer.add_paths(vec![path.clone()], cx);
2877 });
2878 })
2879 .unwrap();
2880 cx.run_until_parked();
2881 cx.update_window(handle, |_, window, cx| {
2882 composer.update(cx, |composer, cx| {
2883 if let Some(chat) = carry {
2884 composer.carry_images_into(chat.to_owned());
2885 }
2886 composer.set_conversation(chosen, "Chat", window, cx);
2887 });
2888 })
2889 .unwrap();
2890 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
2891 }
2892 }
2893
2894 #[gpui_kit::test]
2895 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
2896 cx: &mut TestAppContext,
2897 ) {
2898 let (handle, composer) = demo_composer(cx);
2899 let directory = tempfile::tempdir().unwrap();
2900 let png = small_png(directory.path());
2901 let pdf = directory.path().join("plan.pdf");
2902 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
2903 cx.update_window(handle, |_, window, cx| {
2904 composer.update(cx, |composer, cx| {
2905 composer.set_conversation("bob-chat", "Bob", window, cx);
2906 composer.add_paths(vec![png, pdf], cx);
2907 });
2908 })
2909 .unwrap();
2910 cx.run_until_parked();
2911 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
2912 cx.update_window(handle, |_, window, cx| {
2913 composer.update(cx, |composer, cx| {
2914 composer.carry_images_into(String::new());
2915 composer.set_conversation("", "", window, cx);
2916 });
2917 })
2918 .unwrap();
2919 cx.update(|cx| {
2920 let composer = composer.read(cx);
2921 assert_eq!(composer.tray.items().len(), 1);
2922 assert_eq!(composer.tray.items()[0].name, "dot.png");
2923 assert!(!composer.files_allowed());
2924 });
2925 }
2926 }
2927}