BlueGit

ict rusty-teams

Files

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

composer.rs

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