BlueGit

ict rusty-teams

Files

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

composer.rs

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