BlueGit

ict rusty-teams

Files

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

composer.rs

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