BlueGit

ict rusty-teams

Files

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

composer.rs

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