BlueGit

ict rusty-teams

Files

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

composer.rs

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