BlueGit

ict rusty-teams

Files

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

composer.rs

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