BlueGit

ict rusty-teams

Files

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

composer.rs

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