BlueGit

ict rusty-teams

Files

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

composer.rs

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