BlueGit

ict rusty-teams

Files

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

composer.rs

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