BlueGit

ict rusty-teams

Files

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

composer.rs

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