BlueGit

ict rusty-teams

Files

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

composer.rs

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