BlueGit

ict rusty-teams

Files

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

composer.rs

composer.rs 211.2 KiB Download Raw
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
3use std::ops::Range;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::time::{Duration, Instant};
7
8use 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(error) => {
2300 app_base::diagnostics::record(format!(
2301 "attachments: upload failed: {error}"
2302 ));
2303 return UploadResult::Failed;
2304 }
2305 }
2306 }
2307 JobKind::Share(uploaded) => uploaded,
2308 };
2309 let Some(reference) = uploaded.reference() else {
2310 return UploadResult::Failed;
2311 };
2312 let end = match engine.share_attachment(&conversation_id, &uploaded).await {
2313 Ok(link) => super::attachment_tray::ShareEnd::Linked(link),
2314 Err(error) => {
2315 app_base::diagnostics::record(format!(
2316 "attachments: share failed: {error}"
2317 ));
2318 if matches!(
2319 error,
2320 teams_core::Error::Graph(graph::Error::SharingDenied(_))
2321 ) {
2322 super::attachment_tray::ShareEnd::Denied
2323 } else {
2324 super::attachment_tray::ShareEnd::Failed
2325 }
2326 }
2327 };
2328 super::attachment_tray::result_of_share(uploaded, reference, end)
2329 }
2330 .await;
2331 let _ = finished_sender.send(UploadEvent::Finished(result));
2332 });
2333 self.uploads.insert(id, UploadHandle::Network(handle));
2334 cx.spawn(async move |this, cx| {
2335 while let Some(event) = event_receiver.recv().await {
2336 let updated = this.update(cx, |this, cx| {
2337 let orphan = match event {
2338 UploadEvent::Progress(percent) => {
2339 this.tray.set_progress(id, percent);
2340 None
2341 }
2342 UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded),
2343 UploadEvent::Finished(result) => this.finish_upload(id, result),
2344 };
2345 this.discard_uploaded(orphan.into_iter().collect(), cx);
2346 cx.notify();
2347 });
2348 if updated.is_err() {
2349 break;
2350 }
2351 }
2352 })
2353 .detach();
2354 }
2355
2356 fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) {
2357 let id = job.id;
2358 let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id);
2359 let task = cx.spawn(async move |this, cx| {
2360 for step in 1..=DEMO_UPLOAD_STEPS {
2361 cx.background_executor().timer(DEMO_UPLOAD_STEP).await;
2362 if fails && step == DEMO_FAILURE_STEP {
2363 this.update(cx, |this, cx| {
2364 this.finish_upload_in_demo(id, UploadResult::Failed, cx)
2365 })
2366 .ok();
2367 return;
2368 }
2369 let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8;
2370 this.update(cx, |this, cx| this.set_progress(id, percent, cx))
2371 .ok();
2372 }
2373 let reference = FileReference {
2374 attachment_id: format!("demo-attachment-{id}"),
2375 content_url: format!("https://demo.invalid/files/{}", job.name),
2376 name: job.name,
2377 };
2378 let done = DoneFile {
2379 reference,
2380 uploaded: None,
2381 };
2382 this.update(cx, |this, cx| {
2383 this.finish_upload_in_demo(id, UploadResult::Done(done), cx)
2384 })
2385 .ok();
2386 });
2387 self.uploads.insert(id, UploadHandle::Demo(task));
2388 }
2389
2390 fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) {
2391 self.tray.set_progress(id, percent);
2392 cx.notify();
2393 }
2394
2395 fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> {
2396 self.uploads.remove(&id);
2397 self.tray.finish_upload(id, result)
2398 }
2399
2400 fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) {
2401 self.finish_upload(id, result);
2402 cx.notify();
2403 }
2404
2405 fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
2406 if let Some(handle) = self.uploads.remove(&id) {
2407 handle.cancel();
2408 }
2409 let uploaded = self.tray.remove(id);
2410 self.discard_uploaded(uploaded.into_iter().collect(), cx);
2411 self.schedule_draft_save(cx);
2412 cx.notify();
2413 }
2414
2415 fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) {
2416 if let Some(job) = self.tray.retry(id) {
2417 self.start_upload(job, cx);
2418 }
2419 cx.notify();
2420 }
2421
2422 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2423 if self.scheduling.is_some() && self.scheduling_for == self.conversation_id {
2424 return;
2425 }
2426 let was_editing = self.editing.is_some();
2427 let Some(outgoing) = self.outgoing(cx) else {
2428 return;
2429 };
2430 self.typing.reset();
2431 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
2432 self.mention_inputs.clear();
2433 if self.editing.is_none() {
2434 self.tray.clear();
2435 self.clear_stored_draft(cx);
2436 }
2437 self.reply = None;
2438 self.editing = None;
2439 self.link.reset();
2440 self.close_popup();
2441 self.reset_importance();
2442 self.close_announcement(window, cx);
2443 if was_editing {
2444 self.restore_draft_before_edit(window, cx);
2445 }
2446 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2447 cx.notify();
2448 }
2449
2450 fn with_mention_tokens(
2451 &mut self,
2452 mut content: InputContent,
2453 draft: &Draft,
2454 mentions: &[MentionInput],
2455 ) -> InputContent {
2456 let text = draft.text();
2457 let mut cursor = 0;
2458 for mention in mentions {
2459 let Some(range) = teams_core::plain_mention_spans(draft, &mention.text, false)
2460 .into_iter()
2461 .find(|span| span.start >= cursor)
2462 else {
2463 continue;
2464 };
2465 self.mention_counter += 1;
2466 let token_id = format!("mention-{}", self.mention_counter);
2467 let token = InlineToken::new(token_id.clone(), text[range.clone()].to_owned());
2468 if let Ok(next) = content.clone().with_token(range.clone(), token) {
2469 content = next;
2470 self.mention_inputs.insert(token_id, mention.clone());
2471 cursor = range.end;
2472 }
2473 }
2474 content
2475 }
2476
2477 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2478 let image_ids = if outgoing.edit.is_none() {
2479 self.cancel_uploads();
2480 self.tray.restore(&outgoing.images, &outgoing.files)
2481 } else {
2482 Vec::new()
2483 };
2484 self.restore_content(outgoing, image_ids, window, cx);
2485 }
2486
2487 fn restore_content(
2488 &mut self,
2489 outgoing: &Outgoing,
2490 image_ids: Vec<u64>,
2491 window: &mut Window,
2492 cx: &mut Context<Self>,
2493 ) {
2494 self.mention_inputs.clear();
2495 let text = outgoing.draft.text();
2496 let mut content = InputContent::new(text.to_owned());
2497 for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) {
2498 let range = offset..offset + OBJECT_MARK.len_utf8();
2499 if let Ok(next) = content.clone().with_token(range, image_token(id)) {
2500 content = next;
2501 }
2502 }
2503 let content = self.with_mention_tokens(content, &outgoing.draft, &outgoing.mentions);
2504 self.load_draft(outgoing.draft.clone(), content, window, cx);
2505 self.reply = outgoing.reply.clone();
2506 self.editing = outgoing.edit.clone();
2507 self.link.restore(outgoing.link_preview.clone());
2508 if outgoing.edit.is_none() {
2509 self.restore_announcement(outgoing.banner.as_ref(), window, cx);
2510 if !self.inline && (outgoing.subject.is_some() || outgoing.banner.is_some()) {
2511 cx.emit(ComposerEvent::RestorePost(outgoing.subject.clone()));
2512 }
2513 }
2514 self.close_popup();
2515 self.schedule_draft_save(cx);
2516 cx.notify();
2517 }
2518
2519 /// Text and mentions replace the draft; images join the tray, where oversized ones upload as files.
2520 pub fn load_proposal(
2521 &mut self,
2522 text: &str,
2523 mentions: &[MentionInput],
2524 pictures: Vec<(String, Vec<u8>)>,
2525 window: &mut Window,
2526 cx: &mut Context<Self>,
2527 ) {
2528 let draft = Draft::from_markdown(text);
2529 self.mention_inputs.clear();
2530 let content =
2531 self.with_mention_tokens(InputContent::new(draft.text().to_owned()), &draft, mentions);
2532 self.load_draft(draft, content, window, cx);
2533 self.update_emoji(cx);
2534 self.update_mention(cx);
2535 self.update_link_preview(cx);
2536 for (name, bytes) in pictures {
2537 let ids = self.add_pending(std::slice::from_ref(&name), cx);
2538 let Some(&id) = ids.first() else {
2539 continue;
2540 };
2541 let loaded = LoadedFile {
2542 file_name: Some(name),
2543 ..LoadedFile::new(bytes)
2544 };
2545 self.finish_reading(id, Ok(loaded), window, cx);
2546 }
2547 cx.notify();
2548 }
2549
2550 /// Markdown in `text` arrives formatted.
2551 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2552 let draft = Draft::from_markdown(text);
2553 let content = InputContent::new(draft.text().to_owned());
2554 self.load_draft(draft, content, window, cx);
2555 self.mention_inputs.clear();
2556 self.update_emoji(cx);
2557 self.update_mention(cx);
2558 self.update_link_preview(cx);
2559 cx.notify();
2560 }
2561
2562 pub fn unsent(&self, cx: &App) -> Option<Outgoing> {
2563 (!self.draft.is_blank() && self.editing.is_none()).then(|| self.compose(cx))
2564 }
2565
2566 pub fn is_empty(&self, cx: &App) -> bool {
2567 self.draft.is_blank() && !self.has_attachments(cx)
2568 }
2569
2570 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
2571 self.input.update(cx, |state, cx| state.focus(window, cx));
2572 }
2573
2574 fn render_popup(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<AnyElement> {
2575 let popup = self
2576 .popup
2577 .as_ref()
2578 .filter(|popup| !popup.candidates.is_empty())?;
2579 let at_sign = popup.range.start..popup.range.start + 1;
2580 let anchor = self.input.read(cx).range_to_bounds(&at_sign);
2581 if anchor.is_none() {
2582 window.request_animation_frame();
2583 }
2584 let popup_height = popup.candidates.len() as f32 * POPUP_ROW_HEIGHT + 2. * POPUP_PADDING;
2585 let directory = &self.app.read(cx).directory;
2586 let rows = popup
2587 .candidates
2588 .iter()
2589 .enumerate()
2590 .map(|(index, candidate)| {
2591 let name = candidate.display_name().to_owned();
2592 let avatar = candidate_avatar(candidate, directory);
2593 let subtitle = candidate_subtitle(candidate);
2594 h_flex()
2595 .id(ElementId::Name(format!("mention-row-{index}").into()))
2596 .mx(px(6.))
2597 .px(px(6.))
2598 .h(px(POPUP_ROW_HEIGHT))
2599 .flex_none()
2600 .gap(px(8.))
2601 .items_center()
2602 .rounded(px(6.))
2603 .cursor_pointer()
2604 .when(index == popup.highlighted, |row| {
2605 row.bg(theme::popup_hover())
2606 })
2607 .hover(|row| row.bg(theme::popup_hover()))
2608 .child(avatar)
2609 .child(
2610 v_flex()
2611 .flex_1()
2612 .min_w_0()
2613 .child(
2614 div()
2615 .truncate()
2616 .text_size(px(13.5))
2617 .text_color(theme::text())
2618 .child(name),
2619 )
2620 .when(!subtitle.is_empty(), |column| {
2621 column.child(
2622 div()
2623 .truncate()
2624 .text_size(px(12.))
2625 .text_color(theme::text_muted())
2626 .child(subtitle),
2627 )
2628 }),
2629 )
2630 .on_click(cx.listener(move |this, _, window, cx| {
2631 if let Some(popup) = this.popup.as_mut() {
2632 popup.highlighted = index;
2633 }
2634 this.accept_mention(window, cx);
2635 }))
2636 });
2637 let panel = v_flex()
2638 .id("mention-popup")
2639 .debug_selector(|| MENTION_POPUP_TAG.into())
2640 .w(px(POPUP_WIDTH))
2641 .py(px(POPUP_PADDING))
2642 .rounded(px(10.))
2643 .flyout_surface()
2644 .occlude()
2645 .children(rows);
2646 let Some(anchor) = anchor else {
2647 return Some(
2648 div()
2649 .absolute()
2650 .bottom(relative(1.))
2651 .left_0()
2652 .mb(px(POPUP_GAP))
2653 .child(panel)
2654 .into_any_element(),
2655 );
2656 };
2657 let room_above = f32::from(anchor.top()) - POPUP_GAP - TITLE_BAR_HEIGHT;
2658 let (position, corner) = if room_above >= popup_height {
2659 (
2660 point(anchor.left(), anchor.top() - px(POPUP_GAP)),
2661 Anchor::BottomLeft,
2662 )
2663 } else {
2664 (
2665 point(anchor.left(), anchor.bottom() + px(POPUP_GAP)),
2666 Anchor::TopLeft,
2667 )
2668 };
2669 Some(
2670 deferred(
2671 anchored()
2672 .position(position)
2673 .anchor(corner)
2674 .snap_to_window_with_margin(px(POPUP_GAP))
2675 .child(panel),
2676 )
2677 .with_priority(1)
2678 .into_any_element(),
2679 )
2680 }
2681
2682 fn render_emoji_popup(
2683 &self,
2684 window: &mut Window,
2685 cx: &mut Context<Self>,
2686 ) -> Option<AnyElement> {
2687 let popup = self.emoji_popup.as_ref()?;
2688 let colon = popup.range.start..popup.range.start + 1;
2689 let anchor = self
2690 .input
2691 .read(cx)
2692 .range_to_bounds(&colon)
2693 .map(|bounds| bounds.origin);
2694 if anchor.is_none() {
2695 window.request_animation_frame();
2696 }
2697 let composer = cx.entity().downgrade();
2698 Some(emoji_popup::render(
2699 popup,
2700 anchor,
2701 move |index, window, cx| {
2702 composer
2703 .update(cx, |this, cx| {
2704 if let Some(popup) = this.emoji_popup.as_mut() {
2705 popup.highlighted = index;
2706 }
2707 this.accept_emoji(window, cx);
2708 })
2709 .ok();
2710 },
2711 ))
2712 }
2713
2714 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2715 let composer = cx.entity().downgrade();
2716 let floating = focused
2717 && self.toolbar_requested(cx)
2718 && !self.format_bar_open()
2719 && !self.app.read(cx).markdown_mode;
2720 if self.link_editor.is_none() && !floating {
2721 return None;
2722 }
2723 let state = self.input.read(cx);
2724 let range = self
2725 .link_editor
2726 .as_ref()
2727 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
2728 let start = state.range_to_bounds(&(range.start..range.start))?;
2729 let end = state.range_to_bounds(&(range.end..range.end))?;
2730 let input_bounds = state.input_bounds();
2731 let center_x = if start.origin.y == end.origin.y {
2732 (start.origin.x + end.origin.x) / 2.
2733 } else {
2734 input_bounds.center().x
2735 };
2736 let edges = self
2737 .composer_bounds
2738 .get()
2739 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
2740 (bounds.left(), bounds.right())
2741 });
2742 let width = match self.link_editor {
2743 Some(_) => format_toolbar::link_width(),
2744 None => format_toolbar::bar_width(),
2745 };
2746 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
2747 let element = match &self.link_editor {
2748 Some(editor) => format_toolbar::render(
2749 placement,
2750 format_toolbar::Mode::Link {
2751 field: &editor.field,
2752 refused: editor.refused,
2753 on_apply: Rc::new(move |window, cx| {
2754 composer
2755 .update(cx, |this, cx| this.apply_link(window, cx))
2756 .ok();
2757 }),
2758 },
2759 ),
2760 None => {
2761 let state_of = |button| ButtonState::enabled(self.format_state(button, &range));
2762 let mut overlay = |button| match button {
2763 FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),
2764 _ => None,
2765 };
2766 format_toolbar::render(
2767 placement,
2768 format_toolbar::Mode::Bar {
2769 state: &state_of,
2770 on_press: Rc::new(move |button, window, cx| {
2771 composer
2772 .update(cx, |this, cx| this.press_format(button, window, cx))
2773 .ok();
2774 }),
2775 overlay: &mut overlay,
2776 },
2777 )
2778 }
2779 };
2780 Some(element)
2781 }
2782
2783 fn format_press_handler(&self, cx: &mut Context<Self>) -> format_toolbar::PressHandler {
2784 let composer = cx.weak_entity();
2785 Rc::new(move |button, window, cx| {
2786 composer
2787 .update(cx, |this, cx| this.press_format(button, window, cx))
2788 .ok();
2789 })
2790 }
2791
2792 fn format_bar_fit(&self) -> format_toolbar::BarFit {
2793 let toggle_width = if self.post_layout() {
2794 COMPOSER_BUTTON_SIZE
2795 } else {
2796 0.
2797 };
2798 let available = self.composer_bounds.get().map_or(f32::INFINITY, |bounds| {
2799 f32::from(bounds.size.width) - 2. * (COMPOSER_BUTTON_INSET + 1.) - toggle_width
2800 });
2801 format_toolbar::fit_groups(available, &format_toolbar::BAR_GROUPS)
2802 }
2803
2804 fn render_format_overlay(
2805 &self,
2806 button: FormatButton,
2807 overflow: &[Vec<FormatButton>],
2808 window: &Window,
2809 cx: &mut Context<Self>,
2810 ) -> Option<AnyElement> {
2811 match button {
2812 FormatButton::Table => self.render_table_picker(cx),
2813 FormatButton::TableInsertLine => self.render_table_menu(TableLineMenu::Insert, cx),
2814 FormatButton::TableRemoveLine => self.render_table_menu(TableLineMenu::Remove, cx),
2815 FormatButton::Highlight => self.render_format_popup(FormatPopup::Highlight, cx),
2816 FormatButton::FontColor => self.render_format_popup(FormatPopup::FontColor, cx),
2817 FormatButton::FontSize => self.render_format_popup(FormatPopup::FontSize, cx),
2818 FormatButton::ParagraphStyle => {
2819 self.render_format_popup(FormatPopup::ParagraphStyle, cx)
2820 }
2821 FormatButton::More if self.format_overflow => {
2822 let selection = self.selection(cx);
2823 let in_table = self.in_table(window, cx);
2824 let state_of = |button| self.button_state(button, &selection, in_table);
2825 let on_press = self.format_press_handler(cx);
2826 let mut overlay = |button| self.render_format_overlay(button, &[], window, cx);
2827 let menu = format_toolbar::render_overflow_menu(
2828 overflow,
2829 &state_of,
2830 on_press,
2831 &mut overlay,
2832 );
2833 Some(self.render_overflow_surface(menu, cx))
2834 }
2835 _ => None,
2836 }
2837 }
2838
2839 fn render_format_bar(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
2840 let selection = self.selection(cx);
2841 let in_table = self.in_table(window, cx);
2842 let state_of = |button| self.button_state(button, &selection, in_table);
2843 let on_press = self.format_press_handler(cx);
2844 let fit = self.format_bar_fit();
2845 let mut overlay = |button| self.render_format_overlay(button, &fit.overflow, window, cx);
2846 let row = format_toolbar::render_format_bar(&fit, &state_of, on_press, &mut overlay);
2847 v_flex()
2848 .debug_selector(|| COMPOSER_FORMAT_BAR_TAG.into())
2849 .w_full()
2850 .child(
2851 h_flex()
2852 .w_full()
2853 .p(px(COMPOSER_BUTTON_INSET))
2854 .child(row.flex_1().min_w_0())
2855 .children(self.render_announcement_toggle(cx)),
2856 )
2857 .child(
2858 div()
2859 .debug_selector(|| COMPOSER_FORMAT_DIVIDER_TAG.into())
2860 .w_full()
2861 .h(px(1.))
2862 .bg(theme::border()),
2863 )
2864 .into_any_element()
2865 }
2866
2867 fn render_paste_hint(&self) -> Option<Div> {
2868 self.paste_hint.as_ref()?;
2869 Some(
2870 h_flex()
2871 .mt(px(6.))
2872 .gap(px(6.))
2873 .items_center()
2874 .text_size(px(12.))
2875 .text_color(theme::text_muted())
2876 .child("Formatted from Markdown")
2877 .child(
2878 div()
2879 .px(px(4.))
2880 .py(px(2.))
2881 .rounded(px(4.))
2882 .bg(theme::surface_raised())
2883 .text_size(px(11.))
2884 .text_color(theme::text())
2885 .child("Ctrl+Z"),
2886 )
2887 .child("plain text"),
2888 )
2889 }
2890
2891 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2892 let edit = self.editing.as_ref()?;
2893 Some(
2894 h_flex()
2895 .w_full()
2896 .h(px(52.))
2897 .mb(px(8.))
2898 .gap(px(12.))
2899 .items_center()
2900 .px(px(12.))
2901 .rounded(px(10.))
2902 .bg(theme::row_hover())
2903 .child(match edit.scheduled {
2904 Some(_) => {
2905 symbol("schedule_send", 14., theme::accent_text()).into_any_element()
2906 }
2907 None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2908 })
2909 .child(
2910 v_flex()
2911 .flex_1()
2912 .min_w_0()
2913 .child(
2914 div()
2915 .truncate()
2916 .text_size(px(12.))
2917 .font_weight(FontWeight::SEMIBOLD)
2918 .text_color(theme::accent_text())
2919 .child(match edit.scheduled {
2920 Some(send_at) => format!(
2921 "Editing scheduled message - {}",
2922 scheduled_label(send_at, Utc::now())
2923 ),
2924 None => "Editing message".to_owned(),
2925 }),
2926 )
2927 .child(
2928 div()
2929 .truncate()
2930 .text_size(px(12.))
2931 .text_color(theme::text_muted())
2932 .child(edit.excerpt.clone()),
2933 ),
2934 )
2935 .child(
2936 div()
2937 .id("edit-close")
2938 .size(px(28.))
2939 .flex_none()
2940 .flex()
2941 .items_center()
2942 .justify_center()
2943 .rounded(px(7.))
2944 .cursor_pointer()
2945 .hover(|button| button.bg(theme::row_hover()))
2946 .child(icon(IconName::Close, 14., theme::text_muted()))
2947 .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))),
2948 ),
2949 )
2950 }
2951
2952 fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
2953 let reply = self.reply.as_ref()?;
2954 Some(
2955 h_flex()
2956 .w_full()
2957 .h(px(52.))
2958 .mb(px(8.))
2959 .gap(px(12.))
2960 .items_center()
2961 .px(px(12.))
2962 .rounded(px(10.))
2963 .bg(theme::row_hover())
2964 .child(icon(IconName::Undo2, 14., theme::accent_text()))
2965 .child(
2966 v_flex()
2967 .flex_1()
2968 .min_w_0()
2969 .child(
2970 div()
2971 .truncate()
2972 .text_size(px(12.))
2973 .font_weight(FontWeight::SEMIBOLD)
2974 .text_color(theme::accent_text())
2975 .child(format!("Replying to {}", reply.author)),
2976 )
2977 .child(
2978 div()
2979 .truncate()
2980 .text_size(px(12.))
2981 .text_color(theme::text_muted())
2982 .child(reply.excerpt.clone()),
2983 ),
2984 )
2985 .child(
2986 div()
2987 .id("reply-close")
2988 .size(px(28.))
2989 .flex_none()
2990 .flex()
2991 .items_center()
2992 .justify_center()
2993 .rounded(px(7.))
2994 .cursor_pointer()
2995 .hover(|button| button.bg(theme::row_hover()))
2996 .child(icon(IconName::Close, 14., theme::text_muted()))
2997 .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))),
2998 ),
2999 )
3000 }
3001}
3002
3003impl Render for Composer {
3004 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3005 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
3006 let can_send = self.can_send(cx);
3007 let can_attach = self.editing.is_none();
3008 let send = div()
3009 .id("composer-send")
3010 .debug_selector(|| COMPOSER_SEND_TAG.into())
3011 .size(px(COMPOSER_BUTTON_SIZE))
3012 .ml(px(COMPOSER_BUTTON_INSET))
3013 .flex_none()
3014 .flex()
3015 .items_center()
3016 .justify_center()
3017 .rounded(px(8.))
3018 .child(symbol("send", COMPOSER_ICON_SIZE, theme::text()))
3019 .on_mouse_down(
3020 MouseButton::Right,
3021 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
3022 )
3023 .when(!can_send, |button| button.opacity(0.4))
3024 .when(can_send, |button| {
3025 button
3026 .cursor_pointer()
3027 .hover(|button| button.bg(theme::popup_hover()))
3028 .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx)))
3029 });
3030 let fun = can_attach.then(|| {
3031 let picker = self.fun_picker.clone();
3032 let reset_picker = self.fun_picker.clone();
3033 Popover::new("composer-fun-popover")
3034 .anchor(Anchor::BottomRight)
3035 .offset(px(10.))
3036 .p_0()
3037 .trigger(
3038 Button::new("composer-fun")
3039 .custom(
3040 ButtonCustomVariant::new(cx)
3041 .hover(theme::popup_hover())
3042 .active(theme::popup_hover()),
3043 )
3044 .rounded(px(8.))
3045 .with_size(px(COMPOSER_ICON_SIZE / BUTTON_ICON_SCALE))
3046 .size(px(COMPOSER_BUTTON_SIZE))
3047 .tooltip("Emoji, GIFs und Sticker")
3048 .icon(symbol("mood", COMPOSER_ICON_SIZE, theme::text_muted())),
3049 )
3050 .on_open_change(move |open, window, cx| {
3051 if *open {
3052 reset_picker.update(cx, |picker, cx| picker.reset(window, cx));
3053 }
3054 })
3055 .content(move |_, _, cx| {
3056 let popover = cx.entity().downgrade();
3057 picker.update(cx, |picker, _| picker.set_popover(popover));
3058 picker.clone()
3059 })
3060 });
3061 let attach = can_attach.then(|| self.render_attach_button(cx));
3062 let markdown_mode = self.app.read(cx).markdown_mode;
3063 let post_layout = self.post_layout();
3064 let format_open = (self.format_bar_open() || post_layout) && !markdown_mode;
3065 let format_toggle = (!markdown_mode && !post_layout).then(|| {
3066 div()
3067 .id("composer-format")
3068 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
3069 .size(px(COMPOSER_BUTTON_SIZE))
3070 .flex_none()
3071 .flex()
3072 .items_center()
3073 .justify_center()
3074 .rounded(px(8.))
3075 .cursor_pointer()
3076 .when(format_open, |button| button.bg(theme::popup_hover()))
3077 .hover(|button| button.bg(theme::popup_hover()))
3078 .tooltip(move |window, cx| {
3079 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
3080 })
3081 .child(symbol(
3082 format_toolbar::toggle_symbol(format_open),
3083 COMPOSER_ICON_SIZE,
3084 if format_open {
3085 theme::accent_soft()
3086 } else {
3087 theme::text_muted()
3088 },
3089 ))
3090 .on_mouse_down(MouseButton::Left, |_, window, cx| {
3091 window.prevent_default();
3092 cx.stop_propagation();
3093 })
3094 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
3095 });
3096 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
3097 let actions = h_flex()
3098 .debug_selector(|| COMPOSER_ACTIONS_TAG.into())
3099 .flex_none()
3100 .gap(px(COMPOSER_BUTTON_INSET))
3101 .children(format_toggle)
3102 .children(fun)
3103 .children(attach)
3104 .children(self.render_rewrite_button(cx))
3105 .children(self.render_plus_button(cx));
3106 let stacked = !post_layout
3107 && self
3108 .composer_bounds
3109 .get()
3110 .is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3111 let mut send = Some(send);
3112 let (row_actions, stacked_actions, post_footer) = if post_layout {
3113 (
3114 None,
3115 None,
3116 Some(self.render_post_footer(actions, can_send, cx)),
3117 )
3118 } else if stacked {
3119 (None, Some((actions, send.take())), None)
3120 } else {
3121 (Some(actions.ml(px(COMPOSER_BUTTON_INSET))), None, None)
3122 };
3123 let post_header = self.render_post_header(cx);
3124 let composer = cx.weak_entity();
3125 let tokens_composer = composer.clone();
3126 let input = Textarea::new(&self.input)
3127 .line_box_height(px(COMPOSER_BUTTON_SIZE))
3128 .appearance(false)
3129 .bordered(false)
3130 .on_paste(move |item, window, cx| {
3131 composer
3132 .update(cx, |this, cx| this.paste(item, window, cx))
3133 .unwrap_or(false)
3134 })
3135 .token(move |context, _, cx| {
3136 if context.is_block() && is_rule_token(context.token()) {
3137 return render_rule_token(
3138 context.available_width(),
3139 context.line_height(),
3140 context.is_selected(),
3141 );
3142 }
3143 if context.is_block() && is_table_token(context.token()) {
3144 let token_id = context.token().id().to_string();
3145 let width = context.available_width();
3146 let selected = context.is_selected();
3147 if let Some(table) = tokens_composer
3148 .read_with(cx, |this, _| {
3149 this.render_table_token(&token_id, width, selected)
3150 })
3151 .ok()
3152 .flatten()
3153 {
3154 return table;
3155 }
3156 }
3157 if let Some(id) = context
3158 .is_block()
3159 .then(|| image_id(context.token()))
3160 .flatten()
3161 {
3162 let preview = tokens_composer
3163 .read_with(cx, |this, _| this.tray.image(id))
3164 .ok()
3165 .flatten();
3166 let remove_composer = tokens_composer.clone();
3167 return inline_preview(
3168 id,
3169 preview,
3170 context.available_width(),
3171 context.is_selected(),
3172 Rc::new(move |window, cx| {
3173 remove_composer
3174 .update(cx, |this, cx| this.remove_image_token(id, window, cx))
3175 .ok();
3176 }),
3177 );
3178 }
3179 div()
3180 .h(context.line_height())
3181 .px(px(5.))
3182 .rounded(px(5.))
3183 .bg(if context.is_selected() {
3184 theme::accent().opacity(0.4)
3185 } else {
3186 theme::mention_background(false)
3187 })
3188 .text_color(theme::mention_text())
3189 .font_weight(FontWeight::SEMIBOLD)
3190 .child(context.token().label().clone())
3191 .into_any_element()
3192 });
3193 let tray = can_attach
3194 .then(|| {
3195 render_tray(
3196 &self.tray,
3197 Self::remove_attachment,
3198 Self::retry_attachment,
3199 cx,
3200 )
3201 })
3202 .flatten();
3203 let notice = self.tray.notice().filter(|_| can_attach).map(|notice| {
3204 div()
3205 .w_full()
3206 .mb(px(6.))
3207 .text_size(px(12.))
3208 .text_color(theme::amber())
3209 .child(notice.to_owned())
3210 });
3211 let composer_bounds = self.composer_bounds.clone();
3212 let single_line = {
3213 let state = self.input.read(cx);
3214 state
3215 .line_height()
3216 .is_none_or(|line_height| state.input_bounds().size.height < line_height * 2.)
3217 };
3218 let (inset, top, bottom) = if self.inline {
3219 (0., 0., 0.)
3220 } else {
3221 (20., 0., 16.)
3222 };
3223 v_flex()
3224 .w_full()
3225 .flex_none()
3226 .px(px(inset))
3227 .pt(px(top))
3228 .pb(px(bottom))
3229 .key_context(COMPOSER_KEY_CONTEXT)
3230 .on_action(cx.listener(|this, _: &ToggleBold, window, cx| {
3231 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3232 this.toggle_mark(MarkKind::Bold, cx);
3233 }
3234 }))
3235 .on_action(cx.listener(|this, _: &ToggleItalic, window, cx| {
3236 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3237 this.toggle_mark(MarkKind::Italic, cx);
3238 }
3239 }))
3240 .on_action(cx.listener(|this, _: &ToggleUnderline, window, cx| {
3241 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3242 this.toggle_mark(MarkKind::Underline, cx);
3243 }
3244 }))
3245 .on_action(cx.listener(|this, _: &ToggleStrike, window, cx| {
3246 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3247 this.toggle_mark(MarkKind::Strike, cx);
3248 }
3249 }))
3250 .on_action(cx.listener(|this, _: &ToggleSuperscript, window, cx| {
3251 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3252 this.toggle_mark(MarkKind::Superscript, cx);
3253 }
3254 }))
3255 .on_action(cx.listener(|this, _: &ToggleSubscript, window, cx| {
3256 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3257 this.toggle_mark(MarkKind::Subscript, cx);
3258 }
3259 }))
3260 .on_action(cx.listener(|this, _: &ToggleCode, window, cx| {
3261 if this.link_editor.is_none() && !this.cell_has_focus(window, cx) {
3262 this.toggle_mark(MarkKind::Code, cx);
3263 }
3264 }))
3265 .on_action(cx.listener(|this, _: &EditLink, window, cx| {
3266 if !this.cell_has_focus(window, cx) {
3267 this.edit_link(window, cx);
3268 }
3269 }))
3270 .on_action(
3271 cx.listener(|this, _: &PastePlainText, window, cx| this.paste_plain(window, cx)),
3272 )
3273 .on_action(cx.listener(|this, _: &InsertTableRowAbove, window, cx| {
3274 this.edit_table(TableEdit::InsertRowAbove, window, cx)
3275 }))
3276 .on_action(cx.listener(|this, _: &InsertTableRowBelow, window, cx| {
3277 this.edit_table(TableEdit::InsertRowBelow, window, cx)
3278 }))
3279 .on_action(cx.listener(|this, _: &InsertTableColumnLeft, window, cx| {
3280 this.edit_table(TableEdit::InsertColumnLeft, window, cx)
3281 }))
3282 .on_action(cx.listener(|this, _: &InsertTableColumnRight, window, cx| {
3283 this.edit_table(TableEdit::InsertColumnRight, window, cx)
3284 }))
3285 .on_action(cx.listener(|this, _: &DeleteTableRow, window, cx| {
3286 this.edit_table(TableEdit::DeleteRow, window, cx)
3287 }))
3288 .on_action(cx.listener(|this, _: &DeleteTableColumn, window, cx| {
3289 this.edit_table(TableEdit::DeleteColumn, window, cx)
3290 }))
3291 .on_action(cx.listener(|this, _: &DeleteTable, window, cx| {
3292 this.edit_table(TableEdit::DeleteTable, window, cx)
3293 }))
3294 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
3295 .on_action(cx.listener(|this, _: &ToggleFormatBar, window, cx| {
3296 this.toggle_format_bar(window, cx)
3297 }))
3298 .on_action(
3299 cx.listener(|_, _: &EditLastMessage, _, cx| cx.emit(ComposerEvent::EditLast)),
3300 )
3301 .on_action(cx.listener(|this, _: &InsertTableLine, window, cx| {
3302 this.open_table_menu(TableLineMenu::Insert, window, cx);
3303 }))
3304 .on_action(cx.listener(|this, _: &RemoveTableLine, window, cx| {
3305 this.open_table_menu(TableLineMenu::Remove, window, cx);
3306 }))
3307 .on_action(cx.listener(|this, _: &SetParagraph, window, cx| {
3308 this.set_paragraph_style(None, window, cx)
3309 }))
3310 .on_action(cx.listener(|this, _: &SetHeading1, window, cx| {
3311 this.set_paragraph_style(Some(1), window, cx)
3312 }))
3313 .on_action(cx.listener(|this, _: &SetHeading2, window, cx| {
3314 this.set_paragraph_style(Some(2), window, cx)
3315 }))
3316 .on_action(cx.listener(|this, _: &SetHeading3, window, cx| {
3317 this.set_paragraph_style(Some(3), window, cx)
3318 }))
3319 .on_action(cx.listener(|this, _: &ToggleCodeBlock, window, cx| {
3320 this.toggle_code_block(window, cx)
3321 }))
3322 .on_action(cx.listener(|this, _: &ToggleQuote, window, cx| {
3323 if !this.cell_has_focus(window, cx) {
3324 this.toggle_lines(LineKind::Quote, window, cx)
3325 }
3326 }))
3327 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
3328 if this.side_input_focused(window, cx) {
3329 return;
3330 }
3331 if this.link_editor.is_none() {
3332 this.step_history(true, window, cx);
3333 cx.stop_propagation();
3334 }
3335 }))
3336 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
3337 if this.side_input_focused(window, cx) {
3338 return;
3339 }
3340 if this.link_editor.is_none() {
3341 this.step_history(false, window, cx);
3342 cx.stop_propagation();
3343 }
3344 }))
3345 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
3346 if this.side_input_focused(window, cx) {
3347 return;
3348 }
3349 if this.link_editor.is_none()
3350 && !this.cell_has_focus(window, cx)
3351 && this.copy_selection(cx)
3352 {
3353 cx.stop_propagation();
3354 }
3355 }))
3356 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
3357 if this.side_input_focused(window, cx) {
3358 return;
3359 }
3360 if this.link_editor.is_none()
3361 && !this.cell_has_focus(window, cx)
3362 && this.copy_selection(cx)
3363 {
3364 this.input
3365 .update(cx, |state, cx| state.replace("", window, cx));
3366 cx.stop_propagation();
3367 }
3368 }))
3369 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
3370 if this.side_input_focused(window, cx) {
3371 return;
3372 }
3373 if let Some(menu) = this.table_menu.as_mut() {
3374 menu.step(-1);
3375 cx.notify();
3376 cx.stop_propagation();
3377 } else if this.cell_has_focus(window, cx) {
3378 if this.table_key(TableKey::Up, window, cx) {
3379 cx.stop_propagation();
3380 }
3381 } else if this.link_editor.is_some() {
3382 } else if this.schedule.is_some() {
3383 this.move_schedule_highlight(-1, window, cx);
3384 cx.stop_propagation();
3385 } else if this.popup_is_open() {
3386 this.move_highlight(-1, cx);
3387 cx.stop_propagation();
3388 } else if this.editing.is_none()
3389 && this.is_empty(cx)
3390 && let Some(event) =
3391 up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3392 {
3393 cx.emit(event);
3394 cx.stop_propagation();
3395 }
3396 }))
3397 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
3398 if this.side_input_focused(window, cx) {
3399 return;
3400 }
3401 if let Some(menu) = this.table_menu.as_mut() {
3402 menu.step(1);
3403 cx.notify();
3404 cx.stop_propagation();
3405 } else if this.cell_has_focus(window, cx) {
3406 if this.table_key(TableKey::Down, window, cx) {
3407 cx.stop_propagation();
3408 }
3409 } else if this.link_editor.is_some() {
3410 } else if this.schedule.is_some() {
3411 this.move_schedule_highlight(1, window, cx);
3412 cx.stop_propagation();
3413 } else if this.popup_is_open() {
3414 this.move_highlight(1, cx);
3415 cx.stop_propagation();
3416 } else if this.leave_quote(window, cx) {
3417 cx.stop_propagation();
3418 }
3419 }))
3420 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
3421 if this.side_input_focused(window, cx) {
3422 return;
3423 }
3424 if this.link_editor.is_none()
3425 && !this.cell_has_focus(window, cx)
3426 && this.leave_quote(window, cx)
3427 {
3428 cx.stop_propagation();
3429 }
3430 }))
3431 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
3432 if this.side_input_focused(window, cx) {
3433 return;
3434 }
3435 if this.table_menu.is_some() {
3436 this.accept_table_menu(None, window, cx);
3437 cx.stop_propagation();
3438 } else if this.cell_has_focus(window, cx) {
3439 } else if this.link_editor.is_some() {
3440 this.apply_link(window, cx);
3441 cx.stop_propagation();
3442 } else if this.schedule.is_some() {
3443 this.activate_schedule_row(window, cx);
3444 cx.stop_propagation();
3445 } else if this.popup_is_open() {
3446 this.accept_popup(window, cx);
3447 cx.stop_propagation();
3448 } else if this.break_line(action.shift, window, cx) {
3449 cx.stop_propagation();
3450 } else if enter_starts_line(
3451 enter_behavior(
3452 this.app.read(cx).account_chat_settings().enter_key,
3453 this.format_bar_open() && !this.app.read(cx).markdown_mode,
3454 ),
3455 action.shift,
3456 action.secondary,
3457 ) {
3458 cx.stop_propagation();
3459 window.dispatch_action(
3460 Box::new(Enter {
3461 secondary: false,
3462 shift: true,
3463 }),
3464 cx,
3465 );
3466 }
3467 }))
3468 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
3469 if this.side_input_focused(window, cx) {
3470 return;
3471 }
3472 if this.table_key(TableKey::Next, window, cx) {
3473 cx.stop_propagation();
3474 } else if this.link_editor.is_some() {
3475 } else if this.popup_is_open() {
3476 this.accept_popup(window, cx);
3477 cx.stop_propagation();
3478 } else if this.indent(false, window, cx) {
3479 cx.stop_propagation();
3480 }
3481 }))
3482 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
3483 if this.side_input_focused(window, cx) {
3484 return;
3485 }
3486 if this.table_key(TableKey::Previous, window, cx)
3487 || (this.link_editor.is_none() && this.indent(true, window, cx))
3488 {
3489 cx.stop_propagation();
3490 }
3491 }))
3492 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
3493 if this.side_input_focused(window, cx) {
3494 return;
3495 }
3496 if this.link_editor.is_none()
3497 && !this.cell_has_focus(window, cx)
3498 && (this.undo_conversion(window, cx)
3499 || this.backspace_at_start(window, cx)
3500 || this.enter_table_beside(true, window, cx))
3501 {
3502 cx.stop_propagation();
3503 }
3504 }))
3505 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
3506 if this.side_input_focused(window, cx) {
3507 return;
3508 }
3509 if this.link_editor.is_none()
3510 && !this.cell_has_focus(window, cx)
3511 && (this.enter_table_beside(false, window, cx)
3512 || this.delete_forward(window, cx))
3513 {
3514 cx.stop_propagation();
3515 }
3516 }))
3517 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
3518 if this.table_picker.take().is_some() || this.table_menu.take().is_some() {
3519 cx.notify();
3520 cx.stop_propagation();
3521 return;
3522 }
3523 if this.schedule.is_some() {
3524 this.close_schedule(window, cx);
3525 cx.stop_propagation();
3526 return;
3527 }
3528 if this.link_editor.is_some() {
3529 this.close_link_editor(window, cx);
3530 cx.stop_propagation();
3531 return;
3532 }
3533 if this.close_attach_menu(window, cx) {
3534 cx.stop_propagation();
3535 return;
3536 }
3537 if this.close_rewrite() {
3538 cx.notify();
3539 cx.stop_propagation();
3540 return;
3541 }
3542 if this.toolbar_requested(cx) && !this.format_bar_open() {
3543 this.toolbar_dismissed = Some(this.selection(cx));
3544 cx.notify();
3545 cx.stop_propagation();
3546 return;
3547 }
3548 if let Some(popup) = &this.emoji_popup {
3549 this.emoji_dismissed_at = Some(popup.range.start);
3550 }
3551 if this.slash_popup.is_some() {
3552 this.slash_dismissed = true;
3553 }
3554 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some()
3555 {
3556 this.close_popup();
3557 cx.notify();
3558 cx.stop_propagation();
3559 } else if this.editing.is_some() {
3560 this.cancel_edit(window, cx);
3561 cx.stop_propagation();
3562 }
3563 }))
3564 .children(notice)
3565 .children(self.render_reply_strip(cx))
3566 .children(self.render_edit_strip(cx))
3567 .children(self.render_urgent_banner(cx))
3568 .children(self.render_audience_hint())
3569 .children(self.render_meeting_chip())
3570 .children(self.render_link_preview(cx))
3571 .child(
3572 div()
3573 .relative()
3574 .w_full()
3575 .children(self.render_popup(window, cx))
3576 .children(self.render_slash_popup(cx))
3577 .children(self.render_emoji_popup(window, cx))
3578 .children(self.render_toolbar(focused, cx))
3579 .children(self.render_schedule(cx))
3580 .children(self.render_delivery_menu(cx))
3581 .children(self.render_plus_menu(cx))
3582 .children(self.render_attach_menu(cx))
3583 .children(self.cloud_picker.as_ref().map(|(picker, _)| picker.clone()))
3584 .children(self.render_rewrite_panel(cx))
3585 .child(
3586 v_flex()
3587 .debug_selector(|| COMPOSER_BOX_TAG.into())
3588 .relative()
3589 .w_full()
3590 .rounded(px(12.))
3591 .bg(theme::surface_raised())
3592 .border_1()
3593 .border_color(if focused {
3594 theme::accent()
3595 } else {
3596 transparent_black()
3597 })
3598 .child(
3599 canvas(
3600 move |bounds, window, _| {
3601 let previous = composer_bounds.replace(Some(bounds));
3602 if previous.map(|previous| previous.size.width)
3603 != Some(bounds.size.width)
3604 {
3605 window.refresh();
3606 }
3607 },
3608 |_, _, _, _| {},
3609 )
3610 .absolute()
3611 .size_full(),
3612 )
3613 .children(post_header)
3614 .children(format_bar)
3615 .children(self.render_importance_label(cx))
3616 .children(tray)
3617 .child(
3618 h_flex()
3619 .w_full()
3620 .map(|row| {
3621 if single_line {
3622 row.items_center()
3623 } else {
3624 row.items_end()
3625 }
3626 })
3627 .py(px(COMPOSER_BUTTON_INSET))
3628 .px(px(COMPOSER_BUTTON_INSET))
3629 .child(
3630 div()
3631 .debug_selector(|| COMPOSER_INPUT_TAG.into())
3632 .flex_1()
3633 .min_w_0()
3634 .capture_any_mouse_down(cx.listener(
3635 |this, _: &MouseDownEvent, _, _| {
3636 this.mouse_selecting = true;
3637 this.toolbar_dismissed = None;
3638 this.link_editor = None;
3639 },
3640 ))
3641 .capture_any_mouse_up(cx.listener(
3642 |this, _: &MouseUpEvent, _, cx| {
3643 this.mouse_selecting = false;
3644 cx.notify();
3645 },
3646 ))
3647 .on_mouse_up_out(
3648 MouseButton::Left,
3649 cx.listener(|this, _, _, cx| {
3650 this.mouse_selecting = false;
3651 cx.notify();
3652 }),
3653 )
3654 .child(input),
3655 )
3656 .children(row_actions)
3657 .when_some(send.filter(|_| !post_layout), |row, send| {
3658 row.child(
3659 div()
3660 .flex_none()
3661 .w(px(1.))
3662 .h(px(SEND_DIVIDER_HEIGHT))
3663 .ml(px(COMPOSER_BUTTON_INSET))
3664 .bg(theme::border()),
3665 )
3666 .child(send)
3667 }),
3668 )
3669 .children(stacked_actions.map(|(actions, send)| {
3670 h_flex()
3671 .debug_selector(|| COMPOSER_STACKED_ACTIONS_TAG.into())
3672 .w_full()
3673 .items_center()
3674 .px(px(COMPOSER_BUTTON_INSET))
3675 .pb(px(COMPOSER_BUTTON_INSET))
3676 .child(actions)
3677 .child(div().flex_1())
3678 .children(send)
3679 }))
3680 .children(post_footer),
3681 ),
3682 )
3683 .children(self.render_paste_hint())
3684 }
3685}
3686
3687#[cfg(test)]
3688mod tests {
3689 use super::{
3690 ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_behavior,
3691 enter_starts_line, submitted_text, up_arrow_event,
3692 };
3693
3694 #[test]
3695 fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3696 assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3697 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3698 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3699 assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3700 }
3701
3702 #[test]
3703 fn expanded_compose_box_starts_a_line_on_enter_like_teams() {
3704 assert_eq!(
3705 enter_behavior(EnterKeyBehavior::Send, true),
3706 EnterKeyBehavior::NewLine
3707 );
3708 assert_eq!(
3709 enter_behavior(EnterKeyBehavior::Send, false),
3710 EnterKeyBehavior::Send
3711 );
3712 assert_eq!(
3713 enter_behavior(EnterKeyBehavior::NewLine, false),
3714 EnterKeyBehavior::NewLine
3715 );
3716 }
3717
3718 #[test]
3719 fn up_arrow_follows_the_account_setting() {
3720 assert!(matches!(
3721 up_arrow_event(UpArrowBehavior::EditLastMessage),
3722 Some(ComposerEvent::EditLast)
3723 ));
3724 assert!(matches!(
3725 up_arrow_event(UpArrowBehavior::NavigateToMessages),
3726 Some(ComposerEvent::FocusMessages)
3727 ));
3728 assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3729 }
3730 use gpui_kit::component::input::InputEvent;
3731
3732 fn press(shift: bool) -> InputEvent {
3733 InputEvent::PressEnter {
3734 secondary: false,
3735 shift,
3736 }
3737 }
3738
3739 #[test]
3740 fn enter_sends_trimmed_text() {
3741 assert_eq!(
3742 submitted_text(&press(false), " hello \n"),
3743 Some("hello".into())
3744 );
3745 }
3746
3747 #[test]
3748 fn shift_enter_never_sends() {
3749 assert_eq!(submitted_text(&press(true), "hello"), None);
3750 }
3751
3752 #[test]
3753 fn blank_text_never_sends() {
3754 assert_eq!(submitted_text(&press(false), " \n "), None);
3755 }
3756
3757 #[test]
3758 fn other_events_never_send() {
3759 assert_eq!(submitted_text(&InputEvent::Change, "hello"), None);
3760 }
3761
3762 #[test]
3763 fn at_sign_opens_a_mention_query() {
3764 assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into())));
3765 assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new())));
3766 }
3767
3768 #[test]
3769 fn names_with_a_space_keep_the_query_open() {
3770 assert_eq!(
3771 active_mention("@Mara Lin", 9, &[]),
3772 Some((0..9, "Mara Lin".into()))
3773 );
3774 }
3775
3776 #[test]
3777 fn mail_addresses_and_closed_queries_do_not_open() {
3778 assert_eq!(active_mention("a@b", 3, &[]), None);
3779 assert_eq!(active_mention("@Mara ", 6, &[]), None);
3780 assert_eq!(active_mention("@ x", 3, &[]), None);
3781 assert_eq!(active_mention("@Ma\nrest", 8, &[]), None);
3782 }
3783
3784 #[test]
3785 fn text_inside_a_token_does_not_reopen() {
3786 let token = 0..15;
3787 assert_eq!(
3788 active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)),
3789 None
3790 );
3791 assert_eq!(
3792 active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)),
3793 Some((16..19, "Pr".into()))
3794 );
3795 }
3796
3797 #[test]
3798 fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() {
3799 use std::sync::Arc;
3800
3801 use gpui_kit::{Image, ImageFormat};
3802 use teams_core::FileKind;
3803
3804 use super::super::attachment_tray::InlineImage;
3805 use crate::outgoing::{Outgoing, OutgoingFile, OutgoingImage};
3806
3807 let outgoing = Outgoing {
3808 banner: None,
3809 draft: teams_core::Draft::default(),
3810 subject: None,
3811 mentions: Vec::new(),
3812 link_preview: None,
3813 reply: None,
3814 edit: None,
3815 images: vec![OutgoingImage::Inline(InlineImage {
3816 name: "pasted-image.png".into(),
3817 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
3818 dimensions: Some((1, 1)),
3819 })],
3820 files: vec![OutgoingFile {
3821 name: "plan.pdf".into(),
3822 size: 9,
3823 kind: FileKind::Pdf,
3824 uploaded: None,
3825 reference: teams_core::FileReference {
3826 attachment_id: "guid".into(),
3827 content_url: "https://files.example/plan.pdf".into(),
3828 name: "plan.pdf".into(),
3829 },
3830 }],
3831 importance: Default::default(),
3832 };
3833 let extras = outgoing.extras();
3834 assert_eq!(extras.images[0].content_type, "image/png");
3835 assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]);
3836 assert_eq!(extras.files[0].attachment_id, "guid");
3837 assert!(outgoing.has_attachments());
3838 }
3839
3840 fn placed_image(width: u32) -> crate::outgoing::OutgoingImage {
3841 use std::sync::Arc;
3842
3843 use gpui_kit::{Image, ImageFormat};
3844
3845 crate::outgoing::OutgoingImage::Inline(super::super::attachment_tray::InlineImage {
3846 name: "pasted-image.png".into(),
3847 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
3848 dimensions: Some((width, width)),
3849 })
3850 }
3851
3852 fn remote_gif(title: &str) -> crate::outgoing::OutgoingImage {
3853 crate::outgoing::OutgoingImage::Remote(super::RemoteImage {
3854 kind: crate::remote_image::RemoteKind::Gif,
3855 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
3856 title: title.into(),
3857 width: 200,
3858 height: 100,
3859 })
3860 }
3861
3862 fn outgoing_with(
3863 text: &str,
3864 images: Vec<crate::outgoing::OutgoingImage>,
3865 ) -> crate::outgoing::Outgoing {
3866 crate::outgoing::Outgoing {
3867 banner: None,
3868 draft: teams_core::Draft::plain(text),
3869 subject: None,
3870 mentions: Vec::new(),
3871 link_preview: None,
3872 reply: None,
3873 edit: None,
3874 images,
3875 files: Vec::new(),
3876 importance: Default::default(),
3877 }
3878 }
3879
3880 #[test]
3881 fn an_image_is_placed_in_the_html_where_its_mark_sits() {
3882 let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
3883 assert_eq!(
3884 outgoing.html(),
3885 "a <img src=\"../hostedContents/1/$value\"> b"
3886 );
3887 assert_eq!(outgoing.text(), "a b");
3888 }
3889
3890 #[test]
3891 fn images_keep_the_order_of_their_marks() {
3892 let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
3893 assert_eq!(
3894 outgoing.html(),
3895 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
3896 );
3897 }
3898
3899 #[test]
3900 fn gifs_sit_in_place_and_only_uploaded_images_are_numbered() {
3901 let outgoing = outgoing_with(
3902 "\u{FFFC}a\u{FFFC}b\u{FFFC}",
3903 vec![placed_image(2), remote_gif("Wave"), placed_image(4)],
3904 );
3905 assert_eq!(
3906 outgoing.html(),
3907 "<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\">"
3908 );
3909 assert_eq!(outgoing.extras().images.len(), 2);
3910 }
3911
3912 #[test]
3913 fn a_gif_title_is_escaped_in_the_html() {
3914 let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
3915 assert!(
3916 outgoing
3917 .html()
3918 .contains("alt=\"a &quot;b&quot; &lt;c&gt;\"")
3919 );
3920 }
3921
3922 #[test]
3923 fn a_sticker_carries_the_sticker_itemtype() {
3924 let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3925 let outgoing = outgoing_with(
3926 "\u{FFFC}",
3927 vec![crate::outgoing::OutgoingImage::Remote(sticker)],
3928 );
3929 assert!(
3930 outgoing
3931 .html()
3932 .contains("itemtype=\"http://schema.skype.com/Sticker\"")
3933 );
3934 assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
3935 }
3936
3937 #[test]
3938 fn a_mark_without_an_image_leaves_no_trace() {
3939 assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
3940 }
3941
3942 #[test]
3943 fn enter_sends_attachments_even_without_text() {
3944 assert!(super::is_plain_enter(&press(false)));
3945 assert!(!super::is_plain_enter(&press(true)));
3946 assert!(!super::is_plain_enter(&InputEvent::Change));
3947 }
3948
3949 mod keys {
3950 use std::sync::Arc;
3951
3952 use gpui_kit::test::TestWindowExt as _;
3953 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3954 use store::Store;
3955
3956 use super::super::Composer;
3957 use crate::app_state::{AppState, Mode};
3958
3959 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
3960 #[gpui_kit::test]
3961 fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) {
3962 cx.update(gpui_kit::init);
3963 let store = Arc::new(Store::open_in_memory().unwrap());
3964 let mode = Mode {
3965 demo: true,
3966 read_only: false,
3967 demo_sync: None,
3968 };
3969 let (handle, composer) = cx.update(|cx| {
3970 let app = cx.new(|_| AppState::new(store, mode));
3971 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3972 cx.new(|cx| Composer::new(app, window, cx))
3973 })
3974 .unwrap()
3975 });
3976 let value = cx
3977 .update_window(handle, |_, window, cx| {
3978 composer.update(cx, |composer, cx| composer.focus(window, cx));
3979 window.render_frame(cx);
3980 window.input("first line", cx);
3981 window.press("shift-enter", cx);
3982 window.input("second line", cx);
3983 window.press("ctrl-a", cx);
3984 window.input("X", cx);
3985 composer.read(cx).input.read(cx).value()
3986 })
3987 .unwrap();
3988 assert_eq!(value, "X");
3989 }
3990
3991 struct Typist<'a> {
3992 cx: &'a mut TestAppContext,
3993 handle: gpui_kit::AnyWindowHandle,
3994 composer: gpui_kit::Entity<Composer>,
3995 }
3996
3997 impl Typist<'_> {
3998 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
3999 self.cx
4000 .update_window(self.handle, |_, window, cx| action(window, cx))
4001 .unwrap();
4002 self.cx.run_until_parked();
4003 }
4004
4005 fn type_text(&mut self, text: &str) {
4006 for character in text.chars() {
4007 self.act(|window, cx| window.input(&character.to_string(), cx));
4008 }
4009 }
4010
4011 fn press(&mut self, keys: &str) {
4012 for key in keys.split(' ') {
4013 self.act(|window, cx| window.press(key, cx));
4014 }
4015 }
4016
4017 fn value(&mut self) -> String {
4018 let composer = self.composer.clone();
4019 self.cx
4020 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
4021 }
4022
4023 fn draft(&mut self) -> teams_core::Draft {
4024 let composer = self.composer.clone();
4025 self.cx.update(|cx| composer.read(cx).draft.clone())
4026 }
4027
4028 fn outgoing(&mut self) -> crate::outgoing::Outgoing {
4029 let composer = self.composer.clone();
4030 self.cx
4031 .update(|cx| composer.read(cx).outgoing(cx))
4032 .expect("text to send")
4033 }
4034 }
4035
4036 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
4037 let (handle, composer) = demo_composer(cx);
4038 cx.update(super::super::bind_keys);
4039 let mut typist = Typist {
4040 cx,
4041 handle,
4042 composer: composer.clone(),
4043 };
4044 typist.act(|window, cx| {
4045 composer.update(cx, |composer, cx| composer.focus(window, cx));
4046 window.render_frame(cx);
4047 });
4048 typist
4049 }
4050
4051 fn png_bytes(side: u32) -> Vec<u8> {
4052 let mut bytes = Vec::new();
4053 image::RgbaImage::new(side, side)
4054 .write_to(
4055 &mut std::io::Cursor::new(&mut bytes),
4056 image::ImageFormat::Png,
4057 )
4058 .unwrap();
4059 bytes
4060 }
4061
4062 fn paste_image(typist: &mut Typist<'_>, side: u32) {
4063 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
4064 entries: vec![gpui_kit::ClipboardEntry::Image(
4065 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
4066 )],
4067 });
4068 typist.press("ctrl-v");
4069 }
4070
4071 fn image_ids(composer: &Composer) -> usize {
4072 composer
4073 .tray
4074 .items()
4075 .iter()
4076 .filter(|item| composer.tray.image(item.id).is_some())
4077 .count()
4078 }
4079
4080 fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
4081 let composer = typist.composer.clone();
4082 typist.cx.update(|cx| {
4083 composer
4084 .read(cx)
4085 .input
4086 .read(cx)
4087 .tokens()
4088 .iter()
4089 .map(|span| (span.range(), span.token().is_block()))
4090 .collect()
4091 })
4092 }
4093
4094 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4095 #[gpui_kit::test]
4096 fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
4097 let mut typist = typist(cx);
4098 typist.type_text("ab");
4099 typist.press("left");
4100 paste_image(&mut typist, 2);
4101 assert_eq!(typist.value(), "a\u{FFFC}b");
4102 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
4103 let outgoing = typist.outgoing();
4104 assert_eq!(outgoing.images.len(), 1);
4105 assert_eq!(
4106 outgoing.html(),
4107 "a<img src=\"../hostedContents/1/$value\">b"
4108 );
4109 let composer = typist.composer.clone();
4110 assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
4111 }
4112
4113 fn wide_png_bytes() -> Vec<u8> {
4114 let mut bytes = Vec::new();
4115 image::RgbaImage::new(600, 300)
4116 .write_to(
4117 &mut std::io::Cursor::new(&mut bytes),
4118 image::ImageFormat::Png,
4119 )
4120 .unwrap();
4121 bytes
4122 }
4123
4124 fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
4125 let composer = typist.composer.clone();
4126 typist.cx.update(|cx| {
4127 let state = composer.read(cx).input.read(cx);
4128 let cursor = state.cursor();
4129 let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
4130 let viewport = state.input_bounds();
4131 caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
4132 })
4133 }
4134
4135 #[gpui_kit::test]
4136 fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
4137 let mut typist = typist(cx);
4138 typist.type_text("look at this ");
4139 typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
4140 entries: vec![gpui_kit::ClipboardEntry::Image(
4141 gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
4142 )],
4143 });
4144 typist.press("ctrl-v");
4145 typist.act(|window, _| window.refresh());
4146 typist.type_text("and then more text");
4147 typist.act(|window, _| window.refresh());
4148 assert!(caret_is_visible(&mut typist));
4149 }
4150
4151 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4152 #[gpui_kit::test]
4153 fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
4154 let mut typist = typist(cx);
4155 typist.type_text("ab");
4156 typist.press("left");
4157 paste_image(&mut typist, 2);
4158 typist.press("backspace");
4159 assert_eq!(typist.value(), "ab");
4160 assert!(image_tokens(&mut typist).is_empty());
4161 let outgoing = typist.outgoing();
4162 assert!(outgoing.images.is_empty());
4163 assert_eq!(outgoing.html(), "ab");
4164 typist.press("ctrl-z");
4165 assert_eq!(typist.value(), "a\u{FFFC}b");
4166 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
4167 assert_eq!(typist.outgoing().images.len(), 1);
4168 }
4169
4170 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4171 #[gpui_kit::test]
4172 fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
4173 let mut typist = typist(cx);
4174 typist.type_text("ab");
4175 paste_image(&mut typist, 2);
4176 typist.type_text("cd");
4177 let composer = typist.composer.clone();
4178 let id = typist.cx.update(|cx| {
4179 let state = composer.read(cx).input.read(cx);
4180 super::super::image_id(state.tokens()[0].token()).unwrap()
4181 });
4182 typist.act(|window, cx| {
4183 composer.update(cx, |composer, cx| {
4184 composer.remove_image_token(id, window, cx)
4185 });
4186 });
4187 assert_eq!(typist.value(), "abcd");
4188 assert!(image_tokens(&mut typist).is_empty());
4189 assert!(typist.outgoing().images.is_empty());
4190 typist.press("ctrl-z");
4191 assert_eq!(typist.value(), "ab\u{FFFC}cd");
4192 assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
4193 assert_eq!(typist.outgoing().images.len(), 1);
4194 }
4195
4196 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4197 #[gpui_kit::test]
4198 fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
4199 let mut typist = typist(cx);
4200 typist.type_text("x");
4201 paste_image(&mut typist, 2);
4202 typist.type_text("y");
4203 typist.press("ctrl-home");
4204 paste_image(&mut typist, 4);
4205 assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
4206 let outgoing = typist.outgoing();
4207 let dimensions: Vec<_> = outgoing
4208 .images
4209 .iter()
4210 .map(|image| match image {
4211 crate::outgoing::OutgoingImage::Inline(inline) => inline.dimensions,
4212 crate::outgoing::OutgoingImage::Remote(_) => None,
4213 })
4214 .collect();
4215 assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
4216 assert_eq!(
4217 outgoing.html(),
4218 "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
4219 );
4220 }
4221
4222 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4223 #[gpui_kit::test]
4224 fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
4225 let mut typist = typist(cx);
4226 paste_image(&mut typist, 2);
4227 let composer = typist.composer.clone();
4228 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
4229 let outgoing = typist.outgoing();
4230 assert_eq!(outgoing.text(), "");
4231 assert_eq!(outgoing.images.len(), 1);
4232 typist.type_text("hi");
4233 typist.press("ctrl-a ctrl-c");
4234 let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
4235 assert_eq!(copied.as_deref(), Some("hi"));
4236 }
4237
4238 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4239 #[gpui_kit::test]
4240 fn an_inserted_gif_alone_can_be_sent_and_undo_removes_it(cx: &mut TestAppContext) {
4241 let mut typist = typist(cx);
4242 let composer = typist.composer.clone();
4243 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
4244 typist.act(|window, cx| {
4245 composer.update(cx, |composer, cx| {
4246 composer.insert_remote_image(
4247 super::super::RemoteImage {
4248 kind: crate::remote_image::RemoteKind::Gif,
4249 url: "https://media0.giphy.com/media/a/giphy.gif".into(),
4250 title: "Wave".into(),
4251 width: 200,
4252 height: 100,
4253 },
4254 window,
4255 cx,
4256 )
4257 });
4258 });
4259 assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
4260 assert_eq!(typist.value(), "\u{FFFC}");
4261 let outgoing = typist.outgoing();
4262 assert!(
4263 outgoing
4264 .html()
4265 .starts_with("<img src=\"https://media0.giphy.com/")
4266 );
4267 assert!(outgoing.extras().images.is_empty());
4268 typist.press("ctrl-z");
4269 assert_eq!(typist.value(), "");
4270 assert!(!typist.cx.update(|cx| composer.read(cx).can_send(cx)));
4271 }
4272
4273 #[gpui_kit::test]
4274 fn an_inserted_emoji_lands_at_the_cursor(cx: &mut TestAppContext) {
4275 let mut typist = typist(cx);
4276 typist.type_text("ab");
4277 typist.press("left");
4278 let composer = typist.composer.clone();
4279 typist.act(|window, cx| {
4280 composer.update(cx, |composer, cx| {
4281 composer.insert_emoji("\u{1F44D}", window, cx)
4282 });
4283 });
4284 assert_eq!(typist.value(), "a\u{1F44D}b");
4285 }
4286
4287 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4288 #[gpui_kit::test]
4289 fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
4290 let mut typist = typist(cx);
4291 typist
4292 .cx
4293 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
4294 typist.press("ctrl-v");
4295 assert_eq!(typist.value(), "ab");
4296 }
4297
4298 #[gpui_kit::test]
4299 fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
4300 let mut typist = typist(cx);
4301 let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
4302 let composer = typist.composer.clone();
4303 typist.act(|window, cx| {
4304 composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
4305 });
4306 assert_eq!(typist.value(), "x\u{FFFC}y");
4307 assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
4308 let again = typist.outgoing();
4309 assert_eq!(again.images, outgoing.images);
4310 assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
4311 }
4312
4313 fn load(
4314 typist: &mut Typist<'_>,
4315 entry: &crate::agent_api::ProposalEntry,
4316 ) -> Vec<(String, Vec<u8>)> {
4317 let composer = typist.composer.clone();
4318 let mentions = crate::views::proposal_card::outgoing_for(entry, None).mentions;
4319 let pictures = crate::views::proposal_card::picture_files(entry);
4320 let loaded = pictures.clone();
4321 let text = entry.proposal.text.clone();
4322 typist.act(|window, cx| {
4323 composer.update(cx, |composer, cx| {
4324 composer.load_proposal(&text, &mentions, pictures, window, cx)
4325 });
4326 });
4327 loaded
4328 }
4329
4330 #[gpui_kit::test]
4331 fn a_loaded_proposal_keeps_its_mentions_images_and_the_reply(cx: &mut TestAppContext) {
4332 use crate::views::proposal_card::{sample_entry, sample_png};
4333
4334 let mut typist = typist(cx);
4335 let entry = sample_entry(
4336 "Thanks @Ada Example",
4337 &[("u1", "Ada Example")],
4338 &[sample_png(3, 0)],
4339 );
4340 let composer = typist.composer.clone();
4341 let reply = super::super::ReplyPreview {
4342 message_id: "m1".into(),
4343 author: "Bo".into(),
4344 excerpt: "question".into(),
4345 };
4346 typist.act(|_, cx| {
4347 composer.update(cx, |composer, cx| {
4348 composer.set_reply(Some(reply.clone()), cx)
4349 });
4350 });
4351 load(&mut typist, &entry);
4352 let tokens = image_tokens(&mut typist);
4353 assert_eq!(tokens.iter().filter(|(_, block)| *block).count(), 1);
4354 assert_eq!(tokens.len(), 2);
4355 let outgoing = typist.outgoing();
4356 assert_eq!(outgoing.images.len(), 1);
4357 assert_eq!(
4358 outgoing.mentions,
4359 [teams_core::MentionInput::user("u1", "Ada Example")]
4360 );
4361 assert_eq!(outgoing.reply, Some(reply));
4362 assert!(outgoing.html().starts_with("Thanks @Ada Example"));
4363 }
4364
4365 #[gpui_kit::test]
4366 fn a_mention_at_the_start_of_a_line_is_placed_on_send(cx: &mut TestAppContext) {
4367 use crate::views::proposal_card::sample_entry;
4368
4369 let mut typist = typist(cx);
4370 let entry = sample_entry("Hi team\n\n@Ada\n\nthanks", &[], &[]);
4371 load(&mut typist, &entry);
4372 let composer = typist.composer.clone();
4373 typist.act(|window, cx| {
4374 composer.update(cx, |composer, cx| {
4375 composer.load_proposal(
4376 "Hi team\n\n@Ada\n\nthanks",
4377 &[teams_core::MentionInput::user("u1", "Ada")],
4378 Vec::new(),
4379 window,
4380 cx,
4381 )
4382 });
4383 });
4384 let outgoing = typist.outgoing();
4385 let (_, placed) = teams_core::apply_mentions(&outgoing.html(), &outgoing.mentions);
4386 assert_eq!(placed.len(), 1, "{}", outgoing.html());
4387 }
4388
4389 #[gpui_kit::test]
4390 fn a_text_only_proposal_keeps_a_running_upload(cx: &mut TestAppContext) {
4391 use crate::views::proposal_card::sample_entry;
4392
4393 let mut typist = typist(cx);
4394 let composer = typist.composer.clone();
4395 typist.act(|_, cx| {
4396 composer.update(cx, |composer, _| {
4397 let ids = composer.tray.add_pending(&["plan.pdf".to_owned()]);
4398 assert_eq!(ids.len(), 1);
4399 });
4400 });
4401 load(&mut typist, &sample_entry("just text", &[], &[]));
4402 let items = typist.cx.update(|cx| composer.read(cx).tray.items().len());
4403 assert_eq!(items, 1);
4404 assert_eq!(typist.value(), "just text");
4405 }
4406
4407 #[gpui_kit::test]
4408 fn proposal_images_join_the_tray_and_big_ones_become_uploads(cx: &mut TestAppContext) {
4409 use crate::views::proposal_card::{sample_entry, sample_png};
4410
4411 let mut typist = typist(cx);
4412 let composer = typist.composer.clone();
4413 typist.act(|_, cx| {
4414 composer.update(cx, |composer, _| {
4415 composer.conversation_id = Some("c1".to_owned());
4416 composer.tray.add_pending(&["kept.pdf".to_owned()]);
4417 });
4418 });
4419 let entry = sample_entry(
4420 "pictures",
4421 &[],
4422 &[sample_png(2, 0), sample_png(2, 2 * 1024 * 1024)],
4423 );
4424 load(&mut typist, &entry);
4425 let (items, images) = typist.cx.update(|cx| {
4426 let composer = composer.read(cx);
4427 (composer.tray.items().len(), image_ids(composer))
4428 });
4429 assert_eq!(items, 3);
4430 assert_eq!(images, 1);
4431 }
4432
4433 #[gpui_kit::test]
4434 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
4435 use teams_core::{FormatState, MarkKind};
4436
4437 let mut typist = typist(cx);
4438 typist.type_text("a **bold**");
4439 assert_eq!(typist.value(), "a bold");
4440 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
4441 typist.press("backspace");
4442 assert_eq!(typist.value(), "a **bold**");
4443 assert!(typist.draft().marks().is_empty());
4444 let composer = typist.composer.clone();
4445 assert_eq!(
4446 typist
4447 .cx
4448 .update(|cx| composer.read(cx).input.read(cx).cursor()),
4449 10
4450 );
4451 typist.press("backspace");
4452 typist.type_text("* x");
4453 assert_eq!(typist.value(), "a bold x");
4454 assert_eq!(
4455 typist.draft().state(6..8, &MarkKind::Bold),
4456 FormatState::Off
4457 );
4458 }
4459
4460 #[gpui_kit::test]
4461 fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) {
4462 use teams_core::{Mark, MarkKind};
4463
4464 let mut typist = typist(cx);
4465 typist.type_text("see https://a.b ");
4466 assert_eq!(typist.value(), "see https://a.b ");
4467 assert_eq!(
4468 typist.draft().marks(),
4469 [Mark {
4470 range: 4..15,
4471 kind: MarkKind::Link("https://a.b".into())
4472 }]
4473 );
4474 typist.press("backspace");
4475 assert_eq!(typist.value(), "see https://a.b ");
4476 assert!(typist.draft().marks().is_empty());
4477 }
4478
4479 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4480 #[gpui_kit::test]
4481 fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) {
4482 let mut typist = typist(cx);
4483 typist.type_text("https://a.b ");
4484 assert_eq!(typist.draft().marks().len(), 1);
4485 typist.press("ctrl-z");
4486 assert!(typist.draft().marks().is_empty());
4487 }
4488
4489 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4490 #[gpui_kit::test]
4491 fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
4492 use teams_core::{Mark, MarkKind};
4493
4494 let mut typist = typist(cx);
4495 typist
4496 .cx
4497 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4498 "x https://a.b y".to_owned(),
4499 ));
4500 typist.press("ctrl-v");
4501 assert_eq!(typist.value(), "x https://a.b y");
4502 assert_eq!(
4503 typist.draft().marks(),
4504 [Mark {
4505 range: 2..13,
4506 kind: MarkKind::Link("https://a.b".into())
4507 }]
4508 );
4509 typist.press("ctrl-z");
4510 assert_eq!(typist.value(), "x https://a.b y");
4511 assert!(typist.draft().marks().is_empty());
4512 }
4513
4514 #[gpui_kit::test]
4515 fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) {
4516 use teams_core::{Mark, MarkKind};
4517
4518 let mut typist = typist(cx);
4519 typist.type_text("https://a.b x");
4520 typist.press("home");
4521 typist.press("shift-right ".repeat(11).trim_end());
4522 typist.press("ctrl-k");
4523 typist.type_text("other.de");
4524 typist.press("enter");
4525 assert_eq!(
4526 typist.draft().marks(),
4527 [Mark {
4528 range: 0..11,
4529 kind: MarkKind::Link("https://other.de".into())
4530 }]
4531 );
4532 typist.press("ctrl-k backspace enter");
4533 assert!(typist.draft().marks().is_empty());
4534 assert_eq!(typist.value(), "https://a.b x");
4535 }
4536
4537 #[gpui_kit::test]
4538 fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) {
4539 use teams_core::{Mark, MarkKind};
4540
4541 let mut typist = typist(cx);
4542 typist.type_text("- https://a.b");
4543 typist.press("enter");
4544 assert_eq!(typist.value(), "• https://a.b\n• ");
4545 assert_eq!(
4546 typist.draft().marks(),
4547 [Mark {
4548 range: 4..15,
4549 kind: MarkKind::Link("https://a.b".into())
4550 }]
4551 );
4552 }
4553
4554 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4555 #[gpui_kit::test]
4556 fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) {
4557 let mut typist = typist(cx);
4558 typist
4559 .cx
4560 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4561 "x https://a.b y".to_owned(),
4562 ));
4563 typist.press("ctrl-v");
4564 assert_eq!(typist.draft().marks().len(), 1);
4565 let composer = typist.composer.clone();
4566 assert!(
4567 typist
4568 .cx
4569 .update(|cx| composer.read(cx).paste_hint.is_none())
4570 );
4571 typist.press("ctrl-z");
4572 assert!(typist.draft().marks().is_empty());
4573 }
4574
4575 #[gpui_kit::test]
4576 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
4577 let mut typist = typist(cx);
4578 typist.type_text("1. one");
4579 typist.press("enter");
4580 typist.type_text("two");
4581 assert_eq!(typist.value(), "1. one\n2. two");
4582 typist.press("enter enter");
4583 assert_eq!(typist.value(), "1. one\n2. two\n");
4584 typist.type_text("after");
4585 typist.press("enter");
4586 assert_eq!(typist.value(), "");
4587 }
4588
4589 #[gpui_kit::test]
4590 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
4591 let mut typist = typist(cx);
4592 typist.type_text("- a");
4593 typist.press("enter tab");
4594 typist.type_text("b");
4595 assert_eq!(typist.value(), "• a\n◦ b");
4596 typist.press("shift-tab");
4597 assert_eq!(typist.value(), "• a\n• b");
4598 }
4599
4600 #[gpui_kit::test]
4601 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
4602 use teams_core::{FormatState, MarkKind};
4603
4604 let mut typist = typist(cx);
4605 typist.type_text("hello");
4606 typist.press("shift-left shift-left ctrl-b");
4607 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
4608 assert_eq!(
4609 typist.draft().state(0..5, &MarkKind::Bold),
4610 FormatState::Mixed
4611 );
4612 typist.press("ctrl-b");
4613 assert!(typist.draft().marks().is_empty());
4614 typist.press("end ctrl-i");
4615 typist.type_text("!");
4616 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
4617 }
4618
4619 #[gpui_kit::test]
4620 fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) {
4621 let mut typist = typist(cx);
4622 typist.type_text("x2");
4623 typist.press("shift-left ctrl-shift-=");
4624 assert_eq!(typist.outgoing().html(), "x<sup>2</sup>");
4625 typist.press("ctrl-=");
4626 assert_eq!(typist.outgoing().html(), "x<sub>2</sub>");
4627 }
4628
4629 #[gpui_kit::test]
4630 fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) {
4631 use teams_core::FormatState;
4632
4633 use super::super::FormatButton;
4634
4635 let mut typist = typist(cx);
4636 typist.type_text("big small");
4637 typist.press("shift-left shift-left shift-left shift-left shift-left");
4638 let composer = typist.composer.clone();
4639 typist.act(|window, cx| {
4640 composer.update(cx, |composer, cx| {
4641 composer.press_format(FormatButton::SizeSmall, window, cx)
4642 })
4643 });
4644 let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| {
4645 let composer = typist.composer.clone();
4646 typist.cx.update(|cx| {
4647 let composer = composer.read(cx);
4648 [
4649 FormatButton::SizeSmall,
4650 FormatButton::SizeNormal,
4651 FormatButton::SizeLarge,
4652 ]
4653 .map(|button| composer.format_state(button, &range))
4654 })
4655 };
4656 assert_eq!(
4657 states(&mut typist, 4..9),
4658 [FormatState::On, FormatState::Off, FormatState::Off]
4659 );
4660 assert_eq!(
4661 states(&mut typist, 0..9),
4662 [FormatState::Mixed, FormatState::Off, FormatState::Off]
4663 );
4664 assert_eq!(
4665 states(&mut typist, 0..3),
4666 [FormatState::Off, FormatState::On, FormatState::Off]
4667 );
4668 assert_eq!(
4669 typist.outgoing().html(),
4670 "big <span style=\"font-size:xx-small;\">small</span>"
4671 );
4672 }
4673
4674 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4675 #[gpui_kit::test]
4676 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
4677 let mut typist = typist(cx);
4678 typist
4679 .cx
4680 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
4681 "**hi** there".to_owned(),
4682 ));
4683 typist.press("ctrl-v");
4684 assert_eq!(typist.value(), "hi there");
4685 let composer = typist.composer.clone();
4686 assert!(
4687 typist
4688 .cx
4689 .update(|cx| composer.read(cx).paste_hint.is_some())
4690 );
4691 typist.press("ctrl-z");
4692 assert_eq!(typist.value(), "**hi** there");
4693 assert!(typist.draft().marks().is_empty());
4694 }
4695
4696 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4697 #[gpui_kit::test]
4698 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
4699 use teams_core::{FormatState, MarkKind};
4700
4701 let mut typist = typist(cx);
4702 typist.type_text("`code` ");
4703 typist.press("ctrl-a ctrl-c end ctrl-v");
4704 assert_eq!(typist.value(), "code code ");
4705 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
4706 }
4707
4708 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4709 #[gpui_kit::test]
4710 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
4711 use teams_core::{FormatState, MarkKind};
4712
4713 let mut typist = typist(cx);
4714 typist.type_text("~~old~~");
4715 typist.press("ctrl-a");
4716 typist.type_text("new");
4717 typist.press("ctrl-z ctrl-z");
4718 assert_eq!(typist.value(), "old");
4719 assert_eq!(
4720 typist.draft().state(0..3, &MarkKind::Strike),
4721 FormatState::On
4722 );
4723 }
4724
4725 #[gpui_kit::test]
4726 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
4727 let mut typist = typist(cx);
4728 typist.type_text("see docs");
4729 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
4730 let composer = typist.composer.clone();
4731 assert!(
4732 typist
4733 .cx
4734 .update(|cx| composer.read(cx).link_editor.is_some())
4735 );
4736 typist.type_text("example.com");
4737 typist.press("enter");
4738 assert!(
4739 typist
4740 .cx
4741 .update(|cx| composer.read(cx).link_editor.is_none())
4742 );
4743 assert_eq!(
4744 typist.outgoing().html(),
4745 "see <a href=\"https://example.com\">docs</a>"
4746 );
4747 }
4748
4749 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4750 #[gpui_kit::test]
4751 fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(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");
4757 typist.press("ctrl-z");
4758 assert_eq!(typist.value(), "hello");
4759 assert!(typist.draft().marks().is_empty());
4760 typist.press("ctrl-y");
4761 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
4762 }
4763
4764 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4765 #[gpui_kit::test]
4766 fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) {
4767 use teams_core::{FormatState, MarkKind};
4768
4769 let mut typist = typist(cx);
4770 typist.type_text("hello");
4771 typist.press("shift-left shift-left ctrl-b end");
4772 typist.type_text(" x");
4773 typist.press("backspace backspace");
4774 assert_eq!(typist.value(), "hello");
4775 typist.press("ctrl-z");
4776 assert_ne!(typist.value(), "hello");
4777 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
4778 }
4779
4780 #[gpui_kit::test]
4781 fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
4782 let mut typist = typist(cx);
4783 typist.type_text("```");
4784 typist.press("enter");
4785 typist.type_text("a");
4786 typist.press("enter");
4787 typist.type_text("b");
4788 typist.press("up end delete");
4789 assert_eq!(
4790 typist.outgoing().html(),
4791 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"
4792 );
4793 }
4794
4795 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4796 #[gpui_kit::test]
4797 fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
4798 let mut typist = typist(cx);
4799 typist.type_text("```");
4800 typist.press("enter");
4801 typist.type_text(" x");
4802 typist.press("ctrl-a ctrl-c");
4803 let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
4804 assert_eq!(text.as_deref(), Some(" x"));
4805 }
4806
4807 #[gpui_kit::test]
4808 fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) {
4809 let mut typist = typist(cx);
4810 typist.type_text("docs");
4811 typist.press("ctrl-a ctrl-k");
4812 typist.type_text("javascript:alert(1)");
4813 typist.press("enter");
4814 let composer = typist.composer.clone();
4815 assert!(typist.cx.update(|cx| {
4816 composer
4817 .read(cx)
4818 .link_editor
4819 .as_ref()
4820 .is_some_and(|editor| editor.refused)
4821 }));
4822 assert!(typist.draft().marks().is_empty());
4823 typist.type_text("x");
4824 assert!(typist.cx.update(|cx| {
4825 composer
4826 .read(cx)
4827 .link_editor
4828 .as_ref()
4829 .is_some_and(|editor| !editor.refused)
4830 }));
4831 }
4832
4833 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4834 #[gpui_kit::test]
4835 fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) {
4836 use teams_core::{FormatState, LineKind, MarkKind};
4837
4838 let mut typist = typist(cx);
4839 typist.type_text("hello");
4840 typist.press("ctrl-a ctrl-b");
4841 let composer = typist.composer.clone();
4842 typist.act(|window, cx| {
4843 composer.update(cx, |composer, cx| {
4844 composer.press_format(super::super::FormatButton::Bulleted, window, cx)
4845 })
4846 });
4847 assert_eq!(typist.value(), "• hello");
4848 typist.press("ctrl-z");
4849 assert_eq!(typist.value(), "hello");
4850 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
4851 typist.press("ctrl-z");
4852 assert!(typist.draft().marks().is_empty());
4853 assert_eq!(typist.draft().lines(), [LineKind::Text]);
4854 }
4855
4856 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4857 #[gpui_kit::test]
4858 fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) {
4859 use teams_core::{FormatState, MarkKind};
4860
4861 let mut typist = typist(cx);
4862 typist.type_text("hello");
4863 typist.press("ctrl-a ctrl-b ctrl-z ctrl-z");
4864 assert_eq!(typist.value(), "");
4865 typist.press("ctrl-y");
4866 assert_eq!(typist.value(), "hello");
4867 assert!(typist.draft().marks().is_empty());
4868 typist.press("ctrl-y");
4869 assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On);
4870 }
4871
4872 fn cursor(typist: &mut Typist<'_>) -> usize {
4873 let composer = typist.composer.clone();
4874 typist
4875 .cx
4876 .update(|cx| composer.read(cx).input.read(cx).cursor())
4877 }
4878
4879 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4880 #[gpui_kit::test]
4881 fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there(
4882 cx: &mut TestAppContext,
4883 ) {
4884 let mut typist = typist(cx);
4885 typist.type_text("hello");
4886 typist.press("home");
4887 typist.type_text("X");
4888 typist.press("end ctrl-z");
4889 assert_eq!(typist.value(), "hello");
4890 assert_eq!(cursor(&mut typist), 0);
4891 typist.press("ctrl-y");
4892 assert_eq!(typist.value(), "Xhello");
4893 assert_eq!(cursor(&mut typist), 1);
4894 }
4895
4896 #[gpui_kit::test]
4897 fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) {
4898 let mut typist = typist(cx);
4899 for line in 0..14 {
4900 typist.type_text(&format!("line {line}"));
4901 typist.press("shift-enter");
4902 }
4903 typist.type_text("end");
4904 let composer = typist.composer.clone();
4905 let scroll = |typist: &mut Typist<'_>| {
4906 typist
4907 .cx
4908 .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y)
4909 };
4910 typist.act(|window, cx| window.render_frame(cx));
4911 let before = scroll(&mut typist);
4912 assert!(before < gpui_kit::px(0.));
4913 typist.press("ctrl-z");
4914 typist.act(|window, cx| window.render_frame(cx));
4915 assert_eq!(scroll(&mut typist), before);
4916 }
4917
4918 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4919 #[gpui_kit::test]
4920 fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) {
4921 let mut typist = typist(cx);
4922 typist.type_text("ok :) ");
4923 assert!(typist.value().contains('🙂'));
4924 typist.press("ctrl-z");
4925 assert_eq!(typist.value(), "ok :) ");
4926 assert_eq!(typist.outgoing().text(), "ok :)");
4927 }
4928
4929 #[gpui_kit::test]
4930 fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) {
4931 let mut typist = typist(cx);
4932 typist.press("ctrl-z");
4933 typist.type_text("**a**");
4934 assert_eq!(typist.value(), "a");
4935 }
4936
4937 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
4938 #[gpui_kit::test]
4939 fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
4940 let mut typist = typist(cx);
4941 typist.type_text("```");
4942 typist.press("enter");
4943 typist.type_text(":) ");
4944 typist
4945 .cx
4946 .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
4947 typist.press("ctrl-v");
4948 assert_eq!(typist.value(), ":) **x**");
4949 let composer = typist.composer.clone();
4950 assert!(
4951 typist
4952 .cx
4953 .update(|cx| composer.read(cx).paste_hint.is_none())
4954 );
4955 let outgoing = typist.outgoing();
4956 assert_eq!(
4957 outgoing.html(),
4958 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"
4959 );
4960 }
4961
4962 #[gpui_kit::test]
4963 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
4964 let mut typist = typist(cx);
4965 typist.type_text(">quoted");
4966 typist.press("shift-enter");
4967 typist.type_text("more");
4968 let outgoing = typist.outgoing();
4969 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
4970 assert_eq!(outgoing.text(), "quoted\nmore");
4971 }
4972
4973 #[gpui_kit::test]
4974 fn enter_in_a_quote_adds_a_line_and_enter_on_the_empty_one_leaves_it(
4975 cx: &mut TestAppContext,
4976 ) {
4977 let mut typist = typist(cx);
4978 typist.type_text(">quoted");
4979 typist.press("enter");
4980 typist.type_text("more");
4981 typist.press("enter enter");
4982 typist.type_text("after");
4983 assert_eq!(typist.value(), "quoted\nmore\nafter");
4984 assert_eq!(
4985 typist.outgoing().html(),
4986 "<blockquote>quoted<br>more</blockquote>after"
4987 );
4988 }
4989
4990 #[gpui_kit::test]
4991 fn enter_on_an_empty_quote_line_leaves_it_with_the_format_bar_open(
4992 cx: &mut TestAppContext,
4993 ) {
4994 let mut typist = typist(cx);
4995 typist.press("ctrl-shift-x");
4996 typist.type_text(">quoted");
4997 typist.press("enter enter");
4998 typist.type_text("after");
4999 assert_eq!(
5000 typist.outgoing().html(),
5001 "<blockquote>quoted</blockquote>after"
5002 );
5003 }
5004
5005 #[gpui_kit::test]
5006 fn down_at_the_end_of_a_quote_leaves_it(cx: &mut TestAppContext) {
5007 let mut typist = typist(cx);
5008 typist.type_text(">quoted");
5009 typist.press("down");
5010 typist.type_text("after");
5011 assert_eq!(
5012 typist.outgoing().html(),
5013 "<blockquote>quoted</blockquote>after"
5014 );
5015 }
5016
5017 fn insert_table(typist: &mut Typist<'_>, rows: usize, columns: usize) {
5018 let composer = typist.composer.clone();
5019 typist.act(|window, cx| {
5020 composer.update(cx, |composer, cx| {
5021 composer.insert_table(rows, columns, window, cx)
5022 });
5023 window.render_frame(cx);
5024 });
5025 }
5026
5027 #[gpui_kit::test]
5028 fn a_table_takes_tab_grows_a_row_at_the_end_and_sends_as_teams_html(
5029 cx: &mut TestAppContext,
5030 ) {
5031 let mut typist = typist(cx);
5032 typist.type_text("before");
5033 insert_table(&mut typist, 1, 2);
5034 typist.type_text("a");
5035 typist.press("tab");
5036 typist.type_text("b");
5037 typist.press("tab");
5038 typist.act(|window, cx| window.render_frame(cx));
5039 typist.type_text("c");
5040 typist.press("down");
5041 typist.type_text("after");
5042 assert_eq!(
5043 typist.outgoing().html(),
5044 "before<figure class=\"table\"><table class=\"copy-paste-table\"><tbody>\
5045 <tr><td>a</td><td>b</td></tr><tr><td>c</td><td>&nbsp;</td></tr>\
5046 </tbody></table></figure>after"
5047 );
5048 }
5049
5050 fn format_bar_open(typist: &mut Typist<'_>) -> bool {
5051 let composer = typist.composer.clone();
5052 typist.cx.update(|cx| composer.read(cx).format_bar_open())
5053 }
5054
5055 #[gpui_kit::test]
5056 fn ctrl_shift_x_opens_the_format_bar_per_conversation(cx: &mut TestAppContext) {
5057 let mut typist = typist(cx);
5058 let composer = typist.composer.clone();
5059 let open_chat = |typist: &mut Typist<'_>, id: &'static str| {
5060 let composer = composer.clone();
5061 typist.act(|window, cx| {
5062 composer.update(cx, |composer, cx| {
5063 composer.set_conversation(id, window, cx);
5064 composer.focus(window, cx);
5065 })
5066 });
5067 };
5068 open_chat(&mut typist, "chat-one");
5069 assert!(!format_bar_open(&mut typist));
5070 typist.press("ctrl-shift-x");
5071 assert!(format_bar_open(&mut typist));
5072 open_chat(&mut typist, "chat-two");
5073 assert!(!format_bar_open(&mut typist));
5074 open_chat(&mut typist, "chat-one");
5075 assert!(format_bar_open(&mut typist));
5076 typist.press("ctrl-shift-x");
5077 assert!(!format_bar_open(&mut typist));
5078 }
5079
5080 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
5081 #[gpui_kit::test]
5082 fn ctrl_alt_x_strikes_through_now_that_ctrl_shift_x_is_format(cx: &mut TestAppContext) {
5083 let mut typist = typist(cx);
5084 typist.type_text("gone");
5085 typist.press("ctrl-a ctrl-alt-x");
5086 assert_eq!(typist.outgoing().html(), "<s>gone</s>");
5087 assert!(!format_bar_open(&mut typist));
5088 }
5089
5090 #[gpui_kit::test]
5091 fn the_format_bar_shows_the_style_at_the_caret_without_a_selection(
5092 cx: &mut TestAppContext,
5093 ) {
5094 use teams_core::FormatState;
5095
5096 use super::super::FormatButton;
5097
5098 let mut typist = typist(cx);
5099 typist.press("ctrl-shift-x ctrl-b");
5100 let composer = typist.composer.clone();
5101 let bold = |typist: &mut Typist<'_>| {
5102 let composer = composer.clone();
5103 typist.cx.update(|cx| {
5104 let composer = composer.read(cx);
5105 let caret = composer.selection(cx);
5106 composer.button_state(FormatButton::Bold, &caret, false)
5107 })
5108 };
5109 assert_eq!(bold(&mut typist).format, FormatState::On);
5110 typist.type_text("x");
5111 assert_eq!(bold(&mut typist).format, FormatState::On);
5112 typist.press("ctrl-b");
5113 assert_eq!(bold(&mut typist).format, FormatState::Off);
5114 assert!(bold(&mut typist).enabled);
5115 }
5116
5117 #[gpui_kit::test]
5118 fn the_format_bar_inserts_a_table_without_a_selection(cx: &mut TestAppContext) {
5119 use super::super::FormatButton;
5120
5121 let mut typist = typist(cx);
5122 typist.press("ctrl-shift-x");
5123 let composer = typist.composer.clone();
5124 typist.act(|window, cx| {
5125 composer.update(cx, |composer, cx| {
5126 composer.press_format(FormatButton::Table, window, cx)
5127 })
5128 });
5129 let picker_open = typist
5130 .cx
5131 .update(|cx| composer.read(cx).table_picker.is_some());
5132 assert!(picker_open);
5133 insert_table(&mut typist, 2, 2);
5134 assert!(typist.draft().lines()[0].is_table());
5135 }
5136
5137 #[gpui_kit::test]
5138 fn ctrl_alt_plus_and_minus_open_the_teams_row_and_column_menus(cx: &mut TestAppContext) {
5139 use super::super::table::TableLineMenu;
5140
5141 let mut typist = typist(cx);
5142 let composer = typist.composer.clone();
5143 let menu = |typist: &mut Typist<'_>| {
5144 let composer = composer.clone();
5145 typist
5146 .cx
5147 .update(|cx| composer.read(cx).table_menu.map(|menu| menu.kind))
5148 };
5149 typist.press("ctrl-alt-=");
5150 assert_eq!(menu(&mut typist), None);
5151 insert_table(&mut typist, 1, 1);
5152 typist.type_text("a");
5153 typist.press("ctrl-alt-=");
5154 assert_eq!(menu(&mut typist), Some(TableLineMenu::Insert));
5155 assert!(format_bar_open(&mut typist));
5156 typist.press("enter");
5157 assert_eq!(menu(&mut typist), None);
5158 let shape = |typist: &mut Typist<'_>| {
5159 let draft = typist.draft();
5160 let table = draft.table(0).expect("table").clone();
5161 (table.row_count(), table.column_count())
5162 };
5163 assert_eq!(shape(&mut typist), (1, 2));
5164 typist.press("ctrl-alt-- enter");
5165 assert_eq!(shape(&mut typist), (1, 1));
5166 typist.press("ctrl-alt-- escape");
5167 assert_eq!(menu(&mut typist), None);
5168 assert_eq!(shape(&mut typist), (1, 1));
5169 }
5170
5171 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
5172 #[gpui_kit::test]
5173 fn ctrl_a_highlights_a_table_like_selected_text(cx: &mut TestAppContext) {
5174 use gpui_kit::VisualTestContext;
5175
5176 use super::super::table::SELECTED_TABLE_TAG;
5177
5178 let mut typist = typist(cx);
5179 typist.type_text("before");
5180 insert_table(&mut typist, 1, 2);
5181 typist.type_text("a");
5182 typist.press("down");
5183 typist.type_text("after");
5184 let handle = typist.handle;
5185 let mut visual = VisualTestContext::from_window(handle, typist.cx);
5186 visual.update(|window, cx| window.render_frame(cx));
5187 assert!(visual.debug_bounds(SELECTED_TABLE_TAG).is_none());
5188 visual.simulate_keystrokes("ctrl-a");
5189 visual.run_until_parked();
5190 visual.update(|window, cx| window.render_frame(cx));
5191 assert!(visual.debug_bounds(SELECTED_TABLE_TAG).is_some());
5192 }
5193
5194 #[gpui_kit::test]
5195 fn deleting_the_last_column_deletes_the_table(cx: &mut TestAppContext) {
5196 let mut typist = typist(cx);
5197 insert_table(&mut typist, 1, 1);
5198 let composer = typist.composer.clone();
5199 typist.act(|window, cx| {
5200 composer.update(cx, |composer, cx| {
5201 composer.edit_table(teams_core::TableEdit::DeleteColumn, window, cx)
5202 });
5203 });
5204 assert!(typist.draft().lines().iter().all(|kind| !kind.is_table()));
5205 }
5206
5207 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
5208 #[gpui_kit::test]
5209 fn a_pasted_markdown_table_becomes_a_table(cx: &mut TestAppContext) {
5210 let mut typist = typist(cx);
5211 typist
5212 .cx
5213 .write_to_clipboard(gpui_kit::Clipboa
5214… afgekapt