BlueGit

ict rusty-teams

Files

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

composer.rs

composer.rs 153.7 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, Instant};
8
9use chrono::{DateTime, Utc};
10use gpui_kit::assets::IconName;
11use gpui_kit::component::{
12 ActiveTheme as _, Sizable as _,
13 button::{Button, ButtonVariants as _},
14 h_flex,
15 input::{
16 Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent,
17 InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
18 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
19 },
20 popover::Popover,
21 tooltip::Tooltip,
22 v_flex,
23};
24use gpui_kit::prelude::FluentBuilder as _;
25use gpui_kit::*;
26use serde::{Deserialize, Serialize};
27use teams_core::{
28 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
29 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
30 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
31};
32
33mod drafts;
34mod schedule;
35
36use super::attachment_tray::{
37 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,
38 PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
39 pasted_image_name, prepare_pasted_image, read_attachment, render_tray,
40};
41use super::avatar::{person_avatar, square_avatar};
42use super::draft_style::draft_style;
43use super::emoji_popup::{self, EmojiPopup};
44use super::format_toolbar::{self, FormatButton};
45use super::link_preview::{ComposeLink, draft_link, link_preview_card};
46use super::fun_picker::{FunPicker, FunPickerEvent};
47use super::widgets::{icon, symbol};
48use crate::app_state::AppState;
49use crate::emoji;
50use crate::remote_image::RemoteImage;
51use crate::runtime;
52use crate::scheduled_rows::scheduled_label;
53use crate::theme;
54use crate::typing::OutgoingTyping;
55
56const MIN_ROWS: usize = 1;
57const MAX_ROWS: usize = 8;
58const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
59const MENTION_LIMIT: usize = 8;
60const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600);
61const MENTION_QUERY_MAX_CHARS: usize = 32;
62const MENTION_QUERY_MAX_WORDS: usize = 3;
63const POPUP_WIDTH: f32 = 380.;
64const POPUP_ROW_HEIGHT: f32 = 44.;
65const DEMO_UPLOAD_STEPS: u8 = 10;
66const COMPOSER_ICON_SIZE: f32 = 20.;
67/// gpui-kit draws a `Size::Size` button's icon at this fraction of the button size.
68const BUTTON_ICON_SCALE: f32 = 0.75;
69const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
70const DEMO_FAILURE_STEP: u8 = 6;
71const HISTORY_LIMIT: usize = 200;
72const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
73const KEY_CONTEXT: &str = "Composer";
74const IMAGE_TOKEN_PREFIX: &str = "image-";
75
76actions!(
77 composer,
78 [
79 ToggleBold,
80 ToggleItalic,
81 ToggleUnderline,
82 ToggleStrike,
83 ToggleSuperscript,
84 ToggleSubscript,
85 ToggleCode,
86 EditLink,
87 ScheduleSend
88 ]
89);
90
91pub fn bind_keys(cx: &mut App) {
92 cx.bind_keys([
93 KeyBinding::new("ctrl-b", ToggleBold, Some(KEY_CONTEXT)),
94 KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),
95 KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),
96 KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),
97 KeyBinding::new("ctrl-shift-=", ToggleSuperscript, Some(KEY_CONTEXT)),
98 KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),
99 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
100 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
101 KeyBinding::new("ctrl-shift-enter", ScheduleSend, Some(KEY_CONTEXT)),
102 #[cfg(target_os = "macos")]
103 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
104 #[cfg(target_os = "macos")]
105 KeyBinding::new("cmd-i", ToggleItalic, Some(KEY_CONTEXT)),
106 #[cfg(target_os = "macos")]
107 KeyBinding::new("cmd-u", ToggleUnderline, Some(KEY_CONTEXT)),
108 #[cfg(target_os = "macos")]
109 KeyBinding::new("cmd-k", EditLink, Some(KEY_CONTEXT)),
110 ]);
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct ReplyPreview {
115 pub message_id: String,
116 pub author: String,
117 pub excerpt: String,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct EditPreview {
122 pub message_id: String,
123 pub excerpt: String,
124 pub scheduled: Option<DateTime<Utc>>,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Outgoing {
129 pub draft: Draft,
130 pub subject: Option<String>,
131 pub mentions: Vec<MentionInput>,
132 pub reply: Option<ReplyPreview>,
133 pub edit: Option<EditPreview>,
134 pub images: Vec<OutgoingImage>,
135 pub files: Vec<OutgoingFile>,
136 pub link_preview: Option<LinkPreview>,
137}
138
139impl Outgoing {
140 /// Without list and quote markers, for previews.
141 pub fn text(&self) -> String {
142 self.draft.plain_text()
143 }
144
145 /// The body before mentions become `<at>` tags.
146 pub fn html(&self) -> String {
147 let mut html = String::new();
148 let mut objects = self.images.iter();
149 let mut uploaded = 0;
150 for character in self.draft.to_html().chars() {
151 if character != OBJECT_MARK {
152 html.push(character);
153 continue;
154 }
155 match objects.next() {
156 Some(OutgoingImage::Inline(_)) => {
157 uploaded += 1;
158 html.push_str(&format!("<img src=\"../hostedContents/{uploaded}/$value\">"));
159 }
160 Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),
161 None => {}
162 }
163 }
164 html
165 }
166
167 pub fn has_attachments(&self) -> bool {
168 !self.images.is_empty() || !self.files.is_empty()
169 }
170
171 pub fn extras(&self) -> MessageExtras {
172 MessageExtras {
173 kept: Vec::new(),
174 images: self
175 .images
176 .iter()
177 .filter_map(|outgoing| match outgoing {
178 OutgoingImage::Inline(inline) => Some(HostedImage {
179 content_type: inline.image.format.mime_type().to_owned(),
180 bytes: Arc::new(inline.image.bytes.clone()),
181 }),
182 OutgoingImage::Remote(_) => None,
183 })
184 .collect(),
185 files: self
186 .files
187 .iter()
188 .map(|file| file.reference.clone())
189 .collect(),
190 }
191 }
192}
193
194enum UploadEvent {
195 Progress(u8),
196 Uploaded(UploadedFile),
197 Finished(UploadResult),
198}
199
200enum UploadHandle {
201 Network(tokio::task::AbortHandle),
202 Demo(Task<()>),
203}
204
205impl UploadHandle {
206 fn cancel(self) {
207 match self {
208 UploadHandle::Network(handle) => handle.abort(),
209 UploadHandle::Demo(task) => drop(task),
210 }
211 }
212}
213
214pub enum ComposerEvent {
215 Submit(Box<Outgoing>),
216 Schedule {
217 outgoing: Box<Outgoing>,
218 send_at: DateTime<Utc>,
219 },
220 EditLast,
221 Typing(bool),
222}
223
224struct MentionPopup {
225 range: Range<usize>,
226 query: String,
227 candidates: Vec<MentionCandidate>,
228 highlighted: usize,
229}
230
231/// An automatic edit Backspace takes back while nothing changed since.
232struct Conversion {
233 value: String,
234 cursor: usize,
235 before: Draft,
236 restore: Vec<Edit>,
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240enum StepKind {
241 Typing { at: usize, after_space: bool },
242 Deleting { start: usize, end: usize },
243 Other,
244}
245
246/// One state of the composer's own undo history: text, tokens, formatting and selection.
247struct HistoryStep {
248 draft: Draft,
249 tokens: Vec<(Range<usize>, InlineToken)>,
250 selection: Range<usize>,
251 kind: StepKind,
252}
253
254struct LinkEditor {
255 range: Range<usize>,
256 field: Entity<InputState>,
257 refused: bool,
258 _edits: Subscription,
259}
260
261type DraftDecorations = (
262 TextDecorationCollection<TextareaMode>,
263 RangeDecorationCollection<TextareaMode>,
264);
265
266pub struct Composer {
267 app: Entity<AppState>,
268 input: Entity<TextareaState>,
269 conversation_id: Option<String>,
270 inline: bool,
271 reply: Option<ReplyPreview>,
272 editing: Option<EditPreview>,
273 mention_inputs: HashMap<String, MentionInput>,
274 mention_counter: usize,
275 popup: Option<MentionPopup>,
276 lookup: Option<Task<()>>,
277 emoji_popup: Option<EmojiPopup>,
278 emoji_dismissed_at: Option<usize>,
279 recent_emoji: emoji::Recent,
280 conversion: Option<Conversion>,
281 undone_value: Option<String>,
282 previous_value: String,
283 typing: OutgoingTyping,
284 draft: Draft,
285 decorations: DraftDecorations,
286 pending_style: Option<TypingStyle>,
287 history: Vec<HistoryStep>,
288 history_index: usize,
289 pasted_markdown: Option<String>,
290 paste_hint: Option<Task<()>>,
291 copied: Option<(String, Vec<DraftLine>)>,
292 toolbar_dismissed: Option<Range<usize>>,
293 mouse_selecting: bool,
294 link_editor: Option<LinkEditor>,
295 composer_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
296 tray: AttachmentTray,
297 uploads: HashMap<u64, UploadHandle>,
298 demo_failed: HashSet<u64>,
299 carry_images_into: Option<String>,
300 draft_save: Option<Task<()>>,
301 saved_images: Option<drafts::ImageFingerprint>,
302 schedule: Option<schedule::SchedulePopover>,
303 scheduling: Option<String>,
304 pending_anchors: HashMap<u64, usize>,
305 link: ComposeLink,
306 fun_picker: Entity<FunPicker>,
307 _subscriptions: [Subscription; 4],
308}
309
310impl EventEmitter<ComposerEvent> for Composer {}
311
312pub fn is_plain_enter(event: &InputEvent) -> bool {
313 matches!(event, InputEvent::PressEnter { shift: false, .. })
314}
315
316/// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends.
317pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> {
318 match event {
319 InputEvent::PressEnter { shift: false, .. } => {
320 let trimmed = value.trim();
321 (!trimmed.is_empty()).then(|| trimmed.to_owned())
322 }
323 _ => None,
324 }
325}
326
327pub fn active_mention(
328 text: &str,
329 cursor: usize,
330 tokens: &[Range<usize>],
331) -> Option<(Range<usize>, String)> {
332 if cursor > text.len() || !text.is_char_boundary(cursor) {
333 return None;
334 }
335 let before = &text[..cursor];
336 let at = before.rfind('@')?;
337 if before[..at]
338 .chars()
339 .next_back()
340 .is_some_and(|previous| !previous.is_whitespace())
341 {
342 return None;
343 }
344 let query = &before[at + 1..];
345 let rejected = query.contains('\n')
346 || query.starts_with(char::is_whitespace)
347 || query.ends_with(char::is_whitespace)
348 || query.chars().count() > MENTION_QUERY_MAX_CHARS
349 || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS
350 || tokens
351 .iter()
352 .any(|token| token.start < cursor && at < token.end);
353 (!rejected).then(|| (at..cursor, query.to_owned()))
354}
355
356fn candidate_subtitle(candidate: &MentionCandidate) -> String {
357 match candidate {
358 MentionCandidate::Person(person) => person
359 .job_title
360 .clone()
361 .filter(|title| !title.trim().is_empty())
362 .or_else(|| person.mail.clone())
363 .unwrap_or_default(),
364 MentionCandidate::Channel { .. } => "Channel".to_owned(),
365 MentionCandidate::Team { .. } => "Team".to_owned(),
366 }
367}
368
369fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind {
370 if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') {
371 return StepKind::Typing {
372 at: cursor - typed.len_utf8(),
373 after_space: typed.is_whitespace(),
374 };
375 }
376 let removed = previous.len().saturating_sub(value.len());
377 let one_char_removed = removed > 0
378 && previous.is_char_boundary(cursor)
379 && previous
380 .get(cursor..cursor + removed)
381 .is_some_and(|gone| gone.chars().count() == 1 && gone != "\n")
382 && previous.get(..cursor) == value.get(..cursor)
383 && previous.get(cursor + removed..) == value.get(cursor..);
384 if one_char_removed {
385 StepKind::Deleting {
386 start: cursor,
387 end: cursor + removed,
388 }
389 } else {
390 StepKind::Other
391 }
392}
393
394fn continues(last: &HistoryStep, kind: StepKind) -> bool {
395 let caret = &last.selection;
396 match (last.kind, kind) {
397 (
398 StepKind::Typing { after_space, .. },
399 StepKind::Typing {
400 at,
401 after_space: space,
402 },
403 ) => (!after_space || space) && caret.is_empty() && caret.start == at,
404 (StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => {
405 caret.is_empty() && (caret.start == end || caret.start == start)
406 }
407 _ => false,
408 }
409}
410
411fn looks_like_url(text: &str) -> bool {
412 ["https://", "http://", "www."]
413 .iter()
414 .any(|prefix| text.starts_with(prefix))
415 && !text.contains(char::is_whitespace)
416}
417
418fn image_token(id: u64) -> InlineToken {
419 InlineToken::new(format!("{IMAGE_TOKEN_PREFIX}{id}"), OBJECT_MARK.to_string()).block()
420}
421
422fn image_id(token: &InlineToken) -> Option<u64> {
423 token.id().strip_prefix(IMAGE_TOKEN_PREFIX)?.parse().ok()
424}
425
426fn candidate_key(candidate: &MentionCandidate) -> &str {
427 match candidate {
428 MentionCandidate::Person(person) => &person.user_id,
429 MentionCandidate::Channel { channel_id, .. } => channel_id,
430 MentionCandidate::Team { team_id, .. } => team_id,
431 }
432}
433
434impl Composer {
435 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
436 let input = cx.new(|cx| {
437 TextareaState::new(window, cx)
438 .auto_grow(MIN_ROWS, MAX_ROWS)
439 .submit_on_enter(true)
440 .placeholder("Type a message")
441 });
442 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
443 let observer = cx.observe(&input, |_, _, cx| cx.notify());
444 let image_observer = cx.observe(&app, |this, _, cx| {
445 if this.link_image_pending(cx) {
446 cx.notify();
447 }
448 });
449 let fun_picker = cx.new(|cx| FunPicker::new(app.clone(), window, cx));
450 let picker_subscription = cx.subscribe_in(&fun_picker, window, Self::on_fun_pick);
451 let decorations = input.update(cx, |state, cx| {
452 (
453 state.create_decorations_collection(Vec::new(), cx),
454 state.create_range_decorations_collection(Vec::new(), cx),
455 )
456 });
457 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
458 Composer {
459 app,
460 input,
461 conversation_id: None,
462 inline: false,
463 reply: None,
464 editing: None,
465 mention_inputs: HashMap::new(),
466 mention_counter: 0,
467 popup: None,
468 lookup: None,
469 emoji_popup: None,
470 emoji_dismissed_at: None,
471 recent_emoji,
472 conversion: None,
473 undone_value: None,
474 previous_value: String::new(),
475 typing: OutgoingTyping::default(),
476 draft: Draft::default(),
477 decorations,
478 pending_style: None,
479 history: vec![HistoryStep {
480 draft: Draft::default(),
481 tokens: Vec::new(),
482 selection: 0..0,
483 kind: StepKind::Other,
484 }],
485 history_index: 0,
486 pasted_markdown: None,
487 paste_hint: None,
488 copied: None,
489 toolbar_dismissed: None,
490 mouse_selecting: false,
491 link_editor: None,
492 composer_bounds: Rc::new(Cell::new(None)),
493 tray: AttachmentTray::default(),
494 uploads: HashMap::new(),
495 demo_failed: HashSet::new(),
496 carry_images_into: None,
497 draft_save: None,
498 saved_images: None,
499 schedule: None,
500 scheduling: None,
501 pending_anchors: HashMap::new(),
502 link: ComposeLink::default(),
503 fun_picker,
504 _subscriptions: [subscription, observer, image_observer, picker_subscription],
505 }
506 }
507
508 fn on_input_event(
509 &mut self,
510 input: &Entity<TextareaState>,
511 event: &InputEvent,
512 window: &mut Window,
513 cx: &mut Context<Self>,
514 ) {
515 cx.notify();
516 if matches!(event, InputEvent::Change) {
517 self.on_change(window, cx);
518 self.update_emoji(cx);
519 self.update_mention(cx);
520 self.update_link_preview(cx);
521 self.schedule_draft_save(cx);
522 }
523 let value = input.read(cx).value();
524 if submitted_text(event, &value).is_some()
525 || (is_plain_enter(event) && self.has_attachments(cx))
526 {
527 self.submit_current(window, cx);
528 }
529 }
530
531 fn update_mention(&mut self, cx: &mut Context<Self>) {
532 let state = self.input.read(cx);
533 let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect();
534 let found = active_mention(&state.value(), state.cursor(), &tokens);
535 let Some((range, query)) = found else {
536 self.close_mention_popup();
537 return;
538 };
539 let unchanged = self
540 .popup
541 .as_ref()
542 .is_some_and(|popup| popup.query == query && popup.range == range);
543 if unchanged {
544 return;
545 }
546 let previous = self.popup.take();
547 self.popup = Some(MentionPopup {
548 range,
549 query: query.clone(),
550 candidates: previous.map(|popup| popup.candidates).unwrap_or_default(),
551 highlighted: 0,
552 });
553 self.request_candidates(query, cx);
554 }
555
556 fn close_popup(&mut self) {
557 self.close_mention_popup();
558 self.emoji_popup = None;
559 }
560
561 fn close_mention_popup(&mut self) {
562 self.popup = None;
563 self.lookup = None;
564 }
565
566 fn report_typing(&mut self, has_text: bool, cx: &mut Context<Self>) {
567 if self.editing.is_some() {
568 return;
569 }
570 if let Some(active) = self.typing.on_text(has_text, Instant::now()) {
571 cx.emit(ComposerEvent::Typing(active));
572 }
573 }
574
575 pub fn stop_typing(&mut self) -> bool {
576 self.typing.stop()
577 }
578
579 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
580 let state = self.input.read(cx);
581 let (value, input_cursor) = (state.value().to_string(), state.cursor());
582 self.report_typing(!value.trim().is_empty(), cx);
583 let previous = std::mem::replace(&mut self.previous_value, value.clone());
584 if previous != value {
585 let (start, old_end, new_end) = changed_span(&previous, &value);
586 self.shift_anchors(start, old_end, new_end);
587 }
588 if value == self.draft.text() {
589 self.refresh_style(cx);
590 return;
591 }
592 let kind = step_kind(&previous, &value, input_cursor);
593 let typing = self.pending_style.take();
594 let cursor = self.draft.apply_edit(&value, input_cursor, typing.as_ref());
595 let edits = self.draft.take_edits();
596 self.apply_to_input(edits, cursor..cursor, window, cx);
597 self.record(kind, cx);
598 if let Some(pasted) = self.pasted_markdown.take()
599 && self.convert_paste(&pasted, cursor, window, cx)
600 {
601 return;
602 }
603 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
604 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
605 return;
606 }
607 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
608 return;
609 }
610 self.convert_emoji(typed, cursor, window, cx);
611 }
612
613 fn convert_link(&mut self, cursor: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
614 let before = self.draft.clone();
615 if !self.draft.autolink_typed(cursor) {
616 return false;
617 }
618 self.finish_conversion(before, cursor, window, cx);
619 true
620 }
621
622 fn convert_markdown(
623 &mut self,
624 cursor: usize,
625 window: &mut Window,
626 cx: &mut Context<Self>,
627 ) -> bool {
628 let before = self.draft.clone();
629 let Some((cursor, style)) = self.draft.convert_typed(cursor) else {
630 self.draft.take_edits();
631 return false;
632 };
633 self.finish_conversion(before, cursor, window, cx);
634 self.pending_style = (!style.is_empty()).then_some(style);
635 true
636 }
637
638 fn convert_emoji(
639 &mut self,
640 typed: Option<char>,
641 cursor: usize,
642 window: &mut Window,
643 cx: &mut Context<Self>,
644 ) {
645 if self.draft.in_code(cursor) {
646 return;
647 }
648 let value = self.draft.text();
649 let found = match typed {
650 Some(':') => emoji::closing_code(value, cursor)
651 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
652 Some(' ') => emoji::smiley_before_space(value, cursor),
653 _ => None,
654 };
655 let Some((range, glyph)) = found else {
656 return;
657 };
658 let before = self.draft.clone();
659 self.draft.replace(range.clone(), glyph);
660 self.finish_conversion(before, cursor + glyph.len() - range.len(), window, cx);
661 self.remember_emoji(glyph, cx);
662 }
663
664 fn finish_conversion(
665 &mut self,
666 before: Draft,
667 cursor: usize,
668 window: &mut Window,
669 cx: &mut Context<Self>,
670 ) {
671 let edits = self.draft.take_edits();
672 let restore = reverse_edits(&edits, before.text());
673 self.apply_to_input(edits, cursor..cursor, window, cx);
674 self.record(StepKind::Other, cx);
675 self.conversion = Some(Conversion {
676 value: self.draft.text().to_owned(),
677 cursor,
678 before,
679 restore,
680 });
681 }
682
683 fn convert_paste(
684 &mut self,
685 pasted: &str,
686 cursor: usize,
687 window: &mut Window,
688 cx: &mut Context<Self>,
689 ) -> bool {
690 let pasted = pasted.replace("\r\n", "\n");
691 let Some(start) = cursor
692 .checked_sub(pasted.len())
693 .filter(|start| self.draft.text().get(*start..cursor) == Some(pasted.as_str()))
694 else {
695 return false;
696 };
697 let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);
698 let cursor = self.draft.insert_lines(start..cursor, &lines);
699 let changed_text = self.draft.text().get(start..cursor) != Some(pasted.as_str());
700 self.commit(Some(cursor), window, cx);
701 if !changed_text {
702 return true;
703 }
704 self.paste_hint = Some(cx.spawn(async move |this, cx| {
705 cx.background_executor().timer(PASTE_HINT_DURATION).await;
706 this.update(cx, |this, cx| {
707 this.paste_hint = None;
708 cx.notify();
709 })
710 .ok();
711 }));
712 true
713 }
714
715 /// Puts the draft's pending edits into the input, then places the selection.
716 fn commit(&mut self, cursor: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
717 let edits = self.draft.take_edits();
718 let selection = self.input.read(cx).selected_range();
719 let selection = match cursor {
720 Some(cursor) => cursor..cursor,
721 None if edits.is_empty() => selection,
722 None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),
723 };
724 self.apply_to_input(edits, selection, window, cx);
725 self.record(StepKind::Other, cx);
726 self.schedule_draft_save(cx);
727 }
728
729 fn apply_to_input(
730 &mut self,
731 edits: Vec<Edit>,
732 selection: Range<usize>,
733 window: &mut Window,
734 cx: &mut Context<Self>,
735 ) {
736 self.input.update(cx, |state, cx| {
737 let edited = !edits.is_empty();
738 if edited {
739 state.apply_edits(&edits, window, cx);
740 }
741 if edited || state.selected_range() != selection {
742 state.set_selected_range(selection.clone(), cx);
743 }
744 });
745 for anchor in self.pending_anchors.values_mut() {
746 *anchor = map_offset(&edits, *anchor);
747 }
748 let value = self.input.read(cx).value().to_string();
749 if value != self.draft.text() {
750 self.draft.apply_edit(&value, selection.end, None);
751 self.draft.take_edits();
752 }
753 self.previous_value = value;
754 self.refresh_style(cx);
755 }
756
757 fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
758 for anchor in self.pending_anchors.values_mut() {
759 *anchor = if *anchor <= start {
760 *anchor
761 } else if *anchor >= old_end {
762 *anchor - old_end + new_end
763 } else {
764 new_end
765 };
766 }
767 }
768
769 /// Adds the current state as an undo step. Typing and deleting runs merge into one step;
770 /// a typed space ends a typing step.
771 fn record(&mut self, kind: StepKind, cx: &App) {
772 let state = self.input.read(cx);
773 let step = HistoryStep {
774 draft: self.draft.clone(),
775 tokens: state
776 .tokens()
777 .iter()
778 .map(|span| (span.range(), span.token().clone()))
779 .collect(),
780 selection: state.selected_range(),
781 kind,
782 };
783 let at_end = self.history_index + 1 == self.history.len();
784 let merges = at_end
785 && self
786 .history
787 .last()
788 .is_some_and(|last| continues(last, kind));
789 if merges {
790 if let Some(last) = self.history.last_mut() {
791 *last = step;
792 }
793 return;
794 }
795 self.history.truncate(self.history_index + 1);
796 self.history.push(step);
797 if self.history.len() > HISTORY_LIMIT {
798 self.history.remove(0);
799 }
800 self.history_index = self.history.len() - 1;
801 }
802
803 /// Ctrl+Z / Ctrl+Y move through the composer's own history; the input's is never used.
804 fn step_history(&mut self, back: bool, window: &mut Window, cx: &mut Context<Self>) {
805 let target = if back {
806 self.history_index.checked_sub(1)
807 } else {
808 Some(self.history_index + 1).filter(|index| *index < self.history.len())
809 };
810 let Some(target) = target else {
811 return;
812 };
813 let source_selection = self.history[self.history_index].selection.clone();
814 self.history_index = target;
815 let step = &self.history[target];
816 let (draft, tokens) = (step.draft.clone(), step.tokens.clone());
817 let current = self.input.read(cx).value().to_string();
818 let (start, old_end, new_end) = changed_span(&current, draft.text());
819 let selection = match (start == old_end && start == new_end, back) {
820 (false, _) => new_end..new_end,
821 (true, true) => source_selection,
822 (true, false) => step.selection.clone(),
823 };
824 if start != old_end || start != new_end {
825 self.shift_anchors(start, old_end, new_end);
826 }
827 self.draft = draft.clone();
828 self.previous_value = draft.text().to_owned();
829 self.input.update(cx, |state, cx| {
830 if start != old_end || start != new_end {
831 state.apply_edits(
832 &[(start..old_end, draft.text()[start..new_end].to_owned())],
833 window,
834 cx,
835 );
836 }
837 for (range, token) in tokens {
838 let present = state.tokens().iter().any(|span| span.range() == range);
839 if !present && range.start >= start && range.end <= new_end {
840 state
841 .replace_range_with_token(range, token, window, cx)
842 .ok();
843 }
844 }
845 state.set_selected_range(selection, cx);
846 });
847 self.undone_value = Some(self.input.read(cx).value().to_string());
848 self.pending_style = None;
849 self.conversion = None;
850 self.paste_hint = None;
851 self.refresh_style(cx);
852 self.update_emoji(cx);
853 self.update_mention(cx);
854 self.schedule_draft_save(cx);
855 cx.notify();
856 }
857
858 fn refresh_style(&mut self, cx: &mut Context<Self>) {
859 let style = draft_style(&self.draft, cx.theme().mono_font_family.clone());
860 let (text, ranges) = &self.decorations;
861 text.set(style.text, cx);
862 ranges.set(style.ranges, cx);
863 self.input.update(cx, |state, cx| {
864 state.set_line_indents(style.indents, cx);
865 state.set_hanging_indents(style.markers, cx);
866 });
867 }
868
869 fn load_draft(
870 &mut self,
871 draft: Draft,
872 content: InputContent,
873 window: &mut Window,
874 cx: &mut Context<Self>,
875 ) {
876 let end = draft.text().len();
877 self.input.update(cx, |state, cx| {
878 state.set_value(content, window, cx);
879 state.set_selected_range(end..end, cx);
880 });
881 self.previous_value = draft.text().to_owned();
882 self.draft = draft;
883 self.pending_style = None;
884 self.conversion = None;
885 self.pasted_markdown = None;
886 self.paste_hint = None;
887 self.link_editor = None;
888 self.toolbar_dismissed = None;
889 self.pending_anchors.clear();
890 self.history.clear();
891 self.history_index = 0;
892 self.record(StepKind::Other, cx);
893 self.refresh_style(cx);
894 }
895
896 /// Returns the cursor, kept at the same spot relative to the text after `range`.
897 fn replace_text(
898 &mut self,
899 range: Range<usize>,
900 text: &str,
901 cursor: usize,
902 window: &mut Window,
903 cx: &mut Context<Self>,
904 ) -> usize {
905 let cursor = cursor + text.len() - range.len();
906 self.input.update(cx, |state, cx| {
907 state.set_selected_range(range, cx);
908 state.replace(text.to_owned(), window, cx);
909 state.set_selected_range(cursor..cursor, cx);
910 });
911 cursor
912 }
913
914 fn undo_conversion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
915 let state = self.input.read(cx);
916 let unchanged = self.conversion.as_ref().is_some_and(|conversion| {
917 conversion.value == state.value().as_ref() && conversion.cursor == state.cursor()
918 });
919 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
920 return false;
921 };
922 let cursor = map_offset(&conversion.restore, conversion.cursor);
923 self.draft = conversion.before;
924 self.pending_style = None;
925 self.apply_to_input(conversion.restore, cursor..cursor, window, cx);
926 self.record(StepKind::Other, cx);
927 self.undone_value = Some(self.input.read(cx).value().to_string());
928 self.update_emoji(cx);
929 true
930 }
931
932 fn selection(&self, cx: &App) -> Range<usize> {
933 self.input.read(cx).selected_range()
934 }
935
936 fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) {
937 let selection = self.selection(cx);
938 if selection.is_empty() {
939 let cursor = selection.start;
940 let mut pending = self
941 .pending_style
942 .take()
943 .filter(|pending| pending.at == cursor)
944 .unwrap_or(TypingStyle {
945 at: cursor,
946 ..TypingStyle::default()
947 });
948 pending.toggle(kind, &self.draft.style_at(cursor));
949 self.pending_style = (!pending.is_empty()).then_some(pending);
950 } else {
951 self.draft.toggle(selection, kind);
952 self.draft.take_edits();
953 self.record(StepKind::Other, cx);
954 self.refresh_style(cx);
955 self.schedule_draft_save(cx);
956 }
957 cx.notify();
958 }
959
960 fn set_size(&mut self, size: Option<SizeStep>, cx: &mut Context<Self>) {
961 let selection = self.selection(cx);
962 if selection.is_empty() {
963 let cursor = selection.start;
964 let mut pending = self
965 .pending_style
966 .take()
967 .filter(|pending| pending.at == cursor)
968 .unwrap_or(TypingStyle {
969 at: cursor,
970 ..TypingStyle::default()
971 });
972 pending.set_size(size, &self.draft.style_at(cursor));
973 self.pending_style = (!pending.is_empty()).then_some(pending);
974 } else {
975 self.draft.set_size(selection, size);
976 self.draft.take_edits();
977 self.record(StepKind::Other, cx);
978 self.refresh_style(cx);
979 self.schedule_draft_save(cx);
980 }
981 cx.notify();
982 }
983
984 fn normal_size_state(&self, range: Range<usize>) -> FormatState {
985 let sized = [SizeStep::Small, SizeStep::Large]
986 .into_iter()
987 .any(|step| self.draft.state(range.clone(), &MarkKind::Size(step)) != FormatState::Off);
988 if sized {
989 FormatState::Off
990 } else {
991 FormatState::On
992 }
993 }
994
995 fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {
996 let selection = self.selection(cx);
997 self.draft.toggle_lines(selection, kind);
998 self.commit(None, window, cx);
999 cx.notify();
1000 }
1001
1002 fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {
1003 match button {
1004 FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),
1005 FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
1006 FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),
1007 FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),
1008 FormatButton::Superscript => self.toggle_mark(MarkKind::Superscript, cx),
1009 FormatButton::Subscript => self.toggle_mark(MarkKind::Subscript, cx),
1010 FormatButton::SizeSmall => self.set_size(Some(SizeStep::Small), cx),
1011 FormatButton::SizeNormal => self.set_size(None, cx),
1012 FormatButton::SizeLarge => self.set_size(Some(SizeStep::Large), cx),
1013 FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),
1014 FormatButton::Link => self.open_link_editor(window, cx),
1015 FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),
1016 FormatButton::Numbered => self.toggle_lines(LineKind::Numbered(0), window, cx),
1017 FormatButton::Quote => self.toggle_lines(LineKind::Quote, window, cx),
1018 }
1019 }
1020
1021 fn format_state(&self, button: FormatButton, selection: &Range<usize>) -> FormatState {
1022 let range = selection.clone();
1023 match button {
1024 FormatButton::Bold => self.draft.state(range, &MarkKind::Bold),
1025 FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),
1026 FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),
1027 FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),
1028 FormatButton::Superscript => self.draft.state(range, &MarkKind::Superscript),
1029 FormatButton::Subscript => self.draft.state(range, &MarkKind::Subscript),
1030 FormatButton::SizeSmall => self.draft.state(range, &MarkKind::Size(SizeStep::Small)),
1031 FormatButton::SizeLarge => self.draft.state(range, &MarkKind::Size(SizeStep::Large)),
1032 FormatButton::SizeNormal => self.normal_size_state(range),
1033 FormatButton::Code => self.draft.state(range, &MarkKind::Code),
1034 FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),
1035 FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),
1036 FormatButton::Numbered => self.draft.line_state(range, &LineKind::Numbered(0)),
1037 FormatButton::Quote => self.draft.line_state(range, &LineKind::Quote),
1038 }
1039 }
1040
1041 fn edit_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1042 if self.link_editor.is_some() {
1043 return;
1044 }
1045 if self.draft.is_blank() && self.selection(cx).is_empty() {
1046 window.dispatch_action(Box::new(super::shell::OpenSwitcher), cx);
1047 return;
1048 }
1049 self.open_link_editor(window, cx);
1050 }
1051
1052 fn open_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1053 let range = self.selection(cx);
1054 let prefill = self
1055 .draft
1056 .link_in(range.clone())
1057 .or_else(|| {
1058 cx.read_from_clipboard()
1059 .and_then(|item| item.text())
1060 .map(|text| text.trim().to_owned())
1061 .filter(|text| looks_like_url(text))
1062 })
1063 .unwrap_or_default();
1064 let field = cx.new(|cx| {
1065 InputState::new(window, cx)
1066 .placeholder("Paste or type a link")
1067 .default_value(prefill)
1068 });
1069 field.update(cx, |state, cx| {
1070 state.focus(window, cx);
1071 state.select_all(window, cx);
1072 });
1073 let edits = cx.subscribe(&field, |this, _, event: &InputEvent, cx| {
1074 if matches!(event, InputEvent::Change)
1075 && let Some(editor) = this.link_editor.as_mut()
1076 {
1077 editor.refused = false;
1078 cx.notify();
1079 }
1080 });
1081 self.link_editor = Some(LinkEditor {
1082 range,
1083 field,
1084 refused: false,
1085 _edits: edits,
1086 });
1087 cx.notify();
1088 }
1089
1090 fn apply_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1091 let Some(editor) = self.link_editor.take() else {
1092 return;
1093 };
1094 let typed = editor.field.read(cx).value().trim().to_owned();
1095 let url = if typed.is_empty() {
1096 String::new()
1097 } else if let Some(url) = link_url(&typed) {
1098 url
1099 } else {
1100 self.link_editor = Some(LinkEditor {
1101 refused: true,
1102 ..editor
1103 });
1104 cx.notify();
1105 return;
1106 };
1107 self.focus(window, cx);
1108 if editor.range.is_empty() {
1109 if !url.is_empty() {
1110 let end = self.draft.insert_link(editor.range.start, &url, &url);
1111 self.commit(Some(end), window, cx);
1112 }
1113 } else {
1114 self.draft.set_link(editor.range.clone(), &url);
1115 self.draft.take_edits();
1116 self.refresh_style(cx);
1117 self.input.update(cx, |state, cx| {
1118 state.set_selected_range(editor.range.clone(), cx)
1119 });
1120 self.record(StepKind::Other, cx);
1121 self.toolbar_dismissed = Some(editor.range);
1122 }
1123 cx.notify();
1124 }
1125
1126 fn close_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1127 let Some(editor) = self.link_editor.take() else {
1128 return;
1129 };
1130 self.focus(window, cx);
1131 self.input
1132 .update(cx, |state, cx| state.set_selected_range(editor.range, cx));
1133 cx.notify();
1134 }
1135
1136 fn break_line(&mut self, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1137 let selection = self.selection(cx);
1138 if !selection.is_empty() {
1139 return false;
1140 }
1141 match self.draft.break_line(selection.start, shift) {
1142 Some(cursor) => {
1143 self.draft.link_word_ending_at(selection.start);
1144 self.commit(Some(cursor), window, cx);
1145 true
1146 }
1147 None => false,
1148 }
1149 }
1150
1151 fn backspace_at_start(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1152 let selection = self.selection(cx);
1153 if !selection.is_empty() {
1154 return false;
1155 }
1156 match self.draft.backspace_at_start(selection.start) {
1157 Some(cursor) => {
1158 self.commit(Some(cursor), window, cx);
1159 true
1160 }
1161 None => false,
1162 }
1163 }
1164
1165 fn delete_forward(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1166 let selection = self.selection(cx);
1167 if !selection.is_empty() {
1168 return false;
1169 }
1170 match self.draft.delete_forward(selection.start) {
1171 Some(cursor) => {
1172 self.commit(Some(cursor), window, cx);
1173 true
1174 }
1175 None => false,
1176 }
1177 }
1178
1179 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
1180 let selection = self.selection(cx);
1181 if !self.draft.indent(selection, outdent) {
1182 return false;
1183 }
1184 self.commit(None, window, cx);
1185 true
1186 }
1187
1188 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
1189 let selection = self.selection(cx);
1190 if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
1191 return false;
1192 }
1193 let selected = &self.draft.text()[selection.clone()];
1194 let text = selected.replace(OBJECT_MARK, "");
1195 let lines = if selected.contains(OBJECT_MARK) {
1196 self.draft.slice_without_objects(selection)
1197 } else {
1198 self.draft.slice(selection)
1199 };
1200 if text.is_empty() {
1201 return true;
1202 }
1203 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1204 text.clone(),
1205 lines.clone(),
1206 ));
1207 self.copied = Some((text, lines));
1208 true
1209 }
1210
1211 fn copied_lines(&self, item: &ClipboardItem, text: &str) -> Option<Vec<DraftLine>> {
1212 item.entries()
1213 .iter()
1214 .find_map(|entry| match entry {
1215 ClipboardEntry::String(string) if string.text() == text => {
1216 string.metadata_json::<Vec<DraftLine>>()
1217 }
1218 _ => None,
1219 })
1220 .or_else(|| {
1221 let normalized = text.replace("\r\n", "\n");
1222 self.copied
1223 .as_ref()
1224 .filter(|(copied, _)| *copied == normalized)
1225 .map(|(_, lines)| lines.clone())
1226 })
1227 }
1228
1229 fn toolbar_requested(&self, cx: &App) -> bool {
1230 let selection = self.selection(cx);
1231 !selection.is_empty()
1232 && !self.mouse_selecting
1233 && self.toolbar_dismissed.as_ref() != Some(&selection)
1234 && !self.popup_is_open()
1235 }
1236
1237 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
1238 let store = &self.app.read(cx).store;
1239 self.recent_emoji.reload(store);
1240 self.recent_emoji.push(glyph);
1241 self.recent_emoji.save(store);
1242 }
1243
1244 fn update_emoji(&mut self, cx: &mut Context<Self>) {
1245 let state = self.input.read(cx);
1246 let found = emoji::active_query(&state.value(), state.cursor())
1247 .filter(|_| !self.draft.in_code(state.cursor()));
1248 if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
1249 self.emoji_dismissed_at = None;
1250 }
1251 let found = found.filter(|_| self.emoji_dismissed_at.is_none());
1252 let Some((range, query)) = found else {
1253 self.emoji_popup = None;
1254 return;
1255 };
1256 let unchanged = self
1257 .emoji_popup
1258 .as_ref()
1259 .is_some_and(|popup| popup.query == query && popup.range == range);
1260 if unchanged {
1261 return;
1262 }
1263 let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1264 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1265 }
1266
1267 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1268 let Some(popup) = self.emoji_popup.take() else {
1269 return;
1270 };
1271 let Some(glyph) = popup.selected().map(|found| found.glyph) else {
1272 return;
1273 };
1274 let cursor = popup.range.end;
1275 self.replace_text(popup.range, glyph, cursor, window, cx);
1276 self.remember_emoji(glyph, cx);
1277 cx.notify();
1278 }
1279
1280 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
1281 let Some(conversation_id) = self.conversation_id.clone() else {
1282 return;
1283 };
1284 let (demo, engine) = {
1285 let state = self.app.read(cx);
1286 (state.mode.demo, state.engine.clone())
1287 };
1288 if demo {
1289 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
1290 self.apply_candidates(&query, candidates, cx);
1291 return;
1292 }
1293 let Some(engine) = engine else {
1294 return;
1295 };
1296 self.lookup = Some(cx.spawn(async move |this, cx| {
1297 cx.background_executor().timer(MENTION_DEBOUNCE).await;
1298 let task_query = query.clone();
1299 let receiver = runtime::spawn(async move {
1300 engine
1301 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
1302 .await
1303 });
1304 if let Ok(Ok(candidates)) = receiver.await {
1305 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
1306 .ok();
1307 }
1308 }));
1309 }
1310
1311 fn apply_candidates(
1312 &mut self,
1313 query: &str,
1314 candidates: Vec<MentionCandidate>,
1315 cx: &mut Context<Self>,
1316 ) {
1317 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
1318 return;
1319 };
1320 popup.candidates = candidates;
1321 popup.highlighted = 0;
1322 cx.notify();
1323 }
1324
1325 fn update_link_preview(&mut self, cx: &mut Context<Self>) {
1326 if self.editing.is_some() {
1327 self.link.reset();
1328 return;
1329 }
1330 let draft = self.current_draft(cx);
1331 if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {
1332 self.fetch_link_preview(url, cx);
1333 }
1334 cx.notify();
1335 }
1336
1337 fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) {
1338 let (demo, engine) = {
1339 let state = self.app.read(cx);
1340 (state.mode.demo, state.engine.clone())
1341 };
1342 if demo {
1343 let preview = crate::demo::link_preview(&url);
1344 self.finish_link_preview(&url, preview, cx);
1345 return;
1346 }
1347 let Some(engine) = engine else {
1348 return;
1349 };
1350 self.link.lookup = Some(cx.spawn(async move |this, cx| {
1351 cx.background_executor()
1352 .timer(LINK_PREVIEW_DEBOUNCE)
1353 .await;
1354 let task_url = url.clone();
1355 let receiver =
1356 runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1357 if let Ok(Ok(preview)) = receiver.await {
1358 this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))
1359 .ok();
1360 }
1361 }));
1362 }
1363
1364 fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {
1365 let image = preview.as_ref().and_then(LinkPreview::image);
1366 if !self.link.apply(url, preview) {
1367 return;
1368 }
1369 if let Some(image) = image {
1370 self.app
1371 .update(cx, |state, cx| state.request_images(vec![image], cx));
1372 }
1373 cx.notify();
1374 }
1375
1376 fn link_image_pending(&self, cx: &App) -> bool {
1377 self.link
1378 .shown()
1379 .and_then(LinkPreview::image)
1380 .is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())
1381 }
1382
1383 fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {
1384 let preview = self.link.shown()?;
1385 let composer = cx.weak_entity();
1386 let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| {
1387 composer
1388 .update(cx, |this, cx| {
1389 this.link.dismiss();
1390 cx.notify();
1391 })
1392 .ok();
1393 });
1394 Some(
1395 div().w_full().mb(px(6.)).child(link_preview_card(
1396 preview,
1397 "composer-link-preview".to_owned(),
1398 &self.app.read(cx).directory,
1399 true,
1400 Some(close),
1401 )),
1402 )
1403 }
1404
1405 fn popup_is_open(&self) -> bool {
1406 self.emoji_popup.is_some()
1407 || self
1408 .popup
1409 .as_ref()
1410 .is_some_and(|popup| !popup.candidates.is_empty())
1411 }
1412
1413 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1414 if let Some(popup) = self.emoji_popup.as_mut() {
1415 popup.move_highlight(delta);
1416 cx.notify();
1417 } else if let Some(popup) = self.popup.as_mut() {
1418 let last = popup.candidates.len().saturating_sub(1) as isize;
1419 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
1420 cx.notify();
1421 }
1422 }
1423
1424 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1425 if self.emoji_popup.is_some() {
1426 self.accept_emoji(window, cx);
1427 } else {
1428 self.accept_mention(window, cx);
1429 }
1430 }
1431
1432 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1433 let Some(popup) = self.popup.take() else {
1434 return;
1435 };
1436 self.lookup = None;
1437 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
1438 return;
1439 };
1440 self.mention_counter += 1;
1441 let token_id = format!(
1442 "mention-{}-{}",
1443 self.mention_counter,
1444 candidate_key(candidate)
1445 );
1446 let label = format!("@{}", candidate.display_name());
1447 self.mention_inputs
1448 .insert(token_id.clone(), candidate.to_mention());
1449 self.input.update(cx, |state, cx| {
1450 let token = InlineToken::new(token_id, label);
1451 if state
1452 .replace_range_with_token(popup.range, token, window, cx)
1453 .is_ok()
1454 {
1455 state.insert(" ", window, cx);
1456 }
1457 });
1458 self.close_popup();
1459 cx.notify();
1460 }
1461
1462 pub fn inline(mut self) -> Self {
1463 self.inline = true;
1464 self
1465 }
1466
1467 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1468 let text = text.to_owned();
1469 self.input
1470 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
1471 }
1472
1473 pub fn set_conversation(
1474 &mut self,
1475 conversation_id: &str,
1476 name: &str,
1477 window: &mut Window,
1478 cx: &mut Context<Self>,
1479 ) {
1480 self.set_placeholder(&format!("Message {name}"), window, cx);
1481 if self.conversation_id.as_deref() != Some(conversation_id) {
1482 self.save_draft_now(cx);
1483 self.draft_save = None;
1484 self.saved_images = None;
1485 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1486 self.conversation_id = Some(conversation_id.to_owned());
1487 self.cancel_uploads();
1488 let dropped = if carry {
1489 self.tray.keep_images_only()
1490 } else {
1491 self.tray.clear()
1492 };
1493 self.discard_uploaded(dropped, cx);
1494 self.remove_orphan_image_tokens(window, cx);
1495 self.reply = None;
1496 self.link.reset();
1497 if self.editing.take().is_some() {
1498 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1499 }
1500 self.mention_inputs.clear();
1501 self.close_popup();
1502 self.schedule = None;
1503 if !carry {
1504 self.load_stored_draft(conversation_id, window, cx);
1505 }
1506 cx.notify();
1507 }
1508 }
1509
1510 /// The draft's images follow the user into this chat; any other switch clears the tray.
1511 pub fn carry_images_into(&mut self, conversation_id: String) {
1512 self.carry_images_into = Some(conversation_id);
1513 }
1514
1515 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
1516 discard_uploaded(self.app.read(cx).engine.clone(), files);
1517 }
1518
1519 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
1520 self.reply = reply;
1521 if self.reply.is_some() {
1522 self.editing = None;
1523 }
1524 self.schedule_draft_save(cx);
1525 cx.notify();
1526 }
1527
1528 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1529 self.restore(&draft, window, cx);
1530 self.focus(window, cx);
1531 }
1532
1533 pub fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1534 self.editing = None;
1535 self.set_text("", window, cx);
1536 }
1537
1538 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1539 self.can_send(cx).then(|| self.compose(cx))
1540 }
1541
1542 fn compose(&self, cx: &App) -> Outgoing {
1543 let state = self.input.read(cx);
1544 let mut draft = self.current_draft(cx);
1545 let image_spans: Vec<(Range<usize>, u64)> = state
1546 .tokens()
1547 .iter()
1548 .filter_map(|span| Some((span.range(), image_id(span.token())?)))
1549 .collect();
1550 let image_ids: Vec<u64> = image_spans
1551 .iter()
1552 .filter(|(_, id)| self.tray.image(*id).is_some())
1553 .map(|(_, id)| *id)
1554 .collect();
1555 for (range, _) in image_spans
1556 .iter()
1557 .rev()
1558 .filter(|(_, id)| self.tray.image(*id).is_none())
1559 {
1560 draft.replace(range.clone(), "");
1561 }
1562 draft.take_edits();
1563 let mut draft = draft.trimmed();
1564 let attachments_apply = self.editing.is_none();
1565 if self.undone_value.as_deref() != Some(state.value().as_ref())
1566 && let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
1567 && !draft.in_code(range.end - 1)
1568 {
1569 draft.replace(range, glyph);
1570 draft.take_edits();
1571 }
1572 let mentions = state
1573 .tokens()
1574 .iter()
1575 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1576 .cloned()
1577 .collect();
1578 Outgoing {
1579 draft,
1580 subject: None,
1581 mentions,
1582 reply: self.reply.clone(),
1583 edit: self.editing.clone(),
1584 link_preview: self.link.shown().filter(|_| attachments_apply).cloned(),
1585 images: if attachments_apply {
1586 self.tray.images_in(&image_ids)
1587 } else {
1588 Vec::new()
1589 },
1590 files: if attachments_apply {
1591 self.tray.outgoing_files()
1592 } else {
1593 Vec::new()
1594 },
1595 }
1596 }
1597
1598 /// The draft, or the plain input text while a change is still on its way to the draft.
1599 fn current_draft(&self, cx: &App) -> Draft {
1600 let value = self.input.read(cx).value();
1601 if self.draft.text() == value.as_ref() {
1602 self.draft.clone()
1603 } else {
1604 Draft::plain(&value)
1605 }
1606 }
1607
1608 fn can_send(&self, cx: &App) -> bool {
1609 let has_text = !self.current_draft(cx).is_blank();
1610 if self.editing.is_some() {
1611 return has_text;
1612 }
1613 (has_text || self.has_attachments(cx)) && !self.tray.blocks_send()
1614 }
1615
1616 fn has_attachments(&self, cx: &App) -> bool {
1617 self.tray.has_chips()
1618 || self
1619 .input
1620 .read(cx)
1621 .tokens()
1622 .iter()
1623 .any(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_some()))
1624 }
1625
1626 fn image_token_range(&self, id: u64, cx: &App) -> Option<Range<usize>> {
1627 self.input
1628 .read(cx)
1629 .tokens()
1630 .iter()
1631 .find(|span| image_id(span.token()) == Some(id))
1632 .map(|span| span.range())
1633 }
1634
1635 fn remove_orphan_image_tokens(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1636 let edits: Vec<Edit> = self
1637 .input
1638 .read(cx)
1639 .tokens()
1640 .iter()
1641 .filter(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_none()))
1642 .map(|span| (span.range(), String::new()))
1643 .collect();
1644 if !edits.is_empty() {
1645 self.input
1646 .update(cx, |state, cx| state.apply_edits(&edits, window, cx));
1647 }
1648 }
1649
1650 fn remove_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1651 let Some(range) = self.image_token_range(id, cx) else {
1652 return;
1653 };
1654 self.input.update(cx, |state, cx| {
1655 state.set_selected_range(range, cx);
1656 state.replace("", window, cx);
1657 });
1658 }
1659
1660 fn insert_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1661 let state = self.input.read(cx);
1662 let value = state.value().to_string();
1663 let selection = state.selected_range();
1664 let mut offset = self
1665 .pending_anchors
1666 .remove(&id)
1667 .unwrap_or(selection.end)
1668 .min(value.len());
1669 while !value.is_char_boundary(offset) {
1670 offset -= 1;
1671 }
1672 if value == self.draft.text() && self.draft.in_code(offset) {
1673 offset = value.len();
1674 }
1675 if let Some(span) = state
1676 .tokens()
1677 .iter()
1678 .find(|span| span.range().start < offset && offset < span.range().end)
1679 {
1680 offset = span.range().end;
1681 }
1682 let length = OBJECT_MARK.len_utf8();
1683 let after = |position: usize| {
1684 if position >= offset {
1685 position + length
1686 } else {
1687 position
1688 }
1689 };
1690 let inserted = self.input.update(cx, |state, cx| {
1691 let inserted = state
1692 .replace_range_with_token(offset..offset, image_token(id), window, cx)
1693 .is_ok();
1694 if inserted {
1695 state.set_selected_range(after(selection.start)..after(selection.end), cx);
1696 }
1697 inserted
1698 });
1699 if !inserted {
1700 return;
1701 }
1702 for (other, anchor) in self.pending_anchors.iter_mut() {
1703 if *anchor > offset || (*anchor == offset && *other > id) {
1704 *anchor += length;
1705 }
1706 }
1707 self.previous_value = self.input.read(cx).value().to_string();
1708 }
1709
1710 pub fn is_editing(&self) -> bool {
1711 self.editing.is_some()
1712 }
1713
1714 fn files_allowed(&self) -> bool {
1715 self.conversation_id
1716 .as_deref()
1717 .is_some_and(|conversation_id| !conversation_id.is_empty())
1718 }
1719
1720 fn cancel_uploads(&mut self) {
1721 for (_, handle) in self.uploads.drain() {
1722 handle.cancel();
1723 }
1724 }
1725
1726 pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1727 if self.editing.is_some() {
1728 return;
1729 }
1730 let receiver = cx.prompt_for_paths(PathPromptOptions {
1731 files: true,
1732 directories: false,
1733 multiple: true,
1734 prompt: None,
1735 });
1736 cx.spawn_in(window, async move |this, cx| {
1737 if let Ok(Ok(Some(paths))) = receiver.await {
1738 this.update_in(cx, |this, window, cx| this.add_paths(paths, window, cx))
1739 .ok();
1740 }
1741 })
1742 .detach();
1743 }
1744
1745 pub fn add_paths(&mut self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) {
1746 if self.editing.is_some() || paths.is_empty() {
1747 return;
1748 }
1749 let ids = self.add_pending(&names_of(&paths), cx);
1750 for (id, path) in ids.into_iter().zip(paths) {
1751 cx.spawn_in(window, async move |this, cx| {
1752 let loaded = cx
1753 .background_executor()
1754 .spawn(async move { read_attachment(&path) })
1755 .await;
1756 this.update_in(cx, |this, window, cx| {
1757 this.finish_reading(id, loaded, window, cx)
1758 })
1759 .ok();
1760 })
1761 .detach();
1762 }
1763 cx.notify();
1764 }
1765
1766 /// Images that no longer sit in the text give way to new attachments.
1767 fn make_room(&mut self, needed: usize, cx: &App) {
1768 if self.tray.items().len() + needed > MAX_ATTACHMENTS {
1769 let referenced: Vec<u64> = self
1770 .input
1771 .read(cx)
1772 .tokens()
1773 .iter()
1774 .filter_map(|span| image_id(span.token()))
1775 .collect();
1776 self.tray.discard_images_except(&referenced);
1777 }
1778 }
1779
1780 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1781 self.make_room(names.len(), cx);
1782 let ids = self.tray.add_pending(names);
1783 let anchor = self.selection(cx).end;
1784 self.pending_anchors
1785 .extend(ids.iter().map(|id| (*id, anchor)));
1786 ids
1787 }
1788
1789 fn add_pasted_image(&mut self, pasted: Image, window: &mut Window, cx: &mut Context<Self>) {
1790 let ids = self.add_pending(&[pasted_image_name()], cx);
1791 cx.notify();
1792 let Some(&id) = ids.first() else {
1793 return;
1794 };
1795 cx.spawn_in(window, async move |this, cx| {
1796 let loaded = cx
1797 .background_executor()
1798 .spawn(async move { prepare_pasted_image(pasted) })
1799 .await;
1800 this.update_in(cx, |this, window, cx| {
1801 this.finish_reading(id, loaded, window, cx)
1802 })
1803 .ok();
1804 })
1805 .detach();
1806 }
1807
1808 fn on_fun_pick(
1809 &mut self,
1810 _: &Entity<FunPicker>,
1811 event: &FunPickerEvent,
1812 window: &mut Window,
1813 cx: &mut Context<Self>,
1814 ) {
1815 match event {
1816 FunPickerEvent::Emoji(glyph) => self.insert_emoji(glyph, window, cx),
1817 FunPickerEvent::Image(image) => self.insert_remote_image(image.clone(), window, cx),
1818 }
1819 }
1820
1821 fn insert_emoji(&mut self, glyph: &str, window: &mut Window, cx: &mut Context<Self>) {
1822 let range = self.selection(cx);
1823 let cursor = range.end;
1824 self.replace_text(range, glyph, cursor, window, cx);
1825 self.remember_emoji(glyph, cx);
1826 cx.notify();
1827 }
1828
1829 fn insert_remote_image(
1830 &mut self,
1831 image: RemoteImage,
1832 window: &mut Window,
1833 cx: &mut Context<Self>,
1834 ) {
1835 self.make_room(1, cx);
1836 if let Some(id) = self.tray.add_remote(image) {
1837 self.insert_image_token(id, window, cx);
1838 }
1839 self.focus(window, cx);
1840 cx.notify();
1841 }
1842
1843 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1844 if self.editing.is_none() {
1845 match paste_action(item) {
1846 PasteAction::Text => {}
1847 PasteAction::Files(paths) => {
1848 self.add_paths(paths, window, cx);
1849 return true;
1850 }
1851 PasteAction::Image(pasted) => {
1852 self.add_pasted_image(pasted, window, cx);
1853 return true;
1854 }
1855 }
1856 }
1857 let Some(text) = item.text() else {
1858 return false;
1859 };
1860 if text.contains(OBJECT_MARK) {
1861 let cleaned = text.replace(OBJECT_MARK, "");
1862 self.input
1863 .update(cx, |state, cx| state.replace(cleaned, window, cx));
1864 return true;
1865 }
1866 if self.draft.in_code(self.selection(cx).start) {
1867 return false;
1868 }
1869 if let Some(lines) = self.copied_lines(item, &text) {
1870 let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1871 self.commit(Some(cursor), window, cx);
1872 return true;
1873 }
1874 self.pasted_markdown = has_markdown(&text).then_some(text);
1875 false
1876 }
1877
1878 fn finish_reading(
1879 &mut self,
1880 id: u64,
1881 loaded: Result<LoadedFile, String>,
1882 window: &mut Window,
1883 cx: &mut Context<Self>,
1884 ) {
1885 match loaded {
1886 Ok(loaded) => {
1887 let files_allowed = self.files_allowed();
1888 let job = self.tray.finish_reading(id, loaded, files_allowed);
1889 if self.tray.image(id).is_some() {
1890 self.insert_image_token(id, window, cx);
1891 } else {
1892 self.pending_anchors.remove(&id);
1893 }
1894 if let Some(job) = job {
1895 self.start_upload(job, cx);
1896 }
1897 }
1898 Err(message) => {
1899 self.pending_anchors.remove(&id);
1900 self.tray.fail_reading(id, message);
1901 }
1902 }
1903 cx.notify();
1904 }
1905
1906 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1907 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
1908 self.tray.finish_upload(job.id, UploadResult::Failed);
1909 return;
1910 };
1911 let state = self.app.read(cx);
1912 let (demo, engine) = (state.mode.demo, state.engine.clone());
1913 if demo {
1914 self.simulate_upload(job, cx);
1915 return;
1916 }
1917 let Some(engine) = engine else {
1918 self.tray.finish_upload(job.id, UploadResult::Failed);
1919 return;
1920 };
1921 let id = job.id;
1922 let (event_sender, mut event_receiver) =
1923 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
1924 let finished_sender = event_sender.clone();
1925 let (_, handle) = runtime::spawn_abortable(async move {
1926 let result = async {
1927 let uploaded = match job.kind {
1928 JobKind::Upload => {
1929 let progress_sender = event_sender.clone();
1930 let uploaded = engine
1931 .upload_attachment_file(
1932 &conversation_id,
1933 &job.name,
1934 &job.bytes,
1935 move |percent| {
1936 let _ = progress_sender.send(UploadEvent::Progress(percent));
1937 },
1938 )
1939 .await;
1940 match uploaded {
1941 Ok(uploaded) => {
1942 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
1943 uploaded
1944 }
1945 Err(_) => return UploadResult::Failed,
1946 }
1947 }
1948 JobKind::Share(uploaded) => uploaded,
1949 };
1950 let Some(reference) = uploaded.reference() else {
1951 return UploadResult::Failed;
1952 };
1953 match engine.share_attachment(&conversation_id, &uploaded).await {
1954 Ok(()) => UploadResult::Done(DoneFile {
1955 reference,
1956 uploaded: Some(uploaded),
1957 }),
1958 Err(_) => UploadResult::ShareFailed(uploaded),
1959 }
1960 }
1961 .await;
1962 let _ = finished_sender.send(UploadEvent::Finished(result));
1963 });
1964 self.uploads.insert(id, UploadHandle::Network(handle));
1965 cx.spawn(async move |this, cx| {
1966 while let Some(event) = event_receiver.recv().await {
1967 let updated = this.update(cx, |this, cx| {
1968 let orphan = match event {
1969 UploadEvent::Progress(percent) => {
1970 this.tray.set_progress(id, percent);
1971 None
1972 }
1973 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
1974 UploadEvent::Finished(result) => this.finish_upload(id, result),
1975 };
1976 this.discard_uploaded(orphan.into_iter().collect(), cx);
1977 cx.notify();
1978 });
1979 if updated.is_err() {
1980 break;
1981 }
1982 }
1983 })
1984 .detach();
1985 }
1986
1987 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1988 let id = job.id;
1989 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
1990 let task = cx.spawn(async move |this, cx| {
1991 for step in 1..=DEMO_UPLOAD_STEPS {
1992 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
1993 if fails && step == DEMO_FAILURE_STEP {
1994 this.update(cx, |this, cx| {
1995 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
1996 })
1997 .ok();
1998 return;
1999 }
2000 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
2001 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
2002 .ok();
2003 }
2004 let reference = FileReference {
2005 attachment_id: format!("demo-attachment-{id}"),
2006 content_url: format!("https://demo.invalid/files/{}", job.name),
2007 name: job.name,
2008 };
2009 let done = DoneFile {
2010 reference,
2011 uploaded: None,
2012 };
2013 this.update(cx, |this, cx| {
2014 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
2015 })
2016 .ok();
2017 });
2018 self.uploads.insert(id, UploadHandle::Demo(task));
2019 }
2020
2021 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
2022 self.tray.set_progress(id, percent);
2023 cx.notify();
2024 }
2025
2026 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
2027 self.uploads.remove(&id);
2028 self.tray.finish_upload(id, result)
2029 }
2030
2031 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
2032 self.finish_upload(id, result);
2033 cx.notify();
2034 }
2035
2036 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
2037 if let Some(handle) = self.uploads.remove(&id) {
2038 handle.cancel();
2039 }
2040 let uploaded = self.tray.remove(id);
2041 self.discard_uploaded(uploaded.into_iter().collect(), cx);
2042 self.schedule_draft_save(cx);
2043 cx.notify();
2044 }
2045
2046 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
2047 if let Some(job) = self.tray.retry(id) {
2048 self.start_upload(job, cx);
2049 }
2050 cx.notify();
2051 }
2052
2053 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2054 if self.scheduling.is_some() {
2055 return;
2056 }
2057 let Some(outgoing) = self.outgoing(cx) else {
2058 return;
2059 };
2060 self.typing.reset();
2061 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
2062 self.mention_inputs.clear();
2063 if self.editing.is_none() {
2064 self.tray.clear();
2065 self.clear_stored_draft(cx);
2066 }
2067 self.reply = None;
2068 self.editing = None;
2069 self.link.reset();
2070 self.close_popup();
2071 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2072 cx.notify();
2073 }
2074
2075 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2076 self.mention_inputs.clear();
2077 let image_ids = if outgoing.edit.is_none() {
2078 self.cancel_uploads();
2079 self.tray.restore(&outgoing.images, &outgoing.files)
2080 } else {
2081 Vec::new()
2082 };
2083 let text = outgoing.draft.text();
2084 let mut content = InputContent::new(text.to_owned());
2085 for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) {
2086 let range = offset..offset + OBJECT_MARK.len_utf8();
2087 if let Ok(next) = content.clone().with_token(range, image_token(id)) {
2088 content = next;
2089 }
2090 }
2091 let mut cursor = 0;
2092 for mention in &outgoing.mentions {
2093 let needle = format!("@{}", mention.text);
2094 let Some(offset) = text[cursor..].find(&needle) else {
2095 continue;
2096 };
2097 let range = cursor + offset..cursor + offset + needle.len();
2098 self.mention_counter += 1;
2099 let token_id = format!("mention-{}", self.mention_counter);
2100 let token = InlineToken::new(token_id.clone(), needle);
2101 if let Ok(next) = content.clone().with_token(range.clone(), token) {
2102 content = next;
2103 self.mention_inputs.insert(token_id, mention.clone());
2104 cursor = range.end;
2105 }
2106 }
2107 self.load_draft(outgoing.draft.clone(), content, window, cx);
2108 self.reply = outgoing.reply.clone();
2109 self.editing = outgoing.edit.clone();
2110 self.link.restore(outgoing.link_preview.clone());
2111 self.close_popup();
2112 self.schedule_draft_save(cx);
2113 cx.notify();
2114 }
2115
2116 /// Markdown in `text` arrives formatted.
2117 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2118 let draft = Draft::from_markdown(text);
2119 let content = InputContent::new(draft.text().to_owned());
2120 self.load_draft(draft, content, window, cx);
2121 self.mention_inputs.clear();
2122 self.update_emoji(cx);
2123 self.update_mention(cx);
2124 self.update_link_preview(cx);
2125 cx.notify();
2126 }
2127
2128 pub fn is_empty(&self, cx: &App) -> bool {
2129 self.draft.is_blank() && !self.has_attachments(cx)
2130 }
2131
2132 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
2133 self.input.update(cx, |state, cx| state.focus(window, cx));
2134 }
2135
2136 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2137 let popup = self
2138 .popup
2139 .as_ref()
2140 .filter(|popup| !popup.candidates.is_empty())?;
2141 let directory = &self.app.read(cx).directory;
2142 let rows = popup
2143 .candidates
2144 .iter()
2145 .enumerate()
2146 .map(|(index, candidate)| {
2147 let name = candidate.display_name().to_owned();
2148 let avatar = match candidate {
2149 MentionCandidate::Person(person) => {
2150 person_avatar(directory, Some(&person.user_id), &name, 28.)
2151 }
2152 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
2153 };
2154 let subtitle = candidate_subtitle(candidate);
2155 h_flex()
2156 .id(ElementId::Name(format!("mention-row-{index}").into()))
2157 .mx(px(6.))
2158 .px(px(6.))
2159 .h(px(POPUP_ROW_HEIGHT))
2160 .gap(px(10.))
2161 .items_center()
2162 .rounded(px(6.))
2163 .cursor_pointer()
2164 .when(index == popup.highlighted, |row| {
2165 row.bg(theme::surface_raised())
2166 })
2167 .hover(|row| row.bg(theme::row_hover()))
2168 .child(avatar)
2169 .child(
2170 v_flex()
2171 .flex_1()
2172 .min_w_0()
2173 .child(
2174 div()
2175 .truncate()
2176 .text_size(px(13.5))
2177 .text_color(theme::text())
2178 .child(name),
2179 )
2180 .when(!subtitle.is_empty(), |column| {
2181 column.child(
2182 div()
2183 .truncate()
2184 .text_size(px(12.))
2185 .text_color(theme::text_muted())
2186 .child(subtitle),
2187 )
2188 }),
2189 )
2190 .on_click(cx.listener(move |this, _, window, cx| {
2191 if let Some(popup) = this.popup.as_mut() {
2192 popup.highlighted = index;
2193 }
2194 this.accept_mention(window, cx);
2195 }))
2196 });
2197 Some(
2198 v_flex()
2199 .id("mention-popup")
2200 .absolute()
2201 .bottom(relative(1.))
2202 .left_0()
2203 .mb(px(6.))
2204 .w(px(POPUP_WIDTH))
2205 .py(px(6.))
2206 .rounded(px(10.))
2207 .border_1()
2208 .border_color(theme::border_strong())
2209 .bg(theme::surface())
2210 .shadow_lg()
2211 .occlude()
2212 .children(rows)
2213 .into_any_element(),
2214 )
2215 }
2216
2217 fn render_emoji_popup(
2218 &self,
2219 window: &mut Window,
2220 cx: &mut Context<Self>,
2221 ) -> Option<AnyElement> {
2222 let popup = self.emoji_popup.as_ref()?;
2223 let colon = popup.range.start..popup.range.start + 1;
2224 let anchor = self
2225 .input
2226 .read(cx)
2227 .range_to_bounds(&colon)
2228 .map(|bounds| bounds.origin);
2229 if anchor.is_none() {
2230 window.request_animation_frame();
2231 }
2232 let composer = cx.entity().downgrade();
2233 Some(emoji_popup::render(
2234 popup,
2235 anchor,
2236 move |index, window, cx| {
2237 composer
2238 .update(cx, |this, cx| {
2239 if let Some(popup) = this.emoji_popup.as_mut() {
2240 popup.highlighted = index;
2241 }
2242 this.accept_emoji(window, cx);
2243 })
2244 .ok();
2245 },
2246 ))
2247 }
2248
2249 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2250 let composer = cx.entity().downgrade();
2251 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
2252 return None;
2253 }
2254 let state = self.input.read(cx);
2255 let range = self
2256 .link_editor
2257 .as_ref()
2258 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
2259 let start = state.range_to_bounds(&(range.start..range.start))?;
2260 let end = state.range_to_bounds(&(range.end..range.end))?;
2261 let input_bounds = state.input_bounds();
2262 let center_x = if start.origin.y == end.origin.y {
2263 (start.origin.x + end.origin.x) / 2.
2264 } else {
2265 input_bounds.center().x
2266 };
2267 let edges = self
2268 .composer_bounds
2269 .get()
2270 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
2271 (bounds.left(), bounds.right())
2272 });
2273 let width = match self.link_editor {
2274 Some(_) => format_toolbar::link_width(),
2275 None => format_toolbar::bar_width(),
2276 };
2277 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
2278 let element = match &self.link_editor {
2279 Some(editor) => format_toolbar::render(
2280 placement,
2281 format_toolbar::Mode::Link {
2282 field: &editor.field,
2283 refused: editor.refused,
2284 on_apply: Rc::new(move |window, cx| {
2285 composer
2286 .update(cx, |this, cx| this.apply_link(window, cx))
2287 .ok();
2288 }),
2289 },
2290 ),
2291 None => {
2292 let state_of = |button| self.format_state(button, &range);
2293 format_toolbar::render(
2294 placement,
2295 format_toolbar::Mode::Bar {
2296 state: &state_of,
2297 on_press: Rc::new(move |button, window, cx| {
2298 composer
2299 .update(cx, |this, cx| this.press_format(button, window, cx))
2300 .ok();
2301 }),
2302 },
2303 )
2304 }
2305 };
2306 Some(element)
2307 }
2308
2309 fn render_paste_hint(&self) -> Option<Div> {
2310 self.paste_hint.as_ref()?;
2311 Some(
2312 h_flex()
2313 .mt(px(6.))
2314 .gap(px(6.))
2315 .items_center()
2316 .text_size(px(12.))
2317 .text_color(theme::text_muted())
2318 .child("Formatted from Markdown")
2319 .child(
2320 div()
2321 .px(px(5.))
2322 .py(px(1.))
2323 .rounded(px(4.))
2324 .border_1()
2325 .border_color(theme::border_strong())
2326 .bg(theme::surface_raised())
2327 .text_size(px(11.))
2328 .text_color(theme::text())
2329 .child("Ctrl+Z"),
2330 )
2331 .child("plain text"),
2332 )
2333 }
2334
2335 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2336 let edit = self.editing.as_ref()?;
2337 Some(
2338 h_flex()
2339 .w_full()
2340 .mb(px(6.))
2341 .gap(px(10.))
2342 .items_center()
2343 .pl(px(10.))
2344 .pr(px(4.))
2345 .py(px(6.))
2346 .rounded(px(8.))
2347 .bg(theme::surface())
2348 .border_1()
2349 .border_color(theme::border())
2350 .child(match edit.scheduled {
2351 Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2352 None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2353 })
2354 .child(
2355 v_flex()
2356 .flex_1()
2357 .min_w_0()
2358 .child(
2359 div()
2360 .truncate()
2361 .text_size(px(12.))
2362 .font_weight(FontWeight::SEMIBOLD)
2363 .text_color(theme::accent_text())
2364 .child(match edit.scheduled {
2365 Some(send_at) => format!(
2366 "Editing scheduled message - {}",
2367 scheduled_label(send_at, Utc::now())
2368 ),
2369 None => "Editing message".to_owned(),
2370 }),
2371 )
2372 .child(
2373 div()
2374 .truncate()
2375 .text_size(px(12.))
2376 .text_color(theme::text_muted())
2377 .child(edit.excerpt.clone()),
2378 ),
2379 )
2380 .child(
2381 div()
2382 .id("edit-close")
2383 .size(px(24.))
2384 .flex()
2385 .items_center()
2386 .justify_center()
2387 .rounded(px(6.))
2388 .cursor_pointer()
2389 .hover(|button| button.bg(theme::row_hover()))
2390 .child(icon(IconName::Close, 14., theme::text_muted()))
2391 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
2392 ),
2393 )
2394 }
2395
2396 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2397 let reply = self.reply.as_ref()?;
2398 Some(
2399 h_flex()
2400 .w_full()
2401 .mb(px(6.))
2402 .gap(px(10.))
2403 .items_center()
2404 .pl(px(10.))
2405 .pr(px(4.))
2406 .py(px(6.))
2407 .rounded(px(8.))
2408 .bg(theme::surface())
2409 .border_1()
2410 .border_color(theme::border())
2411 .child(icon(IconName::Undo2, 14., theme::accent_text()))
2412 .child(
2413 v_flex()
2414 .flex_1()
2415 .min_w_0()
2416 .child(
2417 div()
2418 .truncate()
2419 .text_size(px(12.))
2420 .font_weight(FontWeight::SEMIBOLD)
2421 .text_color(theme::accent_text())
2422 .child(format!("Replying to {}", reply.author)),
2423 )
2424 .child(
2425 div()
2426 .truncate()
2427 .text_size(px(12.))
2428 .text_color(theme::text_muted())
2429 .child(reply.excerpt.clone()),
2430 ),
2431 )
2432 .child(
2433 div()
2434 .id("reply-close")
2435 .size(px(24.))
2436 .flex()
2437 .items_center()
2438 .justify_center()
2439 .rounded(px(6.))
2440 .cursor_pointer()
2441 .hover(|button| button.bg(theme::row_hover()))
2442 .child(icon(IconName::Close, 14., theme::text_muted()))
2443 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
2444 ),
2445 )
2446 }
2447}
2448
2449impl Render for Composer {
2450 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2451 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
2452 let can_send = self.can_send(cx);
2453 let can_attach = self.editing.is_none();
2454 let send = div()
2455 .id("composer-send")
2456 .size(px(32.))
2457 .flex_none()
2458 .flex()
2459 .items_center()
2460 .justify_center()
2461 .rounded(px(8.))
2462 .child(symbol("keyboard_return", 20., white()))
2463 .on_mouse_down(
2464 MouseButton::Right,
2465 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
2466 )
2467 .when(!can_send, |button| button.opacity(0.4))
2468 .when(can_send, |button| {
2469 button
2470 .cursor_pointer()
2471 .hover(|button| button.bg(white().opacity(0.1)))
2472 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2473 });
2474 let fun = can_attach.then(|| {
2475 let picker = self.fun_picker.clone();
2476 let reset_picker = self.fun_picker.clone();
2477 Popover::new("composer-fun-popover")
2478 .anchor(Anchor::BottomLeft)
2479 .offset(px(10.))
2480 .p_0()
2481 .trigger(
2482 Button::new("composer-fun")
2483 .ghost()
2484 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2485 .size(px(32.))
2486 .tooltip("Emoji, GIFs und Sticker")
2487 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2488 )
2489 .on_open_change(move |open, window, cx| {
2490 if *open {
2491 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
2492 }
2493 })
2494 .content(move |_, _, cx| {
2495 let popover = cx.entity().downgrade();
2496 picker.update(cx, |picker, _| picker.set_popover(popover));
2497 picker.clone()
2498 })
2499 });
2500 let attach = can_attach.then(|| {
2501 div()
2502 .id("composer-attach")
2503 .size(px(32.))
2504 .flex_none()
2505 .flex()
2506 .items_center()
2507 .justify_center()
2508 .rounded(px(8.))
2509 .cursor_pointer()
2510 .hover(|button| button.bg(theme::row_hover()))
2511 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2512 .child(symbol("attach_file", COMPOSER_ICON_SIZE, theme::text_muted()))
2513 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2514 });
2515 let composer = cx.weak_entity();
2516 let tokens_composer = composer.clone();
2517 let input = Textarea::new(&self.input)
2518 .appearance(false)
2519 .bordered(false)
2520 .on_paste(move |item, window, cx| {
2521 composer
2522 .update(cx, |this, cx| this.paste(item, window, cx))
2523 .unwrap_or(false)
2524 })
2525 .token(move |context, _, cx| {
2526 if let Some(id) = context
2527 .is_block()
2528 .then(|| image_id(context.token()))
2529 .flatten()
2530 {
2531 let preview = tokens_composer
2532 .read_with(cx, |this, _| this.tray.image(id))
2533 .ok()
2534 .flatten();
2535 let remove_composer = tokens_composer.clone();
2536 return inline_preview(
2537 id,
2538 preview,
2539 context.available_width(),
2540 context.is_selected(),
2541 Rc::new(move |window, cx| {
2542 remove_composer
2543 .update(cx, |this, cx| this.remove_image_token(id, window, cx))
2544 .ok();
2545 }),
2546 );
2547 }
2548 div()
2549 .h(context.line_height())
2550 .px(px(5.))
2551 .rounded(px(5.))
2552 .bg(if context.is_selected() {
2553 theme::accent().opacity(0.4)
2554 } else {
2555 theme::mention_background(false)
2556 })
2557 .text_color(theme::mention_text())
2558 .font_weight(FontWeight::SEMIBOLD)
2559 .child(context.token().label().clone())
2560 .into_any_element()
2561 });
2562 let tray = can_attach
2563 .then(|| {
2564 render_tray(
2565 &self.tray,
2566 Self::remove_attachment,
2567 Self::retry_attachment,
2568 cx,
2569 )
2570 })
2571 .flatten();
2572 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
2573 div()
2574 .w_full()
2575 .mb(px(6.))
2576 .text_size(px(12.))
2577 .text_color(theme::amber())
2578 .child(notice.to_owned())
2579 });
2580 let composer_bounds = self.composer_bounds.clone();
2581 let (inset, top, bottom) = if self.inline {
2582 (0., 0., 0.)
2583 } else {
2584 (24., 8., 12.)
2585 };
2586 v_flex()
2587 .w_full()
2588 .flex_none()
2589 .px(px(inset))
2590 .pt(px(top))
2591 .pb(px(bottom))
2592 .key_context(KEY_CONTEXT)
2593 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2594 if this.link_editor.is_none() {
2595 this.toggle_mark(MarkKind::Bold, cx);
2596 }
2597 }))
2598 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2599 if this.link_editor.is_none() {
2600 this.toggle_mark(MarkKind::Italic, cx);
2601 }
2602 }))
2603 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2604 if this.link_editor.is_none() {
2605 this.toggle_mark(MarkKind::Underline, cx);
2606 }
2607 }))
2608 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2609 if this.link_editor.is_none() {
2610 this.toggle_mark(MarkKind::Strike, cx);
2611 }
2612 }))
2613 .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2614 if this.link_editor.is_none() {
2615 this.toggle_mark(MarkKind::Superscript, cx);
2616 }
2617 }))
2618 .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2619 if this.link_editor.is_none() {
2620 this.toggle_mark(MarkKind::Subscript, cx);
2621 }
2622 }))
2623 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2624 if this.link_editor.is_none() {
2625 this.toggle_mark(MarkKind::Code, cx);
2626 }
2627 }))
2628 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2629 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2630 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2631 if this.link_editor.is_none() {
2632 this.step_history(true, window, cx);
2633 cx.stop_propagation();
2634 }
2635 }))
2636 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
2637 if this.link_editor.is_none() {
2638 this.step_history(false, window, cx);
2639 cx.stop_propagation();
2640 }
2641 }))
2642 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2643 if this.link_editor.is_none() && this.copy_selection(cx) {
2644 cx.stop_propagation();
2645 }
2646 }))
2647 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2648 if this.link_editor.is_none() && this.copy_selection(cx) {
2649 this.input
2650 .update(cx, |state, cx| state.replace("", window, cx));
2651 cx.stop_propagation();
2652 }
2653 }))
2654 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2655 if this.link_editor.is_some() {
2656 } else if this.schedule.is_some() {
2657 this.move_schedule_highlight(-1, window, cx);
2658 cx.stop_propagation();
2659 } else if this.popup_is_open() {
2660 this.move_highlight(-1, cx);
2661 cx.stop_propagation();
2662 } else if this.editing.is_none() && this.is_empty(cx) {
2663 cx.emit(ComposerEvent::EditLast);
2664 cx.stop_propagation();
2665 }
2666 }))
2667 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2668 if this.link_editor.is_some() {
2669 } else if this.schedule.is_some() {
2670 this.move_schedule_highlight(1, window, cx);
2671 cx.stop_propagation();
2672 } else if this.popup_is_open() {
2673 this.move_highlight(1, cx);
2674 cx.stop_propagation();
2675 }
2676 }))
2677 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2678 if this.link_editor.is_some() {
2679 this.apply_link(window, cx);
2680 cx.stop_propagation();
2681 } else if this.schedule.is_some() {
2682 this.activate_schedule_row(window, cx);
2683 cx.stop_propagation();
2684 } else if this.popup_is_open() {
2685 this.accept_popup(window, cx);
2686 cx.stop_propagation();
2687 } else if this.break_line(action.shift, window, cx) {
2688 cx.stop_propagation();
2689 }
2690 }))
2691 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2692 if this.link_editor.is_some() {
2693 } else if this.popup_is_open() {
2694 this.accept_popup(window, cx);
2695 cx.stop_propagation();
2696 } else if this.indent(false, window, cx) {
2697 cx.stop_propagation();
2698 }
2699 }))
2700 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2701 if this.link_editor.is_none() && this.indent(true, window, cx) {
2702 cx.stop_propagation();
2703 }
2704 }))
2705 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2706 if this.link_editor.is_none()
2707 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2708 {
2709 cx.stop_propagation();
2710 }
2711 }))
2712 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2713 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2714 cx.stop_propagation();
2715 }
2716 }))
2717 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2718 if this.schedule.is_some() {
2719 this.close_schedule(window, cx);
2720 cx.stop_propagation();
2721 return;
2722 }
2723 if this.link_editor.is_some() {
2724 this.close_link_editor(window, cx);
2725 cx.stop_propagation();
2726 return;
2727 }
2728 if this.toolbar_requested(cx) {
2729 this.toolbar_dismissed = Some(this.selection(cx));
2730 cx.notify();
2731 cx.stop_propagation();
2732 return;
2733 }
2734 if let Some(popup) = &this.emoji_popup {
2735 this.emoji_dismissed_at = Some(popup.range.start);
2736 }
2737 if this.popup.is_some() || this.emoji_popup.is_some() {
2738 this.close_popup();
2739 cx.notify();
2740 cx.stop_propagation();
2741 } else if this.editing.is_some() {
2742 this.cancel_edit(window, cx);
2743 cx.stop_propagation();
2744 }
2745 }))
2746 .children(notice)
2747 .children(self.render_reply_strip(cx))
2748 .children(self.render_edit_strip(cx))
2749 .children(self.render_link_preview(cx))
2750 .child(
2751 div()
2752 .relative()
2753 .w_full()
2754 .children(self.render_popup(cx))
2755 .children(self.render_emoji_popup(window, cx))
2756 .children(self.render_toolbar(focused, cx))
2757 .children(self.render_schedule(cx))
2758 .child(
2759 v_flex()
2760 .relative()
2761 .w_full()
2762 .rounded(px(10.))
2763 .bg(theme::surface())
2764 .border_1()
2765 .border_color(if focused {
2766 theme::accent()
2767 } else {
2768 theme::border_strong()
2769 })
2770 .child(
2771 canvas(
2772 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2773 |_, _, _, _| {},
2774 )
2775 .absolute()
2776 .size_full(),
2777 )
2778 .children(tray)
2779 .child(
2780 h_flex()
2781 .w_full()
2782 .items_end()
2783 .gap(px(6.))
2784 .py(px(6.))
2785 .pl(px(if can_attach { 6. } else { 12. }))
2786 .pr(px(6.))
2787 .children(fun)
2788 .children(attach)
2789 .child(
2790 div()
2791 .flex_1()
2792 .min_w_0()
2793 .capture_any_mouse_down(cx.listener(
2794 |this, _: &MouseDownEvent, _, _| {
2795 this.mouse_selecting = true;
2796 this.toolbar_dismissed = None;
2797 this.link_editor = None;
2798 },
2799 ))
2800 .capture_any_mouse_up(cx.listener(
2801 |this, _: &MouseUpEvent, _, cx| {
2802 this.mouse_selecting = false;
2803 cx.notify();
2804 },
2805 ))
2806 .on_mouse_up_out(
2807 MouseButton::Left,
2808 cx.listener(|this, _, _, cx| {
2809 this.mouse_selecting = false;
2810 cx.notify();
2811 }),
2812 )
2813 .child(input),
2814 )
2815 .child(send),
2816 ),
2817 ),
2818 )
2819 .children(self.render_paste_hint())
2820 }
2821}
2822
2823#[cfg(test)]
2824mod tests {
2825 use super::{active_mention, submitted_text};
2826 use gpui_kit::component::input::InputEvent;
2827
2828 fn press(shift: bool) -> InputEvent {
2829 InputEvent::PressEnter {
2830 secondary: false,
2831 shift,
2832 }
2833 }
2834
2835 #[test]
2836 fn enter_sends_trimmed_text() {
2837 assert_eq!(
2838 submitted_text(&press(false), " hello \n"),
2839 Some("hello".into())
2840 );
2841 }
2842
2843 #[test]
2844 fn shift_enter_never_sends() {
2845 assert_eq!(submitted_text(&press(true), "hello"), None);
2846 }
2847
2848 #[test]
2849 fn blank_text_never_sends() {
2850 assert_eq!(submitted_text(&press(false), " \n "), None);
2851 }
2852
2853 #[test]
2854 fn other_events_never_send() {
2855 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
2856 }
2857
2858 #[test]
2859 fn at_sign_opens_a_mention_query() {
2860 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
2861 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
2862 }
2863
2864 #[test]
2865 fn names_with_a_space_keep_the_query_open() {
2866 assert_eq!(
2867 active_mention("@Mara Lin", 9, &[]),
2868 Some((0..9, "Mara Lin".into()))
2869 );
2870 }
2871
2872 #[test]
2873 fn mail_addresses_and_closed_queries_do_not_open() {
2874 assert_eq!(active_mention("a@b", 3, &[]), None);
2875 assert_eq!(active_mention("@Mara ", 6, &[]), None);
2876 assert_eq!(active_mention("@ x", 3, &[]), None);
2877 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
2878 }
2879
2880 #[test]
2881 fn text_inside_a_token_does_not_reopen() {
2882 let token = 0..15;
2883 assert_eq!(
2884 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
2885 None
2886 );
2887 assert_eq!(
2888 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
2889 Some((16..19, "Pr".into()))
2890 );
2891 }
2892
2893 #[test]
2894 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
2895 use std::sync::Arc;
2896
2897 use gpui_kit::{Image, ImageFormat};
2898 use teams_core::FileKind;
2899
2900 use super::super::attachment_tray::InlineImage;
2901 use super::{Outgoing, OutgoingFile, OutgoingImage};
2902
2903 let outgoing = Outgoing {
2904 draft: teams_core::Draft::default(),
2905 subject: None,
2906 mentions: Vec::new(),
2907 link_preview: None,
2908 reply: None,
2909 edit: None,
2910 images: vec![OutgoingImage::Inline(InlineImage {
2911 name: "pasted-image.png".into(),
2912 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2913 dimensions: Some((1, 1)),
2914 })],
2915 files: vec![OutgoingFile {
2916 name: "plan.pdf".into(),
2917 size: 9,
2918 kind: FileKind::Pdf,
2919 uploaded: None,
2920 reference: teams_core::FileReference {
2921 attachment_id: "guid".into(),
2922 content_url: "https://files.example/plan.pdf".into(),
2923 name: "plan.pdf".into(),
2924 },
2925 }],
2926 };
2927 let extras = outgoing.extras();
2928 assert_eq!(extras.images[0].content_type, "image/png");
2929 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
2930 assert_eq!(extras.files[0].attachment_id, "guid");
2931 assert!(outgoing.has_attachments());
2932 }
2933
2934 fn placed_image(width: u32) -> super::OutgoingImage {
2935 use std::sync::Arc;
2936
2937 use gpui_kit::{Image, ImageFormat};
2938
2939 super::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
2940 name: "pasted-image.png".into(),
2941 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2942 dimensions: Some((width, width)),
2943 })
2944 }
2945
2946 fn remote_gif(title: &str) -> super::OutgoingImage {
2947 super::OutgoingImage::Remote(super::RemoteImage {
2948 kind: crate::remote_image::RemoteKind::Gif,
2949 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
2950 title: title.into(),
2951 width: 200,
2952 height: 100,
2953 })
2954 }
2955
2956 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2957 super::Outgoing {
2958 draft: teams_core::Draft::plain(text),
2959 subject: None,
2960 mentions: Vec::new(),
2961 link_preview: None,
2962 reply: None,
2963 edit: None,
2964 images,
2965 files: Vec::new(),
2966 }
2967 }
2968
2969 #[test]
2970 fn an_image_is_placed_in_the_html_where_its_mark_sits() {
2971 let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
2972 assert_eq!(
2973 outgoing.html(),
2974 "a <img src=\"../hostedContents/1/$value\"> b"
2975 );
2976 assert_eq!(outgoing.text(), "a b");
2977 }
2978
2979 #[test]
2980 fn images_keep_the_order_of_their_marks() {
2981 let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
2982 assert_eq!(
2983 outgoing.html(),
2984 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
2985 );
2986 }
2987
2988 #[test]
2989 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
2990 let outgoing = outgoing_with(
2991 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
2992 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
2993 );
2994 assert_eq!(
2995 outgoing.html(),
2996 "<img src=\"../hostedContents/1/$value\">a<img src=\"https://media0.giphy.com/media/a/giphy.gif\" width=\"200\" height=\"100\" alt=\"Wave\" itemtype=\"http://schema.skype.com/Giphy\">b<img src=\"../hostedContents/2/$value\">"
2997 );
2998 assert_eq!(outgoing.extras().images.len(), 2);
2999 }
3000
3001 #[test]
3002 fn a_gif_title_is_escaped_in_the_html() {
3003 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
3004 assert!(outgoing.html().contains("alt=\"a &quot;b&quot; &lt;c&gt;\""));
3005 }
3006
3007 #[test]
3008 fn a_sticker_carries_the_sticker_itemtype() {
3009 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3010 let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
3011 assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
3012 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
3013 }
3014
3015 #[test]
3016 fn a_mark_without_an_image_leaves_no_trace() {
3017 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
3018 }
3019
3020 #[test]
3021 fn enter_sends_attachments_even_without_text() {
3022 assert!(super::is_plain_enter(&press(false)));
3023 assert!(!super::is_plain_enter(&press(true)));
3024 assert!(!super::is_plain_enter(&InputEvent::Change));
3025 }
3026
3027 mod keys {
3028 use std::sync::Arc;
3029
3030 use gpui_kit::test::TestWindowExt as _;
3031 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3032 use store::Store;
3033
3034 use super::super::Composer;
3035 use crate::app_state::{AppState, Mode};
3036
3037 #[gpui_kit::test]
3038 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
3039 cx.update(gpui_kit::init);
3040 let store = Arc::new(Store::open_in_memory().unwrap());
3041 let mode = Mode {
3042 demo: true,
3043 read_only: false,
3044 demo_sync: None,
3045 };
3046 let (handle, composer) = cx.update(|cx| {
3047 let app = cx.new(|_| AppState::new(store, mode));
3048 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3049 cx.new(|cx| Composer::new(app, window, cx))
3050 })
3051 .unwrap()
3052 });
3053 let value = cx
3054 .update_window(handle, |_, window, cx| {
3055 composer.update(cx, |composer, cx| composer.focus(window, cx));
3056 window.render_frame(cx);
3057 window.input("first line", cx);
3058 window.press("shift-enter", cx);
3059 window.input("second line", cx);
3060 window.press("ctrl-a", cx);
3061 window.input("X", cx);
3062 composer.read(cx).input.read(cx).value()
3063 })
3064 .unwrap();
3065 assert_eq!(value, "X");
3066 }
3067
3068 struct Typist<'a> {
3069 cx: &'a mut TestAppContext,
3070 handle: gpui_kit::AnyWindowHandle,
3071 composer: gpui_kit::Entity<Composer>,
3072 }
3073
3074 impl Typist<'_> {
3075 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
3076 self.cx
3077 .update_window(self.handle, |_, window, cx| action(window, cx))
3078 .unwrap();
3079 self.cx.run_until_parked();
3080 }
3081
3082 fn type_text(&mut self, text: &str) {
3083 for character in text.chars() {
3084 self.act(|window, cx| window.input(&character.to_string(), cx));
3085 }
3086 }
3087
3088 fn press(&mut self, keys: &str) {
3089 for key in keys.split(' ') {
3090 self.act(|window, cx| window.press(key, cx));
3091 }
3092 }
3093
3094 fn value(&mut self) -> String {
3095 let composer = self.composer.clone();
3096 self.cx
3097 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
3098 }
3099
3100 fn draft(&mut self) -> teams_core::Draft {
3101 let composer = self.composer.clone();
3102 self.cx.update(|cx| composer.read(cx).draft.clone())
3103 }
3104
3105 fn outgoing(&mut self) -> super::super::Outgoing {
3106 let composer = self.composer.clone();
3107 self.cx
3108 .update(|cx| composer.read(cx).outgoing(cx))
3109 .expect("text to send")
3110 }
3111 }
3112
3113 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
3114 let (handle, composer) = demo_composer(cx);
3115 cx.update(super::super::bind_keys);
3116 let mut typist = Typist {
3117 cx,
3118 handle,
3119 composer: composer.clone(),
3120 };
3121 typist.act(|window, cx| {
3122 composer.update(cx, |composer, cx| composer.focus(window, cx));
3123 window.render_frame(cx);
3124 });
3125 typist
3126 }
3127
3128 fn png_bytes(side: u32) -> Vec<u8> {
3129 let mut bytes = Vec::new();
3130 image::RgbaImage::new(side, side)
3131 .write_to(
3132 &mut std::io::Cursor::new(&mut bytes),
3133 image::ImageFormat::Png,
3134 )
3135 .unwrap();
3136 bytes
3137 }
3138
3139 fn paste_image(typist: &mut Typist<'_>, side: u32) {
3140 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3141 entries: vec![gpui_kit::ClipboardEntry::Image(
3142 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
3143 )],
3144 });
3145 typist.press("ctrl-v");
3146 }
3147
3148 fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
3149 let composer = typist.composer.clone();
3150 typist.cx.update(|cx| {
3151 composer
3152 .read(cx)
3153 .input
3154 .read(cx)
3155 .tokens()
3156 .iter()
3157 .map(|span| (span.range(), span.token().is_block()))
3158 .collect()
3159 })
3160 }
3161
3162 #[gpui_kit::test]
3163 fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
3164 let mut typist = typist(cx);
3165 typist.type_text("ab");
3166 typist.press("left");
3167 paste_image(&mut typist, 2);
3168 assert_eq!(typist.value(), "a\u{FFFC}b");
3169 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3170 let outgoing = typist.outgoing();
3171 assert_eq!(outgoing.images.len(), 1);
3172 assert_eq!(
3173 outgoing.html(),
3174 "a<img src=\"../hostedContents/1/$value\">b"
3175 );
3176 let composer = typist.composer.clone();
3177 assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
3178 }
3179
3180 fn wide_png_bytes() -> Vec<u8> {
3181 let mut bytes = Vec::new();
3182 image::RgbaImage::new(600, 300)
3183 .write_to(
3184 &mut std::io::Cursor::new(&mut bytes),
3185 image::ImageFormat::Png,
3186 )
3187 .unwrap();
3188 bytes
3189 }
3190
3191 fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
3192 let composer = typist.composer.clone();
3193 typist.cx.update(|cx| {
3194 let state = composer.read(cx).input.read(cx);
3195 let cursor = state.cursor();
3196 let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
3197 let viewport = state.input_bounds();
3198 caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
3199 })
3200 }
3201
3202 #[gpui_kit::test]
3203 fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
3204 let mut typist = typist(cx);
3205 typist.type_text("look at this ");
3206 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3207 entries: vec![gpui_kit::ClipboardEntry::Image(
3208 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
3209 )],
3210 });
3211 typist.press("ctrl-v");
3212 typist.act(|window, _| window.refresh());
3213 typist.type_text("and then more text");
3214 typist.act(|window, _| window.refresh());
3215 assert!(caret_is_visible(&mut typist));
3216 }
3217
3218 #[gpui_kit::test]
3219 fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
3220 let mut typist = typist(cx);
3221 typist.type_text("ab");
3222 typist.press("left");
3223 paste_image(&mut typist, 2);
3224 typist.press("backspace");
3225 assert_eq!(typist.value(), "ab");
3226 assert!(image_tokens(&mut typist).is_empty());
3227 let outgoing = typist.outgoing();
3228 assert!(outgoing.images.is_empty());
3229 assert_eq!(outgoing.html(), "ab");
3230 typist.press("ctrl-z");
3231 assert_eq!(typist.value(), "a\u{FFFC}b");
3232 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3233 assert_eq!(typist.outgoing().images.len(), 1);
3234 }
3235
3236 #[gpui_kit::test]
3237 fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
3238 let mut typist = typist(cx);
3239 typist.type_text("ab");
3240 paste_image(&mut typist, 2);
3241 typist.type_text("cd");
3242 let composer = typist.composer.clone();
3243 let id = typist.cx.update(|cx| {
3244 let state = composer.read(cx).input.read(cx);
3245 super::super::image_id(state.tokens()[0].token()).unwrap()
3246 });
3247 typist.act(|window, cx| {
3248 composer.update(cx, |composer, cx| {
3249 composer.remove_image_token(id, window, cx)
3250 });
3251 });
3252 assert_eq!(typist.value(), "abcd");
3253 assert!(image_tokens(&mut typist).is_empty());
3254 assert!(typist.outgoing().images.is_empty());
3255 typist.press("ctrl-z");
3256 assert_eq!(typist.value(), "ab\u{FFFC}cd");
3257 assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
3258 assert_eq!(typist.outgoing().images.len(), 1);
3259 }
3260
3261 #[gpui_kit::test]
3262 fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
3263 let mut typist = typist(cx);
3264 typist.type_text("x");
3265 paste_image(&mut typist, 2);
3266 typist.type_text("y");
3267 typist.press("ctrl-home");
3268 paste_image(&mut typist, 4);
3269 assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
3270 let outgoing = typist.outgoing();
3271 let dimensions: Vec<_> = outgoing
3272 .images
3273 .iter()
3274 .map(|image| match image {
3275 super::super::OutgoingImage::Inline(inline) => inline.dimensions,
3276 super::super::OutgoingImage::Remote(_) => None,
3277 })
3278 .collect();
3279 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3280 assert_eq!(
3281 outgoing.html(),
3282 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
3283 );
3284 }
3285
3286 #[gpui_kit::test]
3287 fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
3288 let mut typist = typist(cx);
3289 paste_image(&mut typist, 2);
3290 let composer = typist.composer.clone();
3291 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3292 let outgoing = typist.outgoing();
3293 assert_eq!(outgoing.text(), "");
3294 assert_eq!(outgoing.images.len(), 1);
3295 typist.type_text("hi");
3296 typist.press("ctrl-a ctrl-c");
3297 let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
3298 assert_eq!(copied.as_deref(), Some("hi"));
3299 }
3300
3301 #[gpui_kit::test]
3302 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
3303 let mut typist = typist(cx);
3304 let composer = typist.composer.clone();
3305 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3306 typist.act(|window, cx| {
3307 composer.update(cx, |composer, cx| {
3308 composer.insert_remote_image(
3309 super::super::RemoteImage {
3310 kind: crate::remote_image::RemoteKind::Gif,
3311 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3312 title: "Wave".into(),
3313 width: 200,
3314 height: 100,
3315 },
3316 window,
3317 cx,
3318 )
3319 });
3320 });
3321 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3322 assert_eq!(typist.value(), "\u{FFFC}");
3323 let outgoing = typist.outgoing();
3324 assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3325 assert!(outgoing.extras().images.is_empty());
3326 typist.press("ctrl-z");
3327 assert_eq!(typist.value(), "");
3328 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3329 }
3330
3331 #[gpui_kit::test]
3332 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
3333 let mut typist = typist(cx);
3334 typist.type_text("ab");
3335 typist.press("left");
3336 let composer = typist.composer.clone();
3337 typist.act(|window, cx| {
3338 composer.update(cx, |composer, cx| {
3339 composer.insert_emoji("\u{1F44D}", window, cx)
3340 });
3341 });
3342 assert_eq!(typist.value(), "a\u{1F44D}b");
3343 }
3344
3345 #[gpui_kit::test]
3346 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3347 let mut typist = typist(cx);
3348 typist
3349 .cx
3350 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
3351 typist.press("ctrl-v");
3352 assert_eq!(typist.value(), "ab");
3353 }
3354
3355 #[gpui_kit::test]
3356 fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
3357 let mut typist = typist(cx);
3358 let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
3359 let composer = typist.composer.clone();
3360 typist.act(|window, cx| {
3361 composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
3362 });
3363 assert_eq!(typist.value(), "x\u{FFFC}y");
3364 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3365 let again = typist.outgoing();
3366 assert_eq!(again.images, outgoing.images);
3367 assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
3368 }
3369
3370 #[gpui_kit::test]
3371 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
3372 use teams_core::{FormatState, MarkKind};
3373
3374 let mut typist = typist(cx);
3375 typist.type_text("a **bold**");
3376 assert_eq!(typist.value(), "a bold");
3377 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
3378 typist.press("backspace");
3379 assert_eq!(typist.value(), "a **bold**");
3380 assert!(typist.draft().marks().is_empty());
3381 let composer = typist.composer.clone();
3382 assert_eq!(
3383 typist
3384 .cx
3385 .update(|cx| composer.read(cx).input.read(cx).cursor()),
3386 10
3387 );
3388 typist.press("backspace");
3389 typist.type_text("* x");
3390 assert_eq!(typist.value(), "a bold x");
3391 assert_eq!(
3392 typist.draft().state(6..8, &MarkKind::Bold),
3393 FormatState::Off
3394 );
3395 }
3396
3397 #[gpui_kit::test]
3398 fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
3399 use teams_core::{Mark, MarkKind};
3400
3401 let mut typist = typist(cx);
3402 typist.type_text("see https://a.b ");
3403 assert_eq!(typist.value(), "see https://a.b ");
3404 assert_eq!(
3405 typist.draft().marks(),
3406 [Mark {
3407 range: 4..15,
3408 kind: MarkKind::Link("https://a.b".into())
3409 }]
3410 );
3411 typist.press("backspace");
3412 assert_eq!(typist.value(), "see https://a.b ");
3413 assert!(typist.draft().marks().is_empty());
3414 }
3415
3416 #[gpui_kit::test]
3417 fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
3418 let mut typist = typist(cx);
3419 typist.type_text("https://a.b ");
3420 assert_eq!(typist.draft().marks().len(), 1);
3421 typist.press("ctrl-z");
3422 assert!(typist.draft().marks().is_empty());
3423 }
3424
3425 #[gpui_kit::test]
3426 fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3427 use teams_core::{Mark, MarkKind};
3428
3429 let mut typist = typist(cx);
3430 typist
3431 .cx
3432 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3433 "x https://a.b y".to_owned(),
3434 ));
3435 typist.press("ctrl-v");
3436 assert_eq!(typist.value(), "x https://a.b y");
3437 assert_eq!(
3438 typist.draft().marks(),
3439 [Mark {
3440 range: 2..13,
3441 kind: MarkKind::Link("https://a.b".into())
3442 }]
3443 );
3444 typist.press("ctrl-z");
3445 assert_eq!(typist.value(), "x https://a.b y");
3446 assert!(typist.draft().marks().is_empty());
3447 }
3448
3449 #[gpui_kit::test]
3450 fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
3451 use teams_core::{Mark, MarkKind};
3452
3453 let mut typist = typist(cx);
3454 typist.type_text("https://a.b x");
3455 typist.press("home");
3456 typist.press("shift-right ".repeat(11).trim_end());
3457 typist.press("ctrl-k");
3458 typist.type_text("other.de");
3459 typist.press("enter");
3460 assert_eq!(
3461 typist.draft().marks(),
3462 [Mark {
3463 range: 0..11,
3464 kind: MarkKind::Link("https://other.de".into())
3465 }]
3466 );
3467 typist.press("ctrl-k backspace enter");
3468 assert!(typist.draft().marks().is_empty());
3469 assert_eq!(typist.value(), "https://a.b x");
3470 }
3471
3472 #[gpui_kit::test]
3473 fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
3474 use teams_core::{Mark, MarkKind};
3475
3476 let mut typist = typist(cx);
3477 typist.type_text("- https://a.b");
3478 typist.press("enter");
3479 assert_eq!(typist.value(), "• https://a.b\n• ");
3480 assert_eq!(
3481 typist.draft().marks(),
3482 [Mark {
3483 range: 4..15,
3484 kind: MarkKind::Link("https://a.b".into())
3485 }]
3486 );
3487 }
3488
3489 #[gpui_kit::test]
3490 fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
3491 let mut typist = typist(cx);
3492 typist
3493 .cx
3494 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3495 "x https://a.b y".to_owned(),
3496 ));
3497 typist.press("ctrl-v");
3498 assert_eq!(typist.draft().marks().len(), 1);
3499 let composer = typist.composer.clone();
3500 assert!(
3501 typist
3502 .cx
3503 .update(|cx| composer.read(cx).paste_hint.is_none())
3504 );
3505 typist.press("ctrl-z");
3506 assert!(typist.draft().marks().is_empty());
3507 }
3508
3509 #[gpui_kit::test]
3510 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
3511 let mut typist = typist(cx);
3512 typist.type_text("1. one");
3513 typist.press("enter");
3514 typist.type_text("two");
3515 assert_eq!(typist.value(), "1. one\n2. two");
3516 typist.press("enter enter");
3517 assert_eq!(typist.value(), "1. one\n2. two\n");
3518 typist.type_text("after");
3519 typist.press("enter");
3520 assert_eq!(typist.value(), "");
3521 }
3522
3523 #[gpui_kit::test]
3524 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
3525 let mut typist = typist(cx);
3526 typist.type_text("- a");
3527 typist.press("enter tab");
3528 typist.type_text("b");
3529 assert_eq!(typist.value(), "• a\n◦ b");
3530 typist.press("shift-tab");
3531 assert_eq!(typist.value(), "• a\n• b");
3532 }
3533
3534 #[gpui_kit::test]
3535 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
3536 use teams_core::{FormatState, MarkKind};
3537
3538 let mut typist = typist(cx);
3539 typist.type_text("hello");
3540 typist.press("shift-left shift-left ctrl-b");
3541 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3542 assert_eq!(
3543 typist.draft().state(0..5, &MarkKind::Bold),
3544 FormatState::Mixed
3545 );
3546 typist.press("ctrl-b");
3547 assert!(typist.draft().marks().is_empty());
3548 typist.press("end ctrl-i");
3549 typist.type_text("!");
3550 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
3551 }
3552
3553 #[gpui_kit::test]
3554 fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {
3555 let mut typist = typist(cx);
3556 typist.type_text("x2");
3557 typist.press("shift-left ctrl-shift-=");
3558 assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");
3559 typist.press("ctrl-=");
3560 assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");
3561 }
3562
3563 #[gpui_kit::test]
3564 fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {
3565 use teams_core::FormatState;
3566
3567 use super::super::FormatButton;
3568
3569 let mut typist = typist(cx);
3570 typist.type_text("big small");
3571 typist.press("shift-left shift-left shift-left shift-left shift-left");
3572 let composer = typist.composer.clone();
3573 typist.act(|window, cx| {
3574 composer.update(cx, |composer, cx| {
3575 composer.press_format(FormatButton::SizeSmall, window, cx)
3576 })
3577 });
3578 let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {
3579 let composer = typist.composer.clone();
3580 typist.cx.update(|cx| {
3581 let composer = composer.read(cx);
3582 [
3583 FormatButton::SizeSmall,
3584 FormatButton::SizeNormal,
3585 FormatButton::SizeLarge,
3586 ]
3587 .map(|button| composer.format_state(button, &range))
3588 })
3589 };
3590 assert_eq!(
3591 states(&mut typist, 4..9),
3592 [FormatState::On, FormatState::Off, FormatState::Off]
3593 );
3594 assert_eq!(
3595 states(&mut typist, 0..9),
3596 [FormatState::Mixed, FormatState::Off, FormatState::Off]
3597 );
3598 assert_eq!(
3599 states(&mut typist, 0..3),
3600 [FormatState::Off, FormatState::On, FormatState::Off]
3601 );
3602 assert_eq!(
3603 typist.outgoing().html(),
3604 "big <span style=\"font-size:xx-small;\">small</span>"
3605 );
3606 }
3607
3608 #[gpui_kit::test]
3609 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3610 let mut typist = typist(cx);
3611 typist
3612 .cx
3613 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3614 "**hi** there".to_owned(),
3615 ));
3616 typist.press("ctrl-v");
3617 assert_eq!(typist.value(), "hi there");
3618 let composer = typist.composer.clone();
3619 assert!(
3620 typist
3621 .cx
3622 .update(|cx| composer.read(cx).paste_hint.is_some())
3623 );
3624 typist.press("ctrl-z");
3625 assert_eq!(typist.value(), "**hi** there");
3626 assert!(typist.draft().marks().is_empty());
3627 }
3628
3629 #[gpui_kit::test]
3630 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
3631 use teams_core::{FormatState, MarkKind};
3632
3633 let mut typist = typist(cx);
3634 typist.type_text("`code` ");
3635 typist.press("ctrl-a ctrl-c end ctrl-v");
3636 assert_eq!(typist.value(), "code code ");
3637 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
3638 }
3639
3640 #[gpui_kit::test]
3641 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
3642 use teams_core::{FormatState, MarkKind};
3643
3644 let mut typist = typist(cx);
3645 typist.type_text("~~old~~");
3646 typist.press("ctrl-a");
3647 typist.type_text("new");
3648 typist.press("ctrl-z ctrl-z");
3649 assert_eq!(typist.value(), "old");
3650 assert_eq!(
3651 typist.draft().state(0..3, &MarkKind::Strike),
3652 FormatState::On
3653 );
3654 }
3655
3656 #[gpui_kit::test]
3657 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
3658 let mut typist = typist(cx);
3659 typist.type_text("see docs");
3660 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
3661 let composer = typist.composer.clone();
3662 assert!(
3663 typist
3664 .cx
3665 .update(|cx| composer.read(cx).link_editor.is_some())
3666 );
3667 typist.type_text("example.com");
3668 typist.press("enter");
3669 assert!(
3670 typist
3671 .cx
3672 .update(|cx| composer.read(cx).link_editor.is_none())
3673 );
3674 assert_eq!(
3675 typist.outgoing().html(),
3676 "see <a href=\"https://example.com\">docs</a>"
3677 );
3678 }
3679
3680 #[gpui_kit::test]
3681 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
3682 use teams_core::{FormatState, MarkKind};
3683
3684 let mut typist = typist(cx);
3685 typist.type_text("hello");
3686 typist.press("shift-left shift-left ctrl-b");
3687 typist.press("ctrl-z");
3688 assert_eq!(typist.value(), "hello");
3689 assert!(typist.draft().marks().is_empty());
3690 typist.press("ctrl-y");
3691 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3692 }
3693
3694 #[gpui_kit::test]
3695 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
3696 use teams_core::{FormatState, MarkKind};
3697
3698 let mut typist = typist(cx);
3699 typist.type_text("hello");
3700 typist.press("shift-left shift-left ctrl-b end");
3701 typist.type_text(" x");
3702 typist.press("backspace backspace");
3703 assert_eq!(typist.value(), "hello");
3704 typist.press("ctrl-z");
3705 assert_ne!(typist.value(), "hello");
3706 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3707 }
3708
3709 #[gpui_kit::test]
3710 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
3711 let mut typist = typist(cx);
3712 typist.type_text("```");
3713 typist.press("enter");
3714 typist.type_text("a");
3715 typist.press("enter");
3716 typist.type_text("b");
3717 typist.press("up end delete");
3718 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
3719 }
3720
3721 #[gpui_kit::test]
3722 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
3723 let mut typist = typist(cx);
3724 typist.type_text("```");
3725 typist.press("enter");
3726 typist.type_text(" x");
3727 typist.press("ctrl-a ctrl-c");
3728 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
3729 assert_eq!(text.as_deref(), Some(" x"));
3730 }
3731
3732 #[gpui_kit::test]
3733 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
3734 let mut typist = typist(cx);
3735 typist.type_text("docs");
3736 typist.press("ctrl-a ctrl-k");
3737 typist.type_text("javascript:alert(1)");
3738 typist.press("enter");
3739 let composer = typist.composer.clone();
3740 assert!(typist.cx.update(|cx| {
3741 composer
3742 .read(cx)
3743 .link_editor
3744 .as_ref()
3745 .is_some_and(|editor| editor.refused)
3746 }));
3747 assert!(typist.draft().marks().is_empty());
3748 typist.type_text("x");
3749 assert!(typist.cx.update(|cx| {
3750 composer
3751 .read(cx)
3752 .link_editor
3753 .as_ref()
3754 .is_some_and(|editor| !editor.refused)
3755 }));
3756 }
3757
3758 #[gpui_kit::test]
3759 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
3760 use teams_core::{FormatState, LineKind, MarkKind};
3761
3762 let mut typist = typist(cx);
3763 typist.type_text("hello");
3764 typist.press("ctrl-a ctrl-b");
3765 let composer = typist.composer.clone();
3766 typist.act(|window, cx| {
3767 composer.update(cx, |composer, cx| {
3768 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
3769 })
3770 });
3771 assert_eq!(typist.value(), "• hello");
3772 typist.press("ctrl-z");
3773 assert_eq!(typist.value(), "hello");
3774 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3775 typist.press("ctrl-z");
3776 assert!(typist.draft().marks().is_empty());
3777 assert_eq!(typist.draft().lines(), [LineKind::Text]);
3778 }
3779
3780 #[gpui_kit::test]
3781 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
3782 use teams_core::{FormatState, MarkKind};
3783
3784 let mut typist = typist(cx);
3785 typist.type_text("hello");
3786 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
3787 assert_eq!(typist.value(), "");
3788 typist.press("ctrl-y");
3789 assert_eq!(typist.value(), "hello");
3790 assert!(typist.draft().marks().is_empty());
3791 typist.press("ctrl-y");
3792 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3793 }
3794
3795 fn cursor(typist: &mut Typist<'_>) -> usize {
3796 let composer = typist.composer.clone();
3797 typist
3798 .cx
3799 .update(|cx| composer.read(cx).input.read(cx).cursor())
3800 }
3801
3802 #[gpui_kit::test]
3803 fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there(
3804 cx: &mut TestAppContext,
3805 ) {
3806 let mut typist = typist(cx);
3807 typist.type_text("hello");
3808 typist.press("home");
3809 typist.type_text("X");
3810 typist.press("end ctrl-z");
3811 assert_eq!(typist.value(), "hello");
3812 assert_eq!(cursor(&mut typist), 0);
3813 typist.press("ctrl-y");
3814 assert_eq!(typist.value(), "Xhello");
3815 assert_eq!(cursor(&mut typist), 1);
3816 }
3817
3818 #[gpui_kit::test]
3819 fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) {
3820 let mut typist = typist(cx);
3821 for line in 0..14 {
3822 typist.type_text(&format!("line {line}"));
3823 typist.press("shift-enter");
3824 }
3825 typist.type_text("end");
3826 let composer = typist.composer.clone();
3827 let scroll = |typist: &mut Typist<'_>| {
3828 typist
3829 .cx
3830 .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y)
3831 };
3832 typist.act(|window, cx| window.render_frame(cx));
3833 let before = scroll(&mut typist);
3834 assert!(before < gpui_kit::px(0.));
3835 typist.press("ctrl-z");
3836 typist.act(|window, cx| window.render_frame(cx));
3837 assert_eq!(scroll(&mut typist), before);
3838 }
3839
3840 #[gpui_kit::test]
3841 fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) {
3842 let mut typist = typist(cx);
3843 typist.type_text("ok :) ");
3844 assert!(typist.value().contains('🙂'));
3845 typist.press("ctrl-z");
3846 assert_eq!(typist.value(), "ok :) ");
3847 assert_eq!(typist.outgoing().text(), "ok :)");
3848 }
3849
3850 #[gpui_kit::test]
3851 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
3852 let mut typist = typist(cx);
3853 typist.press("ctrl-z");
3854 typist.type_text("**a**");
3855 assert_eq!(typist.value(), "a");
3856 }
3857
3858 #[gpui_kit::test]
3859 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
3860 let mut typist = typist(cx);
3861 typist.type_text("```");
3862 typist.press("enter");
3863 typist.type_text(":) ");
3864 typist
3865 .cx
3866 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
3867 typist.press("ctrl-v");
3868 assert_eq!(typist.value(), ":) **x**");
3869 let composer = typist.composer.clone();
3870 assert!(
3871 typist
3872 .cx
3873 .update(|cx| composer.read(cx).paste_hint.is_none())
3874 );
3875 let outgoing = typist.outgoing();
3876 assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
3877 }
3878
3879 #[gpui_kit::test]
3880 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3881 let mut typist = typist(cx);
3882 typist.type_text("> quoted");
3883 typist.press("shift-enter");
3884 typist.type_text("more");
3885 let outgoing = typist.outgoing();
3886 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
3887 assert_eq!(outgoing.text(), "quoted\nmore");
3888 }
3889
3890 #[gpui_kit::test]
3891 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
3892 cx.update(gpui_kit::init);
3893 let store = Arc::new(Store::open_in_memory().unwrap());
3894 let mode = Mode {
3895 demo: true,
3896 read_only: false,
3897 demo_sync: None,
3898 };
3899 let (handle, composer) = cx.update(|cx| {
3900 let app = cx.new(|_| AppState::new(store, mode));
3901 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3902 cx.new(|cx| Composer::new(app, window, cx))
3903 })
3904 .unwrap()
3905 });
3906 let directory = tempfile::tempdir().unwrap();
3907 let path = directory.path().join("plan.pdf");
3908 std::fs::write(&path, b"%PDF-1.7").unwrap();
3909 cx.update_window(handle, |_, window, cx| {
3910 composer.update(cx, |composer, cx| {
3911 composer.set_conversation("demo-chat", "Demo", window, cx);
3912 composer.add_paths(vec![path], window, cx);
3913 });
3914 })
3915 .unwrap();
3916 cx.run_until_parked();
3917 cx.update(|cx| {
3918 let composer = composer.read(cx);
3919 assert!(composer.tray.blocks_send());
3920 assert!(!composer.can_send(cx));
3921 });
3922 cx.executor()
3923 .advance_clock(std::time::Duration::from_secs(3));
3924 cx.run_until_parked();
3925 cx.update(|cx| {
3926 let composer = composer.read(cx);
3927 assert!(composer.can_send(cx));
3928 let outgoing = composer
3929 .outgoing(cx)
3930 .expect("an attachment alone is a message");
3931 assert_eq!(outgoing.text(), "");
3932 assert_eq!(outgoing.files.len(), 1);
3933 assert_eq!(outgoing.files[0].name, "plan.pdf");
3934 });
3935 }
3936
3937 #[gpui_kit::test]
3938 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
3939 cx.update(gpui_kit::init);
3940 let store = Arc::new(Store::open_in_memory().unwrap());
3941 let mode = Mode {
3942 demo: true,
3943 read_only: false,
3944 demo_sync: None,
3945 };
3946 let (handle, composer) = cx.update(|cx| {
3947 let app = cx.new(|_| AppState::new(store, mode));
3948 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3949 cx.new(|cx| Composer::new(app, window, cx))
3950 })
3951 .unwrap()
3952 });
3953 let directory = tempfile::tempdir().unwrap();
3954 let path = directory.path().join("plan.pdf");
3955 std::fs::write(&path, b"%PDF-1.7").unwrap();
3956 cx.update_window(handle, |_, window, cx| {
3957 composer.update(cx, |composer, cx| {
3958 composer.set_conversation("demo-chat", "Demo", window, cx);
3959 composer.add_paths(vec![path], window, cx);
3960 });
3961 })
3962 .unwrap();
3963 cx.run_until_parked();
3964 cx.update_window(handle, |_, window, cx| {
3965 composer.update(cx, |composer, cx| {
3966 composer.set_conversation("other-chat", "Other", window, cx)
3967 });
3968 })
3969 .unwrap();
3970 cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));
3971 }
3972
3973 fn demo_composer(
3974 cx: &mut TestAppContext,
3975 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
3976 cx.update(gpui_kit::init);
3977 let store = Arc::new(Store::open_in_memory().unwrap());
3978 let mode = Mode {
3979 demo: true,
3980 read_only: false,
3981 demo_sync: None,
3982 };
3983 let (handle, composer) = cx.update(|cx| {
3984 let app = cx.new(|_| AppState::new(store, mode));
3985 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3986 cx.new(|cx| Composer::new(app, window, cx))
3987 })
3988 .unwrap()
3989 });
3990 (handle, composer)
3991 }
3992
3993 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
3994 let path = directory.join("dot.png");
3995 image::RgbaImage::new(2, 2).save(&path).unwrap();
3996 path
3997 }
3998
3999 #[gpui_kit::test]
4000 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
4001 use super::super::{EditPreview, Outgoing};
4002
4003 let (handle, composer) = demo_composer(cx);
4004 let directory = tempfile::tempdir().unwrap();
4005 let path = directory.path().join("plan.pdf");
4006 std::fs::write(&path, b"%PDF-1.7").unwrap();
4007 cx.update_window(handle, |_, window, cx| {
4008 composer.update(cx, |composer, cx| {
4009 composer.set_conversation("demo-chat", "Demo", window, cx);
4010 composer.add_paths(vec![path], window, cx);
4011 });
4012 })
4013 .unwrap();
4014 cx.run_until_parked();
4015 cx.executor()
4016 .advance_clock(std::time::Duration::from_secs(3));
4017 cx.run_until_parked();
4018 cx.update_window(handle, |_, window, cx| {
4019 composer.update(cx, |composer, cx| {
4020 let draft = Outgoing {
4021 draft: teams_core::Draft::plain("old"),
4022 subject: None,
4023 mentions: Vec::new(),
4024 link_preview: None,
4025 reply: None,
4026 edit: Some(EditPreview {
4027 message_id: "m1".into(),
4028 excerpt: "old".into(),
4029 scheduled: None,
4030 }),
4031 images: Vec::new(),
4032 files: Vec::new(),
4033 };
4034 composer.begin_edit(draft, window, cx);
4035 });
4036 })
4037 .unwrap();
4038 cx.update(|cx| {
4039 let composer = composer.read(cx);
4040 assert_eq!(composer.tray.items().len(), 1);
4041 let outgoing = composer.outgoing(cx).unwrap();
4042 assert!(outgoing.files.is_empty());
4043 assert_eq!(outgoing.text(), "old");
4044 });
4045 cx.update_window(handle, |_, window, cx| {
4046 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
4047 })
4048 .unwrap();
4049 cx.update(|cx| {
4050 let composer = composer.read(cx);
4051 assert_eq!(composer.tray.items().len(), 1);
4052 assert!(composer.can_send(cx));
4053 });
4054 }
4055
4056 #[gpui_kit::test]
4057 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
4058 let (handle, composer) = demo_composer(cx);
4059 let directory = tempfile::tempdir().unwrap();
4060 let path = small_png(directory.path());
4061 for (carry, chosen, expected) in [
4062 (Some("chat-a"), "chat-a", 1),
4063 (None, "chat-b", 0),
4064 (Some("chat-a"), "chat-b", 0),
4065 ] {
4066 cx.update_window(handle, |_, window, cx| {
4067 composer.update(cx, |composer, cx| {
4068 composer.set_conversation("", "", window, cx);
4069 composer.add_paths(vec![path.clone()], window, cx);
4070 });
4071 })
4072 .unwrap();
4073 cx.run_until_parked();
4074 cx.update_window(handle, |_, window, cx| {
4075 composer.update(cx, |composer, cx| {
4076 if let Some(chat) = carry {
4077 composer.carry_images_into(chat.to_owned());
4078 }
4079 composer.set_conversation(chosen, "Chat", window, cx);
4080 });
4081 })
4082 .unwrap();
4083 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
4084 }
4085 }
4086
4087 #[gpui_kit::test]
4088 fn each_conversation_keeps_its_own_draft(cx: &mut TestAppContext) {
4089 let (handle, composer) = demo_composer(cx);
4090 cx.update_window(handle, |_, window, cx| {
4091 composer.update(cx, |composer, cx| {
4092 composer.set_conversation("chat-a", "A", window, cx);
4093 composer.set_text("**hello** there", window, cx);
4094 composer.set_conversation("chat-b", "B", window, cx);
4095 });
4096 })
4097 .unwrap();
4098 cx.update(|cx| {
4099 let composer = composer.read(cx);
4100 assert!(composer.draft.is_blank());
4101 let stored = composer
4102 .app
4103 .read(cx)
4104 .store
4105 .draft("chat-a")
4106 .unwrap()
4107 .unwrap();
4108 assert_eq!(stored.preview, "hello there");
4109 });
4110 cx.update_window(handle, |_, window, cx| {
4111 composer.update(cx, |composer, cx| {
4112 composer.set_text("other", window, cx);
4113 composer.set_conversation("chat-a", "A", window, cx);
4114 });
4115 })
4116 .unwrap();
4117 cx.update(|cx| {
4118 let composer = composer.read(cx);
4119 assert_eq!(composer.draft.text(), "hello there");
4120 assert!(composer.draft.to_html().contains("<b>"));
4121 assert!(
4122 composer
4123 .app
4124 .read(cx)
4125 .store
4126 .draft("chat-b")
4127 .unwrap()
4128 .is_some()
4129 );
4130 });
4131 }
4132
4133 #[gpui_kit::test]
4134 fn sending_clears_the_stored_draft_and_a_blank_composer_deletes_it(
4135 cx: &mut TestAppContext,
4136 ) {
4137 let (handle, composer) = demo_composer(cx);
4138 cx.update_window(handle, |_, window, cx| {
4139 composer.update(cx, |composer, cx| {
4140 composer.set_conversation("chat-a", "A", window, cx);
4141 composer.set_text("hi", window, cx);
4142 composer.save_draft_now(cx);
4143 });
4144 })
4145 .unwrap();
4146 cx.update(|cx| {
4147 assert!(
4148 composer
4149 .read(cx)
4150 .app
4151 .read(cx)
4152 .store
4153 .draft("chat-a")
4154 .unwrap()
4155 .is_some()
4156 );
4157 });
4158 cx.update_window(handle, |_, window, cx| {
4159 composer.update(cx, |composer, cx| composer.submit_current(window, cx));
4160 })
4161 .unwrap();
4162 cx.update(|cx| {
4163 assert!(
4164 composer
4165 .read(cx)
4166 .app
4167 .read(cx)
4168 .store
4169 .draft("chat-a")
4170 .unwrap()
4171 .is_none()
4172 );
4173 });
4174 }
4175
4176 #[gpui_kit::test]
4177 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
4178 cx: &mut TestAppContext,
4179 ) {
4180 let (handle, composer) = demo_composer(cx);
4181 let directory = tempfile::tempdir().unwrap();
4182 let png = small_png(directory.path());
4183 let pdf = directory.path().join("plan.pdf");
4184 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
4185 cx.update_window(handle, |_, window, cx| {
4186 composer.update(cx, |composer, cx| {
4187 composer.set_conversation("bob-chat", "Bob", window, cx);
4188 composer.add_paths(vec![png, pdf], window, cx);
4189 });
4190 })
4191 .unwrap();
4192 cx.run_until_parked();
4193 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
4194 cx.update_window(handle, |_, window, cx| {
4195 composer.update(cx, |composer, cx| {
4196 composer.carry_images_into(String::new());
4197 composer.set_conversation("", "", window, cx);
4198 });
4199 })
4200 .unwrap();
4201 cx.update(|cx| {
4202 let composer = composer.read(cx);
4203 assert_eq!(composer.tray.items().len(), 1);
4204 assert_eq!(composer.tray.items()[0].name, "dot.png");
4205 assert!(!composer.files_allowed());
4206 });
4207 }
4208 }
4209}