BlueGit

ict rusty-teams

Files

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

composer.rs

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