BlueGit

ict rusty-teams

Files

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

composer.rs

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