BlueGit

ict rusty-teams

Files

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

composer.rs

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