BlueGit

ict rusty-teams

Files

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

composer.rs

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