BlueGit

ict rusty-teams

Files

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

composer.rs

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