BlueGit

ict rusty-teams

Files

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

composer.rs

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