BlueGit

ict rusty-teams

Files

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

composer.rs

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