BlueGit

ict rusty-teams

Files

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

composer.rs

composer.rs 153.0 KiB Download Raw
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
3use std::ops::Range;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8
9use chrono::{DateTime, Utc};
10use gpui_kit::assets::IconName;
11use gpui_kit::component::{
12 ActiveTheme as _, 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::popup_hover())
2160 })
2161 .hover(|row| row.bg(theme::popup_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 .bg(theme::popup())
2202 .occlude()
2203 .children(rows)
2204 .into_any_element(),
2205 )
2206 }
2207
2208 fn render_emoji_popup(
2209 &self,
2210 window: &mut Window,
2211 cx: &mut Context<Self>,
2212 ) -> Option<AnyElement> {
2213 let popup = self.emoji_popup.as_ref()?;
2214 let colon = popup.range.start..popup.range.start + 1;
2215 let anchor = self
2216 .input
2217 .read(cx)
2218 .range_to_bounds(&colon)
2219 .map(|bounds| bounds.origin);
2220 if anchor.is_none() {
2221 window.request_animation_frame();
2222 }
2223 let composer = cx.entity().downgrade();
2224 Some(emoji_popup::render(
2225 popup,
2226 anchor,
2227 move |index, window, cx| {
2228 composer
2229 .update(cx, |this, cx| {
2230 if let Some(popup) = this.emoji_popup.as_mut() {
2231 popup.highlighted = index;
2232 }
2233 this.accept_emoji(window, cx);
2234 })
2235 .ok();
2236 },
2237 ))
2238 }
2239
2240 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2241 let composer = cx.entity().downgrade();
2242 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
2243 return None;
2244 }
2245 let state = self.input.read(cx);
2246 let range = self
2247 .link_editor
2248 .as_ref()
2249 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
2250 let start = state.range_to_bounds(&(range.start..range.start))?;
2251 let end = state.range_to_bounds(&(range.end..range.end))?;
2252 let input_bounds = state.input_bounds();
2253 let center_x = if start.origin.y == end.origin.y {
2254 (start.origin.x + end.origin.x) / 2.
2255 } else {
2256 input_bounds.center().x
2257 };
2258 let edges = self
2259 .composer_bounds
2260 .get()
2261 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
2262 (bounds.left(), bounds.right())
2263 });
2264 let width = match self.link_editor {
2265 Some(_) => format_toolbar::link_width(),
2266 None => format_toolbar::bar_width(),
2267 };
2268 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
2269 let element = match &self.link_editor {
2270 Some(editor) => format_toolbar::render(
2271 placement,
2272 format_toolbar::Mode::Link {
2273 field: &editor.field,
2274 refused: editor.refused,
2275 on_apply: Rc::new(move |window, cx| {
2276 composer
2277 .update(cx, |this, cx| this.apply_link(window, cx))
2278 .ok();
2279 }),
2280 },
2281 ),
2282 None => {
2283 let state_of = |button| self.format_state(button, &range);
2284 format_toolbar::render(
2285 placement,
2286 format_toolbar::Mode::Bar {
2287 state: &state_of,
2288 on_press: Rc::new(move |button, window, cx| {
2289 composer
2290 .update(cx, |this, cx| this.press_format(button, window, cx))
2291 .ok();
2292 }),
2293 },
2294 )
2295 }
2296 };
2297 Some(element)
2298 }
2299
2300 fn render_paste_hint(&self) -> Option<Div> {
2301 self.paste_hint.as_ref()?;
2302 Some(
2303 h_flex()
2304 .mt(px(6.))
2305 .gap(px(6.))
2306 .items_center()
2307 .text_size(px(12.))
2308 .text_color(theme::text_muted())
2309 .child("Formatted from Markdown")
2310 .child(
2311 div()
2312 .px(px(5.))
2313 .py(px(1.))
2314 .rounded(px(4.))
2315 .border_1()
2316 .border_color(theme::border_strong())
2317 .bg(theme::surface_raised())
2318 .text_size(px(11.))
2319 .text_color(theme::text())
2320 .child("Ctrl+Z"),
2321 )
2322 .child("plain text"),
2323 )
2324 }
2325
2326 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2327 let edit = self.editing.as_ref()?;
2328 Some(
2329 h_flex()
2330 .w_full()
2331 .mb(px(6.))
2332 .gap(px(10.))
2333 .items_center()
2334 .pl(px(10.))
2335 .pr(px(4.))
2336 .py(px(6.))
2337 .rounded(px(8.))
2338 .bg(theme::surface())
2339 .border_1()
2340 .border_color(theme::border())
2341 .child(match edit.scheduled {
2342 Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2343 None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2344 })
2345 .child(
2346 v_flex()
2347 .flex_1()
2348 .min_w_0()
2349 .child(
2350 div()
2351 .truncate()
2352 .text_size(px(12.))
2353 .font_weight(FontWeight::SEMIBOLD)
2354 .text_color(theme::accent_text())
2355 .child(match edit.scheduled {
2356 Some(send_at) => format!(
2357 "Editing scheduled message - {}",
2358 scheduled_label(send_at, Utc::now())
2359 ),
2360 None => "Editing message".to_owned(),
2361 }),
2362 )
2363 .child(
2364 div()
2365 .truncate()
2366 .text_size(px(12.))
2367 .text_color(theme::text_muted())
2368 .child(edit.excerpt.clone()),
2369 ),
2370 )
2371 .child(
2372 div()
2373 .id("edit-close")
2374 .size(px(24.))
2375 .flex()
2376 .items_center()
2377 .justify_center()
2378 .rounded(px(6.))
2379 .cursor_pointer()
2380 .hover(|button| button.bg(theme::row_hover()))
2381 .child(icon(IconName::Close, 14., theme::text_muted()))
2382 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
2383 ),
2384 )
2385 }
2386
2387 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2388 let reply = self.reply.as_ref()?;
2389 Some(
2390 h_flex()
2391 .w_full()
2392 .mb(px(6.))
2393 .gap(px(10.))
2394 .items_center()
2395 .pl(px(10.))
2396 .pr(px(4.))
2397 .py(px(6.))
2398 .rounded(px(8.))
2399 .bg(theme::surface())
2400 .border_1()
2401 .border_color(theme::border())
2402 .child(icon(IconName::Undo2, 14., theme::accent_text()))
2403 .child(
2404 v_flex()
2405 .flex_1()
2406 .min_w_0()
2407 .child(
2408 div()
2409 .truncate()
2410 .text_size(px(12.))
2411 .font_weight(FontWeight::SEMIBOLD)
2412 .text_color(theme::accent_text())
2413 .child(format!("Replying to {}", reply.author)),
2414 )
2415 .child(
2416 div()
2417 .truncate()
2418 .text_size(px(12.))
2419 .text_color(theme::text_muted())
2420 .child(reply.excerpt.clone()),
2421 ),
2422 )
2423 .child(
2424 div()
2425 .id("reply-close")
2426 .size(px(24.))
2427 .flex()
2428 .items_center()
2429 .justify_center()
2430 .rounded(px(6.))
2431 .cursor_pointer()
2432 .hover(|button| button.bg(theme::row_hover()))
2433 .child(icon(IconName::Close, 14., theme::text_muted()))
2434 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
2435 ),
2436 )
2437 }
2438}
2439
2440impl Render for Composer {
2441 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2442 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
2443 let can_send = self.can_send(cx);
2444 let can_attach = self.editing.is_none();
2445 let send = div()
2446 .id("composer-send")
2447 .size(px(32.))
2448 .flex_none()
2449 .flex()
2450 .items_center()
2451 .justify_center()
2452 .rounded(px(8.))
2453 .child(symbol("keyboard_return", 20., white()))
2454 .on_mouse_down(
2455 MouseButton::Right,
2456 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
2457 )
2458 .when(!can_send, |button| button.opacity(0.4))
2459 .when(can_send, |button| {
2460 button
2461 .cursor_pointer()
2462 .hover(|button| button.bg(white().opacity(0.1)))
2463 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2464 });
2465 let fun = can_attach.then(|| {
2466 let picker = self.fun_picker.clone();
2467 let reset_picker = self.fun_picker.clone();
2468 Popover::new("composer-fun-popover")
2469 .anchor(Anchor::BottomLeft)
2470 .offset(px(10.))
2471 .p_0()
2472 .trigger(
2473 Button::new("composer-fun")
2474 .ghost()
2475 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2476 .size(px(32.))
2477 .tooltip("Emoji, GIFs und Sticker")
2478 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2479 )
2480 .on_open_change(move |open, window, cx| {
2481 if *open {
2482 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
2483 }
2484 })
2485 .content(move |_, _, cx| {
2486 let popover = cx.entity().downgrade();
2487 picker.update(cx, |picker, _| picker.set_popover(popover));
2488 picker.clone()
2489 })
2490 });
2491 let attach = can_attach.then(|| {
2492 div()
2493 .id("composer-attach")
2494 .size(px(32.))
2495 .flex_none()
2496 .flex()
2497 .items_center()
2498 .justify_center()
2499 .rounded(px(8.))
2500 .cursor_pointer()
2501 .hover(|button| button.bg(theme::row_hover()))
2502 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2503 .child(symbol("attach_file", COMPOSER_ICON_SIZE, theme::text_muted()))
2504 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2505 });
2506 let composer = cx.weak_entity();
2507 let tokens_composer = composer.clone();
2508 let input = Textarea::new(&self.input)
2509 .appearance(false)
2510 .bordered(false)
2511 .on_paste(move |item, window, cx| {
2512 composer
2513 .update(cx, |this, cx| this.paste(item, window, cx))
2514 .unwrap_or(false)
2515 })
2516 .token(move |context, _, cx| {
2517 if let Some(id) = context
2518 .is_block()
2519 .then(|| image_id(context.token()))
2520 .flatten()
2521 {
2522 let preview = tokens_composer
2523 .read_with(cx, |this, _| this.tray.image(id))
2524 .ok()
2525 .flatten();
2526 let remove_composer = tokens_composer.clone();
2527 return inline_preview(
2528 id,
2529 preview,
2530 context.available_width(),
2531 context.is_selected(),
2532 Rc::new(move |window, cx| {
2533 remove_composer
2534 .update(cx, |this, cx| this.remove_image_token(id, window, cx))
2535 .ok();
2536 }),
2537 );
2538 }
2539 div()
2540 .h(context.line_height())
2541 .px(px(5.))
2542 .rounded(px(5.))
2543 .bg(if context.is_selected() {
2544 theme::accent().opacity(0.4)
2545 } else {
2546 theme::mention_background(false)
2547 })
2548 .text_color(theme::mention_text())
2549 .font_weight(FontWeight::SEMIBOLD)
2550 .child(context.token().label().clone())
2551 .into_any_element()
2552 });
2553 let tray = can_attach
2554 .then(|| {
2555 render_tray(
2556 &self.tray,
2557 Self::remove_attachment,
2558 Self::retry_attachment,
2559 cx,
2560 )
2561 })
2562 .flatten();
2563 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
2564 div()
2565 .w_full()
2566 .mb(px(6.))
2567 .text_size(px(12.))
2568 .text_color(theme::amber())
2569 .child(notice.to_owned())
2570 });
2571 let composer_bounds = self.composer_bounds.clone();
2572 let (inset, top, bottom) = if self.inline {
2573 (0., 0., 0.)
2574 } else {
2575 (24., 8., 12.)
2576 };
2577 v_flex()
2578 .w_full()
2579 .flex_none()
2580 .px(px(inset))
2581 .pt(px(top))
2582 .pb(px(bottom))
2583 .key_context(KEY_CONTEXT)
2584 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2585 if this.link_editor.is_none() {
2586 this.toggle_mark(MarkKind::Bold, cx);
2587 }
2588 }))
2589 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2590 if this.link_editor.is_none() {
2591 this.toggle_mark(MarkKind::Italic, cx);
2592 }
2593 }))
2594 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2595 if this.link_editor.is_none() {
2596 this.toggle_mark(MarkKind::Underline, cx);
2597 }
2598 }))
2599 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2600 if this.link_editor.is_none() {
2601 this.toggle_mark(MarkKind::Strike, cx);
2602 }
2603 }))
2604 .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2605 if this.link_editor.is_none() {
2606 this.toggle_mark(MarkKind::Superscript, cx);
2607 }
2608 }))
2609 .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2610 if this.link_editor.is_none() {
2611 this.toggle_mark(MarkKind::Subscript, cx);
2612 }
2613 }))
2614 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2615 if this.link_editor.is_none() {
2616 this.toggle_mark(MarkKind::Code, cx);
2617 }
2618 }))
2619 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2620 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2621 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2622 if this.link_editor.is_none() {
2623 this.step_history(true, window, cx);
2624 cx.stop_propagation();
2625 }
2626 }))
2627 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
2628 if this.link_editor.is_none() {
2629 this.step_history(false, window, cx);
2630 cx.stop_propagation();
2631 }
2632 }))
2633 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2634 if this.link_editor.is_none() && this.copy_selection(cx) {
2635 cx.stop_propagation();
2636 }
2637 }))
2638 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2639 if this.link_editor.is_none() && this.copy_selection(cx) {
2640 this.input
2641 .update(cx, |state, cx| state.replace("", window, cx));
2642 cx.stop_propagation();
2643 }
2644 }))
2645 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2646 if this.link_editor.is_some() {
2647 } else if this.schedule.is_some() {
2648 this.move_schedule_highlight(-1, window, cx);
2649 cx.stop_propagation();
2650 } else if this.popup_is_open() {
2651 this.move_highlight(-1, cx);
2652 cx.stop_propagation();
2653 } else if this.editing.is_none() && this.is_empty(cx) {
2654 cx.emit(ComposerEvent::EditLast);
2655 cx.stop_propagation();
2656 }
2657 }))
2658 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2659 if this.link_editor.is_some() {
2660 } else if this.schedule.is_some() {
2661 this.move_schedule_highlight(1, window, cx);
2662 cx.stop_propagation();
2663 } else if this.popup_is_open() {
2664 this.move_highlight(1, cx);
2665 cx.stop_propagation();
2666 }
2667 }))
2668 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2669 if this.link_editor.is_some() {
2670 this.apply_link(window, cx);
2671 cx.stop_propagation();
2672 } else if this.schedule.is_some() {
2673 this.activate_schedule_row(window, cx);
2674 cx.stop_propagation();
2675 } else if this.popup_is_open() {
2676 this.accept_popup(window, cx);
2677 cx.stop_propagation();
2678 } else if this.break_line(action.shift, window, cx) {
2679 cx.stop_propagation();
2680 }
2681 }))
2682 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2683 if this.link_editor.is_some() {
2684 } else if this.popup_is_open() {
2685 this.accept_popup(window, cx);
2686 cx.stop_propagation();
2687 } else if this.indent(false, window, cx) {
2688 cx.stop_propagation();
2689 }
2690 }))
2691 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2692 if this.link_editor.is_none() && this.indent(true, window, cx) {
2693 cx.stop_propagation();
2694 }
2695 }))
2696 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2697 if this.link_editor.is_none()
2698 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2699 {
2700 cx.stop_propagation();
2701 }
2702 }))
2703 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2704 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2705 cx.stop_propagation();
2706 }
2707 }))
2708 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2709 if this.schedule.is_some() {
2710 this.close_schedule(window, cx);
2711 cx.stop_propagation();
2712 return;
2713 }
2714 if this.link_editor.is_some() {
2715 this.close_link_editor(window, cx);
2716 cx.stop_propagation();
2717 return;
2718 }
2719 if this.toolbar_requested(cx) {
2720 this.toolbar_dismissed = Some(this.selection(cx));
2721 cx.notify();
2722 cx.stop_propagation();
2723 return;
2724 }
2725 if let Some(popup) = &this.emoji_popup {
2726 this.emoji_dismissed_at = Some(popup.range.start);
2727 }
2728 if this.popup.is_some() || this.emoji_popup.is_some() {
2729 this.close_popup();
2730 cx.notify();
2731 cx.stop_propagation();
2732 } else if this.editing.is_some() {
2733 this.cancel_edit(window, cx);
2734 cx.stop_propagation();
2735 }
2736 }))
2737 .children(notice)
2738 .children(self.render_reply_strip(cx))
2739 .children(self.render_edit_strip(cx))
2740 .children(self.render_meeting_chip())
2741 .children(self.render_link_preview(cx))
2742 .child(
2743 div()
2744 .relative()
2745 .w_full()
2746 .children(self.render_popup(cx))
2747 .children(self.render_emoji_popup(window, cx))
2748 .children(self.render_toolbar(focused, cx))
2749 .children(self.render_schedule(cx))
2750 .child(
2751 v_flex()
2752 .relative()
2753 .w_full()
2754 .rounded(px(12.))
2755 .bg(theme::surface_raised())
2756 .border_1()
2757 .border_color(if focused {
2758 theme::accent()
2759 } else {
2760 transparent_black()
2761 })
2762 .child(
2763 canvas(
2764 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2765 |_, _, _, _| {},
2766 )
2767 .absolute()
2768 .size_full(),
2769 )
2770 .children(tray)
2771 .child(
2772 h_flex()
2773 .w_full()
2774 .items_end()
2775 .gap(px(6.))
2776 .py(px(6.))
2777 .pl(px(if can_attach { 6. } else { 12. }))
2778 .pr(px(6.))
2779 .children(fun)
2780 .children(attach)
2781 .child(
2782 div()
2783 .flex_1()
2784 .min_w_0()
2785 .capture_any_mouse_down(cx.listener(
2786 |this, _: &MouseDownEvent, _, _| {
2787 this.mouse_selecting = true;
2788 this.toolbar_dismissed = None;
2789 this.link_editor = None;
2790 },
2791 ))
2792 .capture_any_mouse_up(cx.listener(
2793 |this, _: &MouseUpEvent, _, cx| {
2794 this.mouse_selecting = false;
2795 cx.notify();
2796 },
2797 ))
2798 .on_mouse_up_out(
2799 MouseButton::Left,
2800 cx.listener(|this, _, _, cx| {
2801 this.mouse_selecting = false;
2802 cx.notify();
2803 }),
2804 )
2805 .child(input),
2806 )
2807 .child(send),
2808 ),
2809 ),
2810 )
2811 .children(self.render_paste_hint())
2812 }
2813}
2814
2815#[cfg(test)]
2816mod tests {
2817 use super::{active_mention, submitted_text};
2818 use gpui_kit::component::input::InputEvent;
2819
2820 fn press(shift: bool) -> InputEvent {
2821 InputEvent::PressEnter {
2822 secondary: false,
2823 shift,
2824 }
2825 }
2826
2827 #[test]
2828 fn enter_sends_trimmed_text() {
2829 assert_eq!(
2830 submitted_text(&press(false), " hello \n"),
2831 Some("hello".into())
2832 );
2833 }
2834
2835 #[test]
2836 fn shift_enter_never_sends() {
2837 assert_eq!(submitted_text(&press(true), "hello"), None);
2838 }
2839
2840 #[test]
2841 fn blank_text_never_sends() {
2842 assert_eq!(submitted_text(&press(false), " \n "), None);
2843 }
2844
2845 #[test]
2846 fn other_events_never_send() {
2847 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
2848 }
2849
2850 #[test]
2851 fn at_sign_opens_a_mention_query() {
2852 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
2853 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
2854 }
2855
2856 #[test]
2857 fn names_with_a_space_keep_the_query_open() {
2858 assert_eq!(
2859 active_mention("@Mara Lin", 9, &[]),
2860 Some((0..9, "Mara Lin".into()))
2861 );
2862 }
2863
2864 #[test]
2865 fn mail_addresses_and_closed_queries_do_not_open() {
2866 assert_eq!(active_mention("a@b", 3, &[]), None);
2867 assert_eq!(active_mention("@Mara ", 6, &[]), None);
2868 assert_eq!(active_mention("@ x", 3, &[]), None);
2869 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
2870 }
2871
2872 #[test]
2873 fn text_inside_a_token_does_not_reopen() {
2874 let token = 0..15;
2875 assert_eq!(
2876 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
2877 None
2878 );
2879 assert_eq!(
2880 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
2881 Some((16..19, "Pr".into()))
2882 );
2883 }
2884
2885 #[test]
2886 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
2887 use std::sync::Arc;
2888
2889 use gpui_kit::{Image, ImageFormat};
2890 use teams_core::FileKind;
2891
2892 use super::super::attachment_tray::InlineImage;
2893 use super::{Outgoing, OutgoingFile, OutgoingImage};
2894
2895 let outgoing = Outgoing {
2896 draft: teams_core::Draft::default(),
2897 subject: None,
2898 mentions: Vec::new(),
2899 link_preview: None,
2900 reply: None,
2901 edit: None,
2902 images: vec![OutgoingImage::Inline(InlineImage {
2903 name: "pasted-image.png".into(),
2904 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2905 dimensions: Some((1, 1)),
2906 })],
2907 files: vec![OutgoingFile {
2908 name: "plan.pdf".into(),
2909 size: 9,
2910 kind: FileKind::Pdf,
2911 uploaded: None,
2912 reference: teams_core::FileReference {
2913 attachment_id: "guid".into(),
2914 content_url: "https://files.example/plan.pdf".into(),
2915 name: "plan.pdf".into(),
2916 },
2917 }],
2918 };
2919 let extras = outgoing.extras();
2920 assert_eq!(extras.images[0].content_type, "image/png");
2921 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
2922 assert_eq!(extras.files[0].attachment_id, "guid");
2923 assert!(outgoing.has_attachments());
2924 }
2925
2926 fn placed_image(width: u32) -> super::OutgoingImage {
2927 use std::sync::Arc;
2928
2929 use gpui_kit::{Image, ImageFormat};
2930
2931 super::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
2932 name: "pasted-image.png".into(),
2933 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2934 dimensions: Some((width, width)),
2935 })
2936 }
2937
2938 fn remote_gif(title: &str) -> super::OutgoingImage {
2939 super::OutgoingImage::Remote(super::RemoteImage {
2940 kind: crate::remote_image::RemoteKind::Gif,
2941 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
2942 title: title.into(),
2943 width: 200,
2944 height: 100,
2945 })
2946 }
2947
2948 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2949 super::Outgoing {
2950 draft: teams_core::Draft::plain(text),
2951 subject: None,
2952 mentions: Vec::new(),
2953 link_preview: None,
2954 reply: None,
2955 edit: None,
2956 images,
2957 files: Vec::new(),
2958 }
2959 }
2960
2961 #[test]
2962 fn an_image_is_placed_in_the_html_where_its_mark_sits() {
2963 let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
2964 assert_eq!(
2965 outgoing.html(),
2966 "a <img src=\"../hostedContents/1/$value\"> b"
2967 );
2968 assert_eq!(outgoing.text(), "a b");
2969 }
2970
2971 #[test]
2972 fn images_keep_the_order_of_their_marks() {
2973 let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
2974 assert_eq!(
2975 outgoing.html(),
2976 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
2977 );
2978 }
2979
2980 #[test]
2981 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
2982 let outgoing = outgoing_with(
2983 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
2984 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
2985 );
2986 assert_eq!(
2987 outgoing.html(),
2988 "<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\">"
2989 );
2990 assert_eq!(outgoing.extras().images.len(), 2);
2991 }
2992
2993 #[test]
2994 fn a_gif_title_is_escaped_in_the_html() {
2995 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
2996 assert!(outgoing.html().contains("alt=\"a &quot;b&quot; &lt;c&gt;\""));
2997 }
2998
2999 #[test]
3000 fn a_sticker_carries_the_sticker_itemtype() {
3001 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3002 let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
3003 assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
3004 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
3005 }
3006
3007 #[test]
3008 fn a_mark_without_an_image_leaves_no_trace() {
3009 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
3010 }
3011
3012 #[test]
3013 fn enter_sends_attachments_even_without_text() {
3014 assert!(super::is_plain_enter(&press(false)));
3015 assert!(!super::is_plain_enter(&press(true)));
3016 assert!(!super::is_plain_enter(&InputEvent::Change));
3017 }
3018
3019 mod keys {
3020 use std::sync::Arc;
3021
3022 use gpui_kit::test::TestWindowExt as _;
3023 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3024 use store::Store;
3025
3026 use super::super::Composer;
3027 use crate::app_state::{AppState, Mode};
3028
3029 #[gpui_kit::test]
3030 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
3031 cx.update(gpui_kit::init);
3032 let store = Arc::new(Store::open_in_memory().unwrap());
3033 let mode = Mode {
3034 demo: true,
3035 read_only: false,
3036 demo_sync: None,
3037 };
3038 let (handle, composer) = cx.update(|cx| {
3039 let app = cx.new(|_| AppState::new(store, mode));
3040 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3041 cx.new(|cx| Composer::new(app, window, cx))
3042 })
3043 .unwrap()
3044 });
3045 let value = cx
3046 .update_window(handle, |_, window, cx| {
3047 composer.update(cx, |composer, cx| composer.focus(window, cx));
3048 window.render_frame(cx);
3049 window.input("first line", cx);
3050 window.press("shift-enter", cx);
3051 window.input("second line", cx);
3052 window.press("ctrl-a", cx);
3053 window.input("X", cx);
3054 composer.read(cx).input.read(cx).value()
3055 })
3056 .unwrap();
3057 assert_eq!(value, "X");
3058 }
3059
3060 struct Typist<'a> {
3061 cx: &'a mut TestAppContext,
3062 handle: gpui_kit::AnyWindowHandle,
3063 composer: gpui_kit::Entity<Composer>,
3064 }
3065
3066 impl Typist<'_> {
3067 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
3068 self.cx
3069 .update_window(self.handle, |_, window, cx| action(window, cx))
3070 .unwrap();
3071 self.cx.run_until_parked();
3072 }
3073
3074 fn type_text(&mut self, text: &str) {
3075 for character in text.chars() {
3076 self.act(|window, cx| window.input(&character.to_string(), cx));
3077 }
3078 }
3079
3080 fn press(&mut self, keys: &str) {
3081 for key in keys.split(' ') {
3082 self.act(|window, cx| window.press(key, cx));
3083 }
3084 }
3085
3086 fn value(&mut self) -> String {
3087 let composer = self.composer.clone();
3088 self.cx
3089 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
3090 }
3091
3092 fn draft(&mut self) -> teams_core::Draft {
3093 let composer = self.composer.clone();
3094 self.cx.update(|cx| composer.read(cx).draft.clone())
3095 }
3096
3097 fn outgoing(&mut self) -> super::super::Outgoing {
3098 let composer = self.composer.clone();
3099 self.cx
3100 .update(|cx| composer.read(cx).outgoing(cx))
3101 .expect("text to send")
3102 }
3103 }
3104
3105 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
3106 let (handle, composer) = demo_composer(cx);
3107 cx.update(super::super::bind_keys);
3108 let mut typist = Typist {
3109 cx,
3110 handle,
3111 composer: composer.clone(),
3112 };
3113 typist.act(|window, cx| {
3114 composer.update(cx, |composer, cx| composer.focus(window, cx));
3115 window.render_frame(cx);
3116 });
3117 typist
3118 }
3119
3120 fn png_bytes(side: u32) -> Vec<u8> {
3121 let mut bytes = Vec::new();
3122 image::RgbaImage::new(side, side)
3123 .write_to(
3124 &mut std::io::Cursor::new(&mut bytes),
3125 image::ImageFormat::Png,
3126 )
3127 .unwrap();
3128 bytes
3129 }
3130
3131 fn paste_image(typist: &mut Typist<'_>, side: u32) {
3132 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3133 entries: vec![gpui_kit::ClipboardEntry::Image(
3134 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
3135 )],
3136 });
3137 typist.press("ctrl-v");
3138 }
3139
3140 fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
3141 let composer = typist.composer.clone();
3142 typist.cx.update(|cx| {
3143 composer
3144 .read(cx)
3145 .input
3146 .read(cx)
3147 .tokens()
3148 .iter()
3149 .map(|span| (span.range(), span.token().is_block()))
3150 .collect()
3151 })
3152 }
3153
3154 #[gpui_kit::test]
3155 fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
3156 let mut typist = typist(cx);
3157 typist.type_text("ab");
3158 typist.press("left");
3159 paste_image(&mut typist, 2);
3160 assert_eq!(typist.value(), "a\u{FFFC}b");
3161 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3162 let outgoing = typist.outgoing();
3163 assert_eq!(outgoing.images.len(), 1);
3164 assert_eq!(
3165 outgoing.html(),
3166 "a<img src=\"../hostedContents/1/$value\">b"
3167 );
3168 let composer = typist.composer.clone();
3169 assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
3170 }
3171
3172 fn wide_png_bytes() -> Vec<u8> {
3173 let mut bytes = Vec::new();
3174 image::RgbaImage::new(600, 300)
3175 .write_to(
3176 &mut std::io::Cursor::new(&mut bytes),
3177 image::ImageFormat::Png,
3178 )
3179 .unwrap();
3180 bytes
3181 }
3182
3183 fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
3184 let composer = typist.composer.clone();
3185 typist.cx.update(|cx| {
3186 let state = composer.read(cx).input.read(cx);
3187 let cursor = state.cursor();
3188 let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
3189 let viewport = state.input_bounds();
3190 caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
3191 })
3192 }
3193
3194 #[gpui_kit::test]
3195 fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
3196 let mut typist = typist(cx);
3197 typist.type_text("look at this ");
3198 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3199 entries: vec![gpui_kit::ClipboardEntry::Image(
3200 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
3201 )],
3202 });
3203 typist.press("ctrl-v");
3204 typist.act(|window, _| window.refresh());
3205 typist.type_text("and then more text");
3206 typist.act(|window, _| window.refresh());
3207 assert!(caret_is_visible(&mut typist));
3208 }
3209
3210 #[gpui_kit::test]
3211 fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
3212 let mut typist = typist(cx);
3213 typist.type_text("ab");
3214 typist.press("left");
3215 paste_image(&mut typist, 2);
3216 typist.press("backspace");
3217 assert_eq!(typist.value(), "ab");
3218 assert!(image_tokens(&mut typist).is_empty());
3219 let outgoing = typist.outgoing();
3220 assert!(outgoing.images.is_empty());
3221 assert_eq!(outgoing.html(), "ab");
3222 typist.press("ctrl-z");
3223 assert_eq!(typist.value(), "a\u{FFFC}b");
3224 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3225 assert_eq!(typist.outgoing().images.len(), 1);
3226 }
3227
3228 #[gpui_kit::test]
3229 fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
3230 let mut typist = typist(cx);
3231 typist.type_text("ab");
3232 paste_image(&mut typist, 2);
3233 typist.type_text("cd");
3234 let composer = typist.composer.clone();
3235 let id = typist.cx.update(|cx| {
3236 let state = composer.read(cx).input.read(cx);
3237 super::super::image_id(state.tokens()[0].token()).unwrap()
3238 });
3239 typist.act(|window, cx| {
3240 composer.update(cx, |composer, cx| {
3241 composer.remove_image_token(id, window, cx)
3242 });
3243 });
3244 assert_eq!(typist.value(), "abcd");
3245 assert!(image_tokens(&mut typist).is_empty());
3246 assert!(typist.outgoing().images.is_empty());
3247 typist.press("ctrl-z");
3248 assert_eq!(typist.value(), "ab\u{FFFC}cd");
3249 assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
3250 assert_eq!(typist.outgoing().images.len(), 1);
3251 }
3252
3253 #[gpui_kit::test]
3254 fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
3255 let mut typist = typist(cx);
3256 typist.type_text("x");
3257 paste_image(&mut typist, 2);
3258 typist.type_text("y");
3259 typist.press("ctrl-home");
3260 paste_image(&mut typist, 4);
3261 assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
3262 let outgoing = typist.outgoing();
3263 let dimensions: Vec<_> = outgoing
3264 .images
3265 .iter()
3266 .map(|image| match image {
3267 super::super::OutgoingImage::Inline(inline) => inline.dimensions,
3268 super::super::OutgoingImage::Remote(_) => None,
3269 })
3270 .collect();
3271 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3272 assert_eq!(
3273 outgoing.html(),
3274 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
3275 );
3276 }
3277
3278 #[gpui_kit::test]
3279 fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
3280 let mut typist = typist(cx);
3281 paste_image(&mut typist, 2);
3282 let composer = typist.composer.clone();
3283 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3284 let outgoing = typist.outgoing();
3285 assert_eq!(outgoing.text(), "");
3286 assert_eq!(outgoing.images.len(), 1);
3287 typist.type_text("hi");
3288 typist.press("ctrl-a ctrl-c");
3289 let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
3290 assert_eq!(copied.as_deref(), Some("hi"));
3291 }
3292
3293 #[gpui_kit::test]
3294 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
3295 let mut typist = typist(cx);
3296 let composer = typist.composer.clone();
3297 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3298 typist.act(|window, cx| {
3299 composer.update(cx, |composer, cx| {
3300 composer.insert_remote_image(
3301 super::super::RemoteImage {
3302 kind: crate::remote_image::RemoteKind::Gif,
3303 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3304 title: "Wave".into(),
3305 width: 200,
3306 height: 100,
3307 },
3308 window,
3309 cx,
3310 )
3311 });
3312 });
3313 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3314 assert_eq!(typist.value(), "\u{FFFC}");
3315 let outgoing = typist.outgoing();
3316 assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3317 assert!(outgoing.extras().images.is_empty());
3318 typist.press("ctrl-z");
3319 assert_eq!(typist.value(), "");
3320 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3321 }
3322
3323 #[gpui_kit::test]
3324 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
3325 let mut typist = typist(cx);
3326 typist.type_text("ab");
3327 typist.press("left");
3328 let composer = typist.composer.clone();
3329 typist.act(|window, cx| {
3330 composer.update(cx, |composer, cx| {
3331 composer.insert_emoji("\u{1F44D}", window, cx)
3332 });
3333 });
3334 assert_eq!(typist.value(), "a\u{1F44D}b");
3335 }
3336
3337 #[gpui_kit::test]
3338 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3339 let mut typist = typist(cx);
3340 typist
3341 .cx
3342 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
3343 typist.press("ctrl-v");
3344 assert_eq!(typist.value(), "ab");
3345 }
3346
3347 #[gpui_kit::test]
3348 fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
3349 let mut typist = typist(cx);
3350 let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
3351 let composer = typist.composer.clone();
3352 typist.act(|window, cx| {
3353 composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
3354 });
3355 assert_eq!(typist.value(), "x\u{FFFC}y");
3356 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3357 let again = typist.outgoing();
3358 assert_eq!(again.images, outgoing.images);
3359 assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
3360 }
3361
3362 #[gpui_kit::test]
3363 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
3364 use teams_core::{FormatState, MarkKind};
3365
3366 let mut typist = typist(cx);
3367 typist.type_text("a **bold**");
3368 assert_eq!(typist.value(), "a bold");
3369 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
3370 typist.press("backspace");
3371 assert_eq!(typist.value(), "a **bold**");
3372 assert!(typist.draft().marks().is_empty());
3373 let composer = typist.composer.clone();
3374 assert_eq!(
3375 typist
3376 .cx
3377 .update(|cx| composer.read(cx).input.read(cx).cursor()),
3378 10
3379 );
3380 typist.press("backspace");
3381 typist.type_text("* x");
3382 assert_eq!(typist.value(), "a bold x");
3383 assert_eq!(
3384 typist.draft().state(6..8, &MarkKind::Bold),
3385 FormatState::Off
3386 );
3387 }
3388
3389 #[gpui_kit::test]
3390 fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
3391 use teams_core::{Mark, MarkKind};
3392
3393 let mut typist = typist(cx);
3394 typist.type_text("see https://a.b ");
3395 assert_eq!(typist.value(), "see https://a.b ");
3396 assert_eq!(
3397 typist.draft().marks(),
3398 [Mark {
3399 range: 4..15,
3400 kind: MarkKind::Link("https://a.b".into())
3401 }]
3402 );
3403 typist.press("backspace");
3404 assert_eq!(typist.value(), "see https://a.b ");
3405 assert!(typist.draft().marks().is_empty());
3406 }
3407
3408 #[gpui_kit::test]
3409 fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
3410 let mut typist = typist(cx);
3411 typist.type_text("https://a.b ");
3412 assert_eq!(typist.draft().marks().len(), 1);
3413 typist.press("ctrl-z");
3414 assert!(typist.draft().marks().is_empty());
3415 }
3416
3417 #[gpui_kit::test]
3418 fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3419 use teams_core::{Mark, MarkKind};
3420
3421 let mut typist = typist(cx);
3422 typist
3423 .cx
3424 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3425 "x https://a.b y".to_owned(),
3426 ));
3427 typist.press("ctrl-v");
3428 assert_eq!(typist.value(), "x https://a.b y");
3429 assert_eq!(
3430 typist.draft().marks(),
3431 [Mark {
3432 range: 2..13,
3433 kind: MarkKind::Link("https://a.b".into())
3434 }]
3435 );
3436 typist.press("ctrl-z");
3437 assert_eq!(typist.value(), "x https://a.b y");
3438 assert!(typist.draft().marks().is_empty());
3439 }
3440
3441 #[gpui_kit::test]
3442 fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
3443 use teams_core::{Mark, MarkKind};
3444
3445 let mut typist = typist(cx);
3446 typist.type_text("https://a.b x");
3447 typist.press("home");
3448 typist.press("shift-right ".repeat(11).trim_end());
3449 typist.press("ctrl-k");
3450 typist.type_text("other.de");
3451 typist.press("enter");
3452 assert_eq!(
3453 typist.draft().marks(),
3454 [Mark {
3455 range: 0..11,
3456 kind: MarkKind::Link("https://other.de".into())
3457 }]
3458 );
3459 typist.press("ctrl-k backspace enter");
3460 assert!(typist.draft().marks().is_empty());
3461 assert_eq!(typist.value(), "https://a.b x");
3462 }
3463
3464 #[gpui_kit::test]
3465 fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
3466 use teams_core::{Mark, MarkKind};
3467
3468 let mut typist = typist(cx);
3469 typist.type_text("- https://a.b");
3470 typist.press("enter");
3471 assert_eq!(typist.value(), "• https://a.b\n• ");
3472 assert_eq!(
3473 typist.draft().marks(),
3474 [Mark {
3475 range: 4..15,
3476 kind: MarkKind::Link("https://a.b".into())
3477 }]
3478 );
3479 }
3480
3481 #[gpui_kit::test]
3482 fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
3483 let mut typist = typist(cx);
3484 typist
3485 .cx
3486 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3487 "x https://a.b y".to_owned(),
3488 ));
3489 typist.press("ctrl-v");
3490 assert_eq!(typist.draft().marks().len(), 1);
3491 let composer = typist.composer.clone();
3492 assert!(
3493 typist
3494 .cx
3495 .update(|cx| composer.read(cx).paste_hint.is_none())
3496 );
3497 typist.press("ctrl-z");
3498 assert!(typist.draft().marks().is_empty());
3499 }
3500
3501 #[gpui_kit::test]
3502 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
3503 let mut typist = typist(cx);
3504 typist.type_text("1. one");
3505 typist.press("enter");
3506 typist.type_text("two");
3507 assert_eq!(typist.value(), "1. one\n2. two");
3508 typist.press("enter enter");
3509 assert_eq!(typist.value(), "1. one\n2. two\n");
3510 typist.type_text("after");
3511 typist.press("enter");
3512 assert_eq!(typist.value(), "");
3513 }
3514
3515 #[gpui_kit::test]
3516 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
3517 let mut typist = typist(cx);
3518 typist.type_text("- a");
3519 typist.press("enter tab");
3520 typist.type_text("b");
3521 assert_eq!(typist.value(), "• a\n◦ b");
3522 typist.press("shift-tab");
3523 assert_eq!(typist.value(), "• a\n• b");
3524 }
3525
3526 #[gpui_kit::test]
3527 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
3528 use teams_core::{FormatState, MarkKind};
3529
3530 let mut typist = typist(cx);
3531 typist.type_text("hello");
3532 typist.press("shift-left shift-left ctrl-b");
3533 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3534 assert_eq!(
3535 typist.draft().state(0..5, &MarkKind::Bold),
3536 FormatState::Mixed
3537 );
3538 typist.press("ctrl-b");
3539 assert!(typist.draft().marks().is_empty());
3540 typist.press("end ctrl-i");
3541 typist.type_text("!");
3542 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
3543 }
3544
3545 #[gpui_kit::test]
3546 fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {
3547 let mut typist = typist(cx);
3548 typist.type_text("x2");
3549 typist.press("shift-left ctrl-shift-=");
3550 assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");
3551 typist.press("ctrl-=");
3552 assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");
3553 }
3554
3555 #[gpui_kit::test]
3556 fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {
3557 use teams_core::FormatState;
3558
3559 use super::super::FormatButton;
3560
3561 let mut typist = typist(cx);
3562 typist.type_text("big small");
3563 typist.press("shift-left shift-left shift-left shift-left shift-left");
3564 let composer = typist.composer.clone();
3565 typist.act(|window, cx| {
3566 composer.update(cx, |composer, cx| {
3567 composer.press_format(FormatButton::SizeSmall, window, cx)
3568 })
3569 });
3570 let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {
3571 let composer = typist.composer.clone();
3572 typist.cx.update(|cx| {
3573 let composer = composer.read(cx);
3574 [
3575 FormatButton::SizeSmall,
3576 FormatButton::SizeNormal,
3577 FormatButton::SizeLarge,
3578 ]
3579 .map(|button| composer.format_state(button, &range))
3580 })
3581 };
3582 assert_eq!(
3583 states(&mut typist, 4..9),
3584 [FormatState::On, FormatState::Off, FormatState::Off]
3585 );
3586 assert_eq!(
3587 states(&mut typist, 0..9),
3588 [FormatState::Mixed, FormatState::Off, FormatState::Off]
3589 );
3590 assert_eq!(
3591 states(&mut typist, 0..3),
3592 [FormatState::Off, FormatState::On, FormatState::Off]
3593 );
3594 assert_eq!(
3595 typist.outgoing().html(),
3596 "big <span style=\"font-size:xx-small;\">small</span>"
3597 );
3598 }
3599
3600 #[gpui_kit::test]
3601 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3602 let mut typist = typist(cx);
3603 typist
3604 .cx
3605 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3606 "**hi** there".to_owned(),
3607 ));
3608 typist.press("ctrl-v");
3609 assert_eq!(typist.value(), "hi there");
3610 let composer = typist.composer.clone();
3611 assert!(
3612 typist
3613 .cx
3614 .update(|cx| composer.read(cx).paste_hint.is_some())
3615 );
3616 typist.press("ctrl-z");
3617 assert_eq!(typist.value(), "**hi** there");
3618 assert!(typist.draft().marks().is_empty());
3619 }
3620
3621 #[gpui_kit::test]
3622 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
3623 use teams_core::{FormatState, MarkKind};
3624
3625 let mut typist = typist(cx);
3626 typist.type_text("`code` ");
3627 typist.press("ctrl-a ctrl-c end ctrl-v");
3628 assert_eq!(typist.value(), "code code ");
3629 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
3630 }
3631
3632 #[gpui_kit::test]
3633 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
3634 use teams_core::{FormatState, MarkKind};
3635
3636 let mut typist = typist(cx);
3637 typist.type_text("~~old~~");
3638 typist.press("ctrl-a");
3639 typist.type_text("new");
3640 typist.press("ctrl-z ctrl-z");
3641 assert_eq!(typist.value(), "old");
3642 assert_eq!(
3643 typist.draft().state(0..3, &MarkKind::Strike),
3644 FormatState::On
3645 );
3646 }
3647
3648 #[gpui_kit::test]
3649 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
3650 let mut typist = typist(cx);
3651 typist.type_text("see docs");
3652 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
3653 let composer = typist.composer.clone();
3654 assert!(
3655 typist
3656 .cx
3657 .update(|cx| composer.read(cx).link_editor.is_some())
3658 );
3659 typist.type_text("example.com");
3660 typist.press("enter");
3661 assert!(
3662 typist
3663 .cx
3664 .update(|cx| composer.read(cx).link_editor.is_none())
3665 );
3666 assert_eq!(
3667 typist.outgoing().html(),
3668 "see <a href=\"https://example.com\">docs</a>"
3669 );
3670 }
3671
3672 #[gpui_kit::test]
3673 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
3674 use teams_core::{FormatState, MarkKind};
3675
3676 let mut typist = typist(cx);
3677 typist.type_text("hello");
3678 typist.press("shift-left shift-left ctrl-b");
3679 typist.press("ctrl-z");
3680 assert_eq!(typist.value(), "hello");
3681 assert!(typist.draft().marks().is_empty());
3682 typist.press("ctrl-y");
3683 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3684 }
3685
3686 #[gpui_kit::test]
3687 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
3688 use teams_core::{FormatState, MarkKind};
3689
3690 let mut typist = typist(cx);
3691 typist.type_text("hello");
3692 typist.press("shift-left shift-left ctrl-b end");
3693 typist.type_text(" x");
3694 typist.press("backspace backspace");
3695 assert_eq!(typist.value(), "hello");
3696 typist.press("ctrl-z");
3697 assert_ne!(typist.value(), "hello");
3698 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3699 }
3700
3701 #[gpui_kit::test]
3702 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
3703 let mut typist = typist(cx);
3704 typist.type_text("```");
3705 typist.press("enter");
3706 typist.type_text("a");
3707 typist.press("enter");
3708 typist.type_text("b");
3709 typist.press("up end delete");
3710 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
3711 }
3712
3713 #[gpui_kit::test]
3714 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
3715 let mut typist = typist(cx);
3716 typist.type_text("```");
3717 typist.press("enter");
3718 typist.type_text(" x");
3719 typist.press("ctrl-a ctrl-c");
3720 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
3721 assert_eq!(text.as_deref(), Some(" x"));
3722 }
3723
3724 #[gpui_kit::test]
3725 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
3726 let mut typist = typist(cx);
3727 typist.type_text("docs");
3728 typist.press("ctrl-a ctrl-k");
3729 typist.type_text("javascript:alert(1)");
3730 typist.press("enter");
3731 let composer = typist.composer.clone();
3732 assert!(typist.cx.update(|cx| {
3733 composer
3734 .read(cx)
3735 .link_editor
3736 .as_ref()
3737 .is_some_and(|editor| editor.refused)
3738 }));
3739 assert!(typist.draft().marks().is_empty());
3740 typist.type_text("x");
3741 assert!(typist.cx.update(|cx| {
3742 composer
3743 .read(cx)
3744 .link_editor
3745 .as_ref()
3746 .is_some_and(|editor| !editor.refused)
3747 }));
3748 }
3749
3750 #[gpui_kit::test]
3751 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
3752 use teams_core::{FormatState, LineKind, MarkKind};
3753
3754 let mut typist = typist(cx);
3755 typist.type_text("hello");
3756 typist.press("ctrl-a ctrl-b");
3757 let composer = typist.composer.clone();
3758 typist.act(|window, cx| {
3759 composer.update(cx, |composer, cx| {
3760 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
3761 })
3762 });
3763 assert_eq!(typist.value(), "• hello");
3764 typist.press("ctrl-z");
3765 assert_eq!(typist.value(), "hello");
3766 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3767 typist.press("ctrl-z");
3768 assert!(typist.draft().marks().is_empty());
3769 assert_eq!(typist.draft().lines(), [LineKind::Text]);
3770 }
3771
3772 #[gpui_kit::test]
3773 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
3774 use teams_core::{FormatState, MarkKind};
3775
3776 let mut typist = typist(cx);
3777 typist.type_text("hello");
3778 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
3779 assert_eq!(typist.value(), "");
3780 typist.press("ctrl-y");
3781 assert_eq!(typist.value(), "hello");
3782 assert!(typist.draft().marks().is_empty());
3783 typist.press("ctrl-y");
3784 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3785 }
3786
3787 fn cursor(typist: &mut Typist<'_>) -> usize {
3788 let composer = typist.composer.clone();
3789 typist
3790 .cx
3791 .update(|cx| composer.read(cx).input.read(cx).cursor())
3792 }
3793
3794 #[gpui_kit::test]
3795 fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there(
3796 cx: &mut TestAppContext,
3797 ) {
3798 let mut typist = typist(cx);
3799 typist.type_text("hello");
3800 typist.press("home");
3801 typist.type_text("X");
3802 typist.press("end ctrl-z");
3803 assert_eq!(typist.value(), "hello");
3804 assert_eq!(cursor(&mut typist), 0);
3805 typist.press("ctrl-y");
3806 assert_eq!(typist.value(), "Xhello");
3807 assert_eq!(cursor(&mut typist), 1);
3808 }
3809
3810 #[gpui_kit::test]
3811 fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) {
3812 let mut typist = typist(cx);
3813 for line in 0..14 {
3814 typist.type_text(&format!("line {line}"));
3815 typist.press("shift-enter");
3816 }
3817 typist.type_text("end");
3818 let composer = typist.composer.clone();
3819 let scroll = |typist: &mut Typist<'_>| {
3820 typist
3821 .cx
3822 .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y)
3823 };
3824 typist.act(|window, cx| window.render_frame(cx));
3825 let before = scroll(&mut typist);
3826 assert!(before < gpui_kit::px(0.));
3827 typist.press("ctrl-z");
3828 typist.act(|window, cx| window.render_frame(cx));
3829 assert_eq!(scroll(&mut typist), before);
3830 }
3831
3832 #[gpui_kit::test]
3833 fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) {
3834 let mut typist = typist(cx);
3835 typist.type_text("ok :) ");
3836 assert!(typist.value().contains('🙂'));
3837 typist.press("ctrl-z");
3838 assert_eq!(typist.value(), "ok :) ");
3839 assert_eq!(typist.outgoing().text(), "ok :)");
3840 }
3841
3842 #[gpui_kit::test]
3843 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
3844 let mut typist = typist(cx);
3845 typist.press("ctrl-z");
3846 typist.type_text("**a**");
3847 assert_eq!(typist.value(), "a");
3848 }
3849
3850 #[gpui_kit::test]
3851 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
3852 let mut typist = typist(cx);
3853 typist.type_text("```");
3854 typist.press("enter");
3855 typist.type_text(":) ");
3856 typist
3857 .cx
3858 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
3859 typist.press("ctrl-v");
3860 assert_eq!(typist.value(), ":) **x**");
3861 let composer = typist.composer.clone();
3862 assert!(
3863 typist
3864 .cx
3865 .update(|cx| composer.read(cx).paste_hint.is_none())
3866 );
3867 let outgoing = typist.outgoing();
3868 assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
3869 }
3870
3871 #[gpui_kit::test]
3872 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3873 let mut typist = typist(cx);
3874 typist.type_text("> quoted");
3875 typist.press("shift-enter");
3876 typist.type_text("more");
3877 let outgoing = typist.outgoing();
3878 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
3879 assert_eq!(outgoing.text(), "quoted\nmore");
3880 }
3881
3882 #[gpui_kit::test]
3883 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
3884 cx.update(gpui_kit::init);
3885 let store = Arc::new(Store::open_in_memory().unwrap());
3886 let mode = Mode {
3887 demo: true,
3888 read_only: false,
3889 demo_sync: None,
3890 };
3891 let (handle, composer) = cx.update(|cx| {
3892 let app = cx.new(|_| AppState::new(store, mode));
3893 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3894 cx.new(|cx| Composer::new(app, window, cx))
3895 })
3896 .unwrap()
3897 });
3898 let directory = tempfile::tempdir().unwrap();
3899 let path = directory.path().join("plan.pdf");
3900 std::fs::write(&path, b"%PDF-1.7").unwrap();
3901 cx.update_window(handle, |_, window, cx| {
3902 composer.update(cx, |composer, cx| {
3903 composer.set_conversation("demo-chat", "Demo", window, cx);
3904 composer.add_paths(vec![path], window, cx);
3905 });
3906 })
3907 .unwrap();
3908 cx.run_until_parked();
3909 cx.update(|cx| {
3910 let composer = composer.read(cx);
3911 assert!(composer.tray.blocks_send());
3912 assert!(!composer.can_send(cx));
3913 });
3914 cx.executor()
3915 .advance_clock(std::time::Duration::from_secs(3));
3916 cx.run_until_parked();
3917 cx.update(|cx| {
3918 let composer = composer.read(cx);
3919 assert!(composer.can_send(cx));
3920 let outgoing = composer
3921 .outgoing(cx)
3922 .expect("an attachment alone is a message");
3923 assert_eq!(outgoing.text(), "");
3924 assert_eq!(outgoing.files.len(), 1);
3925 assert_eq!(outgoing.files[0].name, "plan.pdf");
3926 });
3927 }
3928
3929 #[gpui_kit::test]
3930 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
3931 cx.update(gpui_kit::init);
3932 let store = Arc::new(Store::open_in_memory().unwrap());
3933 let mode = Mode {
3934 demo: true,
3935 read_only: false,
3936 demo_sync: None,
3937 };
3938 let (handle, composer) = cx.update(|cx| {
3939 let app = cx.new(|_| AppState::new(store, mode));
3940 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3941 cx.new(|cx| Composer::new(app, window, cx))
3942 })
3943 .unwrap()
3944 });
3945 let directory = tempfile::tempdir().unwrap();
3946 let path = directory.path().join("plan.pdf");
3947 std::fs::write(&path, b"%PDF-1.7").unwrap();
3948 cx.update_window(handle, |_, window, cx| {
3949 composer.update(cx, |composer, cx| {
3950 composer.set_conversation("demo-chat", "Demo", window, cx);
3951 composer.add_paths(vec![path], window, cx);
3952 });
3953 })
3954 .unwrap();
3955 cx.run_until_parked();
3956 cx.update_window(handle, |_, window, cx| {
3957 composer.update(cx, |composer, cx| {
3958 composer.set_conversation("other-chat", "Other", window, cx)
3959 });
3960 })
3961 .unwrap();
3962 cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));
3963 }
3964
3965 fn demo_composer(
3966 cx: &mut TestAppContext,
3967 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
3968 cx.update(gpui_kit::init);
3969 let store = Arc::new(Store::open_in_memory().unwrap());
3970 let mode = Mode {
3971 demo: true,
3972 read_only: false,
3973 demo_sync: None,
3974 };
3975 let (handle, composer) = cx.update(|cx| {
3976 let app = cx.new(|_| AppState::new(store, mode));
3977 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3978 cx.new(|cx| Composer::new(app, window, cx))
3979 })
3980 .unwrap()
3981 });
3982 (handle, composer)
3983 }
3984
3985 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
3986 let path = directory.join("dot.png");
3987 image::RgbaImage::new(2, 2).save(&path).unwrap();
3988 path
3989 }
3990
3991 #[gpui_kit::test]
3992 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
3993 use super::super::{EditPreview, Outgoing};
3994
3995 let (handle, composer) = demo_composer(cx);
3996 let directory = tempfile::tempdir().unwrap();
3997 let path = directory.path().join("plan.pdf");
3998 std::fs::write(&path, b"%PDF-1.7").unwrap();
3999 cx.update_window(handle, |_, window, cx| {
4000 composer.update(cx, |composer, cx| {
4001 composer.set_conversation("demo-chat", "Demo", window, cx);
4002 composer.add_paths(vec![path], window, cx);
4003 });
4004 })
4005 .unwrap();
4006 cx.run_until_parked();
4007 cx.executor()
4008 .advance_clock(std::time::Duration::from_secs(3));
4009 cx.run_until_parked();
4010 cx.update_window(handle, |_, window, cx| {
4011 composer.update(cx, |composer, cx| {
4012 let draft = Outgoing {
4013 draft: teams_core::Draft::plain("old"),
4014 subject: None,
4015 mentions: Vec::new(),
4016 link_preview: None,
4017 reply: None,
4018 edit: Some(EditPreview {
4019 message_id: "m1".into(),
4020 excerpt: "old".into(),
4021 scheduled: None,
4022 }),
4023 images: Vec::new(),
4024 files: Vec::new(),
4025 };
4026 composer.begin_edit(draft, window, cx);
4027 });
4028 })
4029 .unwrap();
4030 cx.update(|cx| {
4031 let composer = composer.read(cx);
4032 assert_eq!(composer.tray.items().len(), 1);
4033 let outgoing = composer.outgoing(cx).unwrap();
4034 assert!(outgoing.files.is_empty());
4035 assert_eq!(outgoing.text(), "old");
4036 });
4037 cx.update_window(handle, |_, window, cx| {
4038 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
4039 })
4040 .unwrap();
4041 cx.update(|cx| {
4042 let composer = composer.read(cx);
4043 assert_eq!(composer.tray.items().len(), 1);
4044 assert!(composer.can_send(cx));
4045 });
4046 }
4047
4048 #[gpui_kit::test]
4049 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
4050 let (handle, composer) = demo_composer(cx);
4051 let directory = tempfile::tempdir().unwrap();
4052 let path = small_png(directory.path());
4053 for (carry, chosen, expected) in [
4054 (Some("chat-a"), "chat-a", 1),
4055 (None, "chat-b", 0),
4056 (Some("chat-a"), "chat-b", 0),
4057 ] {
4058 cx.update_window(handle, |_, window, cx| {
4059 composer.update(cx, |composer, cx| {
4060 composer.set_conversation("", "", window, cx);
4061 composer.add_paths(vec![path.clone()], window, cx);
4062 });
4063 })
4064 .unwrap();
4065 cx.run_until_parked();
4066 cx.update_window(handle, |_, window, cx| {
4067 composer.update(cx, |composer, cx| {
4068 if let Some(chat) = carry {
4069 composer.carry_images_into(chat.to_owned());
4070 }
4071 composer.set_conversation(chosen, "Chat", window, cx);
4072 });
4073 })
4074 .unwrap();
4075 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
4076 }
4077 }
4078
4079 #[gpui_kit::test]
4080 fn each_conversation_keeps_its_own_draft(cx: &mut TestAppContext) {
4081 let (handle, composer) = demo_composer(cx);
4082 cx.update_window(handle, |_, window, cx| {
4083 composer.update(cx, |composer, cx| {
4084 composer.set_conversation("chat-a", "A", window, cx);
4085 composer.set_text("**hello** there", window, cx);
4086 composer.set_conversation("chat-b", "B", window, cx);
4087 });
4088 })
4089 .unwrap();
4090 cx.update(|cx| {
4091 let composer = composer.read(cx);
4092 assert!(composer.draft.is_blank());
4093 let stored = composer
4094 .app
4095 .read(cx)
4096 .store
4097 .draft("chat-a")
4098 .unwrap()
4099 .unwrap();
4100 assert_eq!(stored.preview, "hello there");
4101 });
4102 cx.update_window(handle, |_, window, cx| {
4103 composer.update(cx, |composer, cx| {
4104 composer.set_text("other", window, cx);
4105 composer.set_conversation("chat-a", "A", window, cx);
4106 });
4107 })
4108 .unwrap();
4109 cx.update(|cx| {
4110 let composer = composer.read(cx);
4111 assert_eq!(composer.draft.text(), "hello there");
4112 assert!(composer.draft.to_html().contains("<b>"));
4113 assert!(
4114 composer
4115 .app
4116 .read(cx)
4117 .store
4118 .draft("chat-b")
4119 .unwrap()
4120 .is_some()
4121 );
4122 });
4123 }
4124
4125 #[gpui_kit::test]
4126 fn sending_clears_the_stored_draft_and_a_blank_composer_deletes_it(
4127 cx: &mut TestAppContext,
4128 ) {
4129 let (handle, composer) = demo_composer(cx);
4130 cx.update_window(handle, |_, window, cx| {
4131 composer.update(cx, |composer, cx| {
4132 composer.set_conversation("chat-a", "A", window, cx);
4133 composer.set_text("hi", window, cx);
4134 composer.save_draft_now(cx);
4135 });
4136 })
4137 .unwrap();
4138 cx.update(|cx| {
4139 assert!(
4140 composer
4141 .read(cx)
4142 .app
4143 .read(cx)
4144 .store
4145 .draft("chat-a")
4146 .unwrap()
4147 .is_some()
4148 );
4149 });
4150 cx.update_window(handle, |_, window, cx| {
4151 composer.update(cx, |composer, cx| composer.submit_current(window, cx));
4152 })
4153 .unwrap();
4154 cx.update(|cx| {
4155 assert!(
4156 composer
4157 .read(cx)
4158 .app
4159 .read(cx)
4160 .store
4161 .draft("chat-a")
4162 .unwrap()
4163 .is_none()
4164 );
4165 });
4166 }
4167
4168 #[gpui_kit::test]
4169 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
4170 cx: &mut TestAppContext,
4171 ) {
4172 let (handle, composer) = demo_composer(cx);
4173 let directory = tempfile::tempdir().unwrap();
4174 let png = small_png(directory.path());
4175 let pdf = directory.path().join("plan.pdf");
4176 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
4177 cx.update_window(handle, |_, window, cx| {
4178 composer.update(cx, |composer, cx| {
4179 composer.set_conversation("bob-chat", "Bob", window, cx);
4180 composer.add_paths(vec![png, pdf], window, cx);
4181 });
4182 })
4183 .unwrap();
4184 cx.run_until_parked();
4185 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
4186 cx.update_window(handle, |_, window, cx| {
4187 composer.update(cx, |composer, cx| {
4188 composer.carry_images_into(String::new());
4189 composer.set_conversation("", "", window, cx);
4190 });
4191 })
4192 .unwrap();
4193 cx.update(|cx| {
4194 let composer = composer.read(cx);
4195 assert_eq!(composer.tray.items().len(), 1);
4196 assert_eq!(composer.tray.items()[0].name, "dot.png");
4197 assert!(!composer.files_allowed());
4198 });
4199 }
4200 }
4201}