BlueGit

ict rusty-teams

Files

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

composer.rs

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