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