BlueGit

ict rusty-teams

Files

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

composer.rs

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