BlueGit

ict rusty-teams

Files

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

composer.rs

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