BlueGit

ict rusty-teams

Files

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

composer.rs

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