BlueGit

ict rusty-teams

Files

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

composer.rs

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