BlueGit

ict rusty-teams

Files

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

composer.rs

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