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 self.recent_emoji.push(glyph);
1113 self.recent_emoji.save(&self.app.read(cx).store);
1114 }
1115
1116 fn update_emoji(&mut self, cx: &mut Context<Self>) {
1117 let state = self.input.read(cx);
1118 let found = emoji::active_query(&state.value(), state.cursor())
1119 .filter(|_| !self.draft.in_code(state.cursor()));
1120 if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at {
1121 self.emoji_dismissed_at = None;
1122 }
1123 let found = found.filter(|_| self.emoji_dismissed_at.is_none());
1124 let Some((range, query)) = found else {
1125 self.emoji_popup = None;
1126 return;
1127 };
1128 let unchanged = self
1129 .emoji_popup
1130 .as_ref()
1131 .is_some_and(|popup| popup.query == query && popup.range == range);
1132 if unchanged {
1133 return;
1134 }
1135 let matches = emoji::search(&query, self.recent_emoji.glyphs(), emoji_popup::LIMIT);
1136 self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches));
1137 }
1138
1139 fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1140 let Some(popup) = self.emoji_popup.take() else {
1141 return;
1142 };
1143 let Some(glyph) = popup.selected().map(|found| found.glyph) else {
1144 return;
1145 };
1146 let cursor = popup.range.end;
1147 self.replace_text(popup.range, glyph, cursor, window, cx);
1148 self.remember_emoji(glyph, cx);
1149 cx.notify();
1150 }
1151
1152 fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) {
1153 let Some(conversation_id) = self.conversation_id.clone() else {
1154 return;
1155 };
1156 let (demo, engine) = {
1157 let state = self.app.read(cx);
1158 (state.mode.demo, state.engine.clone())
1159 };
1160 if demo {
1161 let candidates = crate::demo::mention_candidates(&conversation_id, &query);
1162 self.apply_candidates(&query, candidates, cx);
1163 return;
1164 }
1165 let Some(engine) = engine else {
1166 return;
1167 };
1168 self.lookup = Some(cx.spawn(async move |this, cx| {
1169 cx.background_executor().timer(MENTION_DEBOUNCE).await;
1170 let task_query = query.clone();
1171 let receiver = runtime::spawn(async move {
1172 engine
1173 .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT)
1174 .await
1175 });
1176 if let Ok(Ok(candidates)) = receiver.await {
1177 this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx))
1178 .ok();
1179 }
1180 }));
1181 }
1182
1183 fn apply_candidates(
1184 &mut self,
1185 query: &str,
1186 candidates: Vec<MentionCandidate>,
1187 cx: &mut Context<Self>,
1188 ) {
1189 let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else {
1190 return;
1191 };
1192 popup.candidates = candidates;
1193 popup.highlighted = 0;
1194 cx.notify();
1195 }
1196
1197 fn popup_is_open(&self) -> bool {
1198 self.emoji_popup.is_some()
1199 || self
1200 .popup
1201 .as_ref()
1202 .is_some_and(|popup| !popup.candidates.is_empty())
1203 }
1204
1205 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1206 if let Some(popup) = self.emoji_popup.as_mut() {
1207 popup.move_highlight(delta);
1208 cx.notify();
1209 } else if let Some(popup) = self.popup.as_mut() {
1210 let last = popup.candidates.len().saturating_sub(1) as isize;
1211 popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize;
1212 cx.notify();
1213 }
1214 }
1215
1216 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1217 if self.emoji_popup.is_some() {
1218 self.accept_emoji(window, cx);
1219 } else {
1220 self.accept_mention(window, cx);
1221 }
1222 }
1223
1224 fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1225 let Some(popup) = self.popup.take() else {
1226 return;
1227 };
1228 self.lookup = None;
1229 let Some(candidate) = popup.candidates.get(popup.highlighted) else {
1230 return;
1231 };
1232 self.mention_counter += 1;
1233 let token_id = format!(
1234 "mention-{}-{}",
1235 self.mention_counter,
1236 candidate_key(candidate)
1237 );
1238 let label = format!("@{}", candidate.display_name());
1239 self.mention_inputs
1240 .insert(token_id.clone(), candidate.to_mention());
1241 self.input.update(cx, |state, cx| {
1242 let token = InlineToken::new(token_id, label);
1243 if state
1244 .replace_range_with_token(popup.range, token, window, cx)
1245 .is_ok()
1246 {
1247 state.insert(" ", window, cx);
1248 }
1249 });
1250 self.close_popup();
1251 cx.notify();
1252 }
1253
1254 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1255 let text = text.to_owned();
1256 self.input
1257 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
1258 }
1259
1260 pub fn set_conversation(
1261 &mut self,
1262 conversation_id: &str,
1263 name: &str,
1264 window: &mut Window,
1265 cx: &mut Context<Self>,
1266 ) {
1267 self.set_placeholder(&format!("Message {name}"), window, cx);
1268 if self.conversation_id.as_deref() != Some(conversation_id) {
1269 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1270 self.conversation_id = Some(conversation_id.to_owned());
1271 self.cancel_uploads();
1272 let dropped = if carry {
1273 self.tray.keep_images_only()
1274 } else {
1275 self.tray.clear()
1276 };
1277 self.discard_uploaded(dropped, cx);
1278 self.remove_orphan_image_tokens(window, cx);
1279 self.reply = None;
1280 if self.editing.take().is_some() {
1281 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1282 }
1283 self.mention_inputs.clear();
1284 self.close_popup();
1285 cx.notify();
1286 }
1287 }
1288
1289 /// The draft's images follow the user into this chat; any other switch clears the tray.
1290 pub fn carry_images_into(&mut self, conversation_id: String) {
1291 self.carry_images_into = Some(conversation_id);
1292 }
1293
1294 fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) {
1295 discard_uploaded(self.app.read(cx).engine.clone(), files);
1296 }
1297
1298 pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) {
1299 self.reply = reply;
1300 if self.reply.is_some() {
1301 self.editing = None;
1302 }
1303 cx.notify();
1304 }
1305
1306 pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1307 self.restore(&draft, window, cx);
1308 self.focus(window, cx);
1309 }
1310
1311 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1312 self.editing = None;
1313 self.set_text("", window, cx);
1314 }
1315
1316 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1317 let state = self.input.read(cx);
1318 if !self.can_send(cx) {
1319 return None;
1320 }
1321 let mut draft = self.current_draft(cx);
1322 let image_spans: Vec<(Range<usize>, u64)> = state
1323 .tokens()
1324 .iter()
1325 .filter_map(|span| Some((span.range(), image_id(span.token())?)))
1326 .collect();
1327 let image_ids: Vec<u64> = image_spans
1328 .iter()
1329 .filter(|(_, id)| self.tray.image(*id).is_some())
1330 .map(|(_, id)| *id)
1331 .collect();
1332 for (range, _) in image_spans
1333 .iter()
1334 .rev()
1335 .filter(|(_, id)| self.tray.image(*id).is_none())
1336 {
1337 draft.replace(range.clone(), "");
1338 }
1339 draft.take_edits();
1340 let mut draft = draft.trimmed();
1341 let attachments_apply = self.editing.is_none();
1342 if self.undone_value.as_deref() != Some(state.value().as_ref())
1343 && let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
1344 && !draft.in_code(range.end - 1)
1345 {
1346 draft.replace(range, glyph);
1347 draft.take_edits();
1348 }
1349 let mentions = state
1350 .tokens()
1351 .iter()
1352 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1353 .cloned()
1354 .collect();
1355 Some(Outgoing {
1356 draft,
1357 mentions,
1358 reply: self.reply.clone(),
1359 edit: self.editing.clone(),
1360 images: if attachments_apply {
1361 self.tray.images_in(&image_ids)
1362 } else {
1363 Vec::new()
1364 },
1365 files: if attachments_apply {
1366 self.tray.outgoing_files()
1367 } else {
1368 Vec::new()
1369 },
1370 })
1371 }
1372
1373 /// The draft, or the plain input text while a change is still on its way to the draft.
1374 fn current_draft(&self, cx: &App) -> Draft {
1375 let value = self.input.read(cx).value();
1376 if self.draft.text() == value.as_ref() {
1377 self.draft.clone()
1378 } else {
1379 Draft::plain(&value)
1380 }
1381 }
1382
1383 fn can_send(&self, cx: &App) -> bool {
1384 let has_text = !self.current_draft(cx).is_blank();
1385 if self.editing.is_some() {
1386 return has_text;
1387 }
1388 (has_text || self.has_attachments(cx)) && !self.tray.blocks_send()
1389 }
1390
1391 fn has_attachments(&self, cx: &App) -> bool {
1392 self.tray.has_chips()
1393 || self
1394 .input
1395 .read(cx)
1396 .tokens()
1397 .iter()
1398 .any(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_some()))
1399 }
1400
1401 fn image_token_range(&self, id: u64, cx: &App) -> Option<Range<usize>> {
1402 self.input
1403 .read(cx)
1404 .tokens()
1405 .iter()
1406 .find(|span| image_id(span.token()) == Some(id))
1407 .map(|span| span.range())
1408 }
1409
1410 fn remove_orphan_image_tokens(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1411 let edits: Vec<Edit> = self
1412 .input
1413 .read(cx)
1414 .tokens()
1415 .iter()
1416 .filter(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_none()))
1417 .map(|span| (span.range(), String::new()))
1418 .collect();
1419 if !edits.is_empty() {
1420 self.input
1421 .update(cx, |state, cx| state.apply_edits(&edits, window, cx));
1422 }
1423 }
1424
1425 fn remove_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1426 let Some(range) = self.image_token_range(id, cx) else {
1427 return;
1428 };
1429 self.input.update(cx, |state, cx| {
1430 state.set_selected_range(range, cx);
1431 state.replace("", window, cx);
1432 });
1433 }
1434
1435 fn insert_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1436 let state = self.input.read(cx);
1437 let value = state.value().to_string();
1438 let selection = state.selected_range();
1439 let mut offset = self
1440 .pending_anchors
1441 .remove(&id)
1442 .unwrap_or(selection.end)
1443 .min(value.len());
1444 while !value.is_char_boundary(offset) {
1445 offset -= 1;
1446 }
1447 if value == self.draft.text() && self.draft.in_code(offset) {
1448 offset = value.len();
1449 }
1450 if let Some(span) = state
1451 .tokens()
1452 .iter()
1453 .find(|span| span.range().start < offset && offset < span.range().end)
1454 {
1455 offset = span.range().end;
1456 }
1457 let length = OBJECT_MARK.len_utf8();
1458 let after = |position: usize| {
1459 if position >= offset {
1460 position + length
1461 } else {
1462 position
1463 }
1464 };
1465 let inserted = self.input.update(cx, |state, cx| {
1466 let inserted = state
1467 .replace_range_with_token(offset..offset, image_token(id), window, cx)
1468 .is_ok();
1469 if inserted {
1470 state.set_selected_range(after(selection.start)..after(selection.end), cx);
1471 }
1472 inserted
1473 });
1474 if !inserted {
1475 return;
1476 }
1477 for (other, anchor) in self.pending_anchors.iter_mut() {
1478 if *anchor > offset || (*anchor == offset && *other > id) {
1479 *anchor += length;
1480 }
1481 }
1482 self.previous_value = self.input.read(cx).value().to_string();
1483 }
1484
1485 pub fn is_editing(&self) -> bool {
1486 self.editing.is_some()
1487 }
1488
1489 fn files_allowed(&self) -> bool {
1490 self.conversation_id
1491 .as_deref()
1492 .is_some_and(|conversation_id| !conversation_id.is_empty())
1493 }
1494
1495 fn cancel_uploads(&mut self) {
1496 for (_, handle) in self.uploads.drain() {
1497 handle.cancel();
1498 }
1499 }
1500
1501 pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1502 if self.editing.is_some() {
1503 return;
1504 }
1505 let receiver = cx.prompt_for_paths(PathPromptOptions {
1506 files: true,
1507 directories: false,
1508 multiple: true,
1509 prompt: None,
1510 });
1511 cx.spawn_in(window, async move |this, cx| {
1512 if let Ok(Ok(Some(paths))) = receiver.await {
1513 this.update_in(cx, |this, window, cx| this.add_paths(paths, window, cx))
1514 .ok();
1515 }
1516 })
1517 .detach();
1518 }
1519
1520 pub fn add_paths(&mut self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) {
1521 if self.editing.is_some() || paths.is_empty() {
1522 return;
1523 }
1524 let ids = self.add_pending(&names_of(&paths), cx);
1525 for (id, path) in ids.into_iter().zip(paths) {
1526 cx.spawn_in(window, async move |this, cx| {
1527 let loaded = cx
1528 .background_executor()
1529 .spawn(async move { read_attachment(&path) })
1530 .await;
1531 this.update_in(cx, |this, window, cx| {
1532 this.finish_reading(id, loaded, window, cx)
1533 })
1534 .ok();
1535 })
1536 .detach();
1537 }
1538 cx.notify();
1539 }
1540
1541 fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1542 if self.tray.items().len() + names.len() > MAX_ATTACHMENTS {
1543 let referenced: Vec<u64> = self
1544 .input
1545 .read(cx)
1546 .tokens()
1547 .iter()
1548 .filter_map(|span| image_id(span.token()))
1549 .collect();
1550 self.tray.discard_images_except(&referenced);
1551 }
1552 let ids = self.tray.add_pending(names);
1553 let anchor = self.selection(cx).end;
1554 self.pending_anchors
1555 .extend(ids.iter().map(|id| (*id, anchor)));
1556 ids
1557 }
1558
1559 fn add_pasted_image(&mut self, pasted: Image, window: &mut Window, cx: &mut Context<Self>) {
1560 let ids = self.add_pending(&[pasted_image_name()], cx);
1561 cx.notify();
1562 let Some(&id) = ids.first() else {
1563 return;
1564 };
1565 cx.spawn_in(window, async move |this, cx| {
1566 let loaded = cx
1567 .background_executor()
1568 .spawn(async move { prepare_pasted_image(pasted) })
1569 .await;
1570 this.update_in(cx, |this, window, cx| {
1571 this.finish_reading(id, loaded, window, cx)
1572 })
1573 .ok();
1574 })
1575 .detach();
1576 }
1577
1578 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1579 if self.editing.is_none() {
1580 match paste_action(item) {
1581 PasteAction::Text => {}
1582 PasteAction::Files(paths) => {
1583 self.add_paths(paths, window, cx);
1584 return true;
1585 }
1586 PasteAction::Image(pasted) => {
1587 self.add_pasted_image(pasted, window, cx);
1588 return true;
1589 }
1590 }
1591 }
1592 let Some(text) = item.text() else {
1593 return false;
1594 };
1595 if text.contains(OBJECT_MARK) {
1596 let cleaned = text.replace(OBJECT_MARK, "");
1597 self.input
1598 .update(cx, |state, cx| state.replace(cleaned, window, cx));
1599 return true;
1600 }
1601 if self.draft.in_code(self.selection(cx).start) {
1602 return false;
1603 }
1604 if let Some(lines) = self.copied_lines(item, &text) {
1605 let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1606 self.commit(Some(cursor), window, cx);
1607 return true;
1608 }
1609 self.pasted_markdown = has_markdown(&text).then_some(text);
1610 false
1611 }
1612
1613 fn finish_reading(
1614 &mut self,
1615 id: u64,
1616 loaded: Result<LoadedFile, String>,
1617 window: &mut Window,
1618 cx: &mut Context<Self>,
1619 ) {
1620 match loaded {
1621 Ok(loaded) => {
1622 let files_allowed = self.files_allowed();
1623 let job = self.tray.finish_reading(id, loaded, files_allowed);
1624 if self.tray.image(id).is_some() {
1625 self.insert_image_token(id, window, cx);
1626 } else {
1627 self.pending_anchors.remove(&id);
1628 }
1629 if let Some(job) = job {
1630 self.start_upload(job, cx);
1631 }
1632 }
1633 Err(message) => {
1634 self.pending_anchors.remove(&id);
1635 self.tray.fail_reading(id, message);
1636 }
1637 }
1638 cx.notify();
1639 }
1640
1641 fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1642 let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else {
1643 self.tray.finish_upload(job.id, UploadResult::Failed);
1644 return;
1645 };
1646 let state = self.app.read(cx);
1647 let (demo, engine) = (state.mode.demo, state.engine.clone());
1648 if demo {
1649 self.simulate_upload(job, cx);
1650 return;
1651 }
1652 let Some(engine) = engine else {
1653 self.tray.finish_upload(job.id, UploadResult::Failed);
1654 return;
1655 };
1656 let id = job.id;
1657 let (event_sender, mut event_receiver) =
1658 tokio::sync::mpsc::unbounded_channel::<UploadEvent>();
1659 let finished_sender = event_sender.clone();
1660 let (_, handle) = runtime::spawn_abortable(async move {
1661 let result = async {
1662 let uploaded = match job.kind {
1663 JobKind::Upload => {
1664 let progress_sender = event_sender.clone();
1665 let uploaded = engine
1666 .upload_attachment_file(
1667 &conversation_id,
1668 &job.name,
1669 &job.bytes,
1670 move |percent| {
1671 let _ = progress_sender.send(UploadEvent::Progress(percent));
1672 },
1673 )
1674 .await;
1675 match uploaded {
1676 Ok(uploaded) => {
1677 let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone()));
1678 uploaded
1679 }
1680 Err(_) => return UploadResult::Failed,
1681 }
1682 }
1683 JobKind::Share(uploaded) => uploaded,
1684 };
1685 let Some(reference) = uploaded.reference() else {
1686 return UploadResult::Failed;
1687 };
1688 match engine.share_attachment(&conversation_id, &uploaded).await {
1689 Ok(()) => UploadResult::Done(DoneFile {
1690 reference,
1691 uploaded: Some(uploaded),
1692 }),
1693 Err(_) => UploadResult::ShareFailed(uploaded),
1694 }
1695 }
1696 .await;
1697 let _ = finished_sender.send(UploadEvent::Finished(result));
1698 });
1699 self.uploads.insert(id, UploadHandle::Network(handle));
1700 cx.spawn(async move |this, cx| {
1701 while let Some(event) = event_receiver.recv().await {
1702 let updated = this.update(cx, |this, cx| {
1703 let orphan = match event {
1704 UploadEvent::Progress(percent) => {
1705 this.tray.set_progress(id, percent);
1706 None
1707 }
1708 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
1709 UploadEvent::Finished(result) => this.finish_upload(id, result),
1710 };
1711 this.discard_uploaded(orphan.into_iter().collect(), cx);
1712 cx.notify();
1713 });
1714 if updated.is_err() {
1715 break;
1716 }
1717 }
1718 })
1719 .detach();
1720 }
1721
1722 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
1723 let id = job.id;
1724 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
1725 let task = cx.spawn(async move |this, cx| {
1726 for step in 1..=DEMO_UPLOAD_STEPS {
1727 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
1728 if fails && step == DEMO_FAILURE_STEP {
1729 this.update(cx, |this, cx| {
1730 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
1731 })
1732 .ok();
1733 return;
1734 }
1735 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
1736 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
1737 .ok();
1738 }
1739 let reference = FileReference {
1740 attachment_id: format!("demo-attachment-{id}"),
1741 content_url: format!("https://demo.invalid/files/{}", job.name),
1742 name: job.name,
1743 };
1744 let done = DoneFile {
1745 reference,
1746 uploaded: None,
1747 };
1748 this.update(cx, |this, cx| {
1749 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
1750 })
1751 .ok();
1752 });
1753 self.uploads.insert(id, UploadHandle::Demo(task));
1754 }
1755
1756 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
1757 self.tray.set_progress(id, percent);
1758 cx.notify();
1759 }
1760
1761 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
1762 self.uploads.remove(&id);
1763 self.tray.finish_upload(id, result)
1764 }
1765
1766 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
1767 self.finish_upload(id, result);
1768 cx.notify();
1769 }
1770
1771 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
1772 if let Some(handle) = self.uploads.remove(&id) {
1773 handle.cancel();
1774 }
1775 let uploaded = self.tray.remove(id);
1776 self.discard_uploaded(uploaded.into_iter().collect(), cx);
1777 cx.notify();
1778 }
1779
1780 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
1781 if let Some(job) = self.tray.retry(id) {
1782 self.start_upload(job, cx);
1783 }
1784 cx.notify();
1785 }
1786
1787 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1788 let Some(outgoing) = self.outgoing(cx) else {
1789 return;
1790 };
1791 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1792 self.mention_inputs.clear();
1793 if self.editing.is_none() {
1794 self.tray.clear();
1795 }
1796 self.reply = None;
1797 self.editing = None;
1798 self.close_popup();
1799 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1800 cx.notify();
1801 }
1802
1803 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1804 self.mention_inputs.clear();
1805 let image_ids = if outgoing.edit.is_none() {
1806 self.cancel_uploads();
1807 self.tray.restore(&outgoing.images, &outgoing.files)
1808 } else {
1809 Vec::new()
1810 };
1811 let text = outgoing.draft.text();
1812 let mut content = InputContent::new(text.to_owned());
1813 for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) {
1814 let range = offset..offset + OBJECT_MARK.len_utf8();
1815 if let Ok(next) = content.clone().with_token(range, image_token(id)) {
1816 content = next;
1817 }
1818 }
1819 let mut cursor = 0;
1820 for mention in &outgoing.mentions {
1821 let needle = format!("@{}", mention.text);
1822 let Some(offset) = text[cursor..].find(&needle) else {
1823 continue;
1824 };
1825 let range = cursor + offset..cursor + offset + needle.len();
1826 self.mention_counter += 1;
1827 let token_id = format!("mention-{}", self.mention_counter);
1828 let token = InlineToken::new(token_id.clone(), needle);
1829 if let Ok(next) = content.clone().with_token(range.clone(), token) {
1830 content = next;
1831 self.mention_inputs.insert(token_id, mention.clone());
1832 cursor = range.end;
1833 }
1834 }
1835 self.load_draft(outgoing.draft.clone(), content, window, cx);
1836 self.reply = outgoing.reply.clone();
1837 self.editing = outgoing.edit.clone();
1838 self.close_popup();
1839 cx.notify();
1840 }
1841
1842 /// Markdown in `text` arrives formatted.
1843 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1844 let draft = Draft::from_markdown(text);
1845 let content = InputContent::new(draft.text().to_owned());
1846 self.load_draft(draft, content, window, cx);
1847 self.mention_inputs.clear();
1848 self.update_emoji(cx);
1849 self.update_mention(cx);
1850 cx.notify();
1851 }
1852
1853 pub fn is_empty(&self, cx: &App) -> bool {
1854 self.draft.is_blank() && !self.has_attachments(cx)
1855 }
1856
1857 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1858 self.input.update(cx, |state, cx| state.focus(window, cx));
1859 }
1860
1861 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1862 let popup = self
1863 .popup
1864 .as_ref()
1865 .filter(|popup| !popup.candidates.is_empty())?;
1866 let directory = &self.app.read(cx).directory;
1867 let rows = popup
1868 .candidates
1869 .iter()
1870 .enumerate()
1871 .map(|(index, candidate)| {
1872 let name = candidate.display_name().to_owned();
1873 let avatar = match candidate {
1874 MentionCandidate::Person(person) => {
1875 person_avatar(directory, Some(&person.user_id), &name, 28.)
1876 }
1877 other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(),
1878 };
1879 let subtitle = candidate_subtitle(candidate);
1880 h_flex()
1881 .id(ElementId::Name(format!("mention-row-{index}").into()))
1882 .mx(px(6.))
1883 .px(px(6.))
1884 .h(px(POPUP_ROW_HEIGHT))
1885 .gap(px(10.))
1886 .items_center()
1887 .rounded(px(6.))
1888 .cursor_pointer()
1889 .when(index == popup.highlighted, |row| {
1890 row.bg(theme::surface_raised())
1891 })
1892 .hover(|row| row.bg(theme::row_hover()))
1893 .child(avatar)
1894 .child(
1895 v_flex()
1896 .flex_1()
1897 .min_w_0()
1898 .child(
1899 div()
1900 .truncate()
1901 .text_size(px(13.5))
1902 .text_color(theme::text())
1903 .child(name),
1904 )
1905 .when(!subtitle.is_empty(), |column| {
1906 column.child(
1907 div()
1908 .truncate()
1909 .text_size(px(12.))
1910 .text_color(theme::text_muted())
1911 .child(subtitle),
1912 )
1913 }),
1914 )
1915 .on_click(cx.listener(move |this, _, window, cx| {
1916 if let Some(popup) = this.popup.as_mut() {
1917 popup.highlighted = index;
1918 }
1919 this.accept_mention(window, cx);
1920 }))
1921 });
1922 Some(
1923 v_flex()
1924 .id("mention-popup")
1925 .absolute()
1926 .bottom(relative(1.))
1927 .left_0()
1928 .mb(px(6.))
1929 .w(px(POPUP_WIDTH))
1930 .py(px(6.))
1931 .rounded(px(10.))
1932 .border_1()
1933 .border_color(theme::border_strong())
1934 .bg(theme::surface())
1935 .shadow_lg()
1936 .occlude()
1937 .children(rows)
1938 .into_any_element(),
1939 )
1940 }
1941
1942 fn render_emoji_popup(
1943 &self,
1944 window: &mut Window,
1945 cx: &mut Context<Self>,
1946 ) -> Option<AnyElement> {
1947 let popup = self.emoji_popup.as_ref()?;
1948 let colon = popup.range.start..popup.range.start + 1;
1949 let anchor = self
1950 .input
1951 .read(cx)
1952 .range_to_bounds(&colon)
1953 .map(|bounds| bounds.origin);
1954 if anchor.is_none() {
1955 window.request_animation_frame();
1956 }
1957 let composer = cx.entity().downgrade();
1958 Some(emoji_popup::render(
1959 popup,
1960 anchor,
1961 move |index, window, cx| {
1962 composer
1963 .update(cx, |this, cx| {
1964 if let Some(popup) = this.emoji_popup.as_mut() {
1965 popup.highlighted = index;
1966 }
1967 this.accept_emoji(window, cx);
1968 })
1969 .ok();
1970 },
1971 ))
1972 }
1973
1974 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
1975 let composer = cx.entity().downgrade();
1976 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
1977 return None;
1978 }
1979 let state = self.input.read(cx);
1980 let range = self
1981 .link_editor
1982 .as_ref()
1983 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
1984 let start = state.range_to_bounds(&(range.start..range.start))?;
1985 let end = state.range_to_bounds(&(range.end..range.end))?;
1986 let input_bounds = state.input_bounds();
1987 let center_x = if start.origin.y == end.origin.y {
1988 (start.origin.x + end.origin.x) / 2.
1989 } else {
1990 input_bounds.center().x
1991 };
1992 let edges = self
1993 .composer_bounds
1994 .get()
1995 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
1996 (bounds.left(), bounds.right())
1997 });
1998 let width = match self.link_editor {
1999 Some(_) => format_toolbar::link_width(),
2000 None => format_toolbar::bar_width(),
2001 };
2002 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
2003 let element = match &self.link_editor {
2004 Some(editor) => format_toolbar::render(
2005 placement,
2006 format_toolbar::Mode::Link {
2007 field: &editor.field,
2008 refused: editor.refused,
2009 on_apply: Rc::new(move |window, cx| {
2010 composer
2011 .update(cx, |this, cx| this.apply_link(window, cx))
2012 .ok();
2013 }),
2014 },
2015 ),
2016 None => {
2017 let state_of = |button| self.format_state(button, &range);
2018 format_toolbar::render(
2019 placement,
2020 format_toolbar::Mode::Bar {
2021 state: &state_of,
2022 on_press: Rc::new(move |button, window, cx| {
2023 composer
2024 .update(cx, |this, cx| this.press_format(button, window, cx))
2025 .ok();
2026 }),
2027 },
2028 )
2029 }
2030 };
2031 Some(element)
2032 }
2033
2034 fn render_paste_hint(&self) -> Option<Div> {
2035 self.paste_hint.as_ref()?;
2036 Some(
2037 h_flex()
2038 .mt(px(6.))
2039 .gap(px(6.))
2040 .items_center()
2041 .text_size(px(12.))
2042 .text_color(theme::text_muted())
2043 .child("Formatted from Markdown")
2044 .child(
2045 div()
2046 .px(px(5.))
2047 .py(px(1.))
2048 .rounded(px(4.))
2049 .border_1()
2050 .border_color(theme::border_strong())
2051 .bg(theme::surface_raised())
2052 .text_size(px(11.))
2053 .text_color(theme::text())
2054 .child("Ctrl+Z"),
2055 )
2056 .child("plain text"),
2057 )
2058 }
2059
2060 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2061 let edit = self.editing.as_ref()?;
2062 Some(
2063 h_flex()
2064 .w_full()
2065 .mb(px(6.))
2066 .gap(px(10.))
2067 .items_center()
2068 .pl(px(10.))
2069 .pr(px(4.))
2070 .py(px(6.))
2071 .rounded(px(8.))
2072 .bg(theme::surface())
2073 .border_1()
2074 .border_color(theme::border())
2075 .child(icon(IconName::Pencil, 14., theme::accent_text()))
2076 .child(
2077 v_flex()
2078 .flex_1()
2079 .min_w_0()
2080 .child(
2081 div()
2082 .truncate()
2083 .text_size(px(12.))
2084 .font_weight(FontWeight::SEMIBOLD)
2085 .text_color(theme::accent_text())
2086 .child("Editing message"),
2087 )
2088 .child(
2089 div()
2090 .truncate()
2091 .text_size(px(12.))
2092 .text_color(theme::text_muted())
2093 .child(edit.excerpt.clone()),
2094 ),
2095 )
2096 .child(
2097 div()
2098 .id("edit-close")
2099 .size(px(24.))
2100 .flex()
2101 .items_center()
2102 .justify_center()
2103 .rounded(px(6.))
2104 .cursor_pointer()
2105 .hover(|button| button.bg(theme::row_hover()))
2106 .child(icon(IconName::Close, 14., theme::text_muted()))
2107 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
2108 ),
2109 )
2110 }
2111
2112 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2113 let reply = self.reply.as_ref()?;
2114 Some(
2115 h_flex()
2116 .w_full()
2117 .mb(px(6.))
2118 .gap(px(10.))
2119 .items_center()
2120 .pl(px(10.))
2121 .pr(px(4.))
2122 .py(px(6.))
2123 .rounded(px(8.))
2124 .bg(theme::surface())
2125 .border_1()
2126 .border_color(theme::border())
2127 .child(icon(IconName::Undo2, 14., theme::accent_text()))
2128 .child(
2129 v_flex()
2130 .flex_1()
2131 .min_w_0()
2132 .child(
2133 div()
2134 .truncate()
2135 .text_size(px(12.))
2136 .font_weight(FontWeight::SEMIBOLD)
2137 .text_color(theme::accent_text())
2138 .child(format!("Replying to {}", reply.author)),
2139 )
2140 .child(
2141 div()
2142 .truncate()
2143 .text_size(px(12.))
2144 .text_color(theme::text_muted())
2145 .child(reply.excerpt.clone()),
2146 ),
2147 )
2148 .child(
2149 div()
2150 .id("reply-close")
2151 .size(px(24.))
2152 .flex()
2153 .items_center()
2154 .justify_center()
2155 .rounded(px(6.))
2156 .cursor_pointer()
2157 .hover(|button| button.bg(theme::row_hover()))
2158 .child(icon(IconName::Close, 14., theme::text_muted()))
2159 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
2160 ),
2161 )
2162 }
2163}
2164
2165impl Render for Composer {
2166 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2167 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
2168 let can_send = self.can_send(cx);
2169 let can_attach = self.editing.is_none();
2170 let send = div()
2171 .id("composer-send")
2172 .size(px(32.))
2173 .flex_none()
2174 .flex()
2175 .items_center()
2176 .justify_center()
2177 .rounded(px(8.))
2178 .child(symbol("keyboard_return", 20., white()))
2179 .when(!can_send, |button| button.opacity(0.4))
2180 .when(can_send, |button| {
2181 button
2182 .cursor_pointer()
2183 .hover(|button| button.bg(white().opacity(0.1)))
2184 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
2185 });
2186 let attach = can_attach.then(|| {
2187 div()
2188 .id("composer-attach")
2189 .size(px(32.))
2190 .flex_none()
2191 .flex()
2192 .items_center()
2193 .justify_center()
2194 .rounded(px(8.))
2195 .cursor_pointer()
2196 .hover(|button| button.bg(theme::row_hover()))
2197 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2198 .child(symbol("attach_file", 20., theme::text_muted()))
2199 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2200 });
2201 let composer = cx.weak_entity();
2202 let tokens_composer = composer.clone();
2203 let input = Textarea::new(&self.input)
2204 .appearance(false)
2205 .bordered(false)
2206 .on_paste(move |item, window, cx| {
2207 composer
2208 .update(cx, |this, cx| this.paste(item, window, cx))
2209 .unwrap_or(false)
2210 })
2211 .token(move |context, _, cx| {
2212 if let Some(id) = context
2213 .is_block()
2214 .then(|| image_id(context.token()))
2215 .flatten()
2216 {
2217 let preview = tokens_composer
2218 .read_with(cx, |this, _| this.tray.image(id))
2219 .ok()
2220 .flatten();
2221 let remove_composer = tokens_composer.clone();
2222 return inline_preview(
2223 id,
2224 preview,
2225 context.available_width(),
2226 context.is_selected(),
2227 Rc::new(move |window, cx| {
2228 remove_composer
2229 .update(cx, |this, cx| this.remove_image_token(id, window, cx))
2230 .ok();
2231 }),
2232 );
2233 }
2234 div()
2235 .h(context.line_height())
2236 .px(px(5.))
2237 .rounded(px(5.))
2238 .bg(if context.is_selected() {
2239 theme::accent().opacity(0.4)
2240 } else {
2241 theme::mention_background(false)
2242 })
2243 .text_color(theme::mention_text())
2244 .font_weight(FontWeight::SEMIBOLD)
2245 .child(context.token().label().clone())
2246 .into_any_element()
2247 });
2248 let tray = can_attach
2249 .then(|| {
2250 render_tray(
2251 &self.tray,
2252 Self::remove_attachment,
2253 Self::retry_attachment,
2254 cx,
2255 )
2256 })
2257 .flatten();
2258 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
2259 div()
2260 .w_full()
2261 .mb(px(6.))
2262 .text_size(px(12.))
2263 .text_color(theme::amber())
2264 .child(notice.to_owned())
2265 });
2266 let composer_bounds = self.composer_bounds.clone();
2267 v_flex()
2268 .w_full()
2269 .flex_none()
2270 .px(px(24.))
2271 .pt(px(8.))
2272 .pb(px(12.))
2273 .key_context(KEY_CONTEXT)
2274 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2275 if this.link_editor.is_none() {
2276 this.toggle_mark(MarkKind::Bold, cx);
2277 }
2278 }))
2279 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2280 if this.link_editor.is_none() {
2281 this.toggle_mark(MarkKind::Italic, cx);
2282 }
2283 }))
2284 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2285 if this.link_editor.is_none() {
2286 this.toggle_mark(MarkKind::Underline, cx);
2287 }
2288 }))
2289 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2290 if this.link_editor.is_none() {
2291 this.toggle_mark(MarkKind::Strike, cx);
2292 }
2293 }))
2294 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2295 if this.link_editor.is_none() {
2296 this.toggle_mark(MarkKind::Code, cx);
2297 }
2298 }))
2299 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2300 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2301 if this.link_editor.is_none() {
2302 this.step_history(true, window, cx);
2303 cx.stop_propagation();
2304 }
2305 }))
2306 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
2307 if this.link_editor.is_none() {
2308 this.step_history(false, window, cx);
2309 cx.stop_propagation();
2310 }
2311 }))
2312 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2313 if this.link_editor.is_none() && this.copy_selection(cx) {
2314 cx.stop_propagation();
2315 }
2316 }))
2317 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2318 if this.link_editor.is_none() && this.copy_selection(cx) {
2319 this.input
2320 .update(cx, |state, cx| state.replace("", window, cx));
2321 cx.stop_propagation();
2322 }
2323 }))
2324 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
2325 if this.link_editor.is_some() {
2326 } else if this.popup_is_open() {
2327 this.move_highlight(-1, cx);
2328 cx.stop_propagation();
2329 } else if this.editing.is_none() && this.is_empty(cx) {
2330 cx.emit(ComposerEvent::EditLast);
2331 cx.stop_propagation();
2332 }
2333 }))
2334 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
2335 if this.link_editor.is_none() && this.popup_is_open() {
2336 this.move_highlight(1, cx);
2337 cx.stop_propagation();
2338 }
2339 }))
2340 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2341 if this.link_editor.is_some() {
2342 this.apply_link(window, cx);
2343 cx.stop_propagation();
2344 } else if this.popup_is_open() {
2345 this.accept_popup(window, cx);
2346 cx.stop_propagation();
2347 } else if this.break_line(action.shift, window, cx) {
2348 cx.stop_propagation();
2349 }
2350 }))
2351 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2352 if this.link_editor.is_some() {
2353 } else if this.popup_is_open() {
2354 this.accept_popup(window, cx);
2355 cx.stop_propagation();
2356 } else if this.indent(false, window, cx) {
2357 cx.stop_propagation();
2358 }
2359 }))
2360 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2361 if this.link_editor.is_none() && this.indent(true, window, cx) {
2362 cx.stop_propagation();
2363 }
2364 }))
2365 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2366 if this.link_editor.is_none()
2367 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2368 {
2369 cx.stop_propagation();
2370 }
2371 }))
2372 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2373 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2374 cx.stop_propagation();
2375 }
2376 }))
2377 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2378 if this.link_editor.is_some() {
2379 this.close_link_editor(window, cx);
2380 cx.stop_propagation();
2381 return;
2382 }
2383 if this.toolbar_requested(cx) {
2384 this.toolbar_dismissed = Some(this.selection(cx));
2385 cx.notify();
2386 cx.stop_propagation();
2387 return;
2388 }
2389 if let Some(popup) = &this.emoji_popup {
2390 this.emoji_dismissed_at = Some(popup.range.start);
2391 }
2392 if this.popup.is_some() || this.emoji_popup.is_some() {
2393 this.close_popup();
2394 cx.notify();
2395 cx.stop_propagation();
2396 } else if this.editing.is_some() {
2397 this.cancel_edit(window, cx);
2398 cx.stop_propagation();
2399 }
2400 }))
2401 .children(notice)
2402 .children(self.render_reply_strip(cx))
2403 .children(self.render_edit_strip(cx))
2404 .child(
2405 div()
2406 .relative()
2407 .w_full()
2408 .children(self.render_popup(cx))
2409 .children(self.render_emoji_popup(window, cx))
2410 .children(self.render_toolbar(focused, cx))
2411 .child(
2412 v_flex()
2413 .relative()
2414 .w_full()
2415 .rounded(px(10.))
2416 .bg(theme::surface())
2417 .border_1()
2418 .border_color(if focused {
2419 theme::accent()
2420 } else {
2421 theme::border_strong()
2422 })
2423 .child(
2424 canvas(
2425 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2426 |_, _, _, _| {},
2427 )
2428 .absolute()
2429 .size_full(),
2430 )
2431 .children(tray)
2432 .child(
2433 h_flex()
2434 .w_full()
2435 .items_end()
2436 .gap(px(6.))
2437 .py(px(6.))
2438 .pl(px(if can_attach { 6. } else { 12. }))
2439 .pr(px(6.))
2440 .children(attach)
2441 .child(
2442 div()
2443 .flex_1()
2444 .min_w_0()
2445 .capture_any_mouse_down(cx.listener(
2446 |this, _: &MouseDownEvent, _, _| {
2447 this.mouse_selecting = true;
2448 this.toolbar_dismissed = None;
2449 this.link_editor = None;
2450 },
2451 ))
2452 .capture_any_mouse_up(cx.listener(
2453 |this, _: &MouseUpEvent, _, cx| {
2454 this.mouse_selecting = false;
2455 cx.notify();
2456 },
2457 ))
2458 .on_mouse_up_out(
2459 MouseButton::Left,
2460 cx.listener(|this, _, _, cx| {
2461 this.mouse_selecting = false;
2462 cx.notify();
2463 }),
2464 )
2465 .child(input),
2466 )
2467 .child(send),
2468 ),
2469 ),
2470 )
2471 .children(self.render_paste_hint())
2472 }
2473}
2474
2475#[cfg(test)]
2476mod tests {
2477 use super::{active_mention, submitted_text};
2478 use gpui_kit::component::input::InputEvent;
2479
2480 fn press(shift: bool) -> InputEvent {
2481 InputEvent::PressEnter {
2482 secondary: false,
2483 shift,
2484 }
2485 }
2486
2487 #[test]
2488 fn enter_sends_trimmed_text() {
2489 assert_eq!(
2490 submitted_text(&press(false), " hello \n"),
2491 Some("hello".into())
2492 );
2493 }
2494
2495 #[test]
2496 fn shift_enter_never_sends() {
2497 assert_eq!(submitted_text(&press(true), "hello"), None);
2498 }
2499
2500 #[test]
2501 fn blank_text_never_sends() {
2502 assert_eq!(submitted_text(&press(false), " \n "), None);
2503 }
2504
2505 #[test]
2506 fn other_events_never_send() {
2507 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
2508 }
2509
2510 #[test]
2511 fn at_sign_opens_a_mention_query() {
2512 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
2513 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
2514 }
2515
2516 #[test]
2517 fn names_with_a_space_keep_the_query_open() {
2518 assert_eq!(
2519 active_mention("@Mara Lin", 9, &[]),
2520 Some((0..9, "Mara Lin".into()))
2521 );
2522 }
2523
2524 #[test]
2525 fn mail_addresses_and_closed_queries_do_not_open() {
2526 assert_eq!(active_mention("a@b", 3, &[]), None);
2527 assert_eq!(active_mention("@Mara ", 6, &[]), None);
2528 assert_eq!(active_mention("@ x", 3, &[]), None);
2529 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
2530 }
2531
2532 #[test]
2533 fn text_inside_a_token_does_not_reopen() {
2534 let token = 0..15;
2535 assert_eq!(
2536 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
2537 None
2538 );
2539 assert_eq!(
2540 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
2541 Some((16..19, "Pr".into()))
2542 );
2543 }
2544
2545 #[test]
2546 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
2547 use std::sync::Arc;
2548
2549 use gpui_kit::{Image, ImageFormat};
2550 use teams_core::FileKind;
2551
2552 use super::{Outgoing, OutgoingFile, OutgoingImage};
2553
2554 let outgoing = Outgoing {
2555 draft: teams_core::Draft::default(),
2556 mentions: Vec::new(),
2557 reply: None,
2558 edit: None,
2559 images: vec![OutgoingImage {
2560 name: "pasted-image.png".into(),
2561 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2562 dimensions: Some((1, 1)),
2563 }],
2564 files: vec![OutgoingFile {
2565 name: "plan.pdf".into(),
2566 size: 9,
2567 kind: FileKind::Pdf,
2568 uploaded: None,
2569 reference: teams_core::FileReference {
2570 attachment_id: "guid".into(),
2571 content_url: "https://files.example/plan.pdf".into(),
2572 name: "plan.pdf".into(),
2573 },
2574 }],
2575 };
2576 let extras = outgoing.extras();
2577 assert_eq!(extras.images[0].content_type, "image/png");
2578 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
2579 assert_eq!(extras.files[0].attachment_id, "guid");
2580 assert!(outgoing.has_attachments());
2581 }
2582
2583 fn placed_image(width: u32) -> super::OutgoingImage {
2584 use std::sync::Arc;
2585
2586 use gpui_kit::{Image, ImageFormat};
2587
2588 super::OutgoingImage {
2589 name: "pasted-image.png".into(),
2590 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2591 dimensions: Some((width, width)),
2592 }
2593 }
2594
2595 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2596 super::Outgoing {
2597 draft: teams_core::Draft::plain(text),
2598 mentions: Vec::new(),
2599 reply: None,
2600 edit: None,
2601 images,
2602 files: Vec::new(),
2603 }
2604 }
2605
2606 #[test]
2607 fn an_image_is_placed_in_the_html_where_its_mark_sits() {
2608 let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
2609 assert_eq!(
2610 outgoing.html(),
2611 "a <img src=\"../hostedContents/1/$value\"> b"
2612 );
2613 assert_eq!(outgoing.text(), "a b");
2614 }
2615
2616 #[test]
2617 fn images_keep_the_order_of_their_marks() {
2618 let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
2619 assert_eq!(
2620 outgoing.html(),
2621 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
2622 );
2623 }
2624
2625 #[test]
2626 fn a_mark_without_an_image_leaves_no_trace() {
2627 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
2628 }
2629
2630 #[test]
2631 fn enter_sends_attachments_even_without_text() {
2632 assert!(super::is_plain_enter(&press(false)));
2633 assert!(!super::is_plain_enter(&press(true)));
2634 assert!(!super::is_plain_enter(&InputEvent::Change));
2635 }
2636
2637 mod keys {
2638 use std::sync::Arc;
2639
2640 use gpui_kit::test::TestWindowExt as _;
2641 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2642 use store::Store;
2643
2644 use super::super::Composer;
2645 use crate::app_state::{AppState, Mode};
2646
2647 #[gpui_kit::test]
2648 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
2649 cx.update(gpui_kit::init);
2650 let store = Arc::new(Store::open_in_memory().unwrap());
2651 let mode = Mode {
2652 demo: true,
2653 read_only: false,
2654 demo_sync: None,
2655 };
2656 let (handle, composer) = cx.update(|cx| {
2657 let app = cx.new(|_| AppState::new(store, mode));
2658 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2659 cx.new(|cx| Composer::new(app, window, cx))
2660 })
2661 .unwrap()
2662 });
2663 let value = cx
2664 .update_window(handle, |_, window, cx| {
2665 composer.update(cx, |composer, cx| composer.focus(window, cx));
2666 window.render_frame(cx);
2667 window.input("first line", cx);
2668 window.press("shift-enter", cx);
2669 window.input("second line", cx);
2670 window.press("ctrl-a", cx);
2671 window.input("X", cx);
2672 composer.read(cx).input.read(cx).value()
2673 })
2674 .unwrap();
2675 assert_eq!(value, "X");
2676 }
2677
2678 struct Typist<'a> {
2679 cx: &'a mut TestAppContext,
2680 handle: gpui_kit::AnyWindowHandle,
2681 composer: gpui_kit::Entity<Composer>,
2682 }
2683
2684 impl Typist<'_> {
2685 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
2686 self.cx
2687 .update_window(self.handle, |_, window, cx| action(window, cx))
2688 .unwrap();
2689 self.cx.run_until_parked();
2690 }
2691
2692 fn type_text(&mut self, text: &str) {
2693 for character in text.chars() {
2694 self.act(|window, cx| window.input(&character.to_string(), cx));
2695 }
2696 }
2697
2698 fn press(&mut self, keys: &str) {
2699 for key in keys.split(' ') {
2700 self.act(|window, cx| window.press(key, cx));
2701 }
2702 }
2703
2704 fn value(&mut self) -> String {
2705 let composer = self.composer.clone();
2706 self.cx
2707 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
2708 }
2709
2710 fn draft(&mut self) -> teams_core::Draft {
2711 let composer = self.composer.clone();
2712 self.cx.update(|cx| composer.read(cx).draft.clone())
2713 }
2714
2715 fn outgoing(&mut self) -> super::super::Outgoing {
2716 let composer = self.composer.clone();
2717 self.cx
2718 .update(|cx| composer.read(cx).outgoing(cx))
2719 .expect("text to send")
2720 }
2721 }
2722
2723 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
2724 let (handle, composer) = demo_composer(cx);
2725 cx.update(super::super::bind_keys);
2726 let mut typist = Typist {
2727 cx,
2728 handle,
2729 composer: composer.clone(),
2730 };
2731 typist.act(|window, cx| {
2732 composer.update(cx, |composer, cx| composer.focus(window, cx));
2733 window.render_frame(cx);
2734 });
2735 typist
2736 }
2737
2738 fn png_bytes(side: u32) -> Vec<u8> {
2739 let mut bytes = Vec::new();
2740 image::RgbaImage::new(side, side)
2741 .write_to(
2742 &mut std::io::Cursor::new(&mut bytes),
2743 image::ImageFormat::Png,
2744 )
2745 .unwrap();
2746 bytes
2747 }
2748
2749 fn paste_image(typist: &mut Typist<'_>, side: u32) {
2750 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
2751 entries: vec![gpui_kit::ClipboardEntry::Image(
2752 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
2753 )],
2754 });
2755 typist.press("ctrl-v");
2756 }
2757
2758 fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
2759 let composer = typist.composer.clone();
2760 typist.cx.update(|cx| {
2761 composer
2762 .read(cx)
2763 .input
2764 .read(cx)
2765 .tokens()
2766 .iter()
2767 .map(|span| (span.range(), span.token().is_block()))
2768 .collect()
2769 })
2770 }
2771
2772 #[gpui_kit::test]
2773 fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
2774 let mut typist = typist(cx);
2775 typist.type_text("ab");
2776 typist.press("left");
2777 paste_image(&mut typist, 2);
2778 assert_eq!(typist.value(), "a\u{FFFC}b");
2779 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2780 let outgoing = typist.outgoing();
2781 assert_eq!(outgoing.images.len(), 1);
2782 assert_eq!(
2783 outgoing.html(),
2784 "a<img src=\"../hostedContents/1/$value\">b"
2785 );
2786 let composer = typist.composer.clone();
2787 assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
2788 }
2789
2790 fn wide_png_bytes() -> Vec<u8> {
2791 let mut bytes = Vec::new();
2792 image::RgbaImage::new(600, 300)
2793 .write_to(
2794 &mut std::io::Cursor::new(&mut bytes),
2795 image::ImageFormat::Png,
2796 )
2797 .unwrap();
2798 bytes
2799 }
2800
2801 fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
2802 let composer = typist.composer.clone();
2803 typist.cx.update(|cx| {
2804 let state = composer.read(cx).input.read(cx);
2805 let cursor = state.cursor();
2806 let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
2807 let viewport = state.input_bounds();
2808 caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
2809 })
2810 }
2811
2812 #[gpui_kit::test]
2813 fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
2814 let mut typist = typist(cx);
2815 typist.type_text("look at this ");
2816 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
2817 entries: vec![gpui_kit::ClipboardEntry::Image(
2818 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
2819 )],
2820 });
2821 typist.press("ctrl-v");
2822 typist.act(|window, _| window.refresh());
2823 typist.type_text("and then more text");
2824 typist.act(|window, _| window.refresh());
2825 assert!(caret_is_visible(&mut typist));
2826 }
2827
2828 #[gpui_kit::test]
2829 fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
2830 let mut typist = typist(cx);
2831 typist.type_text("ab");
2832 typist.press("left");
2833 paste_image(&mut typist, 2);
2834 typist.press("backspace");
2835 assert_eq!(typist.value(), "ab");
2836 assert!(image_tokens(&mut typist).is_empty());
2837 let outgoing = typist.outgoing();
2838 assert!(outgoing.images.is_empty());
2839 assert_eq!(outgoing.html(), "ab");
2840 typist.press("ctrl-z");
2841 assert_eq!(typist.value(), "a\u{FFFC}b");
2842 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2843 assert_eq!(typist.outgoing().images.len(), 1);
2844 }
2845
2846 #[gpui_kit::test]
2847 fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
2848 let mut typist = typist(cx);
2849 typist.type_text("ab");
2850 paste_image(&mut typist, 2);
2851 typist.type_text("cd");
2852 let composer = typist.composer.clone();
2853 let id = typist.cx.update(|cx| {
2854 let state = composer.read(cx).input.read(cx);
2855 super::super::image_id(state.tokens()[0].token()).unwrap()
2856 });
2857 typist.act(|window, cx| {
2858 composer.update(cx, |composer, cx| {
2859 composer.remove_image_token(id, window, cx)
2860 });
2861 });
2862 assert_eq!(typist.value(), "abcd");
2863 assert!(image_tokens(&mut typist).is_empty());
2864 assert!(typist.outgoing().images.is_empty());
2865 typist.press("ctrl-z");
2866 assert_eq!(typist.value(), "ab\u{FFFC}cd");
2867 assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
2868 assert_eq!(typist.outgoing().images.len(), 1);
2869 }
2870
2871 #[gpui_kit::test]
2872 fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
2873 let mut typist = typist(cx);
2874 typist.type_text("x");
2875 paste_image(&mut typist, 2);
2876 typist.type_text("y");
2877 typist.press("ctrl-home");
2878 paste_image(&mut typist, 4);
2879 assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
2880 let outgoing = typist.outgoing();
2881 let dimensions: Vec<_> = outgoing
2882 .images
2883 .iter()
2884 .map(|image| image.dimensions)
2885 .collect();
2886 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
2887 assert_eq!(
2888 outgoing.html(),
2889 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
2890 );
2891 }
2892
2893 #[gpui_kit::test]
2894 fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
2895 let mut typist = typist(cx);
2896 paste_image(&mut typist, 2);
2897 let composer = typist.composer.clone();
2898 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
2899 let outgoing = typist.outgoing();
2900 assert_eq!(outgoing.text(), "");
2901 assert_eq!(outgoing.images.len(), 1);
2902 typist.type_text("hi");
2903 typist.press("ctrl-a ctrl-c");
2904 let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
2905 assert_eq!(copied.as_deref(), Some("hi"));
2906 }
2907
2908 #[gpui_kit::test]
2909 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
2910 let mut typist = typist(cx);
2911 typist
2912 .cx
2913 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
2914 typist.press("ctrl-v");
2915 assert_eq!(typist.value(), "ab");
2916 }
2917
2918 #[gpui_kit::test]
2919 fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
2920 let mut typist = typist(cx);
2921 let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
2922 let composer = typist.composer.clone();
2923 typist.act(|window, cx| {
2924 composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2925 });
2926 assert_eq!(typist.value(), "x\u{FFFC}y");
2927 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2928 let again = typist.outgoing();
2929 assert_eq!(again.images, outgoing.images);
2930 assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
2931 }
2932
2933 #[gpui_kit::test]
2934 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
2935 use teams_core::{FormatState, MarkKind};
2936
2937 let mut typist = typist(cx);
2938 typist.type_text("a **bold**");
2939 assert_eq!(typist.value(), "a bold");
2940 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
2941 typist.press("backspace");
2942 assert_eq!(typist.value(), "a **bold**");
2943 assert!(typist.draft().marks().is_empty());
2944 let composer = typist.composer.clone();
2945 assert_eq!(
2946 typist
2947 .cx
2948 .update(|cx| composer.read(cx).input.read(cx).cursor()),
2949 10
2950 );
2951 typist.press("backspace");
2952 typist.type_text("* x");
2953 assert_eq!(typist.value(), "a bold x");
2954 assert_eq!(
2955 typist.draft().state(6..8, &MarkKind::Bold),
2956 FormatState::Off
2957 );
2958 }
2959
2960 #[gpui_kit::test]
2961 fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
2962 use teams_core::{Mark, MarkKind};
2963
2964 let mut typist = typist(cx);
2965 typist.type_text("see https://a.b ");
2966 assert_eq!(typist.value(), "see https://a.b ");
2967 assert_eq!(
2968 typist.draft().marks(),
2969 [Mark {
2970 range: 4..15,
2971 kind: MarkKind::Link("https://a.b".into())
2972 }]
2973 );
2974 typist.press("backspace");
2975 assert_eq!(typist.value(), "see https://a.b ");
2976 assert!(typist.draft().marks().is_empty());
2977 }
2978
2979 #[gpui_kit::test]
2980 fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
2981 let mut typist = typist(cx);
2982 typist.type_text("https://a.b ");
2983 assert_eq!(typist.draft().marks().len(), 1);
2984 typist.press("ctrl-z");
2985 assert!(typist.draft().marks().is_empty());
2986 }
2987
2988 #[gpui_kit::test]
2989 fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
2990 use teams_core::{Mark, MarkKind};
2991
2992 let mut typist = typist(cx);
2993 typist
2994 .cx
2995 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2996 "x https://a.b y".to_owned(),
2997 ));
2998 typist.press("ctrl-v");
2999 assert_eq!(typist.value(), "x https://a.b y");
3000 assert_eq!(
3001 typist.draft().marks(),
3002 [Mark {
3003 range: 2..13,
3004 kind: MarkKind::Link("https://a.b".into())
3005 }]
3006 );
3007 typist.press("ctrl-z");
3008 assert_eq!(typist.value(), "x https://a.b y");
3009 assert!(typist.draft().marks().is_empty());
3010 }
3011
3012 #[gpui_kit::test]
3013 fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
3014 use teams_core::{Mark, MarkKind};
3015
3016 let mut typist = typist(cx);
3017 typist.type_text("https://a.b x");
3018 typist.press("home");
3019 typist.press("shift-right ".repeat(11).trim_end());
3020 typist.press("ctrl-k");
3021 typist.type_text("other.de");
3022 typist.press("enter");
3023 assert_eq!(
3024 typist.draft().marks(),
3025 [Mark {
3026 range: 0..11,
3027 kind: MarkKind::Link("https://other.de".into())
3028 }]
3029 );
3030 typist.press("ctrl-k backspace enter");
3031 assert!(typist.draft().marks().is_empty());
3032 assert_eq!(typist.value(), "https://a.b x");
3033 }
3034
3035 #[gpui_kit::test]
3036 fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
3037 use teams_core::{Mark, MarkKind};
3038
3039 let mut typist = typist(cx);
3040 typist.type_text("- https://a.b");
3041 typist.press("enter");
3042 assert_eq!(typist.value(), "• https://a.b\n• ");
3043 assert_eq!(
3044 typist.draft().marks(),
3045 [Mark {
3046 range: 4..15,
3047 kind: MarkKind::Link("https://a.b".into())
3048 }]
3049 );
3050 }
3051
3052 #[gpui_kit::test]
3053 fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
3054 let mut typist = typist(cx);
3055 typist
3056 .cx
3057 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3058 "x https://a.b y".to_owned(),
3059 ));
3060 typist.press("ctrl-v");
3061 assert_eq!(typist.draft().marks().len(), 1);
3062 let composer = typist.composer.clone();
3063 assert!(
3064 typist
3065 .cx
3066 .update(|cx| composer.read(cx).paste_hint.is_none())
3067 );
3068 typist.press("ctrl-z");
3069 assert!(typist.draft().marks().is_empty());
3070 }
3071
3072 #[gpui_kit::test]
3073 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
3074 let mut typist = typist(cx);
3075 typist.type_text("1. one");
3076 typist.press("enter");
3077 typist.type_text("two");
3078 assert_eq!(typist.value(), "1. one\n2. two");
3079 typist.press("enter enter");
3080 assert_eq!(typist.value(), "1. one\n2. two\n");
3081 typist.type_text("after");
3082 typist.press("enter");
3083 assert_eq!(typist.value(), "");
3084 }
3085
3086 #[gpui_kit::test]
3087 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
3088 let mut typist = typist(cx);
3089 typist.type_text("- a");
3090 typist.press("enter tab");
3091 typist.type_text("b");
3092 assert_eq!(typist.value(), "• a\n◦ b");
3093 typist.press("shift-tab");
3094 assert_eq!(typist.value(), "• a\n• b");
3095 }
3096
3097 #[gpui_kit::test]
3098 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
3099 use teams_core::{FormatState, MarkKind};
3100
3101 let mut typist = typist(cx);
3102 typist.type_text("hello");
3103 typist.press("shift-left shift-left ctrl-b");
3104 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3105 assert_eq!(
3106 typist.draft().state(0..5, &MarkKind::Bold),
3107 FormatState::Mixed
3108 );
3109 typist.press("ctrl-b");
3110 assert!(typist.draft().marks().is_empty());
3111 typist.press("end ctrl-i");
3112 typist.type_text("!");
3113 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
3114 }
3115
3116 #[gpui_kit::test]
3117 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3118 let mut typist = typist(cx);
3119 typist
3120 .cx
3121 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3122 "**hi** there".to_owned(),
3123 ));
3124 typist.press("ctrl-v");
3125 assert_eq!(typist.value(), "hi there");
3126 let composer = typist.composer.clone();
3127 assert!(
3128 typist
3129 .cx
3130 .update(|cx| composer.read(cx).paste_hint.is_some())
3131 );
3132 typist.press("ctrl-z");
3133 assert_eq!(typist.value(), "**hi** there");
3134 assert!(typist.draft().marks().is_empty());
3135 }
3136
3137 #[gpui_kit::test]
3138 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
3139 use teams_core::{FormatState, MarkKind};
3140
3141 let mut typist = typist(cx);
3142 typist.type_text("`code` ");
3143 typist.press("ctrl-a ctrl-c end ctrl-v");
3144 assert_eq!(typist.value(), "code code ");
3145 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
3146 }
3147
3148 #[gpui_kit::test]
3149 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
3150 use teams_core::{FormatState, MarkKind};
3151
3152 let mut typist = typist(cx);
3153 typist.type_text("~~old~~");
3154 typist.press("ctrl-a");
3155 typist.type_text("new");
3156 typist.press("ctrl-z ctrl-z");
3157 assert_eq!(typist.value(), "old");
3158 assert_eq!(
3159 typist.draft().state(0..3, &MarkKind::Strike),
3160 FormatState::On
3161 );
3162 }
3163
3164 #[gpui_kit::test]
3165 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
3166 let mut typist = typist(cx);
3167 typist.type_text("see docs");
3168 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
3169 let composer = typist.composer.clone();
3170 assert!(
3171 typist
3172 .cx
3173 .update(|cx| composer.read(cx).link_editor.is_some())
3174 );
3175 typist.type_text("example.com");
3176 typist.press("enter");
3177 assert!(
3178 typist
3179 .cx
3180 .update(|cx| composer.read(cx).link_editor.is_none())
3181 );
3182 assert_eq!(
3183 typist.outgoing().html(),
3184 "see <a href=\"https://example.com\">docs</a>"
3185 );
3186 }
3187
3188 #[gpui_kit::test]
3189 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
3190 use teams_core::{FormatState, MarkKind};
3191
3192 let mut typist = typist(cx);
3193 typist.type_text("hello");
3194 typist.press("shift-left shift-left ctrl-b");
3195 typist.press("ctrl-z");
3196 assert_eq!(typist.value(), "hello");
3197 assert!(typist.draft().marks().is_empty());
3198 typist.press("ctrl-y");
3199 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3200 }
3201
3202 #[gpui_kit::test]
3203 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
3204 use teams_core::{FormatState, MarkKind};
3205
3206 let mut typist = typist(cx);
3207 typist.type_text("hello");
3208 typist.press("shift-left shift-left ctrl-b end");
3209 typist.type_text(" x");
3210 typist.press("backspace backspace");
3211 assert_eq!(typist.value(), "hello");
3212 typist.press("ctrl-z");
3213 assert_ne!(typist.value(), "hello");
3214 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3215 }
3216
3217 #[gpui_kit::test]
3218 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
3219 let mut typist = typist(cx);
3220 typist.type_text("```");
3221 typist.press("enter");
3222 typist.type_text("a");
3223 typist.press("enter");
3224 typist.type_text("b");
3225 typist.press("up end delete");
3226 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
3227 }
3228
3229 #[gpui_kit::test]
3230 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
3231 let mut typist = typist(cx);
3232 typist.type_text("```");
3233 typist.press("enter");
3234 typist.type_text(" x");
3235 typist.press("ctrl-a ctrl-c");
3236 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
3237 assert_eq!(text.as_deref(), Some(" x"));
3238 }
3239
3240 #[gpui_kit::test]
3241 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
3242 let mut typist = typist(cx);
3243 typist.type_text("docs");
3244 typist.press("ctrl-a ctrl-k");
3245 typist.type_text("javascript:alert(1)");
3246 typist.press("enter");
3247 let composer = typist.composer.clone();
3248 assert!(typist.cx.update(|cx| {
3249 composer
3250 .read(cx)
3251 .link_editor
3252 .as_ref()
3253 .is_some_and(|editor| editor.refused)
3254 }));
3255 assert!(typist.draft().marks().is_empty());
3256 typist.type_text("x");
3257 assert!(typist.cx.update(|cx| {
3258 composer
3259 .read(cx)
3260 .link_editor
3261 .as_ref()
3262 .is_some_and(|editor| !editor.refused)
3263 }));
3264 }
3265
3266 #[gpui_kit::test]
3267 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
3268 use teams_core::{FormatState, LineKind, MarkKind};
3269
3270 let mut typist = typist(cx);
3271 typist.type_text("hello");
3272 typist.press("ctrl-a ctrl-b");
3273 let composer = typist.composer.clone();
3274 typist.act(|window, cx| {
3275 composer.update(cx, |composer, cx| {
3276 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
3277 })
3278 });
3279 assert_eq!(typist.value(), "• hello");
3280 typist.press("ctrl-z");
3281 assert_eq!(typist.value(), "hello");
3282 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3283 typist.press("ctrl-z");
3284 assert!(typist.draft().marks().is_empty());
3285 assert_eq!(typist.draft().lines(), [LineKind::Text]);
3286 }
3287
3288 #[gpui_kit::test]
3289 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
3290 use teams_core::{FormatState, MarkKind};
3291
3292 let mut typist = typist(cx);
3293 typist.type_text("hello");
3294 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
3295 assert_eq!(typist.value(), "");
3296 typist.press("ctrl-y");
3297 assert_eq!(typist.value(), "hello");
3298 assert!(typist.draft().marks().is_empty());
3299 typist.press("ctrl-y");
3300 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3301 }
3302
3303 fn cursor(typist: &mut Typist<'_>) -> usize {
3304 let composer = typist.composer.clone();
3305 typist
3306 .cx
3307 .update(|cx| composer.read(cx).input.read(cx).cursor())
3308 }
3309
3310 #[gpui_kit::test]
3311 fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there(
3312 cx: &mut TestAppContext,
3313 ) {
3314 let mut typist = typist(cx);
3315 typist.type_text("hello");
3316 typist.press("home");
3317 typist.type_text("X");
3318 typist.press("end ctrl-z");
3319 assert_eq!(typist.value(), "hello");
3320 assert_eq!(cursor(&mut typist), 0);
3321 typist.press("ctrl-y");
3322 assert_eq!(typist.value(), "Xhello");
3323 assert_eq!(cursor(&mut typist), 1);
3324 }
3325
3326 #[gpui_kit::test]
3327 fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) {
3328 let mut typist = typist(cx);
3329 for line in 0..14 {
3330 typist.type_text(&format!("line {line}"));
3331 typist.press("shift-enter");
3332 }
3333 typist.type_text("end");
3334 let composer = typist.composer.clone();
3335 let scroll = |typist: &mut Typist<'_>| {
3336 typist
3337 .cx
3338 .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y)
3339 };
3340 typist.act(|window, cx| window.render_frame(cx));
3341 let before = scroll(&mut typist);
3342 assert!(before < gpui_kit::px(0.));
3343 typist.press("ctrl-z");
3344 typist.act(|window, cx| window.render_frame(cx));
3345 assert_eq!(scroll(&mut typist), before);
3346 }
3347
3348 #[gpui_kit::test]
3349 fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) {
3350 let mut typist = typist(cx);
3351 typist.type_text("ok :) ");
3352 assert!(typist.value().contains('🙂'));
3353 typist.press("ctrl-z");
3354 assert_eq!(typist.value(), "ok :) ");
3355 assert_eq!(typist.outgoing().text(), "ok :)");
3356 }
3357
3358 #[gpui_kit::test]
3359 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
3360 let mut typist = typist(cx);
3361 typist.press("ctrl-z");
3362 typist.type_text("**a**");
3363 assert_eq!(typist.value(), "a");
3364 }
3365
3366 #[gpui_kit::test]
3367 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
3368 let mut typist = typist(cx);
3369 typist.type_text("```");
3370 typist.press("enter");
3371 typist.type_text(":) ");
3372 typist
3373 .cx
3374 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
3375 typist.press("ctrl-v");
3376 assert_eq!(typist.value(), ":) **x**");
3377 let composer = typist.composer.clone();
3378 assert!(
3379 typist
3380 .cx
3381 .update(|cx| composer.read(cx).paste_hint.is_none())
3382 );
3383 let outgoing = typist.outgoing();
3384 assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
3385 }
3386
3387 #[gpui_kit::test]
3388 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3389 let mut typist = typist(cx);
3390 typist.type_text("> quoted");
3391 typist.press("shift-enter");
3392 typist.type_text("more");
3393 let outgoing = typist.outgoing();
3394 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
3395 assert_eq!(outgoing.text(), "quoted\nmore");
3396 }
3397
3398 #[gpui_kit::test]
3399 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
3400 cx.update(gpui_kit::init);
3401 let store = Arc::new(Store::open_in_memory().unwrap());
3402 let mode = Mode {
3403 demo: true,
3404 read_only: false,
3405 demo_sync: None,
3406 };
3407 let (handle, composer) = cx.update(|cx| {
3408 let app = cx.new(|_| AppState::new(store, mode));
3409 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3410 cx.new(|cx| Composer::new(app, window, cx))
3411 })
3412 .unwrap()
3413 });
3414 let directory = tempfile::tempdir().unwrap();
3415 let path = directory.path().join("plan.pdf");
3416 std::fs::write(&path, b"%PDF-1.7").unwrap();
3417 cx.update_window(handle, |_, window, cx| {
3418 composer.update(cx, |composer, cx| {
3419 composer.set_conversation("demo-chat", "Demo", window, cx);
3420 composer.add_paths(vec![path], window, cx);
3421 });
3422 })
3423 .unwrap();
3424 cx.run_until_parked();
3425 cx.update(|cx| {
3426 let composer = composer.read(cx);
3427 assert!(composer.tray.blocks_send());
3428 assert!(!composer.can_send(cx));
3429 });
3430 cx.executor()
3431 .advance_clock(std::time::Duration::from_secs(3));
3432 cx.run_until_parked();
3433 cx.update(|cx| {
3434 let composer = composer.read(cx);
3435 assert!(composer.can_send(cx));
3436 let outgoing = composer
3437 .outgoing(cx)
3438 .expect("an attachment alone is a message");
3439 assert_eq!(outgoing.text(), "");
3440 assert_eq!(outgoing.files.len(), 1);
3441 assert_eq!(outgoing.files[0].name, "plan.pdf");
3442 });
3443 }
3444
3445 #[gpui_kit::test]
3446 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
3447 cx.update(gpui_kit::init);
3448 let store = Arc::new(Store::open_in_memory().unwrap());
3449 let mode = Mode {
3450 demo: true,
3451 read_only: false,
3452 demo_sync: None,
3453 };
3454 let (handle, composer) = cx.update(|cx| {
3455 let app = cx.new(|_| AppState::new(store, mode));
3456 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3457 cx.new(|cx| Composer::new(app, window, cx))
3458 })
3459 .unwrap()
3460 });
3461 let directory = tempfile::tempdir().unwrap();
3462 let path = directory.path().join("plan.pdf");
3463 std::fs::write(&path, b"%PDF-1.7").unwrap();
3464 cx.update_window(handle, |_, window, cx| {
3465 composer.update(cx, |composer, cx| {
3466 composer.set_conversation("demo-chat", "Demo", window, cx);
3467 composer.add_paths(vec![path], window, cx);
3468 });
3469 })
3470 .unwrap();
3471 cx.run_until_parked();
3472 cx.update_window(handle, |_, window, cx| {
3473 composer.update(cx, |composer, cx| {
3474 composer.set_conversation("other-chat", "Other", window, cx)
3475 });
3476 })
3477 .unwrap();
3478 cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));
3479 }
3480
3481 fn demo_composer(
3482 cx: &mut TestAppContext,
3483 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
3484 cx.update(gpui_kit::init);
3485 let store = Arc::new(Store::open_in_memory().unwrap());
3486 let mode = Mode {
3487 demo: true,
3488 read_only: false,
3489 demo_sync: None,
3490 };
3491 let (handle, composer) = cx.update(|cx| {
3492 let app = cx.new(|_| AppState::new(store, mode));
3493 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3494 cx.new(|cx| Composer::new(app, window, cx))
3495 })
3496 .unwrap()
3497 });
3498 (handle, composer)
3499 }
3500
3501 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
3502 let path = directory.join("dot.png");
3503 image::RgbaImage::new(2, 2).save(&path).unwrap();
3504 path
3505 }
3506
3507 #[gpui_kit::test]
3508 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
3509 use super::super::{EditPreview, Outgoing};
3510
3511 let (handle, composer) = demo_composer(cx);
3512 let directory = tempfile::tempdir().unwrap();
3513 let path = directory.path().join("plan.pdf");
3514 std::fs::write(&path, b"%PDF-1.7").unwrap();
3515 cx.update_window(handle, |_, window, cx| {
3516 composer.update(cx, |composer, cx| {
3517 composer.set_conversation("demo-chat", "Demo", window, cx);
3518 composer.add_paths(vec![path], window, cx);
3519 });
3520 })
3521 .unwrap();
3522 cx.run_until_parked();
3523 cx.executor()
3524 .advance_clock(std::time::Duration::from_secs(3));
3525 cx.run_until_parked();
3526 cx.update_window(handle, |_, window, cx| {
3527 composer.update(cx, |composer, cx| {
3528 let draft = Outgoing {
3529 draft: teams_core::Draft::plain("old"),
3530 mentions: Vec::new(),
3531 reply: None,
3532 edit: Some(EditPreview {
3533 message_id: "m1".into(),
3534 excerpt: "old".into(),
3535 }),
3536 images: Vec::new(),
3537 files: Vec::new(),
3538 };
3539 composer.begin_edit(draft, window, cx);
3540 });
3541 })
3542 .unwrap();
3543 cx.update(|cx| {
3544 let composer = composer.read(cx);
3545 assert_eq!(composer.tray.items().len(), 1);
3546 let outgoing = composer.outgoing(cx).unwrap();
3547 assert!(outgoing.files.is_empty());
3548 assert_eq!(outgoing.text(), "old");
3549 });
3550 cx.update_window(handle, |_, window, cx| {
3551 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
3552 })
3553 .unwrap();
3554 cx.update(|cx| {
3555 let composer = composer.read(cx);
3556 assert_eq!(composer.tray.items().len(), 1);
3557 assert!(composer.can_send(cx));
3558 });
3559 }
3560
3561 #[gpui_kit::test]
3562 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
3563 let (handle, composer) = demo_composer(cx);
3564 let directory = tempfile::tempdir().unwrap();
3565 let path = small_png(directory.path());
3566 for (carry, chosen, expected) in [
3567 (Some("chat-a"), "chat-a", 1),
3568 (None, "chat-b", 0),
3569 (Some("chat-a"), "chat-b", 0),
3570 ] {
3571 cx.update_window(handle, |_, window, cx| {
3572 composer.update(cx, |composer, cx| {
3573 composer.set_conversation("", "", window, cx);
3574 composer.add_paths(vec![path.clone()], window, cx);
3575 });
3576 })
3577 .unwrap();
3578 cx.run_until_parked();
3579 cx.update_window(handle, |_, window, cx| {
3580 composer.update(cx, |composer, cx| {
3581 if let Some(chat) = carry {
3582 composer.carry_images_into(chat.to_owned());
3583 }
3584 composer.set_conversation(chosen, "Chat", window, cx);
3585 });
3586 })
3587 .unwrap();
3588 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
3589 }
3590 }
3591
3592 #[gpui_kit::test]
3593 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
3594 cx: &mut TestAppContext,
3595 ) {
3596 let (handle, composer) = demo_composer(cx);
3597 let directory = tempfile::tempdir().unwrap();
3598 let png = small_png(directory.path());
3599 let pdf = directory.path().join("plan.pdf");
3600 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
3601 cx.update_window(handle, |_, window, cx| {
3602 composer.update(cx, |composer, cx| {
3603 composer.set_conversation("bob-chat", "Bob", window, cx);
3604 composer.add_paths(vec![png, pdf], window, cx);
3605 });
3606 })
3607 .unwrap();
3608 cx.run_until_parked();
3609 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
3610 cx.update_window(handle, |_, window, cx| {
3611 composer.update(cx, |composer, cx| {
3612 composer.carry_images_into(String::new());
3613 composer.set_conversation("", "", window, cx);
3614 });
3615 })
3616 .unwrap();
3617 cx.update(|cx| {
3618 let composer = composer.read(cx);
3619 assert_eq!(composer.tray.items().len(), 1);
3620 assert_eq!(composer.tray.items()[0].name, "dot.png");
3621 assert!(!composer.files_allowed());
3622 });
3623 }
3624 }
3625}