BlueGit

ict rusty-teams

Files

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

composer.rs

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