BlueGit

ict rusty-teams

Files

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

composer.rs

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