BlueGit

ict rusty-teams

Files

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

composer.rs

composer.rs 153.1 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, ButtonCustomVariant, 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 .custom(
2469 ButtonCustomVariant::new(cx)
2470 .hover(theme::popup_hover())
2471 .active(theme::popup_hover()),
2472 )
2473 .rounded(px(8.))
2474 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
2475 .size(px(32.))
2476 .tooltip("Emoji, GIFs und Sticker")
2477 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
2478 )
2479 .on_open_change(move |open, window, cx| {
2480 if *open {
2481 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
2482 }
2483 })
2484 .content(move |_, _, cx| {
2485 let popover = cx.entity().downgrade();
2486 picker.update(cx, |picker, _| picker.set_popover(popover));
2487 picker.clone()
2488 })
2489 });
2490 let attach = can_attach.then(|| {
2491 div()
2492 .id("composer-attach")
2493 .size(px(32.))
2494 .flex_none()
2495 .flex()
2496 .items_center()
2497 .justify_center()
2498 .rounded(px(8.))
2499 .cursor_pointer()
2500 .hover(|button| button.bg(theme::popup_hover()))
2501 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2502 .child(symbol("attach_file", COMPOSER_ICON_SIZE, theme::text_muted()))
2503 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2504 });
2505 let composer = cx.weak_entity();
2506 let tokens_composer = composer.clone();
2507 let input = Textarea::new(&self.input)
2508 .appearance(false)
2509 .bordered(false)
2510 .on_paste(move |item, window, cx| {
2511 composer
2512 .update(cx, |this, cx| this.paste(item, window, cx))
2513 .unwrap_or(false)
2514 })
2515 .token(move |context, _, cx| {
2516 if let Some(id) = context
2517 .is_block()
2518 .then(|| image_id(context.token()))
2519 .flatten()
2520 {
2521 let preview = tokens_composer
2522 .read_with(cx, |this, _| this.tray.image(id))
2523 .ok()
2524 .flatten();
2525 let remove_composer = tokens_composer.clone();
2526 return inline_preview(
2527 id,
2528 preview,
2529 context.available_width(),
2530 context.is_selected(),
2531 Rc::new(move |window, cx| {
2532 remove_composer
2533 .update(cx, |this, cx| this.remove_image_token(id, window, cx))
2534 .ok();
2535 }),
2536 );
2537 }
2538 div()
2539 .h(context.line_height())
2540 .px(px(5.))
2541 .rounded(px(5.))
2542 .bg(if context.is_selected() {
2543 theme::accent().opacity(0.4)
2544 } else {
2545 theme::mention_background(false)
2546 })
2547 .text_color(theme::mention_text())
2548 .font_weight(FontWeight::SEMIBOLD)
2549 .child(context.token().label().clone())
2550 .into_any_element()
2551 });
2552 let tray = can_attach
2553 .then(|| {
2554 render_tray(
2555 &self.tray,
2556 Self::remove_attachment,
2557 Self::retry_attachment,
2558 cx,
2559 )
2560 })
2561 .flatten();
2562 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
2563 div()
2564 .w_full()
2565 .mb(px(6.))
2566 .text_size(px(12.))
2567 .text_color(theme::amber())
2568 .child(notice.to_owned())
2569 });
2570 let composer_bounds = self.composer_bounds.clone();
2571 let (inset, top, bottom) = if self.inline {
2572 (0., 0., 0.)
2573 } else {
2574 (20., 8., 16.)
2575 };
2576 v_flex()
2577 .w_full()
2578 .flex_none()
2579 .px(px(inset))
2580 .pt(px(top))
2581 .pb(px(bottom))
2582 .key_context(KEY_CONTEXT)
2583 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2584 if this.link_editor.is_none() {
2585 this.toggle_mark(MarkKind::Bold, cx);
2586 }
2587 }))
2588 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
2589 if this.link_editor.is_none() {
2590 this.toggle_mark(MarkKind::Italic, cx);
2591 }
2592 }))
2593 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
2594 if this.link_editor.is_none() {
2595 this.toggle_mark(MarkKind::Underline, cx);
2596 }
2597 }))
2598 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
2599 if this.link_editor.is_none() {
2600 this.toggle_mark(MarkKind::Strike, cx);
2601 }
2602 }))
2603 .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| {
2604 if this.link_editor.is_none() {
2605 this.toggle_mark(MarkKind::Superscript, cx);
2606 }
2607 }))
2608 .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| {
2609 if this.link_editor.is_none() {
2610 this.toggle_mark(MarkKind::Subscript, cx);
2611 }
2612 }))
2613 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
2614 if this.link_editor.is_none() {
2615 this.toggle_mark(MarkKind::Code, cx);
2616 }
2617 }))
2618 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2619 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2620 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2621 if this.link_editor.is_none() {
2622 this.step_history(true, window, cx);
2623 cx.stop_propagation();
2624 }
2625 }))
2626 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
2627 if this.link_editor.is_none() {
2628 this.step_history(false, window, cx);
2629 cx.stop_propagation();
2630 }
2631 }))
2632 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
2633 if this.link_editor.is_none() && this.copy_selection(cx) {
2634 cx.stop_propagation();
2635 }
2636 }))
2637 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
2638 if this.link_editor.is_none() && this.copy_selection(cx) {
2639 this.input
2640 .update(cx, |state, cx| state.replace("", window, cx));
2641 cx.stop_propagation();
2642 }
2643 }))
2644 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2645 if this.link_editor.is_some() {
2646 } else if this.schedule.is_some() {
2647 this.move_schedule_highlight(-1, window, cx);
2648 cx.stop_propagation();
2649 } else if this.popup_is_open() {
2650 this.move_highlight(-1, cx);
2651 cx.stop_propagation();
2652 } else if this.editing.is_none() && this.is_empty(cx) {
2653 cx.emit(ComposerEvent::EditLast);
2654 cx.stop_propagation();
2655 }
2656 }))
2657 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2658 if this.link_editor.is_some() {
2659 } else if this.schedule.is_some() {
2660 this.move_schedule_highlight(1, window, cx);
2661 cx.stop_propagation();
2662 } else if this.popup_is_open() {
2663 this.move_highlight(1, cx);
2664 cx.stop_propagation();
2665 }
2666 }))
2667 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
2668 if this.link_editor.is_some() {
2669 this.apply_link(window, cx);
2670 cx.stop_propagation();
2671 } else if this.schedule.is_some() {
2672 this.activate_schedule_row(window, cx);
2673 cx.stop_propagation();
2674 } else if this.popup_is_open() {
2675 this.accept_popup(window, cx);
2676 cx.stop_propagation();
2677 } else if this.break_line(action.shift, window, cx) {
2678 cx.stop_propagation();
2679 }
2680 }))
2681 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
2682 if this.link_editor.is_some() {
2683 } else if this.popup_is_open() {
2684 this.accept_popup(window, cx);
2685 cx.stop_propagation();
2686 } else if this.indent(false, window, cx) {
2687 cx.stop_propagation();
2688 }
2689 }))
2690 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
2691 if this.link_editor.is_none() && this.indent(true, window, cx) {
2692 cx.stop_propagation();
2693 }
2694 }))
2695 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
2696 if this.link_editor.is_none()
2697 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
2698 {
2699 cx.stop_propagation();
2700 }
2701 }))
2702 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
2703 if this.link_editor.is_none() && this.delete_forward(window, cx) {
2704 cx.stop_propagation();
2705 }
2706 }))
2707 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2708 if this.schedule.is_some() {
2709 this.close_schedule(window, cx);
2710 cx.stop_propagation();
2711 return;
2712 }
2713 if this.link_editor.is_some() {
2714 this.close_link_editor(window, cx);
2715 cx.stop_propagation();
2716 return;
2717 }
2718 if this.toolbar_requested(cx) {
2719 this.toolbar_dismissed = Some(this.selection(cx));
2720 cx.notify();
2721 cx.stop_propagation();
2722 return;
2723 }
2724 if let Some(popup) = &this.emoji_popup {
2725 this.emoji_dismissed_at = Some(popup.range.start);
2726 }
2727 if this.popup.is_some() || this.emoji_popup.is_some() {
2728 this.close_popup();
2729 cx.notify();
2730 cx.stop_propagation();
2731 } else if this.editing.is_some() {
2732 this.cancel_edit(window, cx);
2733 cx.stop_propagation();
2734 }
2735 }))
2736 .children(notice)
2737 .children(self.render_reply_strip(cx))
2738 .children(self.render_edit_strip(cx))
2739 .children(self.render_meeting_chip())
2740 .children(self.render_link_preview(cx))
2741 .child(
2742 div()
2743 .relative()
2744 .w_full()
2745 .children(self.render_popup(cx))
2746 .children(self.render_emoji_popup(window, cx))
2747 .children(self.render_toolbar(focused, cx))
2748 .children(self.render_schedule(cx))
2749 .child(
2750 v_flex()
2751 .relative()
2752 .w_full()
2753 .rounded(px(12.))
2754 .bg(theme::surface_raised())
2755 .border_1()
2756 .border_color(if focused {
2757 theme::accent()
2758 } else {
2759 transparent_black()
2760 })
2761 .child(
2762 canvas(
2763 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2764 |_, _, _, _| {},
2765 )
2766 .absolute()
2767 .size_full(),
2768 )
2769 .children(tray)
2770 .child(
2771 h_flex()
2772 .w_full()
2773 .items_end()
2774 .gap(px(6.))
2775 .py(px(6.))
2776 .pl(px(if can_attach { 6. } else { 12. }))
2777 .pr(px(6.))
2778 .children(fun)
2779 .children(attach)
2780 .child(
2781 div()
2782 .flex_1()
2783 .min_w_0()
2784 .capture_any_mouse_down(cx.listener(
2785 |this, _: &MouseDownEvent, _, _| {
2786 this.mouse_selecting = true;
2787 this.toolbar_dismissed = None;
2788 this.link_editor = None;
2789 },
2790 ))
2791 .capture_any_mouse_up(cx.listener(
2792 |this, _: &MouseUpEvent, _, cx| {
2793 this.mouse_selecting = false;
2794 cx.notify();
2795 },
2796 ))
2797 .on_mouse_up_out(
2798 MouseButton::Left,
2799 cx.listener(|this, _, _, cx| {
2800 this.mouse_selecting = false;
2801 cx.notify();
2802 }),
2803 )
2804 .child(input),
2805 )
2806 .child(send),
2807 ),
2808 ),
2809 )
2810 .children(self.render_paste_hint())
2811 }
2812}
2813
2814#[cfg(test)]
2815mod tests {
2816 use super::{active_mention, submitted_text};
2817 use gpui_kit::component::input::InputEvent;
2818
2819 fn press(shift: bool) -> InputEvent {
2820 InputEvent::PressEnter {
2821 secondary: false,
2822 shift,
2823 }
2824 }
2825
2826 #[test]
2827 fn enter_sends_trimmed_text() {
2828 assert_eq!(
2829 submitted_text(&press(false), " hello \n"),
2830 Some("hello".into())
2831 );
2832 }
2833
2834 #[test]
2835 fn shift_enter_never_sends() {
2836 assert_eq!(submitted_text(&press(true), "hello"), None);
2837 }
2838
2839 #[test]
2840 fn blank_text_never_sends() {
2841 assert_eq!(submitted_text(&press(false), " \n "), None);
2842 }
2843
2844 #[test]
2845 fn other_events_never_send() {
2846 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
2847 }
2848
2849 #[test]
2850 fn at_sign_opens_a_mention_query() {
2851 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
2852 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
2853 }
2854
2855 #[test]
2856 fn names_with_a_space_keep_the_query_open() {
2857 assert_eq!(
2858 active_mention("@Mara Lin", 9, &[]),
2859 Some((0..9, "Mara Lin".into()))
2860 );
2861 }
2862
2863 #[test]
2864 fn mail_addresses_and_closed_queries_do_not_open() {
2865 assert_eq!(active_mention("a@b", 3, &[]), None);
2866 assert_eq!(active_mention("@Mara ", 6, &[]), None);
2867 assert_eq!(active_mention("@ x", 3, &[]), None);
2868 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
2869 }
2870
2871 #[test]
2872 fn text_inside_a_token_does_not_reopen() {
2873 let token = 0..15;
2874 assert_eq!(
2875 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
2876 None
2877 );
2878 assert_eq!(
2879 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
2880 Some((16..19, "Pr".into()))
2881 );
2882 }
2883
2884 #[test]
2885 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
2886 use std::sync::Arc;
2887
2888 use gpui_kit::{Image, ImageFormat};
2889 use teams_core::FileKind;
2890
2891 use super::super::attachment_tray::InlineImage;
2892 use super::{Outgoing, OutgoingFile, OutgoingImage};
2893
2894 let outgoing = Outgoing {
2895 draft: teams_core::Draft::default(),
2896 subject: None,
2897 mentions: Vec::new(),
2898 link_preview: None,
2899 reply: None,
2900 edit: None,
2901 images: vec![OutgoingImage::Inline(InlineImage {
2902 name: "pasted-image.png".into(),
2903 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
2904 dimensions: Some((1, 1)),
2905 })],
2906 files: vec![OutgoingFile {
2907 name: "plan.pdf".into(),
2908 size: 9,
2909 kind: FileKind::Pdf,
2910 uploaded: None,
2911 reference: teams_core::FileReference {
2912 attachment_id: "guid".into(),
2913 content_url: "https://files.example/plan.pdf".into(),
2914 name: "plan.pdf".into(),
2915 },
2916 }],
2917 };
2918 let extras = outgoing.extras();
2919 assert_eq!(extras.images[0].content_type, "image/png");
2920 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
2921 assert_eq!(extras.files[0].attachment_id, "guid");
2922 assert!(outgoing.has_attachments());
2923 }
2924
2925 fn placed_image(width: u32) -> super::OutgoingImage {
2926 use std::sync::Arc;
2927
2928 use gpui_kit::{Image, ImageFormat};
2929
2930 super::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
2931 name: "pasted-image.png".into(),
2932 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2933 dimensions: Some((width, width)),
2934 })
2935 }
2936
2937 fn remote_gif(title: &str) -> super::OutgoingImage {
2938 super::OutgoingImage::Remote(super::RemoteImage {
2939 kind: crate::remote_image::RemoteKind::Gif,
2940 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
2941 title: title.into(),
2942 width: 200,
2943 height: 100,
2944 })
2945 }
2946
2947 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2948 super::Outgoing {
2949 draft: teams_core::Draft::plain(text),
2950 subject: None,
2951 mentions: Vec::new(),
2952 link_preview: None,
2953 reply: None,
2954 edit: None,
2955 images,
2956 files: Vec::new(),
2957 }
2958 }
2959
2960 #[test]
2961 fn an_image_is_placed_in_the_html_where_its_mark_sits() {
2962 let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
2963 assert_eq!(
2964 outgoing.html(),
2965 "a <img src=\"../hostedContents/1/$value\"> b"
2966 );
2967 assert_eq!(outgoing.text(), "a b");
2968 }
2969
2970 #[test]
2971 fn images_keep_the_order_of_their_marks() {
2972 let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
2973 assert_eq!(
2974 outgoing.html(),
2975 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
2976 );
2977 }
2978
2979 #[test]
2980 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
2981 let outgoing = outgoing_with(
2982 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
2983 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
2984 );
2985 assert_eq!(
2986 outgoing.html(),
2987 "<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\">"
2988 );
2989 assert_eq!(outgoing.extras().images.len(), 2);
2990 }
2991
2992 #[test]
2993 fn a_gif_title_is_escaped_in_the_html() {
2994 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
2995 assert!(outgoing.html().contains("alt=\"a &quot;b&quot; &lt;c&gt;\""));
2996 }
2997
2998 #[test]
2999 fn a_sticker_carries_the_sticker_itemtype() {
3000 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3001 let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
3002 assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
3003 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
3004 }
3005
3006 #[test]
3007 fn a_mark_without_an_image_leaves_no_trace() {
3008 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
3009 }
3010
3011 #[test]
3012 fn enter_sends_attachments_even_without_text() {
3013 assert!(super::is_plain_enter(&press(false)));
3014 assert!(!super::is_plain_enter(&press(true)));
3015 assert!(!super::is_plain_enter(&InputEvent::Change));
3016 }
3017
3018 mod keys {
3019 use std::sync::Arc;
3020
3021 use gpui_kit::test::TestWindowExt as _;
3022 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3023 use store::Store;
3024
3025 use super::super::Composer;
3026 use crate::app_state::{AppState, Mode};
3027
3028 #[gpui_kit::test]
3029 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
3030 cx.update(gpui_kit::init);
3031 let store = Arc::new(Store::open_in_memory().unwrap());
3032 let mode = Mode {
3033 demo: true,
3034 read_only: false,
3035 demo_sync: None,
3036 };
3037 let (handle, composer) = cx.update(|cx| {
3038 let app = cx.new(|_| AppState::new(store, mode));
3039 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3040 cx.new(|cx| Composer::new(app, window, cx))
3041 })
3042 .unwrap()
3043 });
3044 let value = cx
3045 .update_window(handle, |_, window, cx| {
3046 composer.update(cx, |composer, cx| composer.focus(window, cx));
3047 window.render_frame(cx);
3048 window.input("first line", cx);
3049 window.press("shift-enter", cx);
3050 window.input("second line", cx);
3051 window.press("ctrl-a", cx);
3052 window.input("X", cx);
3053 composer.read(cx).input.read(cx).value()
3054 })
3055 .unwrap();
3056 assert_eq!(value, "X");
3057 }
3058
3059 struct Typist<'a> {
3060 cx: &'a mut TestAppContext,
3061 handle: gpui_kit::AnyWindowHandle,
3062 composer: gpui_kit::Entity<Composer>,
3063 }
3064
3065 impl Typist<'_> {
3066 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
3067 self.cx
3068 .update_window(self.handle, |_, window, cx| action(window, cx))
3069 .unwrap();
3070 self.cx.run_until_parked();
3071 }
3072
3073 fn type_text(&mut self, text: &str) {
3074 for character in text.chars() {
3075 self.act(|window, cx| window.input(&character.to_string(), cx));
3076 }
3077 }
3078
3079 fn press(&mut self, keys: &str) {
3080 for key in keys.split(' ') {
3081 self.act(|window, cx| window.press(key, cx));
3082 }
3083 }
3084
3085 fn value(&mut self) -> String {
3086 let composer = self.composer.clone();
3087 self.cx
3088 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
3089 }
3090
3091 fn draft(&mut self) -> teams_core::Draft {
3092 let composer = self.composer.clone();
3093 self.cx.update(|cx| composer.read(cx).draft.clone())
3094 }
3095
3096 fn outgoing(&mut self) -> super::super::Outgoing {
3097 let composer = self.composer.clone();
3098 self.cx
3099 .update(|cx| composer.read(cx).outgoing(cx))
3100 .expect("text to send")
3101 }
3102 }
3103
3104 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
3105 let (handle, composer) = demo_composer(cx);
3106 cx.update(super::super::bind_keys);
3107 let mut typist = Typist {
3108 cx,
3109 handle,
3110 composer: composer.clone(),
3111 };
3112 typist.act(|window, cx| {
3113 composer.update(cx, |composer, cx| composer.focus(window, cx));
3114 window.render_frame(cx);
3115 });
3116 typist
3117 }
3118
3119 fn png_bytes(side: u32) -> Vec<u8> {
3120 let mut bytes = Vec::new();
3121 image::RgbaImage::new(side, side)
3122 .write_to(
3123 &mut std::io::Cursor::new(&mut bytes),
3124 image::ImageFormat::Png,
3125 )
3126 .unwrap();
3127 bytes
3128 }
3129
3130 fn paste_image(typist: &mut Typist<'_>, side: u32) {
3131 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3132 entries: vec![gpui_kit::ClipboardEntry::Image(
3133 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
3134 )],
3135 });
3136 typist.press("ctrl-v");
3137 }
3138
3139 fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
3140 let composer = typist.composer.clone();
3141 typist.cx.update(|cx| {
3142 composer
3143 .read(cx)
3144 .input
3145 .read(cx)
3146 .tokens()
3147 .iter()
3148 .map(|span| (span.range(), span.token().is_block()))
3149 .collect()
3150 })
3151 }
3152
3153 #[gpui_kit::test]
3154 fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
3155 let mut typist = typist(cx);
3156 typist.type_text("ab");
3157 typist.press("left");
3158 paste_image(&mut typist, 2);
3159 assert_eq!(typist.value(), "a\u{FFFC}b");
3160 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3161 let outgoing = typist.outgoing();
3162 assert_eq!(outgoing.images.len(), 1);
3163 assert_eq!(
3164 outgoing.html(),
3165 "a<img src=\"../hostedContents/1/$value\">b"
3166 );
3167 let composer = typist.composer.clone();
3168 assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
3169 }
3170
3171 fn wide_png_bytes() -> Vec<u8> {
3172 let mut bytes = Vec::new();
3173 image::RgbaImage::new(600, 300)
3174 .write_to(
3175 &mut std::io::Cursor::new(&mut bytes),
3176 image::ImageFormat::Png,
3177 )
3178 .unwrap();
3179 bytes
3180 }
3181
3182 fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
3183 let composer = typist.composer.clone();
3184 typist.cx.update(|cx| {
3185 let state = composer.read(cx).input.read(cx);
3186 let cursor = state.cursor();
3187 let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
3188 let viewport = state.input_bounds();
3189 caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
3190 })
3191 }
3192
3193 #[gpui_kit::test]
3194 fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
3195 let mut typist = typist(cx);
3196 typist.type_text("look at this ");
3197 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
3198 entries: vec![gpui_kit::ClipboardEntry::Image(
3199 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
3200 )],
3201 });
3202 typist.press("ctrl-v");
3203 typist.act(|window, _| window.refresh());
3204 typist.type_text("and then more text");
3205 typist.act(|window, _| window.refresh());
3206 assert!(caret_is_visible(&mut typist));
3207 }
3208
3209 #[gpui_kit::test]
3210 fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
3211 let mut typist = typist(cx);
3212 typist.type_text("ab");
3213 typist.press("left");
3214 paste_image(&mut typist, 2);
3215 typist.press("backspace");
3216 assert_eq!(typist.value(), "ab");
3217 assert!(image_tokens(&mut typist).is_empty());
3218 let outgoing = typist.outgoing();
3219 assert!(outgoing.images.is_empty());
3220 assert_eq!(outgoing.html(), "ab");
3221 typist.press("ctrl-z");
3222 assert_eq!(typist.value(), "a\u{FFFC}b");
3223 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3224 assert_eq!(typist.outgoing().images.len(), 1);
3225 }
3226
3227 #[gpui_kit::test]
3228 fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
3229 let mut typist = typist(cx);
3230 typist.type_text("ab");
3231 paste_image(&mut typist, 2);
3232 typist.type_text("cd");
3233 let composer = typist.composer.clone();
3234 let id = typist.cx.update(|cx| {
3235 let state = composer.read(cx).input.read(cx);
3236 super::super::image_id(state.tokens()[0].token()).unwrap()
3237 });
3238 typist.act(|window, cx| {
3239 composer.update(cx, |composer, cx| {
3240 composer.remove_image_token(id, window, cx)
3241 });
3242 });
3243 assert_eq!(typist.value(), "abcd");
3244 assert!(image_tokens(&mut typist).is_empty());
3245 assert!(typist.outgoing().images.is_empty());
3246 typist.press("ctrl-z");
3247 assert_eq!(typist.value(), "ab\u{FFFC}cd");
3248 assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
3249 assert_eq!(typist.outgoing().images.len(), 1);
3250 }
3251
3252 #[gpui_kit::test]
3253 fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
3254 let mut typist = typist(cx);
3255 typist.type_text("x");
3256 paste_image(&mut typist, 2);
3257 typist.type_text("y");
3258 typist.press("ctrl-home");
3259 paste_image(&mut typist, 4);
3260 assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
3261 let outgoing = typist.outgoing();
3262 let dimensions: Vec<_> = outgoing
3263 .images
3264 .iter()
3265 .map(|image| match image {
3266 super::super::OutgoingImage::Inline(inline) => inline.dimensions,
3267 super::super::OutgoingImage::Remote(_) => None,
3268 })
3269 .collect();
3270 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
3271 assert_eq!(
3272 outgoing.html(),
3273 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
3274 );
3275 }
3276
3277 #[gpui_kit::test]
3278 fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
3279 let mut typist = typist(cx);
3280 paste_image(&mut typist, 2);
3281 let composer = typist.composer.clone();
3282 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3283 let outgoing = typist.outgoing();
3284 assert_eq!(outgoing.text(), "");
3285 assert_eq!(outgoing.images.len(), 1);
3286 typist.type_text("hi");
3287 typist.press("ctrl-a ctrl-c");
3288 let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
3289 assert_eq!(copied.as_deref(), Some("hi"));
3290 }
3291
3292 #[gpui_kit::test]
3293 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
3294 let mut typist = typist(cx);
3295 let composer = typist.composer.clone();
3296 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3297 typist.act(|window, cx| {
3298 composer.update(cx, |composer, cx| {
3299 composer.insert_remote_image(
3300 super::super::RemoteImage {
3301 kind: crate::remote_image::RemoteKind::Gif,
3302 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3303 title: "Wave".into(),
3304 width: 200,
3305 height: 100,
3306 },
3307 window,
3308 cx,
3309 )
3310 });
3311 });
3312 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3313 assert_eq!(typist.value(), "\u{FFFC}");
3314 let outgoing = typist.outgoing();
3315 assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3316 assert!(outgoing.extras().images.is_empty());
3317 typist.press("ctrl-z");
3318 assert_eq!(typist.value(), "");
3319 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3320 }
3321
3322 #[gpui_kit::test]
3323 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
3324 let mut typist = typist(cx);
3325 typist.type_text("ab");
3326 typist.press("left");
3327 let composer = typist.composer.clone();
3328 typist.act(|window, cx| {
3329 composer.update(cx, |composer, cx| {
3330 composer.insert_emoji("\u{1F44D}", window, cx)
3331 });
3332 });
3333 assert_eq!(typist.value(), "a\u{1F44D}b");
3334 }
3335
3336 #[gpui_kit::test]
3337 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
3338 let mut typist = typist(cx);
3339 typist
3340 .cx
3341 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
3342 typist.press("ctrl-v");
3343 assert_eq!(typist.value(), "ab");
3344 }
3345
3346 #[gpui_kit::test]
3347 fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
3348 let mut typist = typist(cx);
3349 let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
3350 let composer = typist.composer.clone();
3351 typist.act(|window, cx| {
3352 composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
3353 });
3354 assert_eq!(typist.value(), "x\u{FFFC}y");
3355 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
3356 let again = typist.outgoing();
3357 assert_eq!(again.images, outgoing.images);
3358 assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
3359 }
3360
3361 #[gpui_kit::test]
3362 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
3363 use teams_core::{FormatState, MarkKind};
3364
3365 let mut typist = typist(cx);
3366 typist.type_text("a **bold**");
3367 assert_eq!(typist.value(), "a bold");
3368 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
3369 typist.press("backspace");
3370 assert_eq!(typist.value(), "a **bold**");
3371 assert!(typist.draft().marks().is_empty());
3372 let composer = typist.composer.clone();
3373 assert_eq!(
3374 typist
3375 .cx
3376 .update(|cx| composer.read(cx).input.read(cx).cursor()),
3377 10
3378 );
3379 typist.press("backspace");
3380 typist.type_text("* x");
3381 assert_eq!(typist.value(), "a bold x");
3382 assert_eq!(
3383 typist.draft().state(6..8, &MarkKind::Bold),
3384 FormatState::Off
3385 );
3386 }
3387
3388 #[gpui_kit::test]
3389 fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
3390 use teams_core::{Mark, MarkKind};
3391
3392 let mut typist = typist(cx);
3393 typist.type_text("see https://a.b ");
3394 assert_eq!(typist.value(), "see https://a.b ");
3395 assert_eq!(
3396 typist.draft().marks(),
3397 [Mark {
3398 range: 4..15,
3399 kind: MarkKind::Link("https://a.b".into())
3400 }]
3401 );
3402 typist.press("backspace");
3403 assert_eq!(typist.value(), "see https://a.b ");
3404 assert!(typist.draft().marks().is_empty());
3405 }
3406
3407 #[gpui_kit::test]
3408 fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
3409 let mut typist = typist(cx);
3410 typist.type_text("https://a.b ");
3411 assert_eq!(typist.draft().marks().len(), 1);
3412 typist.press("ctrl-z");
3413 assert!(typist.draft().marks().is_empty());
3414 }
3415
3416 #[gpui_kit::test]
3417 fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3418 use teams_core::{Mark, MarkKind};
3419
3420 let mut typist = typist(cx);
3421 typist
3422 .cx
3423 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3424 "x https://a.b y".to_owned(),
3425 ));
3426 typist.press("ctrl-v");
3427 assert_eq!(typist.value(), "x https://a.b y");
3428 assert_eq!(
3429 typist.draft().marks(),
3430 [Mark {
3431 range: 2..13,
3432 kind: MarkKind::Link("https://a.b".into())
3433 }]
3434 );
3435 typist.press("ctrl-z");
3436 assert_eq!(typist.value(), "x https://a.b y");
3437 assert!(typist.draft().marks().is_empty());
3438 }
3439
3440 #[gpui_kit::test]
3441 fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
3442 use teams_core::{Mark, MarkKind};
3443
3444 let mut typist = typist(cx);
3445 typist.type_text("https://a.b x");
3446 typist.press("home");
3447 typist.press("shift-right ".repeat(11).trim_end());
3448 typist.press("ctrl-k");
3449 typist.type_text("other.de");
3450 typist.press("enter");
3451 assert_eq!(
3452 typist.draft().marks(),
3453 [Mark {
3454 range: 0..11,
3455 kind: MarkKind::Link("https://other.de".into())
3456 }]
3457 );
3458 typist.press("ctrl-k backspace enter");
3459 assert!(typist.draft().marks().is_empty());
3460 assert_eq!(typist.value(), "https://a.b x");
3461 }
3462
3463 #[gpui_kit::test]
3464 fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
3465 use teams_core::{Mark, MarkKind};
3466
3467 let mut typist = typist(cx);
3468 typist.type_text("- https://a.b");
3469 typist.press("enter");
3470 assert_eq!(typist.value(), "• https://a.b\n• ");
3471 assert_eq!(
3472 typist.draft().marks(),
3473 [Mark {
3474 range: 4..15,
3475 kind: MarkKind::Link("https://a.b".into())
3476 }]
3477 );
3478 }
3479
3480 #[gpui_kit::test]
3481 fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
3482 let mut typist = typist(cx);
3483 typist
3484 .cx
3485 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3486 "x https://a.b y".to_owned(),
3487 ));
3488 typist.press("ctrl-v");
3489 assert_eq!(typist.draft().marks().len(), 1);
3490 let composer = typist.composer.clone();
3491 assert!(
3492 typist
3493 .cx
3494 .update(|cx| composer.read(cx).paste_hint.is_none())
3495 );
3496 typist.press("ctrl-z");
3497 assert!(typist.draft().marks().is_empty());
3498 }
3499
3500 #[gpui_kit::test]
3501 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
3502 let mut typist = typist(cx);
3503 typist.type_text("1. one");
3504 typist.press("enter");
3505 typist.type_text("two");
3506 assert_eq!(typist.value(), "1. one\n2. two");
3507 typist.press("enter enter");
3508 assert_eq!(typist.value(), "1. one\n2. two\n");
3509 typist.type_text("after");
3510 typist.press("enter");
3511 assert_eq!(typist.value(), "");
3512 }
3513
3514 #[gpui_kit::test]
3515 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
3516 let mut typist = typist(cx);
3517 typist.type_text("- a");
3518 typist.press("enter tab");
3519 typist.type_text("b");
3520 assert_eq!(typist.value(), "• a\n◦ b");
3521 typist.press("shift-tab");
3522 assert_eq!(typist.value(), "• a\n• b");
3523 }
3524
3525 #[gpui_kit::test]
3526 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
3527 use teams_core::{FormatState, MarkKind};
3528
3529 let mut typist = typist(cx);
3530 typist.type_text("hello");
3531 typist.press("shift-left shift-left ctrl-b");
3532 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3533 assert_eq!(
3534 typist.draft().state(0..5, &MarkKind::Bold),
3535 FormatState::Mixed
3536 );
3537 typist.press("ctrl-b");
3538 assert!(typist.draft().marks().is_empty());
3539 typist.press("end ctrl-i");
3540 typist.type_text("!");
3541 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
3542 }
3543
3544 #[gpui_kit::test]
3545 fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {
3546 let mut typist = typist(cx);
3547 typist.type_text("x2");
3548 typist.press("shift-left ctrl-shift-=");
3549 assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");
3550 typist.press("ctrl-=");
3551 assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");
3552 }
3553
3554 #[gpui_kit::test]
3555 fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {
3556 use teams_core::FormatState;
3557
3558 use super::super::FormatButton;
3559
3560 let mut typist = typist(cx);
3561 typist.type_text("big small");
3562 typist.press("shift-left shift-left shift-left shift-left shift-left");
3563 let composer = typist.composer.clone();
3564 typist.act(|window, cx| {
3565 composer.update(cx, |composer, cx| {
3566 composer.press_format(FormatButton::SizeSmall, window, cx)
3567 })
3568 });
3569 let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {
3570 let composer = typist.composer.clone();
3571 typist.cx.update(|cx| {
3572 let composer = composer.read(cx);
3573 [
3574 FormatButton::SizeSmall,
3575 FormatButton::SizeNormal,
3576 FormatButton::SizeLarge,
3577 ]
3578 .map(|button| composer.format_state(button, &range))
3579 })
3580 };
3581 assert_eq!(
3582 states(&mut typist, 4..9),
3583 [FormatState::On, FormatState::Off, FormatState::Off]
3584 );
3585 assert_eq!(
3586 states(&mut typist, 0..9),
3587 [FormatState::Mixed, FormatState::Off, FormatState::Off]
3588 );
3589 assert_eq!(
3590 states(&mut typist, 0..3),
3591 [FormatState::Off, FormatState::On, FormatState::Off]
3592 );
3593 assert_eq!(
3594 typist.outgoing().html(),
3595 "big <span style=\"font-size:xx-small;\">small</span>"
3596 );
3597 }
3598
3599 #[gpui_kit::test]
3600 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
3601 let mut typist = typist(cx);
3602 typist
3603 .cx
3604 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
3605 "**hi** there".to_owned(),
3606 ));
3607 typist.press("ctrl-v");
3608 assert_eq!(typist.value(), "hi there");
3609 let composer = typist.composer.clone();
3610 assert!(
3611 typist
3612 .cx
3613 .update(|cx| composer.read(cx).paste_hint.is_some())
3614 );
3615 typist.press("ctrl-z");
3616 assert_eq!(typist.value(), "**hi** there");
3617 assert!(typist.draft().marks().is_empty());
3618 }
3619
3620 #[gpui_kit::test]
3621 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
3622 use teams_core::{FormatState, MarkKind};
3623
3624 let mut typist = typist(cx);
3625 typist.type_text("`code` ");
3626 typist.press("ctrl-a ctrl-c end ctrl-v");
3627 assert_eq!(typist.value(), "code code ");
3628 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
3629 }
3630
3631 #[gpui_kit::test]
3632 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
3633 use teams_core::{FormatState, MarkKind};
3634
3635 let mut typist = typist(cx);
3636 typist.type_text("~~old~~");
3637 typist.press("ctrl-a");
3638 typist.type_text("new");
3639 typist.press("ctrl-z ctrl-z");
3640 assert_eq!(typist.value(), "old");
3641 assert_eq!(
3642 typist.draft().state(0..3, &MarkKind::Strike),
3643 FormatState::On
3644 );
3645 }
3646
3647 #[gpui_kit::test]
3648 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
3649 let mut typist = typist(cx);
3650 typist.type_text("see docs");
3651 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
3652 let composer = typist.composer.clone();
3653 assert!(
3654 typist
3655 .cx
3656 .update(|cx| composer.read(cx).link_editor.is_some())
3657 );
3658 typist.type_text("example.com");
3659 typist.press("enter");
3660 assert!(
3661 typist
3662 .cx
3663 .update(|cx| composer.read(cx).link_editor.is_none())
3664 );
3665 assert_eq!(
3666 typist.outgoing().html(),
3667 "see <a href=\"https://example.com\">docs</a>"
3668 );
3669 }
3670
3671 #[gpui_kit::test]
3672 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) {
3673 use teams_core::{FormatState, MarkKind};
3674
3675 let mut typist = typist(cx);
3676 typist.type_text("hello");
3677 typist.press("shift-left shift-left ctrl-b");
3678 typist.press("ctrl-z");
3679 assert_eq!(typist.value(), "hello");
3680 assert!(typist.draft().marks().is_empty());
3681 typist.press("ctrl-y");
3682 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3683 }
3684
3685 #[gpui_kit::test]
3686 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
3687 use teams_core::{FormatState, MarkKind};
3688
3689 let mut typist = typist(cx);
3690 typist.type_text("hello");
3691 typist.press("shift-left shift-left ctrl-b end");
3692 typist.type_text(" x");
3693 typist.press("backspace backspace");
3694 assert_eq!(typist.value(), "hello");
3695 typist.press("ctrl-z");
3696 assert_ne!(typist.value(), "hello");
3697 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
3698 }
3699
3700 #[gpui_kit::test]
3701 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
3702 let mut typist = typist(cx);
3703 typist.type_text("```");
3704 typist.press("enter");
3705 typist.type_text("a");
3706 typist.press("enter");
3707 typist.type_text("b");
3708 typist.press("up end delete");
3709 assert_eq!(typist.outgoing().html(), "<pre>ab</pre>");
3710 }
3711
3712 #[gpui_kit::test]
3713 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
3714 let mut typist = typist(cx);
3715 typist.type_text("```");
3716 typist.press("enter");
3717 typist.type_text(" x");
3718 typist.press("ctrl-a ctrl-c");
3719 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
3720 assert_eq!(text.as_deref(), Some(" x"));
3721 }
3722
3723 #[gpui_kit::test]
3724 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
3725 let mut typist = typist(cx);
3726 typist.type_text("docs");
3727 typist.press("ctrl-a ctrl-k");
3728 typist.type_text("javascript:alert(1)");
3729 typist.press("enter");
3730 let composer = typist.composer.clone();
3731 assert!(typist.cx.update(|cx| {
3732 composer
3733 .read(cx)
3734 .link_editor
3735 .as_ref()
3736 .is_some_and(|editor| editor.refused)
3737 }));
3738 assert!(typist.draft().marks().is_empty());
3739 typist.type_text("x");
3740 assert!(typist.cx.update(|cx| {
3741 composer
3742 .read(cx)
3743 .link_editor
3744 .as_ref()
3745 .is_some_and(|editor| !editor.refused)
3746 }));
3747 }
3748
3749 #[gpui_kit::test]
3750 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
3751 use teams_core::{FormatState, LineKind, MarkKind};
3752
3753 let mut typist = typist(cx);
3754 typist.type_text("hello");
3755 typist.press("ctrl-a ctrl-b");
3756 let composer = typist.composer.clone();
3757 typist.act(|window, cx| {
3758 composer.update(cx, |composer, cx| {
3759 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
3760 })
3761 });
3762 assert_eq!(typist.value(), "• hello");
3763 typist.press("ctrl-z");
3764 assert_eq!(typist.value(), "hello");
3765 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3766 typist.press("ctrl-z");
3767 assert!(typist.draft().marks().is_empty());
3768 assert_eq!(typist.draft().lines(), [LineKind::Text]);
3769 }
3770
3771 #[gpui_kit::test]
3772 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
3773 use teams_core::{FormatState, MarkKind};
3774
3775 let mut typist = typist(cx);
3776 typist.type_text("hello");
3777 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
3778 assert_eq!(typist.value(), "");
3779 typist.press("ctrl-y");
3780 assert_eq!(typist.value(), "hello");
3781 assert!(typist.draft().marks().is_empty());
3782 typist.press("ctrl-y");
3783 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
3784 }
3785
3786 fn cursor(typist: &mut Typist<'_>) -> usize {
3787 let composer = typist.composer.clone();
3788 typist
3789 .cx
3790 .update(|cx| composer.read(cx).input.read(cx).cursor())
3791 }
3792
3793 #[gpui_kit::test]
3794 fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there(
3795 cx: &mut TestAppContext,
3796 ) {
3797 let mut typist = typist(cx);
3798 typist.type_text("hello");
3799 typist.press("home");
3800 typist.type_text("X");
3801 typist.press("end ctrl-z");
3802 assert_eq!(typist.value(), "hello");
3803 assert_eq!(cursor(&mut typist), 0);
3804 typist.press("ctrl-y");
3805 assert_eq!(typist.value(), "Xhello");
3806 assert_eq!(cursor(&mut typist), 1);
3807 }
3808
3809 #[gpui_kit::test]
3810 fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) {
3811 let mut typist = typist(cx);
3812 for line in 0..14 {
3813 typist.type_text(&format!("line {line}"));
3814 typist.press("shift-enter");
3815 }
3816 typist.type_text("end");
3817 let composer = typist.composer.clone();
3818 let scroll = |typist: &mut Typist<'_>| {
3819 typist
3820 .cx
3821 .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y)
3822 };
3823 typist.act(|window, cx| window.render_frame(cx));
3824 let before = scroll(&mut typist);
3825 assert!(before < gpui_kit::px(0.));
3826 typist.press("ctrl-z");
3827 typist.act(|window, cx| window.render_frame(cx));
3828 assert_eq!(scroll(&mut typist), before);
3829 }
3830
3831 #[gpui_kit::test]
3832 fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) {
3833 let mut typist = typist(cx);
3834 typist.type_text("ok :) ");
3835 assert!(typist.value().contains('🙂'));
3836 typist.press("ctrl-z");
3837 assert_eq!(typist.value(), "ok :) ");
3838 assert_eq!(typist.outgoing().text(), "ok :)");
3839 }
3840
3841 #[gpui_kit::test]
3842 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
3843 let mut typist = typist(cx);
3844 typist.press("ctrl-z");
3845 typist.type_text("**a**");
3846 assert_eq!(typist.value(), "a");
3847 }
3848
3849 #[gpui_kit::test]
3850 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
3851 let mut typist = typist(cx);
3852 typist.type_text("```");
3853 typist.press("enter");
3854 typist.type_text(":) ");
3855 typist
3856 .cx
3857 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
3858 typist.press("ctrl-v");
3859 assert_eq!(typist.value(), ":) **x**");
3860 let composer = typist.composer.clone();
3861 assert!(
3862 typist
3863 .cx
3864 .update(|cx| composer.read(cx).paste_hint.is_none())
3865 );
3866 let outgoing = typist.outgoing();
3867 assert_eq!(outgoing.html(), "<pre>:) **x**</pre>");
3868 }
3869
3870 #[gpui_kit::test]
3871 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
3872 let mut typist = typist(cx);
3873 typist.type_text("> quoted");
3874 typist.press("shift-enter");
3875 typist.type_text("more");
3876 let outgoing = typist.outgoing();
3877 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
3878 assert_eq!(outgoing.text(), "quoted\nmore");
3879 }
3880
3881 #[gpui_kit::test]
3882 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
3883 cx.update(gpui_kit::init);
3884 let store = Arc::new(Store::open_in_memory().unwrap());
3885 let mode = Mode {
3886 demo: true,
3887 read_only: false,
3888 demo_sync: None,
3889 };
3890 let (handle, composer) = cx.update(|cx| {
3891 let app = cx.new(|_| AppState::new(store, mode));
3892 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3893 cx.new(|cx| Composer::new(app, window, cx))
3894 })
3895 .unwrap()
3896 });
3897 let directory = tempfile::tempdir().unwrap();
3898 let path = directory.path().join("plan.pdf");
3899 std::fs::write(&path, b"%PDF-1.7").unwrap();
3900 cx.update_window(handle, |_, window, cx| {
3901 composer.update(cx, |composer, cx| {
3902 composer.set_conversation("demo-chat", "Demo", window, cx);
3903 composer.add_paths(vec![path], window, cx);
3904 });
3905 })
3906 .unwrap();
3907 cx.run_until_parked();
3908 cx.update(|cx| {
3909 let composer = composer.read(cx);
3910 assert!(composer.tray.blocks_send());
3911 assert!(!composer.can_send(cx));
3912 });
3913 cx.executor()
3914 .advance_clock(std::time::Duration::from_secs(3));
3915 cx.run_until_parked();
3916 cx.update(|cx| {
3917 let composer = composer.read(cx);
3918 assert!(composer.can_send(cx));
3919 let outgoing = composer
3920 .outgoing(cx)
3921 .expect("an attachment alone is a message");
3922 assert_eq!(outgoing.text(), "");
3923 assert_eq!(outgoing.files.len(), 1);
3924 assert_eq!(outgoing.files[0].name, "plan.pdf");
3925 });
3926 }
3927
3928 #[gpui_kit::test]
3929 fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) {
3930 cx.update(gpui_kit::init);
3931 let store = Arc::new(Store::open_in_memory().unwrap());
3932 let mode = Mode {
3933 demo: true,
3934 read_only: false,
3935 demo_sync: None,
3936 };
3937 let (handle, composer) = cx.update(|cx| {
3938 let app = cx.new(|_| AppState::new(store, mode));
3939 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3940 cx.new(|cx| Composer::new(app, window, cx))
3941 })
3942 .unwrap()
3943 });
3944 let directory = tempfile::tempdir().unwrap();
3945 let path = directory.path().join("plan.pdf");
3946 std::fs::write(&path, b"%PDF-1.7").unwrap();
3947 cx.update_window(handle, |_, window, cx| {
3948 composer.update(cx, |composer, cx| {
3949 composer.set_conversation("demo-chat", "Demo", window, cx);
3950 composer.add_paths(vec![path], window, cx);
3951 });
3952 })
3953 .unwrap();
3954 cx.run_until_parked();
3955 cx.update_window(handle, |_, window, cx| {
3956 composer.update(cx, |composer, cx| {
3957 composer.set_conversation("other-chat", "Other", window, cx)
3958 });
3959 })
3960 .unwrap();
3961 cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));
3962 }
3963
3964 fn demo_composer(
3965 cx: &mut TestAppContext,
3966 ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) {
3967 cx.update(gpui_kit::init);
3968 let store = Arc::new(Store::open_in_memory().unwrap());
3969 let mode = Mode {
3970 demo: true,
3971 read_only: false,
3972 demo_sync: None,
3973 };
3974 let (handle, composer) = cx.update(|cx| {
3975 let app = cx.new(|_| AppState::new(store, mode));
3976 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3977 cx.new(|cx| Composer::new(app, window, cx))
3978 })
3979 .unwrap()
3980 });
3981 (handle, composer)
3982 }
3983
3984 fn small_png(directory: &std::path::Path) -> std::path::PathBuf {
3985 let path = directory.join("dot.png");
3986 image::RgbaImage::new(2, 2).save(&path).unwrap();
3987 path
3988 }
3989
3990 #[gpui_kit::test]
3991 fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) {
3992 use super::super::{EditPreview, Outgoing};
3993
3994 let (handle, composer) = demo_composer(cx);
3995 let directory = tempfile::tempdir().unwrap();
3996 let path = directory.path().join("plan.pdf");
3997 std::fs::write(&path, b"%PDF-1.7").unwrap();
3998 cx.update_window(handle, |_, window, cx| {
3999 composer.update(cx, |composer, cx| {
4000 composer.set_conversation("demo-chat", "Demo", window, cx);
4001 composer.add_paths(vec![path], window, cx);
4002 });
4003 })
4004 .unwrap();
4005 cx.run_until_parked();
4006 cx.executor()
4007 .advance_clock(std::time::Duration::from_secs(3));
4008 cx.run_until_parked();
4009 cx.update_window(handle, |_, window, cx| {
4010 composer.update(cx, |composer, cx| {
4011 let draft = Outgoing {
4012 draft: teams_core::Draft::plain("old"),
4013 subject: None,
4014 mentions: Vec::new(),
4015 link_preview: None,
4016 reply: None,
4017 edit: Some(EditPreview {
4018 message_id: "m1".into(),
4019 excerpt: "old".into(),
4020 scheduled: None,
4021 }),
4022 images: Vec::new(),
4023 files: Vec::new(),
4024 };
4025 composer.begin_edit(draft, window, cx);
4026 });
4027 })
4028 .unwrap();
4029 cx.update(|cx| {
4030 let composer = composer.read(cx);
4031 assert_eq!(composer.tray.items().len(), 1);
4032 let outgoing = composer.outgoing(cx).unwrap();
4033 assert!(outgoing.files.is_empty());
4034 assert_eq!(outgoing.text(), "old");
4035 });
4036 cx.update_window(handle, |_, window, cx| {
4037 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
4038 })
4039 .unwrap();
4040 cx.update(|cx| {
4041 let composer = composer.read(cx);
4042 assert_eq!(composer.tray.items().len(), 1);
4043 assert!(composer.can_send(cx));
4044 });
4045 }
4046
4047 #[gpui_kit::test]
4048 fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) {
4049 let (handle, composer) = demo_composer(cx);
4050 let directory = tempfile::tempdir().unwrap();
4051 let path = small_png(directory.path());
4052 for (carry, chosen, expected) in [
4053 (Some("chat-a"), "chat-a", 1),
4054 (None, "chat-b", 0),
4055 (Some("chat-a"), "chat-b", 0),
4056 ] {
4057 cx.update_window(handle, |_, window, cx| {
4058 composer.update(cx, |composer, cx| {
4059 composer.set_conversation("", "", window, cx);
4060 composer.add_paths(vec![path.clone()], window, cx);
4061 });
4062 })
4063 .unwrap();
4064 cx.run_until_parked();
4065 cx.update_window(handle, |_, window, cx| {
4066 composer.update(cx, |composer, cx| {
4067 if let Some(chat) = carry {
4068 composer.carry_images_into(chat.to_owned());
4069 }
4070 composer.set_conversation(chosen, "Chat", window, cx);
4071 });
4072 })
4073 .unwrap();
4074 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected));
4075 }
4076 }
4077
4078 #[gpui_kit::test]
4079 fn each_conversation_keeps_its_own_draft(cx: &mut TestAppContext) {
4080 let (handle, composer) = demo_composer(cx);
4081 cx.update_window(handle, |_, window, cx| {
4082 composer.update(cx, |composer, cx| {
4083 composer.set_conversation("chat-a", "A", window, cx);
4084 composer.set_text("**hello** there", window, cx);
4085 composer.set_conversation("chat-b", "B", window, cx);
4086 });
4087 })
4088 .unwrap();
4089 cx.update(|cx| {
4090 let composer = composer.read(cx);
4091 assert!(composer.draft.is_blank());
4092 let stored = composer
4093 .app
4094 .read(cx)
4095 .store
4096 .draft("chat-a")
4097 .unwrap()
4098 .unwrap();
4099 assert_eq!(stored.preview, "hello there");
4100 });
4101 cx.update_window(handle, |_, window, cx| {
4102 composer.update(cx, |composer, cx| {
4103 composer.set_text("other", window, cx);
4104 composer.set_conversation("chat-a", "A", window, cx);
4105 });
4106 })
4107 .unwrap();
4108 cx.update(|cx| {
4109 let composer = composer.read(cx);
4110 assert_eq!(composer.draft.text(), "hello there");
4111 assert!(composer.draft.to_html().contains("<b>"));
4112 assert!(
4113 composer
4114 .app
4115 .read(cx)
4116 .store
4117 .draft("chat-b")
4118 .unwrap()
4119 .is_some()
4120 );
4121 });
4122 }
4123
4124 #[gpui_kit::test]
4125 fn sending_clears_the_stored_draft_and_a_blank_composer_deletes_it(
4126 cx: &mut TestAppContext,
4127 ) {
4128 let (handle, composer) = demo_composer(cx);
4129 cx.update_window(handle, |_, window, cx| {
4130 composer.update(cx, |composer, cx| {
4131 composer.set_conversation("chat-a", "A", window, cx);
4132 composer.set_text("hi", window, cx);
4133 composer.save_draft_now(cx);
4134 });
4135 })
4136 .unwrap();
4137 cx.update(|cx| {
4138 assert!(
4139 composer
4140 .read(cx)
4141 .app
4142 .read(cx)
4143 .store
4144 .draft("chat-a")
4145 .unwrap()
4146 .is_some()
4147 );
4148 });
4149 cx.update_window(handle, |_, window, cx| {
4150 composer.update(cx, |composer, cx| composer.submit_current(window, cx));
4151 })
4152 .unwrap();
4153 cx.update(|cx| {
4154 assert!(
4155 composer
4156 .read(cx)
4157 .app
4158 .read(cx)
4159 .store
4160 .draft("chat-a")
4161 .unwrap()
4162 .is_none()
4163 );
4164 });
4165 }
4166
4167 #[gpui_kit::test]
4168 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
4169 cx: &mut TestAppContext,
4170 ) {
4171 let (handle, composer) = demo_composer(cx);
4172 let directory = tempfile::tempdir().unwrap();
4173 let png = small_png(directory.path());
4174 let pdf = directory.path().join("plan.pdf");
4175 std::fs::write(&pdf, b"%PDF-1.7").unwrap();
4176 cx.update_window(handle, |_, window, cx| {
4177 composer.update(cx, |composer, cx| {
4178 composer.set_conversation("bob-chat", "Bob", window, cx);
4179 composer.add_paths(vec![png, pdf], window, cx);
4180 });
4181 })
4182 .unwrap();
4183 cx.run_until_parked();
4184 cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2));
4185 cx.update_window(handle, |_, window, cx| {
4186 composer.update(cx, |composer, cx| {
4187 composer.carry_images_into(String::new());
4188 composer.set_conversation("", "", window, cx);
4189 });
4190 })
4191 .unwrap();
4192 cx.update(|cx| {
4193 let composer = composer.read(cx);
4194 assert_eq!(composer.tray.items().len(), 1);
4195 assert_eq!(composer.tray.items()[0].name, "dot.png");
4196 assert!(!composer.files_allowed());
4197 });
4198 }
4199 }
4200}