BlueGit

ict rusty-teams

Files

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

composer.rs

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