BlueGit

ict rusty-teams

Files

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

composer.rs

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