BlueGit

ict rusty-teams

Files

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

composer.rs

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