BlueGit

ict rusty-teams

Files

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

composer.rs

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