BlueGit

ict rusty-teams

Files

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

composer.rs

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