BlueGit

ict rusty-teams

Files

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

composer.rs

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