BlueGit

ict rusty-teams

Files

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

composer.rs

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