BlueGit

ict rusty-teams

Files

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

composer.rs

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