BlueGit

ict rusty-teams

Files

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

composer.rs

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