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