BlueGit

ict rusty-teams

Files

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

composer.rs

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