BlueGit

ict rusty-teams

Files

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

composer.rs

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