BlueGit

ict rusty-teams

Files

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

composer.rs

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