BlueGit

ict rusty-teams

Files

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

composer.rs

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