| 1 | use std::cell::Cell; |
| 2 | use std::collections::{HashMap, HashSet}; |
| 3 | use std::ops::Range; |
| 4 | use std::path::PathBuf; |
| 5 | use std::rc::Rc; |
| 6 | use std::sync::Arc; |
| 7 | use std::time::{Duration, Instant}; |
| 8 | |
| 9 | use gpui_kit::assets::IconName; |
| 10 | use gpui_kit::component::{ |
| 11 | ActiveTheme as _, h_flex, |
| 12 | input::{ |
| 13 | Backspace, Copy, Cut, Delete, Enter, Escape, IndentInline, InlineToken, InputContent, |
| 14 | InputEvent, InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo, |
| 15 | TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo, |
| 16 | }, |
| 17 | tooltip::Tooltip, |
| 18 | v_flex, |
| 19 | }; |
| 20 | use gpui_kit::prelude::FluentBuilder as _; |
| 21 | use gpui_kit::*; |
| 22 | use teams_core::{ |
| 23 | Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind, |
| 24 | LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle, |
| 25 | UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits, |
| 26 | }; |
| 27 | |
| 28 | use super::attachment_tray::{ |
| 29 | AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage, |
| 30 | PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action, |
| 31 | pasted_image_name, prepare_pasted_image, read_attachment, render_tray, |
| 32 | }; |
| 33 | use super::avatar::{person_avatar, square_avatar}; |
| 34 | use super::draft_style::draft_style; |
| 35 | use super::emoji_popup::{self, EmojiPopup}; |
| 36 | use super::format_toolbar::{self, FormatButton}; |
| 37 | use super::link_preview::{ComposeLink, draft_link, link_preview_card}; |
| 38 | use super::widgets::{icon, symbol}; |
| 39 | use crate::app_state::AppState; |
| 40 | use crate::emoji; |
| 41 | use crate::runtime; |
| 42 | use crate::theme; |
| 43 | use crate::typing::OutgoingTyping; |
| 44 | |
| 45 | const MIN_ROWS: usize = 1; |
| 46 | const MAX_ROWS: usize = 8; |
| 47 | const MENTION_DEBOUNCE: Duration = Duration::from_millis(150); |
| 48 | const MENTION_LIMIT: usize = 8; |
| 49 | const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600); |
| 50 | const MENTION_QUERY_MAX_CHARS: usize = 32; |
| 51 | const MENTION_QUERY_MAX_WORDS: usize = 3; |
| 52 | const POPUP_WIDTH: f32 = 380.; |
| 53 | const POPUP_ROW_HEIGHT: f32 = 44.; |
| 54 | const DEMO_UPLOAD_STEPS: u8 = 10; |
| 55 | const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120); |
| 56 | const DEMO_FAILURE_STEP: u8 = 6; |
| 57 | const HISTORY_LIMIT: usize = 200; |
| 58 | const PASTE_HINT_DURATION: Duration = Duration::from_secs(4); |
| 59 | const KEY_CONTEXT: &str = "Composer"; |
| 60 | const IMAGE_TOKEN_PREFIX: &str = "image-"; |
| 61 | |
| 62 | actions!( |
| 63 | composer, |
| 64 | [ |
| 65 | ToggleBold, |
| 66 | ToggleItalic, |
| 67 | ToggleUnderline, |
| 68 | ToggleStrike, |
| 69 | ToggleSuperscript, |
| 70 | ToggleSubscript, |
| 71 | ToggleCode, |
| 72 | EditLink |
| 73 | ] |
| 74 | ); |
| 75 | |
| 76 | pub fn bind_keys(cx: &mut App) { |
| 77 | cx.bind_keys([ |
| 78 | KeyBinding::new("ctrl-b", ToggleBold, Some(KEY_CONTEXT)), |
| 79 | KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)), |
| 80 | KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)), |
| 81 | KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)), |
| 82 | KeyBinding::new("ctrl-shift-=", ToggleSuperscript, Some(KEY_CONTEXT)), |
| 83 | KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)), |
| 84 | KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)), |
| 85 | KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)), |
| 86 | #[cfg(target_os = "macos")] |
| 87 | KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)), |
| 88 | #[cfg(target_os = "macos")] |
| 89 | KeyBinding::new("cmd-i", ToggleItalic, Some(KEY_CONTEXT)), |
| 90 | #[cfg(target_os = "macos")] |
| 91 | KeyBinding::new("cmd-u", ToggleUnderline, Some(KEY_CONTEXT)), |
| 92 | #[cfg(target_os = "macos")] |
| 93 | KeyBinding::new("cmd-k", EditLink, Some(KEY_CONTEXT)), |
| 94 | ]); |
| 95 | } |
| 96 | |
| 97 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 98 | pub struct ReplyPreview { |
| 99 | pub message_id: String, |
| 100 | pub author: String, |
| 101 | pub excerpt: String, |
| 102 | } |
| 103 | |
| 104 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 105 | pub struct EditPreview { |
| 106 | pub message_id: String, |
| 107 | pub excerpt: String, |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 111 | pub struct Outgoing { |
| 112 | pub draft: Draft, |
| 113 | pub mentions: Vec<MentionInput>, |
| 114 | pub reply: Option<ReplyPreview>, |
| 115 | pub edit: Option<EditPreview>, |
| 116 | pub images: Vec<OutgoingImage>, |
| 117 | pub files: Vec<OutgoingFile>, |
| 118 | pub link_preview: Option<LinkPreview>, |
| 119 | } |
| 120 | |
| 121 | impl Outgoing { |
| 122 | /// Without list and quote markers, for previews. |
| 123 | pub fn text(&self) -> String { |
| 124 | self.draft.plain_text() |
| 125 | } |
| 126 | |
| 127 | /// The body before mentions become `<at>` tags. |
| 128 | pub fn html(&self) -> String { |
| 129 | let mut html = String::new(); |
| 130 | let mut placed = 0; |
| 131 | for character in self.draft.to_html().chars() { |
| 132 | if character != OBJECT_MARK { |
| 133 | html.push(character); |
| 134 | continue; |
| 135 | } |
| 136 | placed += 1; |
| 137 | if placed <= self.images.len() { |
| 138 | html.push_str(&format!("<img src=\"../hostedContents/{placed}/$value\">")); |
| 139 | } |
| 140 | } |
| 141 | html |
| 142 | } |
| 143 | |
| 144 | pub fn has_attachments(&self) -> bool { |
| 145 | !self.images.is_empty() || !self.files.is_empty() |
| 146 | } |
| 147 | |
| 148 | pub fn extras(&self) -> MessageExtras { |
| 149 | MessageExtras { |
| 150 | kept: Vec::new(), |
| 151 | images: self |
| 152 | .images |
| 153 | .iter() |
| 154 | .map(|outgoing| HostedImage { |
| 155 | content_type: outgoing.image.format.mime_type().to_owned(), |
| 156 | bytes: Arc::new(outgoing.image.bytes.clone()), |
| 157 | }) |
| 158 | .collect(), |
| 159 | files: self |
| 160 | .files |
| 161 | .iter() |
| 162 | .map(|file| file.reference.clone()) |
| 163 | .collect(), |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | enum UploadEvent { |
| 169 | Progress(u8), |
| 170 | Uploaded(UploadedFile), |
| 171 | Finished(UploadResult), |
| 172 | } |
| 173 | |
| 174 | enum UploadHandle { |
| 175 | Network(tokio::task::AbortHandle), |
| 176 | Demo(Task<()>), |
| 177 | } |
| 178 | |
| 179 | impl UploadHandle { |
| 180 | fn cancel(self) { |
| 181 | match self { |
| 182 | UploadHandle::Network(handle) => handle.abort(), |
| 183 | UploadHandle::Demo(task) => drop(task), |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | pub enum ComposerEvent { |
| 189 | Submit(Box<Outgoing>), |
| 190 | EditLast, |
| 191 | Typing(bool), |
| 192 | } |
| 193 | |
| 194 | struct MentionPopup { |
| 195 | range: Range<usize>, |
| 196 | query: String, |
| 197 | candidates: Vec<MentionCandidate>, |
| 198 | highlighted: usize, |
| 199 | } |
| 200 | |
| 201 | /// An automatic edit Backspace takes back while nothing changed since. |
| 202 | struct Conversion { |
| 203 | value: String, |
| 204 | cursor: usize, |
| 205 | before: Draft, |
| 206 | restore: Vec<Edit>, |
| 207 | } |
| 208 | |
| 209 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 210 | enum StepKind { |
| 211 | Typing { at: usize, after_space: bool }, |
| 212 | Deleting { start: usize, end: usize }, |
| 213 | Other, |
| 214 | } |
| 215 | |
| 216 | /// One state of the composer's own undo history: text, tokens, formatting and selection. |
| 217 | struct HistoryStep { |
| 218 | draft: Draft, |
| 219 | tokens: Vec<(Range<usize>, InlineToken)>, |
| 220 | selection: Range<usize>, |
| 221 | kind: StepKind, |
| 222 | } |
| 223 | |
| 224 | struct LinkEditor { |
| 225 | range: Range<usize>, |
| 226 | field: Entity<InputState>, |
| 227 | refused: bool, |
| 228 | _edits: Subscription, |
| 229 | } |
| 230 | |
| 231 | type DraftDecorations = ( |
| 232 | TextDecorationCollection<TextareaMode>, |
| 233 | RangeDecorationCollection<TextareaMode>, |
| 234 | ); |
| 235 | |
| 236 | pub struct Composer { |
| 237 | app: Entity<AppState>, |
| 238 | input: Entity<TextareaState>, |
| 239 | conversation_id: Option<String>, |
| 240 | reply: Option<ReplyPreview>, |
| 241 | editing: Option<EditPreview>, |
| 242 | mention_inputs: HashMap<String, MentionInput>, |
| 243 | mention_counter: usize, |
| 244 | popup: Option<MentionPopup>, |
| 245 | lookup: Option<Task<()>>, |
| 246 | emoji_popup: Option<EmojiPopup>, |
| 247 | emoji_dismissed_at: Option<usize>, |
| 248 | recent_emoji: emoji::Recent, |
| 249 | conversion: Option<Conversion>, |
| 250 | undone_value: Option<String>, |
| 251 | previous_value: String, |
| 252 | typing: OutgoingTyping, |
| 253 | draft: Draft, |
| 254 | decorations: DraftDecorations, |
| 255 | pending_style: Option<TypingStyle>, |
| 256 | history: Vec<HistoryStep>, |
| 257 | history_index: usize, |
| 258 | pasted_markdown: Option<String>, |
| 259 | paste_hint: Option<Task<()>>, |
| 260 | copied: Option<(String, Vec<DraftLine>)>, |
| 261 | toolbar_dismissed: Option<Range<usize>>, |
| 262 | mouse_selecting: bool, |
| 263 | link_editor: Option<LinkEditor>, |
| 264 | composer_bounds: Rc<Cell<Option<Bounds<Pixels>>>>, |
| 265 | tray: AttachmentTray, |
| 266 | uploads: HashMap<u64, UploadHandle>, |
| 267 | demo_failed: HashSet<u64>, |
| 268 | carry_images_into: Option<String>, |
| 269 | pending_anchors: HashMap<u64, usize>, |
| 270 | link: ComposeLink, |
| 271 | _subscriptions: [Subscription; 3], |
| 272 | } |
| 273 | |
| 274 | impl EventEmitter<ComposerEvent> for Composer {} |
| 275 | |
| 276 | pub fn is_plain_enter(event: &InputEvent) -> bool { |
| 277 | matches!(event, InputEvent::PressEnter { shift: false, .. }) |
| 278 | } |
| 279 | |
| 280 | /// Enter sends, Shift+Enter is a newline (handled by the input itself). Blank text never sends. |
| 281 | pub fn submitted_text(event: &InputEvent, value: &str) -> Option<String> { |
| 282 | match event { |
| 283 | InputEvent::PressEnter { shift: false, .. } => { |
| 284 | let trimmed = value.trim(); |
| 285 | (!trimmed.is_empty()).then(|| trimmed.to_owned()) |
| 286 | } |
| 287 | _ => None, |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | pub fn active_mention( |
| 292 | text: &str, |
| 293 | cursor: usize, |
| 294 | tokens: &[Range<usize>], |
| 295 | ) -> Option<(Range<usize>, String)> { |
| 296 | if cursor > text.len() || !text.is_char_boundary(cursor) { |
| 297 | return None; |
| 298 | } |
| 299 | let before = &text[..cursor]; |
| 300 | let at = before.rfind('@')?; |
| 301 | if before[..at] |
| 302 | .chars() |
| 303 | .next_back() |
| 304 | .is_some_and(|previous| !previous.is_whitespace()) |
| 305 | { |
| 306 | return None; |
| 307 | } |
| 308 | let query = &before[at + 1..]; |
| 309 | let rejected = query.contains('\n') |
| 310 | || query.starts_with(char::is_whitespace) |
| 311 | || query.ends_with(char::is_whitespace) |
| 312 | || query.chars().count() > MENTION_QUERY_MAX_CHARS |
| 313 | || query.split_whitespace().count() > MENTION_QUERY_MAX_WORDS |
| 314 | || tokens |
| 315 | .iter() |
| 316 | .any(|token| token.start < cursor && at < token.end); |
| 317 | (!rejected).then(|| (at..cursor, query.to_owned())) |
| 318 | } |
| 319 | |
| 320 | fn candidate_subtitle(candidate: &MentionCandidate) -> String { |
| 321 | match candidate { |
| 322 | MentionCandidate::Person(person) => person |
| 323 | .job_title |
| 324 | .clone() |
| 325 | .filter(|title| !title.trim().is_empty()) |
| 326 | .or_else(|| person.mail.clone()) |
| 327 | .unwrap_or_default(), |
| 328 | MentionCandidate::Channel { .. } => "Channel".to_owned(), |
| 329 | MentionCandidate::Team { .. } => "Team".to_owned(), |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | fn step_kind(previous: &str, value: &str, cursor: usize) -> StepKind { |
| 334 | if let Some(typed) = emoji::typed_char(previous, value, cursor).filter(|typed| *typed != '\n') { |
| 335 | return StepKind::Typing { |
| 336 | at: cursor - typed.len_utf8(), |
| 337 | after_space: typed.is_whitespace(), |
| 338 | }; |
| 339 | } |
| 340 | let removed = previous.len().saturating_sub(value.len()); |
| 341 | let one_char_removed = removed > 0 |
| 342 | && previous.is_char_boundary(cursor) |
| 343 | && previous |
| 344 | .get(cursor..cursor + removed) |
| 345 | .is_some_and(|gone| gone.chars().count() == 1 && gone != "\n") |
| 346 | && previous.get(..cursor) == value.get(..cursor) |
| 347 | && previous.get(cursor + removed..) == value.get(cursor..); |
| 348 | if one_char_removed { |
| 349 | StepKind::Deleting { |
| 350 | start: cursor, |
| 351 | end: cursor + removed, |
| 352 | } |
| 353 | } else { |
| 354 | StepKind::Other |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | fn continues(last: &HistoryStep, kind: StepKind) -> bool { |
| 359 | let caret = &last.selection; |
| 360 | match (last.kind, kind) { |
| 361 | ( |
| 362 | StepKind::Typing { after_space, .. }, |
| 363 | StepKind::Typing { |
| 364 | at, |
| 365 | after_space: space, |
| 366 | }, |
| 367 | ) => (!after_space || space) && caret.is_empty() && caret.start == at, |
| 368 | (StepKind::Deleting { .. }, StepKind::Deleting { start, end }) => { |
| 369 | caret.is_empty() && (caret.start == end || caret.start == start) |
| 370 | } |
| 371 | _ => false, |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | fn looks_like_url(text: &str) -> bool { |
| 376 | ["https://", "http://", "www."] |
| 377 | .iter() |
| 378 | .any(|prefix| text.starts_with(prefix)) |
| 379 | && !text.contains(char::is_whitespace) |
| 380 | } |
| 381 | |
| 382 | fn image_token(id: u64) -> InlineToken { |
| 383 | InlineToken::new(format!("{IMAGE_TOKEN_PREFIX}{id}"), OBJECT_MARK.to_string()).block() |
| 384 | } |
| 385 | |
| 386 | fn image_id(token: &InlineToken) -> Option<u64> { |
| 387 | token.id().strip_prefix(IMAGE_TOKEN_PREFIX)?.parse().ok() |
| 388 | } |
| 389 | |
| 390 | fn candidate_key(candidate: &MentionCandidate) -> &str { |
| 391 | match candidate { |
| 392 | MentionCandidate::Person(person) => &person.user_id, |
| 393 | MentionCandidate::Channel { channel_id, .. } => channel_id, |
| 394 | MentionCandidate::Team { team_id, .. } => team_id, |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | impl Composer { |
| 399 | pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 400 | let input = cx.new(|cx| { |
| 401 | TextareaState::new(window, cx) |
| 402 | .auto_grow(MIN_ROWS, MAX_ROWS) |
| 403 | .submit_on_enter(true) |
| 404 | .placeholder("Type a message") |
| 405 | }); |
| 406 | let subscription = cx.subscribe_in(&input, window, Self::on_input_event); |
| 407 | let observer = cx.observe(&input, |_, _, cx| cx.notify()); |
| 408 | let image_observer = cx.observe(&app, |this, _, cx| { |
| 409 | if this.link_image_pending(cx) { |
| 410 | cx.notify(); |
| 411 | } |
| 412 | }); |
| 413 | let decorations = input.update(cx, |state, cx| { |
| 414 | ( |
| 415 | state.create_decorations_collection(Vec::new(), cx), |
| 416 | state.create_range_decorations_collection(Vec::new(), cx), |
| 417 | ) |
| 418 | }); |
| 419 | let recent_emoji = emoji::Recent::load(&app.read(cx).store); |
| 420 | Composer { |
| 421 | app, |
| 422 | input, |
| 423 | conversation_id: None, |
| 424 | reply: None, |
| 425 | editing: None, |
| 426 | mention_inputs: HashMap::new(), |
| 427 | mention_counter: 0, |
| 428 | popup: None, |
| 429 | lookup: None, |
| 430 | emoji_popup: None, |
| 431 | emoji_dismissed_at: None, |
| 432 | recent_emoji, |
| 433 | conversion: None, |
| 434 | undone_value: None, |
| 435 | previous_value: String::new(), |
| 436 | typing: OutgoingTyping::default(), |
| 437 | draft: Draft::default(), |
| 438 | decorations, |
| 439 | pending_style: None, |
| 440 | history: vec![HistoryStep { |
| 441 | draft: Draft::default(), |
| 442 | tokens: Vec::new(), |
| 443 | selection: 0..0, |
| 444 | kind: StepKind::Other, |
| 445 | }], |
| 446 | history_index: 0, |
| 447 | pasted_markdown: None, |
| 448 | paste_hint: None, |
| 449 | copied: None, |
| 450 | toolbar_dismissed: None, |
| 451 | mouse_selecting: false, |
| 452 | link_editor: None, |
| 453 | composer_bounds: Rc::new(Cell::new(None)), |
| 454 | tray: AttachmentTray::default(), |
| 455 | uploads: HashMap::new(), |
| 456 | demo_failed: HashSet::new(), |
| 457 | carry_images_into: None, |
| 458 | pending_anchors: HashMap::new(), |
| 459 | link: ComposeLink::default(), |
| 460 | _subscriptions: [subscription, observer, image_observer], |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | fn on_input_event( |
| 465 | &mut self, |
| 466 | input: &Entity<TextareaState>, |
| 467 | event: &InputEvent, |
| 468 | window: &mut Window, |
| 469 | cx: &mut Context<Self>, |
| 470 | ) { |
| 471 | cx.notify(); |
| 472 | if matches!(event, InputEvent::Change) { |
| 473 | self.on_change(window, cx); |
| 474 | self.update_emoji(cx); |
| 475 | self.update_mention(cx); |
| 476 | self.update_link_preview(cx); |
| 477 | } |
| 478 | let value = input.read(cx).value(); |
| 479 | if submitted_text(event, &value).is_some() |
| 480 | || (is_plain_enter(event) && self.has_attachments(cx)) |
| 481 | { |
| 482 | self.submit_current(window, cx); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | fn update_mention(&mut self, cx: &mut Context<Self>) { |
| 487 | let state = self.input.read(cx); |
| 488 | let tokens: Vec<Range<usize>> = state.tokens().iter().map(|span| span.range()).collect(); |
| 489 | let found = active_mention(&state.value(), state.cursor(), &tokens); |
| 490 | let Some((range, query)) = found else { |
| 491 | self.close_mention_popup(); |
| 492 | return; |
| 493 | }; |
| 494 | let unchanged = self |
| 495 | .popup |
| 496 | .as_ref() |
| 497 | .is_some_and(|popup| popup.query == query && popup.range == range); |
| 498 | if unchanged { |
| 499 | return; |
| 500 | } |
| 501 | let previous = self.popup.take(); |
| 502 | self.popup = Some(MentionPopup { |
| 503 | range, |
| 504 | query: query.clone(), |
| 505 | candidates: previous.map(|popup| popup.candidates).unwrap_or_default(), |
| 506 | highlighted: 0, |
| 507 | }); |
| 508 | self.request_candidates(query, cx); |
| 509 | } |
| 510 | |
| 511 | fn close_popup(&mut self) { |
| 512 | self.close_mention_popup(); |
| 513 | self.emoji_popup = None; |
| 514 | } |
| 515 | |
| 516 | fn close_mention_popup(&mut self) { |
| 517 | self.popup = None; |
| 518 | self.lookup = None; |
| 519 | } |
| 520 | |
| 521 | fn report_typing(&mut self, has_text: bool, cx: &mut Context<Self>) { |
| 522 | if self.editing.is_some() { |
| 523 | return; |
| 524 | } |
| 525 | if let Some(active) = self.typing.on_text(has_text, Instant::now()) { |
| 526 | cx.emit(ComposerEvent::Typing(active)); |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | pub fn stop_typing(&mut self) -> bool { |
| 531 | self.typing.stop() |
| 532 | } |
| 533 | |
| 534 | fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 535 | let state = self.input.read(cx); |
| 536 | let (value, input_cursor) = (state.value().to_string(), state.cursor()); |
| 537 | self.report_typing(!value.trim().is_empty(), cx); |
| 538 | let previous = std::mem::replace(&mut self.previous_value, value.clone()); |
| 539 | if previous != value { |
| 540 | let (start, old_end, new_end) = changed_span(&previous, &value); |
| 541 | self.shift_anchors(start, old_end, new_end); |
| 542 | } |
| 543 | if value == self.draft.text() { |
| 544 | self.refresh_style(cx); |
| 545 | return; |
| 546 | } |
| 547 | let kind = step_kind(&previous, &value, input_cursor); |
| 548 | let typing = self.pending_style.take(); |
| 549 | let cursor = self.draft.apply_edit(&value, input_cursor, typing.as_ref()); |
| 550 | let edits = self.draft.take_edits(); |
| 551 | self.apply_to_input(edits, cursor..cursor, window, cx); |
| 552 | self.record(kind, cx); |
| 553 | if let Some(pasted) = self.pasted_markdown.take() |
| 554 | && self.convert_paste(&pasted, cursor, window, cx) |
| 555 | { |
| 556 | return; |
| 557 | } |
| 558 | let typed = emoji::typed_char(&previous, self.draft.text(), cursor); |
| 559 | if typed.is_some() && self.convert_markdown(cursor, window, cx) { |
| 560 | return; |
| 561 | } |
| 562 | if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) { |
| 563 | return; |
| 564 | } |
| 565 | self.convert_emoji(typed, cursor, window, cx); |
| 566 | } |
| 567 | |
| 568 | fn convert_link(&mut self, cursor: usize, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 569 | let before = self.draft.clone(); |
| 570 | if !self.draft.autolink_typed(cursor) { |
| 571 | return false; |
| 572 | } |
| 573 | self.finish_conversion(before, cursor, window, cx); |
| 574 | true |
| 575 | } |
| 576 | |
| 577 | fn convert_markdown( |
| 578 | &mut self, |
| 579 | cursor: usize, |
| 580 | window: &mut Window, |
| 581 | cx: &mut Context<Self>, |
| 582 | ) -> bool { |
| 583 | let before = self.draft.clone(); |
| 584 | let Some((cursor, style)) = self.draft.convert_typed(cursor) else { |
| 585 | self.draft.take_edits(); |
| 586 | return false; |
| 587 | }; |
| 588 | self.finish_conversion(before, cursor, window, cx); |
| 589 | self.pending_style = (!style.is_empty()).then_some(style); |
| 590 | true |
| 591 | } |
| 592 | |
| 593 | fn convert_emoji( |
| 594 | &mut self, |
| 595 | typed: Option<char>, |
| 596 | cursor: usize, |
| 597 | window: &mut Window, |
| 598 | cx: &mut Context<Self>, |
| 599 | ) { |
| 600 | if self.draft.in_code(cursor) { |
| 601 | return; |
| 602 | } |
| 603 | let value = self.draft.text(); |
| 604 | let found = match typed { |
| 605 | Some(':') => emoji::closing_code(value, cursor) |
| 606 | .and_then(|(range, code)| Some((range, emoji::lookup(code)?))), |
| 607 | Some(' ') => emoji::smiley_before_space(value, cursor), |
| 608 | _ => None, |
| 609 | }; |
| 610 | let Some((range, glyph)) = found else { |
| 611 | return; |
| 612 | }; |
| 613 | let before = self.draft.clone(); |
| 614 | self.draft.replace(range.clone(), glyph); |
| 615 | self.finish_conversion(before, cursor + glyph.len() - range.len(), window, cx); |
| 616 | self.remember_emoji(glyph, cx); |
| 617 | } |
| 618 | |
| 619 | fn finish_conversion( |
| 620 | &mut self, |
| 621 | before: Draft, |
| 622 | cursor: usize, |
| 623 | window: &mut Window, |
| 624 | cx: &mut Context<Self>, |
| 625 | ) { |
| 626 | let edits = self.draft.take_edits(); |
| 627 | let restore = reverse_edits(&edits, before.text()); |
| 628 | self.apply_to_input(edits, cursor..cursor, window, cx); |
| 629 | self.record(StepKind::Other, cx); |
| 630 | self.conversion = Some(Conversion { |
| 631 | value: self.draft.text().to_owned(), |
| 632 | cursor, |
| 633 | before, |
| 634 | restore, |
| 635 | }); |
| 636 | } |
| 637 | |
| 638 | fn convert_paste( |
| 639 | &mut self, |
| 640 | pasted: &str, |
| 641 | cursor: usize, |
| 642 | window: &mut Window, |
| 643 | cx: &mut Context<Self>, |
| 644 | ) -> bool { |
| 645 | let pasted = pasted.replace("\r\n", "\n"); |
| 646 | let Some(start) = cursor |
| 647 | .checked_sub(pasted.len()) |
| 648 | .filter(|start| self.draft.text().get(*start..cursor) == Some(pasted.as_str())) |
| 649 | else { |
| 650 | return false; |
| 651 | }; |
| 652 | let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX); |
| 653 | let cursor = self.draft.insert_lines(start..cursor, &lines); |
| 654 | let changed_text = self.draft.text().get(start..cursor) != Some(pasted.as_str()); |
| 655 | self.commit(Some(cursor), window, cx); |
| 656 | if !changed_text { |
| 657 | return true; |
| 658 | } |
| 659 | self.paste_hint = Some(cx.spawn(async move |this, cx| { |
| 660 | cx.background_executor().timer(PASTE_HINT_DURATION).await; |
| 661 | this.update(cx, |this, cx| { |
| 662 | this.paste_hint = None; |
| 663 | cx.notify(); |
| 664 | }) |
| 665 | .ok(); |
| 666 | })); |
| 667 | true |
| 668 | } |
| 669 | |
| 670 | /// Puts the draft's pending edits into the input, then places the selection. |
| 671 | fn commit(&mut self, cursor: Option<usize>, window: &mut Window, cx: &mut Context<Self>) { |
| 672 | let edits = self.draft.take_edits(); |
| 673 | let selection = self.input.read(cx).selected_range(); |
| 674 | let selection = match cursor { |
| 675 | Some(cursor) => cursor..cursor, |
| 676 | None if edits.is_empty() => selection, |
| 677 | None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end), |
| 678 | }; |
| 679 | self.apply_to_input(edits, selection, window, cx); |
| 680 | self.record(StepKind::Other, cx); |
| 681 | } |
| 682 | |
| 683 | fn apply_to_input( |
| 684 | &mut self, |
| 685 | edits: Vec<Edit>, |
| 686 | selection: Range<usize>, |
| 687 | window: &mut Window, |
| 688 | cx: &mut Context<Self>, |
| 689 | ) { |
| 690 | self.input.update(cx, |state, cx| { |
| 691 | let edited = !edits.is_empty(); |
| 692 | if edited { |
| 693 | state.apply_edits(&edits, window, cx); |
| 694 | } |
| 695 | if edited || state.selected_range() != selection { |
| 696 | state.set_selected_range(selection.clone(), cx); |
| 697 | } |
| 698 | }); |
| 699 | for anchor in self.pending_anchors.values_mut() { |
| 700 | *anchor = map_offset(&edits, *anchor); |
| 701 | } |
| 702 | let value = self.input.read(cx).value().to_string(); |
| 703 | if value != self.draft.text() { |
| 704 | self.draft.apply_edit(&value, selection.end, None); |
| 705 | self.draft.take_edits(); |
| 706 | } |
| 707 | self.previous_value = value; |
| 708 | self.refresh_style(cx); |
| 709 | } |
| 710 | |
| 711 | fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) { |
| 712 | for anchor in self.pending_anchors.values_mut() { |
| 713 | *anchor = if *anchor <= start { |
| 714 | *anchor |
| 715 | } else if *anchor >= old_end { |
| 716 | *anchor - old_end + new_end |
| 717 | } else { |
| 718 | new_end |
| 719 | }; |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | /// Adds the current state as an undo step. Typing and deleting runs merge into one step; |
| 724 | /// a typed space ends a typing step. |
| 725 | fn record(&mut self, kind: StepKind, cx: &App) { |
| 726 | let state = self.input.read(cx); |
| 727 | let step = HistoryStep { |
| 728 | draft: self.draft.clone(), |
| 729 | tokens: state |
| 730 | .tokens() |
| 731 | .iter() |
| 732 | .map(|span| (span.range(), span.token().clone())) |
| 733 | .collect(), |
| 734 | selection: state.selected_range(), |
| 735 | kind, |
| 736 | }; |
| 737 | let at_end = self.history_index + 1 == self.history.len(); |
| 738 | let merges = at_end |
| 739 | && self |
| 740 | .history |
| 741 | .last() |
| 742 | .is_some_and(|last| continues(last, kind)); |
| 743 | if merges { |
| 744 | if let Some(last) = self.history.last_mut() { |
| 745 | *last = step; |
| 746 | } |
| 747 | return; |
| 748 | } |
| 749 | self.history.truncate(self.history_index + 1); |
| 750 | self.history.push(step); |
| 751 | if self.history.len() > HISTORY_LIMIT { |
| 752 | self.history.remove(0); |
| 753 | } |
| 754 | self.history_index = self.history.len() - 1; |
| 755 | } |
| 756 | |
| 757 | /// Ctrl+Z / Ctrl+Y move through the composer's own history; the input's is never used. |
| 758 | fn step_history(&mut self, back: bool, window: &mut Window, cx: &mut Context<Self>) { |
| 759 | let target = if back { |
| 760 | self.history_index.checked_sub(1) |
| 761 | } else { |
| 762 | Some(self.history_index + 1).filter(|index| *index < self.history.len()) |
| 763 | }; |
| 764 | let Some(target) = target else { |
| 765 | return; |
| 766 | }; |
| 767 | let source_selection = self.history[self.history_index].selection.clone(); |
| 768 | self.history_index = target; |
| 769 | let step = &self.history[target]; |
| 770 | let (draft, tokens) = (step.draft.clone(), step.tokens.clone()); |
| 771 | let current = self.input.read(cx).value().to_string(); |
| 772 | let (start, old_end, new_end) = changed_span(¤t, draft.text()); |
| 773 | let selection = match (start == old_end && start == new_end, back) { |
| 774 | (false, _) => new_end..new_end, |
| 775 | (true, true) => source_selection, |
| 776 | (true, false) => step.selection.clone(), |
| 777 | }; |
| 778 | if start != old_end || start != new_end { |
| 779 | self.shift_anchors(start, old_end, new_end); |
| 780 | } |
| 781 | self.draft = draft.clone(); |
| 782 | self.previous_value = draft.text().to_owned(); |
| 783 | self.input.update(cx, |state, cx| { |
| 784 | if start != old_end || start != new_end { |
| 785 | state.apply_edits( |
| 786 | &[(start..old_end, draft.text()[start..new_end].to_owned())], |
| 787 | window, |
| 788 | cx, |
| 789 | ); |
| 790 | } |
| 791 | for (range, token) in tokens { |
| 792 | let present = state.tokens().iter().any(|span| span.range() == range); |
| 793 | if !present && range.start >= start && range.end <= new_end { |
| 794 | state |
| 795 | .replace_range_with_token(range, token, window, cx) |
| 796 | .ok(); |
| 797 | } |
| 798 | } |
| 799 | state.set_selected_range(selection, cx); |
| 800 | }); |
| 801 | self.undone_value = Some(self.input.read(cx).value().to_string()); |
| 802 | self.pending_style = None; |
| 803 | self.conversion = None; |
| 804 | self.paste_hint = None; |
| 805 | self.refresh_style(cx); |
| 806 | self.update_emoji(cx); |
| 807 | self.update_mention(cx); |
| 808 | cx.notify(); |
| 809 | } |
| 810 | |
| 811 | fn refresh_style(&mut self, cx: &mut Context<Self>) { |
| 812 | let style = draft_style(&self.draft, cx.theme().mono_font_family.clone()); |
| 813 | let (text, ranges) = &self.decorations; |
| 814 | text.set(style.text, cx); |
| 815 | ranges.set(style.ranges, cx); |
| 816 | self.input.update(cx, |state, cx| { |
| 817 | state.set_line_indents(style.indents, cx); |
| 818 | state.set_hanging_indents(style.markers, cx); |
| 819 | }); |
| 820 | } |
| 821 | |
| 822 | fn load_draft( |
| 823 | &mut self, |
| 824 | draft: Draft, |
| 825 | content: InputContent, |
| 826 | window: &mut Window, |
| 827 | cx: &mut Context<Self>, |
| 828 | ) { |
| 829 | let end = draft.text().len(); |
| 830 | self.input.update(cx, |state, cx| { |
| 831 | state.set_value(content, window, cx); |
| 832 | state.set_selected_range(end..end, cx); |
| 833 | }); |
| 834 | self.previous_value = draft.text().to_owned(); |
| 835 | self.draft = draft; |
| 836 | self.pending_style = None; |
| 837 | self.conversion = None; |
| 838 | self.pasted_markdown = None; |
| 839 | self.paste_hint = None; |
| 840 | self.link_editor = None; |
| 841 | self.toolbar_dismissed = None; |
| 842 | self.pending_anchors.clear(); |
| 843 | self.history.clear(); |
| 844 | self.history_index = 0; |
| 845 | self.record(StepKind::Other, cx); |
| 846 | self.refresh_style(cx); |
| 847 | } |
| 848 | |
| 849 | /// Returns the cursor, kept at the same spot relative to the text after `range`. |
| 850 | fn replace_text( |
| 851 | &mut self, |
| 852 | range: Range<usize>, |
| 853 | text: &str, |
| 854 | cursor: usize, |
| 855 | window: &mut Window, |
| 856 | cx: &mut Context<Self>, |
| 857 | ) -> usize { |
| 858 | let cursor = cursor + text.len() - range.len(); |
| 859 | self.input.update(cx, |state, cx| { |
| 860 | state.set_selected_range(range, cx); |
| 861 | state.replace(text.to_owned(), window, cx); |
| 862 | state.set_selected_range(cursor..cursor, cx); |
| 863 | }); |
| 864 | cursor |
| 865 | } |
| 866 | |
| 867 | fn undo_conversion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 868 | let state = self.input.read(cx); |
| 869 | let unchanged = self.conversion.as_ref().is_some_and(|conversion| { |
| 870 | conversion.value == state.value().as_ref() && conversion.cursor == state.cursor() |
| 871 | }); |
| 872 | let Some(conversion) = self.conversion.take().filter(|_| unchanged) else { |
| 873 | return false; |
| 874 | }; |
| 875 | let cursor = map_offset(&conversion.restore, conversion.cursor); |
| 876 | self.draft = conversion.before; |
| 877 | self.pending_style = None; |
| 878 | self.apply_to_input(conversion.restore, cursor..cursor, window, cx); |
| 879 | self.record(StepKind::Other, cx); |
| 880 | self.undone_value = Some(self.input.read(cx).value().to_string()); |
| 881 | self.update_emoji(cx); |
| 882 | true |
| 883 | } |
| 884 | |
| 885 | fn selection(&self, cx: &App) -> Range<usize> { |
| 886 | self.input.read(cx).selected_range() |
| 887 | } |
| 888 | |
| 889 | fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) { |
| 890 | let selection = self.selection(cx); |
| 891 | if selection.is_empty() { |
| 892 | let cursor = selection.start; |
| 893 | let mut pending = self |
| 894 | .pending_style |
| 895 | .take() |
| 896 | .filter(|pending| pending.at == cursor) |
| 897 | .unwrap_or(TypingStyle { |
| 898 | at: cursor, |
| 899 | ..TypingStyle::default() |
| 900 | }); |
| 901 | pending.toggle(kind, &self.draft.style_at(cursor)); |
| 902 | self.pending_style = (!pending.is_empty()).then_some(pending); |
| 903 | } else { |
| 904 | self.draft.toggle(selection, kind); |
| 905 | self.draft.take_edits(); |
| 906 | self.record(StepKind::Other, cx); |
| 907 | self.refresh_style(cx); |
| 908 | } |
| 909 | cx.notify(); |
| 910 | } |
| 911 | |
| 912 | fn set_size(&mut self, size: Option<SizeStep>, cx: &mut Context<Self>) { |
| 913 | let selection = self.selection(cx); |
| 914 | if selection.is_empty() { |
| 915 | let cursor = selection.start; |
| 916 | let mut pending = self |
| 917 | .pending_style |
| 918 | .take() |
| 919 | .filter(|pending| pending.at == cursor) |
| 920 | .unwrap_or(TypingStyle { |
| 921 | at: cursor, |
| 922 | ..TypingStyle::default() |
| 923 | }); |
| 924 | pending.set_size(size, &self.draft.style_at(cursor)); |
| 925 | self.pending_style = (!pending.is_empty()).then_some(pending); |
| 926 | } else { |
| 927 | self.draft.set_size(selection, size); |
| 928 | self.draft.take_edits(); |
| 929 | self.record(StepKind::Other, cx); |
| 930 | self.refresh_style(cx); |
| 931 | } |
| 932 | cx.notify(); |
| 933 | } |
| 934 | |
| 935 | fn normal_size_state(&self, range: Range<usize>) -> FormatState { |
| 936 | let sized = [SizeStep::Small, SizeStep::Large] |
| 937 | .into_iter() |
| 938 | .any(|step| self.draft.state(range.clone(), &MarkKind::Size(step)) != FormatState::Off); |
| 939 | if sized { |
| 940 | FormatState::Off |
| 941 | } else { |
| 942 | FormatState::On |
| 943 | } |
| 944 | } |
| 945 | |
| 946 | fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) { |
| 947 | let selection = self.selection(cx); |
| 948 | self.draft.toggle_lines(selection, kind); |
| 949 | self.commit(None, window, cx); |
| 950 | cx.notify(); |
| 951 | } |
| 952 | |
| 953 | fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) { |
| 954 | match button { |
| 955 | FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx), |
| 956 | FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx), |
| 957 | FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx), |
| 958 | FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx), |
| 959 | FormatButton::Superscript => self.toggle_mark(MarkKind::Superscript, cx), |
| 960 | FormatButton::Subscript => self.toggle_mark(MarkKind::Subscript, cx), |
| 961 | FormatButton::SizeSmall => self.set_size(Some(SizeStep::Small), cx), |
| 962 | FormatButton::SizeNormal => self.set_size(None, cx), |
| 963 | FormatButton::SizeLarge => self.set_size(Some(SizeStep::Large), cx), |
| 964 | FormatButton::Code => self.toggle_mark(MarkKind::Code, cx), |
| 965 | FormatButton::Link => self.open_link_editor(window, cx), |
| 966 | FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx), |
| 967 | FormatButton::Numbered => self.toggle_lines(LineKind::Numbered(0), window, cx), |
| 968 | FormatButton::Quote => self.toggle_lines(LineKind::Quote, window, cx), |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | fn format_state(&self, button: FormatButton, selection: &Range<usize>) -> FormatState { |
| 973 | let range = selection.clone(); |
| 974 | match button { |
| 975 | FormatButton::Bold => self.draft.state(range, &MarkKind::Bold), |
| 976 | FormatButton::Italic => self.draft.state(range, &MarkKind::Italic), |
| 977 | FormatButton::Underline => self.draft.state(range, &MarkKind::Underline), |
| 978 | FormatButton::Strike => self.draft.state(range, &MarkKind::Strike), |
| 979 | FormatButton::Superscript => self.draft.state(range, &MarkKind::Superscript), |
| 980 | FormatButton::Subscript => self.draft.state(range, &MarkKind::Subscript), |
| 981 | FormatButton::SizeSmall => self.draft.state(range, &MarkKind::Size(SizeStep::Small)), |
| 982 | FormatButton::SizeLarge => self.draft.state(range, &MarkKind::Size(SizeStep::Large)), |
| 983 | FormatButton::SizeNormal => self.normal_size_state(range), |
| 984 | FormatButton::Code => self.draft.state(range, &MarkKind::Code), |
| 985 | FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())), |
| 986 | FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)), |
| 987 | FormatButton::Numbered => self.draft.line_state(range, &LineKind::Numbered(0)), |
| 988 | FormatButton::Quote => self.draft.line_state(range, &LineKind::Quote), |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | fn edit_link(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 993 | if self.link_editor.is_some() { |
| 994 | return; |
| 995 | } |
| 996 | if self.draft.is_blank() && self.selection(cx).is_empty() { |
| 997 | window.dispatch_action(Box::new(super::shell::OpenSwitcher), cx); |
| 998 | return; |
| 999 | } |
| 1000 | self.open_link_editor(window, cx); |
| 1001 | } |
| 1002 | |
| 1003 | fn open_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1004 | let range = self.selection(cx); |
| 1005 | let prefill = self |
| 1006 | .draft |
| 1007 | .link_in(range.clone()) |
| 1008 | .or_else(|| { |
| 1009 | cx.read_from_clipboard() |
| 1010 | .and_then(|item| item.text()) |
| 1011 | .map(|text| text.trim().to_owned()) |
| 1012 | .filter(|text| looks_like_url(text)) |
| 1013 | }) |
| 1014 | .unwrap_or_default(); |
| 1015 | let field = cx.new(|cx| { |
| 1016 | InputState::new(window, cx) |
| 1017 | .placeholder("Paste or type a link") |
| 1018 | .default_value(prefill) |
| 1019 | }); |
| 1020 | field.update(cx, |state, cx| { |
| 1021 | state.focus(window, cx); |
| 1022 | state.select_all(window, cx); |
| 1023 | }); |
| 1024 | let edits = cx.subscribe(&field, |this, _, event: &InputEvent, cx| { |
| 1025 | if matches!(event, InputEvent::Change) |
| 1026 | && let Some(editor) = this.link_editor.as_mut() |
| 1027 | { |
| 1028 | editor.refused = false; |
| 1029 | cx.notify(); |
| 1030 | } |
| 1031 | }); |
| 1032 | self.link_editor = Some(LinkEditor { |
| 1033 | range, |
| 1034 | field, |
| 1035 | refused: false, |
| 1036 | _edits: edits, |
| 1037 | }); |
| 1038 | cx.notify(); |
| 1039 | } |
| 1040 | |
| 1041 | fn apply_link(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1042 | let Some(editor) = self.link_editor.take() else { |
| 1043 | return; |
| 1044 | }; |
| 1045 | let typed = editor.field.read(cx).value().trim().to_owned(); |
| 1046 | let url = if typed.is_empty() { |
| 1047 | String::new() |
| 1048 | } else if let Some(url) = link_url(&typed) { |
| 1049 | url |
| 1050 | } else { |
| 1051 | self.link_editor = Some(LinkEditor { |
| 1052 | refused: true, |
| 1053 | ..editor |
| 1054 | }); |
| 1055 | cx.notify(); |
| 1056 | return; |
| 1057 | }; |
| 1058 | self.focus(window, cx); |
| 1059 | if editor.range.is_empty() { |
| 1060 | if !url.is_empty() { |
| 1061 | let end = self.draft.insert_link(editor.range.start, &url, &url); |
| 1062 | self.commit(Some(end), window, cx); |
| 1063 | } |
| 1064 | } else { |
| 1065 | self.draft.set_link(editor.range.clone(), &url); |
| 1066 | self.draft.take_edits(); |
| 1067 | self.refresh_style(cx); |
| 1068 | self.input.update(cx, |state, cx| { |
| 1069 | state.set_selected_range(editor.range.clone(), cx) |
| 1070 | }); |
| 1071 | self.record(StepKind::Other, cx); |
| 1072 | self.toolbar_dismissed = Some(editor.range); |
| 1073 | } |
| 1074 | cx.notify(); |
| 1075 | } |
| 1076 | |
| 1077 | fn close_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1078 | let Some(editor) = self.link_editor.take() else { |
| 1079 | return; |
| 1080 | }; |
| 1081 | self.focus(window, cx); |
| 1082 | self.input |
| 1083 | .update(cx, |state, cx| state.set_selected_range(editor.range, cx)); |
| 1084 | cx.notify(); |
| 1085 | } |
| 1086 | |
| 1087 | fn break_line(&mut self, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 1088 | let selection = self.selection(cx); |
| 1089 | if !selection.is_empty() { |
| 1090 | return false; |
| 1091 | } |
| 1092 | match self.draft.break_line(selection.start, shift) { |
| 1093 | Some(cursor) => { |
| 1094 | self.draft.link_word_ending_at(selection.start); |
| 1095 | self.commit(Some(cursor), window, cx); |
| 1096 | true |
| 1097 | } |
| 1098 | None => false, |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | fn backspace_at_start(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 1103 | let selection = self.selection(cx); |
| 1104 | if !selection.is_empty() { |
| 1105 | return false; |
| 1106 | } |
| 1107 | match self.draft.backspace_at_start(selection.start) { |
| 1108 | Some(cursor) => { |
| 1109 | self.commit(Some(cursor), window, cx); |
| 1110 | true |
| 1111 | } |
| 1112 | None => false, |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | fn delete_forward(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 1117 | let selection = self.selection(cx); |
| 1118 | if !selection.is_empty() { |
| 1119 | return false; |
| 1120 | } |
| 1121 | match self.draft.delete_forward(selection.start) { |
| 1122 | Some(cursor) => { |
| 1123 | self.commit(Some(cursor), window, cx); |
| 1124 | true |
| 1125 | } |
| 1126 | None => false, |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 1131 | let selection = self.selection(cx); |
| 1132 | if !self.draft.indent(selection, outdent) { |
| 1133 | return false; |
| 1134 | } |
| 1135 | self.commit(None, window, cx); |
| 1136 | true |
| 1137 | } |
| 1138 | |
| 1139 | fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool { |
| 1140 | let selection = self.selection(cx); |
| 1141 | if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() { |
| 1142 | return false; |
| 1143 | } |
| 1144 | let selected = &self.draft.text()[selection.clone()]; |
| 1145 | let text = selected.replace(OBJECT_MARK, ""); |
| 1146 | let lines = if selected.contains(OBJECT_MARK) { |
| 1147 | self.draft.slice_without_objects(selection) |
| 1148 | } else { |
| 1149 | self.draft.slice(selection) |
| 1150 | }; |
| 1151 | if text.is_empty() { |
| 1152 | return true; |
| 1153 | } |
| 1154 | cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata( |
| 1155 | text.clone(), |
| 1156 | lines.clone(), |
| 1157 | )); |
| 1158 | self.copied = Some((text, lines)); |
| 1159 | true |
| 1160 | } |
| 1161 | |
| 1162 | fn copied_lines(&self, item: &ClipboardItem, text: &str) -> Option<Vec<DraftLine>> { |
| 1163 | item.entries() |
| 1164 | .iter() |
| 1165 | .find_map(|entry| match entry { |
| 1166 | ClipboardEntry::String(string) if string.text() == text => { |
| 1167 | string.metadata_json::<Vec<DraftLine>>() |
| 1168 | } |
| 1169 | _ => None, |
| 1170 | }) |
| 1171 | .or_else(|| { |
| 1172 | let normalized = text.replace("\r\n", "\n"); |
| 1173 | self.copied |
| 1174 | .as_ref() |
| 1175 | .filter(|(copied, _)| *copied == normalized) |
| 1176 | .map(|(_, lines)| lines.clone()) |
| 1177 | }) |
| 1178 | } |
| 1179 | |
| 1180 | fn toolbar_requested(&self, cx: &App) -> bool { |
| 1181 | let selection = self.selection(cx); |
| 1182 | !selection.is_empty() |
| 1183 | && !self.mouse_selecting |
| 1184 | && self.toolbar_dismissed.as_ref() != Some(&selection) |
| 1185 | && !self.popup_is_open() |
| 1186 | } |
| 1187 | |
| 1188 | fn remember_emoji(&mut self, glyph: &str, cx: &App) { |
| 1189 | let store = &self.app.read(cx).store; |
| 1190 | self.recent_emoji.reload(store); |
| 1191 | self.recent_emoji.push(glyph); |
| 1192 | self.recent_emoji.save(store); |
| 1193 | } |
| 1194 | |
| 1195 | fn update_emoji(&mut self, cx: &mut Context<Self>) { |
| 1196 | let state = self.input.read(cx); |
| 1197 | let found = emoji::active_query(&state.value(), state.cursor()) |
| 1198 | .filter(|_| !self.draft.in_code(state.cursor())); |
| 1199 | if found.as_ref().map(|(range, _)| range.start) != self.emoji_dismissed_at { |
| 1200 | self.emoji_dismissed_at = None; |
| 1201 | } |
| 1202 | let found = found.filter(|_| self.emoji_dismissed_at.is_none()); |
| 1203 | let Some((range, query)) = found else { |
| 1204 | self.emoji_popup = None; |
| 1205 | return; |
| 1206 | }; |
| 1207 | let unchanged = self |
| 1208 | .emoji_popup |
| 1209 | .as_ref() |
| 1210 | .is_some_and(|popup| popup.query == query && popup.range == range); |
| 1211 | if unchanged { |
| 1212 | return; |
| 1213 | } |
| 1214 | let matches = emoji::search(&query, &self.recent_emoji.glyphs(), emoji_popup::LIMIT); |
| 1215 | self.emoji_popup = (!matches.is_empty()).then(|| EmojiPopup::new(range, query, matches)); |
| 1216 | } |
| 1217 | |
| 1218 | fn accept_emoji(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1219 | let Some(popup) = self.emoji_popup.take() else { |
| 1220 | return; |
| 1221 | }; |
| 1222 | let Some(glyph) = popup.selected().map(|found| found.glyph) else { |
| 1223 | return; |
| 1224 | }; |
| 1225 | let cursor = popup.range.end; |
| 1226 | self.replace_text(popup.range, glyph, cursor, window, cx); |
| 1227 | self.remember_emoji(glyph, cx); |
| 1228 | cx.notify(); |
| 1229 | } |
| 1230 | |
| 1231 | fn request_candidates(&mut self, query: String, cx: &mut Context<Self>) { |
| 1232 | let Some(conversation_id) = self.conversation_id.clone() else { |
| 1233 | return; |
| 1234 | }; |
| 1235 | let (demo, engine) = { |
| 1236 | let state = self.app.read(cx); |
| 1237 | (state.mode.demo, state.engine.clone()) |
| 1238 | }; |
| 1239 | if demo { |
| 1240 | let candidates = crate::demo::mention_candidates(&conversation_id, &query); |
| 1241 | self.apply_candidates(&query, candidates, cx); |
| 1242 | return; |
| 1243 | } |
| 1244 | let Some(engine) = engine else { |
| 1245 | return; |
| 1246 | }; |
| 1247 | self.lookup = Some(cx.spawn(async move |this, cx| { |
| 1248 | cx.background_executor().timer(MENTION_DEBOUNCE).await; |
| 1249 | let task_query = query.clone(); |
| 1250 | let receiver = runtime::spawn(async move { |
| 1251 | engine |
| 1252 | .mention_candidates(&conversation_id, &task_query, MENTION_LIMIT) |
| 1253 | .await |
| 1254 | }); |
| 1255 | if let Ok(Ok(candidates)) = receiver.await { |
| 1256 | this.update(cx, |this, cx| this.apply_candidates(&query, candidates, cx)) |
| 1257 | .ok(); |
| 1258 | } |
| 1259 | })); |
| 1260 | } |
| 1261 | |
| 1262 | fn apply_candidates( |
| 1263 | &mut self, |
| 1264 | query: &str, |
| 1265 | candidates: Vec<MentionCandidate>, |
| 1266 | cx: &mut Context<Self>, |
| 1267 | ) { |
| 1268 | let Some(popup) = self.popup.as_mut().filter(|popup| popup.query == query) else { |
| 1269 | return; |
| 1270 | }; |
| 1271 | popup.candidates = candidates; |
| 1272 | popup.highlighted = 0; |
| 1273 | cx.notify(); |
| 1274 | } |
| 1275 | |
| 1276 | fn update_link_preview(&mut self, cx: &mut Context<Self>) { |
| 1277 | if self.editing.is_some() { |
| 1278 | self.link.reset(); |
| 1279 | return; |
| 1280 | } |
| 1281 | let draft = self.current_draft(cx); |
| 1282 | if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) { |
| 1283 | self.fetch_link_preview(url, cx); |
| 1284 | } |
| 1285 | cx.notify(); |
| 1286 | } |
| 1287 | |
| 1288 | fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) { |
| 1289 | let (demo, engine) = { |
| 1290 | let state = self.app.read(cx); |
| 1291 | (state.mode.demo, state.engine.clone()) |
| 1292 | }; |
| 1293 | if demo { |
| 1294 | let preview = crate::demo::link_preview(&url); |
| 1295 | self.finish_link_preview(&url, preview, cx); |
| 1296 | return; |
| 1297 | } |
| 1298 | let Some(engine) = engine else { |
| 1299 | return; |
| 1300 | }; |
| 1301 | self.link.lookup = Some(cx.spawn(async move |this, cx| { |
| 1302 | cx.background_executor() |
| 1303 | .timer(LINK_PREVIEW_DEBOUNCE) |
| 1304 | .await; |
| 1305 | let task_url = url.clone(); |
| 1306 | let receiver = |
| 1307 | runtime::spawn(async move { engine.link_preview_for(&task_url).await }); |
| 1308 | if let Ok(Ok(preview)) = receiver.await { |
| 1309 | this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx)) |
| 1310 | .ok(); |
| 1311 | } |
| 1312 | })); |
| 1313 | } |
| 1314 | |
| 1315 | fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) { |
| 1316 | let image = preview.as_ref().and_then(LinkPreview::image); |
| 1317 | if !self.link.apply(url, preview) { |
| 1318 | return; |
| 1319 | } |
| 1320 | if let Some(image) = image { |
| 1321 | self.app |
| 1322 | .update(cx, |state, cx| state.request_images(vec![image], cx)); |
| 1323 | } |
| 1324 | cx.notify(); |
| 1325 | } |
| 1326 | |
| 1327 | fn link_image_pending(&self, cx: &App) -> bool { |
| 1328 | self.link |
| 1329 | .shown() |
| 1330 | .and_then(LinkPreview::image) |
| 1331 | .is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none()) |
| 1332 | } |
| 1333 | |
| 1334 | fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> { |
| 1335 | let preview = self.link.shown()?; |
| 1336 | let composer = cx.weak_entity(); |
| 1337 | let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| { |
| 1338 | composer |
| 1339 | .update(cx, |this, cx| { |
| 1340 | this.link.dismiss(); |
| 1341 | cx.notify(); |
| 1342 | }) |
| 1343 | .ok(); |
| 1344 | }); |
| 1345 | Some( |
| 1346 | div().w_full().mb(px(6.)).child(link_preview_card( |
| 1347 | preview, |
| 1348 | "composer-link-preview".to_owned(), |
| 1349 | &self.app.read(cx).directory, |
| 1350 | true, |
| 1351 | Some(close), |
| 1352 | )), |
| 1353 | ) |
| 1354 | } |
| 1355 | |
| 1356 | fn popup_is_open(&self) -> bool { |
| 1357 | self.emoji_popup.is_some() |
| 1358 | || self |
| 1359 | .popup |
| 1360 | .as_ref() |
| 1361 | .is_some_and(|popup| !popup.candidates.is_empty()) |
| 1362 | } |
| 1363 | |
| 1364 | fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) { |
| 1365 | if let Some(popup) = self.emoji_popup.as_mut() { |
| 1366 | popup.move_highlight(delta); |
| 1367 | cx.notify(); |
| 1368 | } else if let Some(popup) = self.popup.as_mut() { |
| 1369 | let last = popup.candidates.len().saturating_sub(1) as isize; |
| 1370 | popup.highlighted = (popup.highlighted as isize + delta).clamp(0, last) as usize; |
| 1371 | cx.notify(); |
| 1372 | } |
| 1373 | } |
| 1374 | |
| 1375 | fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1376 | if self.emoji_popup.is_some() { |
| 1377 | self.accept_emoji(window, cx); |
| 1378 | } else { |
| 1379 | self.accept_mention(window, cx); |
| 1380 | } |
| 1381 | } |
| 1382 | |
| 1383 | fn accept_mention(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1384 | let Some(popup) = self.popup.take() else { |
| 1385 | return; |
| 1386 | }; |
| 1387 | self.lookup = None; |
| 1388 | let Some(candidate) = popup.candidates.get(popup.highlighted) else { |
| 1389 | return; |
| 1390 | }; |
| 1391 | self.mention_counter += 1; |
| 1392 | let token_id = format!( |
| 1393 | "mention-{}-{}", |
| 1394 | self.mention_counter, |
| 1395 | candidate_key(candidate) |
| 1396 | ); |
| 1397 | let label = format!("@{}", candidate.display_name()); |
| 1398 | self.mention_inputs |
| 1399 | .insert(token_id.clone(), candidate.to_mention()); |
| 1400 | self.input.update(cx, |state, cx| { |
| 1401 | let token = InlineToken::new(token_id, label); |
| 1402 | if state |
| 1403 | .replace_range_with_token(popup.range, token, window, cx) |
| 1404 | .is_ok() |
| 1405 | { |
| 1406 | state.insert(" ", window, cx); |
| 1407 | } |
| 1408 | }); |
| 1409 | self.close_popup(); |
| 1410 | cx.notify(); |
| 1411 | } |
| 1412 | |
| 1413 | pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 1414 | let text = text.to_owned(); |
| 1415 | self.input |
| 1416 | .update(cx, |state, cx| state.set_placeholder(text, window, cx)); |
| 1417 | } |
| 1418 | |
| 1419 | pub fn set_conversation( |
| 1420 | &mut self, |
| 1421 | conversation_id: &str, |
| 1422 | name: &str, |
| 1423 | window: &mut Window, |
| 1424 | cx: &mut Context<Self>, |
| 1425 | ) { |
| 1426 | self.set_placeholder(&format!("Message {name}"), window, cx); |
| 1427 | if self.conversation_id.as_deref() != Some(conversation_id) { |
| 1428 | let carry = self.carry_images_into.take().as_deref() == Some(conversation_id); |
| 1429 | self.conversation_id = Some(conversation_id.to_owned()); |
| 1430 | self.cancel_uploads(); |
| 1431 | let dropped = if carry { |
| 1432 | self.tray.keep_images_only() |
| 1433 | } else { |
| 1434 | self.tray.clear() |
| 1435 | }; |
| 1436 | self.discard_uploaded(dropped, cx); |
| 1437 | self.remove_orphan_image_tokens(window, cx); |
| 1438 | self.reply = None; |
| 1439 | self.link.reset(); |
| 1440 | if self.editing.take().is_some() { |
| 1441 | self.load_draft(Draft::default(), InputContent::new(""), window, cx); |
| 1442 | } |
| 1443 | self.mention_inputs.clear(); |
| 1444 | self.close_popup(); |
| 1445 | cx.notify(); |
| 1446 | } |
| 1447 | } |
| 1448 | |
| 1449 | /// The draft's images follow the user into this chat; any other switch clears the tray. |
| 1450 | pub fn carry_images_into(&mut self, conversation_id: String) { |
| 1451 | self.carry_images_into = Some(conversation_id); |
| 1452 | } |
| 1453 | |
| 1454 | fn discard_uploaded(&self, files: Vec<UploadedFile>, cx: &App) { |
| 1455 | discard_uploaded(self.app.read(cx).engine.clone(), files); |
| 1456 | } |
| 1457 | |
| 1458 | pub fn set_reply(&mut self, reply: Option<ReplyPreview>, cx: &mut Context<Self>) { |
| 1459 | self.reply = reply; |
| 1460 | if self.reply.is_some() { |
| 1461 | self.editing = None; |
| 1462 | } |
| 1463 | cx.notify(); |
| 1464 | } |
| 1465 | |
| 1466 | pub fn begin_edit(&mut self, draft: Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 1467 | self.restore(&draft, window, cx); |
| 1468 | self.focus(window, cx); |
| 1469 | } |
| 1470 | |
| 1471 | fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1472 | self.editing = None; |
| 1473 | self.set_text("", window, cx); |
| 1474 | } |
| 1475 | |
| 1476 | fn outgoing(&self, cx: &App) -> Option<Outgoing> { |
| 1477 | let state = self.input.read(cx); |
| 1478 | if !self.can_send(cx) { |
| 1479 | return None; |
| 1480 | } |
| 1481 | let mut draft = self.current_draft(cx); |
| 1482 | let image_spans: Vec<(Range<usize>, u64)> = state |
| 1483 | .tokens() |
| 1484 | .iter() |
| 1485 | .filter_map(|span| Some((span.range(), image_id(span.token())?))) |
| 1486 | .collect(); |
| 1487 | let image_ids: Vec<u64> = image_spans |
| 1488 | .iter() |
| 1489 | .filter(|(_, id)| self.tray.image(*id).is_some()) |
| 1490 | .map(|(_, id)| *id) |
| 1491 | .collect(); |
| 1492 | for (range, _) in image_spans |
| 1493 | .iter() |
| 1494 | .rev() |
| 1495 | .filter(|(_, id)| self.tray.image(*id).is_none()) |
| 1496 | { |
| 1497 | draft.replace(range.clone(), ""); |
| 1498 | } |
| 1499 | draft.take_edits(); |
| 1500 | let mut draft = draft.trimmed(); |
| 1501 | let attachments_apply = self.editing.is_none(); |
| 1502 | if self.undone_value.as_deref() != Some(state.value().as_ref()) |
| 1503 | && let Some((range, glyph)) = emoji::trailing_smiley(draft.text()) |
| 1504 | && !draft.in_code(range.end - 1) |
| 1505 | { |
| 1506 | draft.replace(range, glyph); |
| 1507 | draft.take_edits(); |
| 1508 | } |
| 1509 | let mentions = state |
| 1510 | .tokens() |
| 1511 | .iter() |
| 1512 | .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref())) |
| 1513 | .cloned() |
| 1514 | .collect(); |
| 1515 | Some(Outgoing { |
| 1516 | draft, |
| 1517 | mentions, |
| 1518 | reply: self.reply.clone(), |
| 1519 | edit: self.editing.clone(), |
| 1520 | link_preview: self.link.shown().filter(|_| attachments_apply).cloned(), |
| 1521 | images: if attachments_apply { |
| 1522 | self.tray.images_in(&image_ids) |
| 1523 | } else { |
| 1524 | Vec::new() |
| 1525 | }, |
| 1526 | files: if attachments_apply { |
| 1527 | self.tray.outgoing_files() |
| 1528 | } else { |
| 1529 | Vec::new() |
| 1530 | }, |
| 1531 | }) |
| 1532 | } |
| 1533 | |
| 1534 | /// The draft, or the plain input text while a change is still on its way to the draft. |
| 1535 | fn current_draft(&self, cx: &App) -> Draft { |
| 1536 | let value = self.input.read(cx).value(); |
| 1537 | if self.draft.text() == value.as_ref() { |
| 1538 | self.draft.clone() |
| 1539 | } else { |
| 1540 | Draft::plain(&value) |
| 1541 | } |
| 1542 | } |
| 1543 | |
| 1544 | fn can_send(&self, cx: &App) -> bool { |
| 1545 | let has_text = !self.current_draft(cx).is_blank(); |
| 1546 | if self.editing.is_some() { |
| 1547 | return has_text; |
| 1548 | } |
| 1549 | (has_text || self.has_attachments(cx)) && !self.tray.blocks_send() |
| 1550 | } |
| 1551 | |
| 1552 | fn has_attachments(&self, cx: &App) -> bool { |
| 1553 | self.tray.has_chips() |
| 1554 | || self |
| 1555 | .input |
| 1556 | .read(cx) |
| 1557 | .tokens() |
| 1558 | .iter() |
| 1559 | .any(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_some())) |
| 1560 | } |
| 1561 | |
| 1562 | fn image_token_range(&self, id: u64, cx: &App) -> Option<Range<usize>> { |
| 1563 | self.input |
| 1564 | .read(cx) |
| 1565 | .tokens() |
| 1566 | .iter() |
| 1567 | .find(|span| image_id(span.token()) == Some(id)) |
| 1568 | .map(|span| span.range()) |
| 1569 | } |
| 1570 | |
| 1571 | fn remove_orphan_image_tokens(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1572 | let edits: Vec<Edit> = self |
| 1573 | .input |
| 1574 | .read(cx) |
| 1575 | .tokens() |
| 1576 | .iter() |
| 1577 | .filter(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_none())) |
| 1578 | .map(|span| (span.range(), String::new())) |
| 1579 | .collect(); |
| 1580 | if !edits.is_empty() { |
| 1581 | self.input |
| 1582 | .update(cx, |state, cx| state.apply_edits(&edits, window, cx)); |
| 1583 | } |
| 1584 | } |
| 1585 | |
| 1586 | fn remove_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) { |
| 1587 | let Some(range) = self.image_token_range(id, cx) else { |
| 1588 | return; |
| 1589 | }; |
| 1590 | self.input.update(cx, |state, cx| { |
| 1591 | state.set_selected_range(range, cx); |
| 1592 | state.replace("", window, cx); |
| 1593 | }); |
| 1594 | } |
| 1595 | |
| 1596 | fn insert_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) { |
| 1597 | let state = self.input.read(cx); |
| 1598 | let value = state.value().to_string(); |
| 1599 | let selection = state.selected_range(); |
| 1600 | let mut offset = self |
| 1601 | .pending_anchors |
| 1602 | .remove(&id) |
| 1603 | .unwrap_or(selection.end) |
| 1604 | .min(value.len()); |
| 1605 | while !value.is_char_boundary(offset) { |
| 1606 | offset -= 1; |
| 1607 | } |
| 1608 | if value == self.draft.text() && self.draft.in_code(offset) { |
| 1609 | offset = value.len(); |
| 1610 | } |
| 1611 | if let Some(span) = state |
| 1612 | .tokens() |
| 1613 | .iter() |
| 1614 | .find(|span| span.range().start < offset && offset < span.range().end) |
| 1615 | { |
| 1616 | offset = span.range().end; |
| 1617 | } |
| 1618 | let length = OBJECT_MARK.len_utf8(); |
| 1619 | let after = |position: usize| { |
| 1620 | if position >= offset { |
| 1621 | position + length |
| 1622 | } else { |
| 1623 | position |
| 1624 | } |
| 1625 | }; |
| 1626 | let inserted = self.input.update(cx, |state, cx| { |
| 1627 | let inserted = state |
| 1628 | .replace_range_with_token(offset..offset, image_token(id), window, cx) |
| 1629 | .is_ok(); |
| 1630 | if inserted { |
| 1631 | state.set_selected_range(after(selection.start)..after(selection.end), cx); |
| 1632 | } |
| 1633 | inserted |
| 1634 | }); |
| 1635 | if !inserted { |
| 1636 | return; |
| 1637 | } |
| 1638 | for (other, anchor) in self.pending_anchors.iter_mut() { |
| 1639 | if *anchor > offset || (*anchor == offset && *other > id) { |
| 1640 | *anchor += length; |
| 1641 | } |
| 1642 | } |
| 1643 | self.previous_value = self.input.read(cx).value().to_string(); |
| 1644 | } |
| 1645 | |
| 1646 | pub fn is_editing(&self) -> bool { |
| 1647 | self.editing.is_some() |
| 1648 | } |
| 1649 | |
| 1650 | fn files_allowed(&self) -> bool { |
| 1651 | self.conversation_id |
| 1652 | .as_deref() |
| 1653 | .is_some_and(|conversation_id| !conversation_id.is_empty()) |
| 1654 | } |
| 1655 | |
| 1656 | fn cancel_uploads(&mut self) { |
| 1657 | for (_, handle) in self.uploads.drain() { |
| 1658 | handle.cancel(); |
| 1659 | } |
| 1660 | } |
| 1661 | |
| 1662 | pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1663 | if self.editing.is_some() { |
| 1664 | return; |
| 1665 | } |
| 1666 | let receiver = cx.prompt_for_paths(PathPromptOptions { |
| 1667 | files: true, |
| 1668 | directories: false, |
| 1669 | multiple: true, |
| 1670 | prompt: None, |
| 1671 | }); |
| 1672 | cx.spawn_in(window, async move |this, cx| { |
| 1673 | if let Ok(Ok(Some(paths))) = receiver.await { |
| 1674 | this.update_in(cx, |this, window, cx| this.add_paths(paths, window, cx)) |
| 1675 | .ok(); |
| 1676 | } |
| 1677 | }) |
| 1678 | .detach(); |
| 1679 | } |
| 1680 | |
| 1681 | pub fn add_paths(&mut self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) { |
| 1682 | if self.editing.is_some() || paths.is_empty() { |
| 1683 | return; |
| 1684 | } |
| 1685 | let ids = self.add_pending(&names_of(&paths), cx); |
| 1686 | for (id, path) in ids.into_iter().zip(paths) { |
| 1687 | cx.spawn_in(window, async move |this, cx| { |
| 1688 | let loaded = cx |
| 1689 | .background_executor() |
| 1690 | .spawn(async move { read_attachment(&path) }) |
| 1691 | .await; |
| 1692 | this.update_in(cx, |this, window, cx| { |
| 1693 | this.finish_reading(id, loaded, window, cx) |
| 1694 | }) |
| 1695 | .ok(); |
| 1696 | }) |
| 1697 | .detach(); |
| 1698 | } |
| 1699 | cx.notify(); |
| 1700 | } |
| 1701 | |
| 1702 | fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> { |
| 1703 | if self.tray.items().len() + names.len() > MAX_ATTACHMENTS { |
| 1704 | let referenced: Vec<u64> = self |
| 1705 | .input |
| 1706 | .read(cx) |
| 1707 | .tokens() |
| 1708 | .iter() |
| 1709 | .filter_map(|span| image_id(span.token())) |
| 1710 | .collect(); |
| 1711 | self.tray.discard_images_except(&referenced); |
| 1712 | } |
| 1713 | let ids = self.tray.add_pending(names); |
| 1714 | let anchor = self.selection(cx).end; |
| 1715 | self.pending_anchors |
| 1716 | .extend(ids.iter().map(|id| (*id, anchor))); |
| 1717 | ids |
| 1718 | } |
| 1719 | |
| 1720 | fn add_pasted_image(&mut self, pasted: Image, window: &mut Window, cx: &mut Context<Self>) { |
| 1721 | let ids = self.add_pending(&[pasted_image_name()], cx); |
| 1722 | cx.notify(); |
| 1723 | let Some(&id) = ids.first() else { |
| 1724 | return; |
| 1725 | }; |
| 1726 | cx.spawn_in(window, async move |this, cx| { |
| 1727 | let loaded = cx |
| 1728 | .background_executor() |
| 1729 | .spawn(async move { prepare_pasted_image(pasted) }) |
| 1730 | .await; |
| 1731 | this.update_in(cx, |this, window, cx| { |
| 1732 | this.finish_reading(id, loaded, window, cx) |
| 1733 | }) |
| 1734 | .ok(); |
| 1735 | }) |
| 1736 | .detach(); |
| 1737 | } |
| 1738 | |
| 1739 | fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 1740 | if self.editing.is_none() { |
| 1741 | match paste_action(item) { |
| 1742 | PasteAction::Text => {} |
| 1743 | PasteAction::Files(paths) => { |
| 1744 | self.add_paths(paths, window, cx); |
| 1745 | return true; |
| 1746 | } |
| 1747 | PasteAction::Image(pasted) => { |
| 1748 | self.add_pasted_image(pasted, window, cx); |
| 1749 | return true; |
| 1750 | } |
| 1751 | } |
| 1752 | } |
| 1753 | let Some(text) = item.text() else { |
| 1754 | return false; |
| 1755 | }; |
| 1756 | if text.contains(OBJECT_MARK) { |
| 1757 | let cleaned = text.replace(OBJECT_MARK, ""); |
| 1758 | self.input |
| 1759 | .update(cx, |state, cx| state.replace(cleaned, window, cx)); |
| 1760 | return true; |
| 1761 | } |
| 1762 | if self.draft.in_code(self.selection(cx).start) { |
| 1763 | return false; |
| 1764 | } |
| 1765 | if let Some(lines) = self.copied_lines(item, &text) { |
| 1766 | let cursor = self.draft.insert_lines(self.selection(cx), &lines); |
| 1767 | self.commit(Some(cursor), window, cx); |
| 1768 | return true; |
| 1769 | } |
| 1770 | self.pasted_markdown = has_markdown(&text).then_some(text); |
| 1771 | false |
| 1772 | } |
| 1773 | |
| 1774 | fn finish_reading( |
| 1775 | &mut self, |
| 1776 | id: u64, |
| 1777 | loaded: Result<LoadedFile, String>, |
| 1778 | window: &mut Window, |
| 1779 | cx: &mut Context<Self>, |
| 1780 | ) { |
| 1781 | match loaded { |
| 1782 | Ok(loaded) => { |
| 1783 | let files_allowed = self.files_allowed(); |
| 1784 | let job = self.tray.finish_reading(id, loaded, files_allowed); |
| 1785 | if self.tray.image(id).is_some() { |
| 1786 | self.insert_image_token(id, window, cx); |
| 1787 | } else { |
| 1788 | self.pending_anchors.remove(&id); |
| 1789 | } |
| 1790 | if let Some(job) = job { |
| 1791 | self.start_upload(job, cx); |
| 1792 | } |
| 1793 | } |
| 1794 | Err(message) => { |
| 1795 | self.pending_anchors.remove(&id); |
| 1796 | self.tray.fail_reading(id, message); |
| 1797 | } |
| 1798 | } |
| 1799 | cx.notify(); |
| 1800 | } |
| 1801 | |
| 1802 | fn start_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) { |
| 1803 | let Some(conversation_id) = self.conversation_id.clone().filter(|id| !id.is_empty()) else { |
| 1804 | self.tray.finish_upload(job.id, UploadResult::Failed); |
| 1805 | return; |
| 1806 | }; |
| 1807 | let state = self.app.read(cx); |
| 1808 | let (demo, engine) = (state.mode.demo, state.engine.clone()); |
| 1809 | if demo { |
| 1810 | self.simulate_upload(job, cx); |
| 1811 | return; |
| 1812 | } |
| 1813 | let Some(engine) = engine else { |
| 1814 | self.tray.finish_upload(job.id, UploadResult::Failed); |
| 1815 | return; |
| 1816 | }; |
| 1817 | let id = job.id; |
| 1818 | let (event_sender, mut event_receiver) = |
| 1819 | tokio::sync::mpsc::unbounded_channel::<UploadEvent>(); |
| 1820 | let finished_sender = event_sender.clone(); |
| 1821 | let (_, handle) = runtime::spawn_abortable(async move { |
| 1822 | let result = async { |
| 1823 | let uploaded = match job.kind { |
| 1824 | JobKind::Upload => { |
| 1825 | let progress_sender = event_sender.clone(); |
| 1826 | let uploaded = engine |
| 1827 | .upload_attachment_file( |
| 1828 | &conversation_id, |
| 1829 | &job.name, |
| 1830 | &job.bytes, |
| 1831 | move |percent| { |
| 1832 | let _ = progress_sender.send(UploadEvent::Progress(percent)); |
| 1833 | }, |
| 1834 | ) |
| 1835 | .await; |
| 1836 | match uploaded { |
| 1837 | Ok(uploaded) => { |
| 1838 | let _ = event_sender.send(UploadEvent::Uploaded(uploaded.clone())); |
| 1839 | uploaded |
| 1840 | } |
| 1841 | Err(_) => return UploadResult::Failed, |
| 1842 | } |
| 1843 | } |
| 1844 | JobKind::Share(uploaded) => uploaded, |
| 1845 | }; |
| 1846 | let Some(reference) = uploaded.reference() else { |
| 1847 | return UploadResult::Failed; |
| 1848 | }; |
| 1849 | match engine.share_attachment(&conversation_id, &uploaded).await { |
| 1850 | Ok(()) => UploadResult::Done(DoneFile { |
| 1851 | reference, |
| 1852 | uploaded: Some(uploaded), |
| 1853 | }), |
| 1854 | Err(_) => UploadResult::ShareFailed(uploaded), |
| 1855 | } |
| 1856 | } |
| 1857 | .await; |
| 1858 | let _ = finished_sender.send(UploadEvent::Finished(result)); |
| 1859 | }); |
| 1860 | self.uploads.insert(id, UploadHandle::Network(handle)); |
| 1861 | cx.spawn(async move |this, cx| { |
| 1862 | while let Some(event) = event_receiver.recv().await { |
| 1863 | let updated = this.update(cx, |this, cx| { |
| 1864 | let orphan = match event { |
| 1865 | UploadEvent::Progress(percent) => { |
| 1866 | this.tray.set_progress(id, percent); |
| 1867 | None |
| 1868 | } |
| 1869 | UploadEvent::Uploaded(uploaded) => this.tray.mark_uploaded(id, uploaded), |
| 1870 | UploadEvent::Finished(result) => this.finish_upload(id, result), |
| 1871 | }; |
| 1872 | this.discard_uploaded(orphan.into_iter().collect(), cx); |
| 1873 | cx.notify(); |
| 1874 | }); |
| 1875 | if updated.is_err() { |
| 1876 | break; |
| 1877 | } |
| 1878 | } |
| 1879 | }) |
| 1880 | .detach(); |
| 1881 | } |
| 1882 | |
| 1883 | fn simulate_upload(&mut self, job: UploadJob, cx: &mut Context<Self>) { |
| 1884 | let id = job.id; |
| 1885 | let fails = job.name.to_lowercase().contains("fail") && self.demo_failed.insert(id); |
| 1886 | let task = cx.spawn(async move |this, cx| { |
| 1887 | for step in 1..=DEMO_UPLOAD_STEPS { |
| 1888 | cx.background_executor().timer(DEMO_UPLOAD_STEP).await; |
| 1889 | if fails && step == DEMO_FAILURE_STEP { |
| 1890 | this.update(cx, |this, cx| { |
| 1891 | this.finish_upload_in_demo(id, UploadResult::Failed, cx) |
| 1892 | }) |
| 1893 | .ok(); |
| 1894 | return; |
| 1895 | } |
| 1896 | let percent = (u32::from(step) * 100 / u32::from(DEMO_UPLOAD_STEPS)) as u8; |
| 1897 | this.update(cx, |this, cx| this.set_progress(id, percent, cx)) |
| 1898 | .ok(); |
| 1899 | } |
| 1900 | let reference = FileReference { |
| 1901 | attachment_id: format!("demo-attachment-{id}"), |
| 1902 | content_url: format!("https://demo.invalid/files/{}", job.name), |
| 1903 | name: job.name, |
| 1904 | }; |
| 1905 | let done = DoneFile { |
| 1906 | reference, |
| 1907 | uploaded: None, |
| 1908 | }; |
| 1909 | this.update(cx, |this, cx| { |
| 1910 | this.finish_upload_in_demo(id, UploadResult::Done(done), cx) |
| 1911 | }) |
| 1912 | .ok(); |
| 1913 | }); |
| 1914 | self.uploads.insert(id, UploadHandle::Demo(task)); |
| 1915 | } |
| 1916 | |
| 1917 | fn set_progress(&mut self, id: u64, percent: u8, cx: &mut Context<Self>) { |
| 1918 | self.tray.set_progress(id, percent); |
| 1919 | cx.notify(); |
| 1920 | } |
| 1921 | |
| 1922 | fn finish_upload(&mut self, id: u64, result: UploadResult) -> Option<UploadedFile> { |
| 1923 | self.uploads.remove(&id); |
| 1924 | self.tray.finish_upload(id, result) |
| 1925 | } |
| 1926 | |
| 1927 | fn finish_upload_in_demo(&mut self, id: u64, result: UploadResult, cx: &mut Context<Self>) { |
| 1928 | self.finish_upload(id, result); |
| 1929 | cx.notify(); |
| 1930 | } |
| 1931 | |
| 1932 | fn remove_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) { |
| 1933 | if let Some(handle) = self.uploads.remove(&id) { |
| 1934 | handle.cancel(); |
| 1935 | } |
| 1936 | let uploaded = self.tray.remove(id); |
| 1937 | self.discard_uploaded(uploaded.into_iter().collect(), cx); |
| 1938 | cx.notify(); |
| 1939 | } |
| 1940 | |
| 1941 | fn retry_attachment(&mut self, id: u64, _: &mut Window, cx: &mut Context<Self>) { |
| 1942 | if let Some(job) = self.tray.retry(id) { |
| 1943 | self.start_upload(job, cx); |
| 1944 | } |
| 1945 | cx.notify(); |
| 1946 | } |
| 1947 | |
| 1948 | pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1949 | let Some(outgoing) = self.outgoing(cx) else { |
| 1950 | return; |
| 1951 | }; |
| 1952 | self.typing.reset(); |
| 1953 | self.load_draft(Draft::default(), InputContent::new(""), window, cx); |
| 1954 | self.mention_inputs.clear(); |
| 1955 | if self.editing.is_none() { |
| 1956 | self.tray.clear(); |
| 1957 | } |
| 1958 | self.reply = None; |
| 1959 | self.editing = None; |
| 1960 | self.link.reset(); |
| 1961 | self.close_popup(); |
| 1962 | cx.emit(ComposerEvent::Submit(Box::new(outgoing))); |
| 1963 | cx.notify(); |
| 1964 | } |
| 1965 | |
| 1966 | pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) { |
| 1967 | self.mention_inputs.clear(); |
| 1968 | let image_ids = if outgoing.edit.is_none() { |
| 1969 | self.cancel_uploads(); |
| 1970 | self.tray.restore(&outgoing.images, &outgoing.files) |
| 1971 | } else { |
| 1972 | Vec::new() |
| 1973 | }; |
| 1974 | let text = outgoing.draft.text(); |
| 1975 | let mut content = InputContent::new(text.to_owned()); |
| 1976 | for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) { |
| 1977 | let range = offset..offset + OBJECT_MARK.len_utf8(); |
| 1978 | if let Ok(next) = content.clone().with_token(range, image_token(id)) { |
| 1979 | content = next; |
| 1980 | } |
| 1981 | } |
| 1982 | let mut cursor = 0; |
| 1983 | for mention in &outgoing.mentions { |
| 1984 | let needle = format!("@{}", mention.text); |
| 1985 | let Some(offset) = text[cursor..].find(&needle) else { |
| 1986 | continue; |
| 1987 | }; |
| 1988 | let range = cursor + offset..cursor + offset + needle.len(); |
| 1989 | self.mention_counter += 1; |
| 1990 | let token_id = format!("mention-{}", self.mention_counter); |
| 1991 | let token = InlineToken::new(token_id.clone(), needle); |
| 1992 | if let Ok(next) = content.clone().with_token(range.clone(), token) { |
| 1993 | content = next; |
| 1994 | self.mention_inputs.insert(token_id, mention.clone()); |
| 1995 | cursor = range.end; |
| 1996 | } |
| 1997 | } |
| 1998 | self.load_draft(outgoing.draft.clone(), content, window, cx); |
| 1999 | self.reply = outgoing.reply.clone(); |
| 2000 | self.editing = outgoing.edit.clone(); |
| 2001 | self.link.restore(outgoing.link_preview.clone()); |
| 2002 | self.close_popup(); |
| 2003 | cx.notify(); |
| 2004 | } |
| 2005 | |
| 2006 | /// Markdown in `text` arrives formatted. |
| 2007 | pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 2008 | let draft = Draft::from_markdown(text); |
| 2009 | let content = InputContent::new(draft.text().to_owned()); |
| 2010 | self.load_draft(draft, content, window, cx); |
| 2011 | self.mention_inputs.clear(); |
| 2012 | self.update_emoji(cx); |
| 2013 | self.update_mention(cx); |
| 2014 | self.update_link_preview(cx); |
| 2015 | cx.notify(); |
| 2016 | } |
| 2017 | |
| 2018 | pub fn is_empty(&self, cx: &App) -> bool { |
| 2019 | self.draft.is_blank() && !self.has_attachments(cx) |
| 2020 | } |
| 2021 | |
| 2022 | pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 2023 | self.input.update(cx, |state, cx| state.focus(window, cx)); |
| 2024 | } |
| 2025 | |
| 2026 | fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> { |
| 2027 | let popup = self |
| 2028 | .popup |
| 2029 | .as_ref() |
| 2030 | .filter(|popup| !popup.candidates.is_empty())?; |
| 2031 | let directory = &self.app.read(cx).directory; |
| 2032 | let rows = popup |
| 2033 | .candidates |
| 2034 | .iter() |
| 2035 | .enumerate() |
| 2036 | .map(|(index, candidate)| { |
| 2037 | let name = candidate.display_name().to_owned(); |
| 2038 | let avatar = match candidate { |
| 2039 | MentionCandidate::Person(person) => { |
| 2040 | person_avatar(directory, Some(&person.user_id), &name, 28.) |
| 2041 | } |
| 2042 | other => square_avatar(&name, candidate_key(other), 28., 7.).into_any_element(), |
| 2043 | }; |
| 2044 | let subtitle = candidate_subtitle(candidate); |
| 2045 | h_flex() |
| 2046 | .id(ElementId::Name(format!("mention-row-{index}").into())) |
| 2047 | .mx(px(6.)) |
| 2048 | .px(px(6.)) |
| 2049 | .h(px(POPUP_ROW_HEIGHT)) |
| 2050 | .gap(px(10.)) |
| 2051 | .items_center() |
| 2052 | .rounded(px(6.)) |
| 2053 | .cursor_pointer() |
| 2054 | .when(index == popup.highlighted, |row| { |
| 2055 | row.bg(theme::surface_raised()) |
| 2056 | }) |
| 2057 | .hover(|row| row.bg(theme::row_hover())) |
| 2058 | .child(avatar) |
| 2059 | .child( |
| 2060 | v_flex() |
| 2061 | .flex_1() |
| 2062 | .min_w_0() |
| 2063 | .child( |
| 2064 | div() |
| 2065 | .truncate() |
| 2066 | .text_size(px(13.5)) |
| 2067 | .text_color(theme::text()) |
| 2068 | .child(name), |
| 2069 | ) |
| 2070 | .when(!subtitle.is_empty(), |column| { |
| 2071 | column.child( |
| 2072 | div() |
| 2073 | .truncate() |
| 2074 | .text_size(px(12.)) |
| 2075 | .text_color(theme::text_muted()) |
| 2076 | .child(subtitle), |
| 2077 | ) |
| 2078 | }), |
| 2079 | ) |
| 2080 | .on_click(cx.listener(move |this, _, window, cx| { |
| 2081 | if let Some(popup) = this.popup.as_mut() { |
| 2082 | popup.highlighted = index; |
| 2083 | } |
| 2084 | this.accept_mention(window, cx); |
| 2085 | })) |
| 2086 | }); |
| 2087 | Some( |
| 2088 | v_flex() |
| 2089 | .id("mention-popup") |
| 2090 | .absolute() |
| 2091 | .bottom(relative(1.)) |
| 2092 | .left_0() |
| 2093 | .mb(px(6.)) |
| 2094 | .w(px(POPUP_WIDTH)) |
| 2095 | .py(px(6.)) |
| 2096 | .rounded(px(10.)) |
| 2097 | .border_1() |
| 2098 | .border_color(theme::border_strong()) |
| 2099 | .bg(theme::surface()) |
| 2100 | .shadow_lg() |
| 2101 | .occlude() |
| 2102 | .children(rows) |
| 2103 | .into_any_element(), |
| 2104 | ) |
| 2105 | } |
| 2106 | |
| 2107 | fn render_emoji_popup( |
| 2108 | &self, |
| 2109 | window: &mut Window, |
| 2110 | cx: &mut Context<Self>, |
| 2111 | ) -> Option<AnyElement> { |
| 2112 | let popup = self.emoji_popup.as_ref()?; |
| 2113 | let colon = popup.range.start..popup.range.start + 1; |
| 2114 | let anchor = self |
| 2115 | .input |
| 2116 | .read(cx) |
| 2117 | .range_to_bounds(&colon) |
| 2118 | .map(|bounds| bounds.origin); |
| 2119 | if anchor.is_none() { |
| 2120 | window.request_animation_frame(); |
| 2121 | } |
| 2122 | let composer = cx.entity().downgrade(); |
| 2123 | Some(emoji_popup::render( |
| 2124 | popup, |
| 2125 | anchor, |
| 2126 | move |index, window, cx| { |
| 2127 | composer |
| 2128 | .update(cx, |this, cx| { |
| 2129 | if let Some(popup) = this.emoji_popup.as_mut() { |
| 2130 | popup.highlighted = index; |
| 2131 | } |
| 2132 | this.accept_emoji(window, cx); |
| 2133 | }) |
| 2134 | .ok(); |
| 2135 | }, |
| 2136 | )) |
| 2137 | } |
| 2138 | |
| 2139 | fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> { |
| 2140 | let composer = cx.entity().downgrade(); |
| 2141 | if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) { |
| 2142 | return None; |
| 2143 | } |
| 2144 | let state = self.input.read(cx); |
| 2145 | let range = self |
| 2146 | .link_editor |
| 2147 | .as_ref() |
| 2148 | .map_or_else(|| state.selected_range(), |editor| editor.range.clone()); |
| 2149 | let start = state.range_to_bounds(&(range.start..range.start))?; |
| 2150 | let end = state.range_to_bounds(&(range.end..range.end))?; |
| 2151 | let input_bounds = state.input_bounds(); |
| 2152 | let center_x = if start.origin.y == end.origin.y { |
| 2153 | (start.origin.x + end.origin.x) / 2. |
| 2154 | } else { |
| 2155 | input_bounds.center().x |
| 2156 | }; |
| 2157 | let edges = self |
| 2158 | .composer_bounds |
| 2159 | .get() |
| 2160 | .map_or((input_bounds.left(), input_bounds.right()), |bounds| { |
| 2161 | (bounds.left(), bounds.right()) |
| 2162 | }); |
| 2163 | let width = match self.link_editor { |
| 2164 | Some(_) => format_toolbar::link_width(), |
| 2165 | None => format_toolbar::bar_width(), |
| 2166 | }; |
| 2167 | let placement = format_toolbar::place(center_x, start.origin.y, edges, width); |
| 2168 | let element = match &self.link_editor { |
| 2169 | Some(editor) => format_toolbar::render( |
| 2170 | placement, |
| 2171 | format_toolbar::Mode::Link { |
| 2172 | field: &editor.field, |
| 2173 | refused: editor.refused, |
| 2174 | on_apply: Rc::new(move |window, cx| { |
| 2175 | composer |
| 2176 | .update(cx, |this, cx| this.apply_link(window, cx)) |
| 2177 | .ok(); |
| 2178 | }), |
| 2179 | }, |
| 2180 | ), |
| 2181 | None => { |
| 2182 | let state_of = |button| self.format_state(button, &range); |
| 2183 | format_toolbar::render( |
| 2184 | placement, |
| 2185 | format_toolbar::Mode::Bar { |
| 2186 | state: &state_of, |
| 2187 | on_press: Rc::new(move |button, window, cx| { |
| 2188 | composer |
| 2189 | .update(cx, |this, cx| this.press_format(button, window, cx)) |
| 2190 | .ok(); |
| 2191 | }), |
| 2192 | }, |
| 2193 | ) |
| 2194 | } |
| 2195 | }; |
| 2196 | Some(element) |
| 2197 | } |
| 2198 | |
| 2199 | fn render_paste_hint(&self) -> Option<Div> { |
| 2200 | self.paste_hint.as_ref()?; |
| 2201 | Some( |
| 2202 | h_flex() |
| 2203 | .mt(px(6.)) |
| 2204 | .gap(px(6.)) |
| 2205 | .items_center() |
| 2206 | .text_size(px(12.)) |
| 2207 | .text_color(theme::text_muted()) |
| 2208 | .child("Formatted from Markdown") |
| 2209 | .child( |
| 2210 | div() |
| 2211 | .px(px(5.)) |
| 2212 | .py(px(1.)) |
| 2213 | .rounded(px(4.)) |
| 2214 | .border_1() |
| 2215 | .border_color(theme::border_strong()) |
| 2216 | .bg(theme::surface_raised()) |
| 2217 | .text_size(px(11.)) |
| 2218 | .text_color(theme::text()) |
| 2219 | .child("Ctrl+Z"), |
| 2220 | ) |
| 2221 | .child("plain text"), |
| 2222 | ) |
| 2223 | } |
| 2224 | |
| 2225 | fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> { |
| 2226 | let edit = self.editing.as_ref()?; |
| 2227 | Some( |
| 2228 | h_flex() |
| 2229 | .w_full() |
| 2230 | .mb(px(6.)) |
| 2231 | .gap(px(10.)) |
| 2232 | .items_center() |
| 2233 | .pl(px(10.)) |
| 2234 | .pr(px(4.)) |
| 2235 | .py(px(6.)) |
| 2236 | .rounded(px(8.)) |
| 2237 | .bg(theme::surface()) |
| 2238 | .border_1() |
| 2239 | .border_color(theme::border()) |
| 2240 | .child(icon(IconName::Pencil, 14., theme::accent_text())) |
| 2241 | .child( |
| 2242 | v_flex() |
| 2243 | .flex_1() |
| 2244 | .min_w_0() |
| 2245 | .child( |
| 2246 | div() |
| 2247 | .truncate() |
| 2248 | .text_size(px(12.)) |
| 2249 | .font_weight(FontWeight::SEMIBOLD) |
| 2250 | .text_color(theme::accent_text()) |
| 2251 | .child("Editing message"), |
| 2252 | ) |
| 2253 | .child( |
| 2254 | div() |
| 2255 | .truncate() |
| 2256 | .text_size(px(12.)) |
| 2257 | .text_color(theme::text_muted()) |
| 2258 | .child(edit.excerpt.clone()), |
| 2259 | ), |
| 2260 | ) |
| 2261 | .child( |
| 2262 | div() |
| 2263 | .id("edit-close") |
| 2264 | .size(px(24.)) |
| 2265 | .flex() |
| 2266 | .items_center() |
| 2267 | .justify_center() |
| 2268 | .rounded(px(6.)) |
| 2269 | .cursor_pointer() |
| 2270 | .hover(|button| button.bg(theme::row_hover())) |
| 2271 | .child(icon(IconName::Close, 14., theme::text_muted())) |
| 2272 | .on_click(cx.listener(|this, _, window, cx| this.cancel_edit(window, cx))), |
| 2273 | ), |
| 2274 | ) |
| 2275 | } |
| 2276 | |
| 2277 | fn render_reply_strip(&self, cx: &mut Context<Self>) -> Option<Div> { |
| 2278 | let reply = self.reply.as_ref()?; |
| 2279 | Some( |
| 2280 | h_flex() |
| 2281 | .w_full() |
| 2282 | .mb(px(6.)) |
| 2283 | .gap(px(10.)) |
| 2284 | .items_center() |
| 2285 | .pl(px(10.)) |
| 2286 | .pr(px(4.)) |
| 2287 | .py(px(6.)) |
| 2288 | .rounded(px(8.)) |
| 2289 | .bg(theme::surface()) |
| 2290 | .border_1() |
| 2291 | .border_color(theme::border()) |
| 2292 | .child(icon(IconName::Undo2, 14., theme::accent_text())) |
| 2293 | .child( |
| 2294 | v_flex() |
| 2295 | .flex_1() |
| 2296 | .min_w_0() |
| 2297 | .child( |
| 2298 | div() |
| 2299 | .truncate() |
| 2300 | .text_size(px(12.)) |
| 2301 | .font_weight(FontWeight::SEMIBOLD) |
| 2302 | .text_color(theme::accent_text()) |
| 2303 | .child(format!("Replying to {}", reply.author)), |
| 2304 | ) |
| 2305 | .child( |
| 2306 | div() |
| 2307 | .truncate() |
| 2308 | .text_size(px(12.)) |
| 2309 | .text_color(theme::text_muted()) |
| 2310 | .child(reply.excerpt.clone()), |
| 2311 | ), |
| 2312 | ) |
| 2313 | .child( |
| 2314 | div() |
| 2315 | .id("reply-close") |
| 2316 | .size(px(24.)) |
| 2317 | .flex() |
| 2318 | .items_center() |
| 2319 | .justify_center() |
| 2320 | .rounded(px(6.)) |
| 2321 | .cursor_pointer() |
| 2322 | .hover(|button| button.bg(theme::row_hover())) |
| 2323 | .child(icon(IconName::Close, 14., theme::text_muted())) |
| 2324 | .on_click(cx.listener(|this, _, _, cx| this.set_reply(None, cx))), |
| 2325 | ), |
| 2326 | ) |
| 2327 | } |
| 2328 | } |
| 2329 | |
| 2330 | impl Render for Composer { |
| 2331 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 2332 | let focused = self.input.focus_handle(cx).contains_focused(window, cx); |
| 2333 | let can_send = self.can_send(cx); |
| 2334 | let can_attach = self.editing.is_none(); |
| 2335 | let send = div() |
| 2336 | .id("composer-send") |
| 2337 | .size(px(32.)) |
| 2338 | .flex_none() |
| 2339 | .flex() |
| 2340 | .items_center() |
| 2341 | .justify_center() |
| 2342 | .rounded(px(8.)) |
| 2343 | .child(symbol("keyboard_return", 20., white())) |
| 2344 | .when(!can_send, |button| button.opacity(0.4)) |
| 2345 | .when(can_send, |button| { |
| 2346 | button |
| 2347 | .cursor_pointer() |
| 2348 | .hover(|button| button.bg(white().opacity(0.1))) |
| 2349 | .on_click(cx.listener(|this, _, window, cx| this.submit_current(window, cx))) |
| 2350 | }); |
| 2351 | let attach = can_attach.then(|| { |
| 2352 | div() |
| 2353 | .id("composer-attach") |
| 2354 | .size(px(32.)) |
| 2355 | .flex_none() |
| 2356 | .flex() |
| 2357 | .items_center() |
| 2358 | .justify_center() |
| 2359 | .rounded(px(8.)) |
| 2360 | .cursor_pointer() |
| 2361 | .hover(|button| button.bg(theme::row_hover())) |
| 2362 | .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx)) |
| 2363 | .child(symbol("attach_file", 20., theme::text_muted())) |
| 2364 | .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx))) |
| 2365 | }); |
| 2366 | let composer = cx.weak_entity(); |
| 2367 | let tokens_composer = composer.clone(); |
| 2368 | let input = Textarea::new(&self.input) |
| 2369 | .appearance(false) |
| 2370 | .bordered(false) |
| 2371 | .on_paste(move |item, window, cx| { |
| 2372 | composer |
| 2373 | .update(cx, |this, cx| this.paste(item, window, cx)) |
| 2374 | .unwrap_or(false) |
| 2375 | }) |
| 2376 | .token(move |context, _, cx| { |
| 2377 | if let Some(id) = context |
| 2378 | .is_block() |
| 2379 | .then(|| image_id(context.token())) |
| 2380 | .flatten() |
| 2381 | { |
| 2382 | let preview = tokens_composer |
| 2383 | .read_with(cx, |this, _| this.tray.image(id)) |
| 2384 | .ok() |
| 2385 | .flatten(); |
| 2386 | let remove_composer = tokens_composer.clone(); |
| 2387 | return inline_preview( |
| 2388 | id, |
| 2389 | preview, |
| 2390 | context.available_width(), |
| 2391 | context.is_selected(), |
| 2392 | Rc::new(move |window, cx| { |
| 2393 | remove_composer |
| 2394 | .update(cx, |this, cx| this.remove_image_token(id, window, cx)) |
| 2395 | .ok(); |
| 2396 | }), |
| 2397 | ); |
| 2398 | } |
| 2399 | div() |
| 2400 | .h(context.line_height()) |
| 2401 | .px(px(5.)) |
| 2402 | .rounded(px(5.)) |
| 2403 | .bg(if context.is_selected() { |
| 2404 | theme::accent().opacity(0.4) |
| 2405 | } else { |
| 2406 | theme::mention_background(false) |
| 2407 | }) |
| 2408 | .text_color(theme::mention_text()) |
| 2409 | .font_weight(FontWeight::SEMIBOLD) |
| 2410 | .child(context.token().label().clone()) |
| 2411 | .into_any_element() |
| 2412 | }); |
| 2413 | let tray = can_attach |
| 2414 | .then(|| { |
| 2415 | render_tray( |
| 2416 | &self.tray, |
| 2417 | Self::remove_attachment, |
| 2418 | Self::retry_attachment, |
| 2419 | cx, |
| 2420 | ) |
| 2421 | }) |
| 2422 | .flatten(); |
| 2423 | let notice = self.tray.notice().filter(|_| can_attach).map(|notice| { |
| 2424 | div() |
| 2425 | .w_full() |
| 2426 | .mb(px(6.)) |
| 2427 | .text_size(px(12.)) |
| 2428 | .text_color(theme::amber()) |
| 2429 | .child(notice.to_owned()) |
| 2430 | }); |
| 2431 | let composer_bounds = self.composer_bounds.clone(); |
| 2432 | v_flex() |
| 2433 | .w_full() |
| 2434 | .flex_none() |
| 2435 | .px(px(24.)) |
| 2436 | .pt(px(8.)) |
| 2437 | .pb(px(12.)) |
| 2438 | .key_context(KEY_CONTEXT) |
| 2439 | .on_action(cx.listener(|this, _: &ToggleBold, _, cx| { |
| 2440 | if this.link_editor.is_none() { |
| 2441 | this.toggle_mark(MarkKind::Bold, cx); |
| 2442 | } |
| 2443 | })) |
| 2444 | .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| { |
| 2445 | if this.link_editor.is_none() { |
| 2446 | this.toggle_mark(MarkKind::Italic, cx); |
| 2447 | } |
| 2448 | })) |
| 2449 | .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| { |
| 2450 | if this.link_editor.is_none() { |
| 2451 | this.toggle_mark(MarkKind::Underline, cx); |
| 2452 | } |
| 2453 | })) |
| 2454 | .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| { |
| 2455 | if this.link_editor.is_none() { |
| 2456 | this.toggle_mark(MarkKind::Strike, cx); |
| 2457 | } |
| 2458 | })) |
| 2459 | .on_action(cx.listener(|this, _: &ToggleSuperscript, _, cx| { |
| 2460 | if this.link_editor.is_none() { |
| 2461 | this.toggle_mark(MarkKind::Superscript, cx); |
| 2462 | } |
| 2463 | })) |
| 2464 | .on_action(cx.listener(|this, _: &ToggleSubscript, _, cx| { |
| 2465 | if this.link_editor.is_none() { |
| 2466 | this.toggle_mark(MarkKind::Subscript, cx); |
| 2467 | } |
| 2468 | })) |
| 2469 | .on_action(cx.listener(|this, _: &ToggleCode, _, cx| { |
| 2470 | if this.link_editor.is_none() { |
| 2471 | this.toggle_mark(MarkKind::Code, cx); |
| 2472 | } |
| 2473 | })) |
| 2474 | .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx))) |
| 2475 | .capture_action(cx.listener(|this, _: &Undo, window, cx| { |
| 2476 | if this.link_editor.is_none() { |
| 2477 | this.step_history(true, window, cx); |
| 2478 | cx.stop_propagation(); |
| 2479 | } |
| 2480 | })) |
| 2481 | .capture_action(cx.listener(|this, _: &Redo, window, cx| { |
| 2482 | if this.link_editor.is_none() { |
| 2483 | this.step_history(false, window, cx); |
| 2484 | cx.stop_propagation(); |
| 2485 | } |
| 2486 | })) |
| 2487 | .capture_action(cx.listener(|this, _: &Copy, _, cx| { |
| 2488 | if this.link_editor.is_none() && this.copy_selection(cx) { |
| 2489 | cx.stop_propagation(); |
| 2490 | } |
| 2491 | })) |
| 2492 | .capture_action(cx.listener(|this, _: &Cut, window, cx| { |
| 2493 | if this.link_editor.is_none() && this.copy_selection(cx) { |
| 2494 | this.input |
| 2495 | .update(cx, |state, cx| state.replace("", window, cx)); |
| 2496 | cx.stop_propagation(); |
| 2497 | } |
| 2498 | })) |
| 2499 | .capture_action(cx.listener(|this, _: &MoveUp, _, cx| { |
| 2500 | if this.link_editor.is_some() { |
| 2501 | } else if this.popup_is_open() { |
| 2502 | this.move_highlight(-1, cx); |
| 2503 | cx.stop_propagation(); |
| 2504 | } else if this.editing.is_none() && this.is_empty(cx) { |
| 2505 | cx.emit(ComposerEvent::EditLast); |
| 2506 | cx.stop_propagation(); |
| 2507 | } |
| 2508 | })) |
| 2509 | .capture_action(cx.listener(|this, _: &MoveDown, _, cx| { |
| 2510 | if this.link_editor.is_none() && this.popup_is_open() { |
| 2511 | this.move_highlight(1, cx); |
| 2512 | cx.stop_propagation(); |
| 2513 | } |
| 2514 | })) |
| 2515 | .capture_action(cx.listener(|this, action: &Enter, window, cx| { |
| 2516 | if this.link_editor.is_some() { |
| 2517 | this.apply_link(window, cx); |
| 2518 | cx.stop_propagation(); |
| 2519 | } else if this.popup_is_open() { |
| 2520 | this.accept_popup(window, cx); |
| 2521 | cx.stop_propagation(); |
| 2522 | } else if this.break_line(action.shift, window, cx) { |
| 2523 | cx.stop_propagation(); |
| 2524 | } |
| 2525 | })) |
| 2526 | .capture_action(cx.listener(|this, _: &IndentInline, window, cx| { |
| 2527 | if this.link_editor.is_some() { |
| 2528 | } else if this.popup_is_open() { |
| 2529 | this.accept_popup(window, cx); |
| 2530 | cx.stop_propagation(); |
| 2531 | } else if this.indent(false, window, cx) { |
| 2532 | cx.stop_propagation(); |
| 2533 | } |
| 2534 | })) |
| 2535 | .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| { |
| 2536 | if this.link_editor.is_none() && this.indent(true, window, cx) { |
| 2537 | cx.stop_propagation(); |
| 2538 | } |
| 2539 | })) |
| 2540 | .capture_action(cx.listener(|this, _: &Backspace, window, cx| { |
| 2541 | if this.link_editor.is_none() |
| 2542 | && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx)) |
| 2543 | { |
| 2544 | cx.stop_propagation(); |
| 2545 | } |
| 2546 | })) |
| 2547 | .capture_action(cx.listener(|this, _: &Delete, window, cx| { |
| 2548 | if this.link_editor.is_none() && this.delete_forward(window, cx) { |
| 2549 | cx.stop_propagation(); |
| 2550 | } |
| 2551 | })) |
| 2552 | .capture_action(cx.listener(|this, _: &Escape, window, cx| { |
| 2553 | if this.link_editor.is_some() { |
| 2554 | this.close_link_editor(window, cx); |
| 2555 | cx.stop_propagation(); |
| 2556 | return; |
| 2557 | } |
| 2558 | if this.toolbar_requested(cx) { |
| 2559 | this.toolbar_dismissed = Some(this.selection(cx)); |
| 2560 | cx.notify(); |
| 2561 | cx.stop_propagation(); |
| 2562 | return; |
| 2563 | } |
| 2564 | if let Some(popup) = &this.emoji_popup { |
| 2565 | this.emoji_dismissed_at = Some(popup.range.start); |
| 2566 | } |
| 2567 | if this.popup.is_some() || this.emoji_popup.is_some() { |
| 2568 | this.close_popup(); |
| 2569 | cx.notify(); |
| 2570 | cx.stop_propagation(); |
| 2571 | } else if this.editing.is_some() { |
| 2572 | this.cancel_edit(window, cx); |
| 2573 | cx.stop_propagation(); |
| 2574 | } |
| 2575 | })) |
| 2576 | .children(notice) |
| 2577 | .children(self.render_reply_strip(cx)) |
| 2578 | .children(self.render_edit_strip(cx)) |
| 2579 | .children(self.render_link_preview(cx)) |
| 2580 | .child( |
| 2581 | div() |
| 2582 | .relative() |
| 2583 | .w_full() |
| 2584 | .children(self.render_popup(cx)) |
| 2585 | .children(self.render_emoji_popup(window, cx)) |
| 2586 | .children(self.render_toolbar(focused, cx)) |
| 2587 | .child( |
| 2588 | v_flex() |
| 2589 | .relative() |
| 2590 | .w_full() |
| 2591 | .rounded(px(10.)) |
| 2592 | .bg(theme::surface()) |
| 2593 | .border_1() |
| 2594 | .border_color(if focused { |
| 2595 | theme::accent() |
| 2596 | } else { |
| 2597 | theme::border_strong() |
| 2598 | }) |
| 2599 | .child( |
| 2600 | canvas( |
| 2601 | move |bounds, _, _| composer_bounds.set(Some(bounds)), |
| 2602 | |_, _, _, _| {}, |
| 2603 | ) |
| 2604 | .absolute() |
| 2605 | .size_full(), |
| 2606 | ) |
| 2607 | .children(tray) |
| 2608 | .child( |
| 2609 | h_flex() |
| 2610 | .w_full() |
| 2611 | .items_end() |
| 2612 | .gap(px(6.)) |
| 2613 | .py(px(6.)) |
| 2614 | .pl(px(if can_attach { 6. } else { 12. })) |
| 2615 | .pr(px(6.)) |
| 2616 | .children(attach) |
| 2617 | .child( |
| 2618 | div() |
| 2619 | .flex_1() |
| 2620 | .min_w_0() |
| 2621 | .capture_any_mouse_down(cx.listener( |
| 2622 | |this, _: &MouseDownEvent, _, _| { |
| 2623 | this.mouse_selecting = true; |
| 2624 | this.toolbar_dismissed = None; |
| 2625 | this.link_editor = None; |
| 2626 | }, |
| 2627 | )) |
| 2628 | .capture_any_mouse_up(cx.listener( |
| 2629 | |this, _: &MouseUpEvent, _, cx| { |
| 2630 | this.mouse_selecting = false; |
| 2631 | cx.notify(); |
| 2632 | }, |
| 2633 | )) |
| 2634 | .on_mouse_up_out( |
| 2635 | MouseButton::Left, |
| 2636 | cx.listener(|this, _, _, cx| { |
| 2637 | this.mouse_selecting = false; |
| 2638 | cx.notify(); |
| 2639 | }), |
| 2640 | ) |
| 2641 | .child(input), |
| 2642 | ) |
| 2643 | .child(send), |
| 2644 | ), |
| 2645 | ), |
| 2646 | ) |
| 2647 | .children(self.render_paste_hint()) |
| 2648 | } |
| 2649 | } |
| 2650 | |
| 2651 | #[cfg(test)] |
| 2652 | mod tests { |
| 2653 | use super::{active_mention, submitted_text}; |
| 2654 | use gpui_kit::component::input::InputEvent; |
| 2655 | |
| 2656 | fn press(shift: bool) -> InputEvent { |
| 2657 | InputEvent::PressEnter { |
| 2658 | secondary: false, |
| 2659 | shift, |
| 2660 | } |
| 2661 | } |
| 2662 | |
| 2663 | #[test] |
| 2664 | fn enter_sends_trimmed_text() { |
| 2665 | assert_eq!( |
| 2666 | submitted_text(&press(false), " hello \n"), |
| 2667 | Some("hello".into()) |
| 2668 | ); |
| 2669 | } |
| 2670 | |
| 2671 | #[test] |
| 2672 | fn shift_enter_never_sends() { |
| 2673 | assert_eq!(submitted_text(&press(true), "hello"), None); |
| 2674 | } |
| 2675 | |
| 2676 | #[test] |
| 2677 | fn blank_text_never_sends() { |
| 2678 | assert_eq!(submitted_text(&press(false), " \n "), None); |
| 2679 | } |
| 2680 | |
| 2681 | #[test] |
| 2682 | fn other_events_never_send() { |
| 2683 | assert_eq!(submitted_text(&InputEvent::Change, "hello"), None); |
| 2684 | } |
| 2685 | |
| 2686 | #[test] |
| 2687 | fn at_sign_opens_a_mention_query() { |
| 2688 | assert_eq!(active_mention("hi @Ma", 6, &[]), Some((3..6, "Ma".into()))); |
| 2689 | assert_eq!(active_mention("@", 1, &[]), Some((0..1, String::new()))); |
| 2690 | } |
| 2691 | |
| 2692 | #[test] |
| 2693 | fn names_with_a_space_keep_the_query_open() { |
| 2694 | assert_eq!( |
| 2695 | active_mention("@Mara Lin", 9, &[]), |
| 2696 | Some((0..9, "Mara Lin".into())) |
| 2697 | ); |
| 2698 | } |
| 2699 | |
| 2700 | #[test] |
| 2701 | fn mail_addresses_and_closed_queries_do_not_open() { |
| 2702 | assert_eq!(active_mention("a@b", 3, &[]), None); |
| 2703 | assert_eq!(active_mention("@Mara ", 6, &[]), None); |
| 2704 | assert_eq!(active_mention("@ x", 3, &[]), None); |
| 2705 | assert_eq!(active_mention("@Ma\nrest", 8, &[]), None); |
| 2706 | } |
| 2707 | |
| 2708 | #[test] |
| 2709 | fn text_inside_a_token_does_not_reopen() { |
| 2710 | let token = 0..15; |
| 2711 | assert_eq!( |
| 2712 | active_mention("@Mara Lindqvist", 15, std::slice::from_ref(&token)), |
| 2713 | None |
| 2714 | ); |
| 2715 | assert_eq!( |
| 2716 | active_mention("@Mara Lindqvist @Pr", 19, std::slice::from_ref(&token)), |
| 2717 | Some((16..19, "Pr".into())) |
| 2718 | ); |
| 2719 | } |
| 2720 | |
| 2721 | #[test] |
| 2722 | fn extras_carry_image_bytes_with_their_mime_type_and_the_file_references() { |
| 2723 | use std::sync::Arc; |
| 2724 | |
| 2725 | use gpui_kit::{Image, ImageFormat}; |
| 2726 | use teams_core::FileKind; |
| 2727 | |
| 2728 | use super::{Outgoing, OutgoingFile, OutgoingImage}; |
| 2729 | |
| 2730 | let outgoing = Outgoing { |
| 2731 | draft: teams_core::Draft::default(), |
| 2732 | mentions: Vec::new(), |
| 2733 | link_preview: None, |
| 2734 | reply: None, |
| 2735 | edit: None, |
| 2736 | images: vec![OutgoingImage { |
| 2737 | name: "pasted-image.png".into(), |
| 2738 | image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])), |
| 2739 | dimensions: Some((1, 1)), |
| 2740 | }], |
| 2741 | files: vec![OutgoingFile { |
| 2742 | name: "plan.pdf".into(), |
| 2743 | size: 9, |
| 2744 | kind: FileKind::Pdf, |
| 2745 | uploaded: None, |
| 2746 | reference: teams_core::FileReference { |
| 2747 | attachment_id: "guid".into(), |
| 2748 | content_url: "https://files.example/plan.pdf".into(), |
| 2749 | name: "plan.pdf".into(), |
| 2750 | }, |
| 2751 | }], |
| 2752 | }; |
| 2753 | let extras = outgoing.extras(); |
| 2754 | assert_eq!(extras.images[0].content_type, "image/png"); |
| 2755 | assert_eq!(extras.images[0].bytes.as_slice(), [1, 2, 3]); |
| 2756 | assert_eq!(extras.files[0].attachment_id, "guid"); |
| 2757 | assert!(outgoing.has_attachments()); |
| 2758 | } |
| 2759 | |
| 2760 | fn placed_image(width: u32) -> super::OutgoingImage { |
| 2761 | use std::sync::Arc; |
| 2762 | |
| 2763 | use gpui_kit::{Image, ImageFormat}; |
| 2764 | |
| 2765 | super::OutgoingImage { |
| 2766 | name: "pasted-image.png".into(), |
| 2767 | image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])), |
| 2768 | dimensions: Some((width, width)), |
| 2769 | } |
| 2770 | } |
| 2771 | |
| 2772 | fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing { |
| 2773 | super::Outgoing { |
| 2774 | draft: teams_core::Draft::plain(text), |
| 2775 | mentions: Vec::new(), |
| 2776 | link_preview: None, |
| 2777 | reply: None, |
| 2778 | edit: None, |
| 2779 | images, |
| 2780 | files: Vec::new(), |
| 2781 | } |
| 2782 | } |
| 2783 | |
| 2784 | #[test] |
| 2785 | fn an_image_is_placed_in_the_html_where_its_mark_sits() { |
| 2786 | let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]); |
| 2787 | assert_eq!( |
| 2788 | outgoing.html(), |
| 2789 | "a <img src=\"../hostedContents/1/$value\"> b" |
| 2790 | ); |
| 2791 | assert_eq!(outgoing.text(), "a b"); |
| 2792 | } |
| 2793 | |
| 2794 | #[test] |
| 2795 | fn images_keep_the_order_of_their_marks() { |
| 2796 | let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]); |
| 2797 | assert_eq!( |
| 2798 | outgoing.html(), |
| 2799 | "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">" |
| 2800 | ); |
| 2801 | } |
| 2802 | |
| 2803 | #[test] |
| 2804 | fn a_mark_without_an_image_leaves_no_trace() { |
| 2805 | assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab"); |
| 2806 | } |
| 2807 | |
| 2808 | #[test] |
| 2809 | fn enter_sends_attachments_even_without_text() { |
| 2810 | assert!(super::is_plain_enter(&press(false))); |
| 2811 | assert!(!super::is_plain_enter(&press(true))); |
| 2812 | assert!(!super::is_plain_enter(&InputEvent::Change)); |
| 2813 | } |
| 2814 | |
| 2815 | mod keys { |
| 2816 | use std::sync::Arc; |
| 2817 | |
| 2818 | use gpui_kit::test::TestWindowExt as _; |
| 2819 | use gpui_kit::{AppContext as _, TestAppContext, WindowOptions}; |
| 2820 | use store::Store; |
| 2821 | |
| 2822 | use super::super::Composer; |
| 2823 | use crate::app_state::{AppState, Mode}; |
| 2824 | |
| 2825 | #[gpui_kit::test] |
| 2826 | fn ctrl_a_selects_the_whole_draft(cx: &mut TestAppContext) { |
| 2827 | cx.update(gpui_kit::init); |
| 2828 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 2829 | let mode = Mode { |
| 2830 | demo: true, |
| 2831 | read_only: false, |
| 2832 | demo_sync: None, |
| 2833 | }; |
| 2834 | let (handle, composer) = cx.update(|cx| { |
| 2835 | let app = cx.new(|_| AppState::new(store, mode)); |
| 2836 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 2837 | cx.new(|cx| Composer::new(app, window, cx)) |
| 2838 | }) |
| 2839 | .unwrap() |
| 2840 | }); |
| 2841 | let value = cx |
| 2842 | .update_window(handle, |_, window, cx| { |
| 2843 | composer.update(cx, |composer, cx| composer.focus(window, cx)); |
| 2844 | window.render_frame(cx); |
| 2845 | window.input("first line", cx); |
| 2846 | window.press("shift-enter", cx); |
| 2847 | window.input("second line", cx); |
| 2848 | window.press("ctrl-a", cx); |
| 2849 | window.input("X", cx); |
| 2850 | composer.read(cx).input.read(cx).value() |
| 2851 | }) |
| 2852 | .unwrap(); |
| 2853 | assert_eq!(value, "X"); |
| 2854 | } |
| 2855 | |
| 2856 | struct Typist<'a> { |
| 2857 | cx: &'a mut TestAppContext, |
| 2858 | handle: gpui_kit::AnyWindowHandle, |
| 2859 | composer: gpui_kit::Entity<Composer>, |
| 2860 | } |
| 2861 | |
| 2862 | impl Typist<'_> { |
| 2863 | fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) { |
| 2864 | self.cx |
| 2865 | .update_window(self.handle, |_, window, cx| action(window, cx)) |
| 2866 | .unwrap(); |
| 2867 | self.cx.run_until_parked(); |
| 2868 | } |
| 2869 | |
| 2870 | fn type_text(&mut self, text: &str) { |
| 2871 | for character in text.chars() { |
| 2872 | self.act(|window, cx| window.input(&character.to_string(), cx)); |
| 2873 | } |
| 2874 | } |
| 2875 | |
| 2876 | fn press(&mut self, keys: &str) { |
| 2877 | for key in keys.split(' ') { |
| 2878 | self.act(|window, cx| window.press(key, cx)); |
| 2879 | } |
| 2880 | } |
| 2881 | |
| 2882 | fn value(&mut self) -> String { |
| 2883 | let composer = self.composer.clone(); |
| 2884 | self.cx |
| 2885 | .update(|cx| composer.read(cx).input.read(cx).value().to_string()) |
| 2886 | } |
| 2887 | |
| 2888 | fn draft(&mut self) -> teams_core::Draft { |
| 2889 | let composer = self.composer.clone(); |
| 2890 | self.cx.update(|cx| composer.read(cx).draft.clone()) |
| 2891 | } |
| 2892 | |
| 2893 | fn outgoing(&mut self) -> super::super::Outgoing { |
| 2894 | let composer = self.composer.clone(); |
| 2895 | self.cx |
| 2896 | .update(|cx| composer.read(cx).outgoing(cx)) |
| 2897 | .expect("text to send") |
| 2898 | } |
| 2899 | } |
| 2900 | |
| 2901 | fn typist(cx: &mut TestAppContext) -> Typist<'_> { |
| 2902 | let (handle, composer) = demo_composer(cx); |
| 2903 | cx.update(super::super::bind_keys); |
| 2904 | let mut typist = Typist { |
| 2905 | cx, |
| 2906 | handle, |
| 2907 | composer: composer.clone(), |
| 2908 | }; |
| 2909 | typist.act(|window, cx| { |
| 2910 | composer.update(cx, |composer, cx| composer.focus(window, cx)); |
| 2911 | window.render_frame(cx); |
| 2912 | }); |
| 2913 | typist |
| 2914 | } |
| 2915 | |
| 2916 | fn png_bytes(side: u32) -> Vec<u8> { |
| 2917 | let mut bytes = Vec::new(); |
| 2918 | image::RgbaImage::new(side, side) |
| 2919 | .write_to( |
| 2920 | &mut std::io::Cursor::new(&mut bytes), |
| 2921 | image::ImageFormat::Png, |
| 2922 | ) |
| 2923 | .unwrap(); |
| 2924 | bytes |
| 2925 | } |
| 2926 | |
| 2927 | fn paste_image(typist: &mut Typist<'_>, side: u32) { |
| 2928 | typist.cx.write_to_clipboard(gpui_kit::ClipboardItem { |
| 2929 | entries: vec![gpui_kit::ClipboardEntry::Image( |
| 2930 | gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)), |
| 2931 | )], |
| 2932 | }); |
| 2933 | typist.press("ctrl-v"); |
| 2934 | } |
| 2935 | |
| 2936 | fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> { |
| 2937 | let composer = typist.composer.clone(); |
| 2938 | typist.cx.update(|cx| { |
| 2939 | composer |
| 2940 | .read(cx) |
| 2941 | .input |
| 2942 | .read(cx) |
| 2943 | .tokens() |
| 2944 | .iter() |
| 2945 | .map(|span| (span.range(), span.token().is_block())) |
| 2946 | .collect() |
| 2947 | }) |
| 2948 | } |
| 2949 | |
| 2950 | #[gpui_kit::test] |
| 2951 | fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) { |
| 2952 | let mut typist = typist(cx); |
| 2953 | typist.type_text("ab"); |
| 2954 | typist.press("left"); |
| 2955 | paste_image(&mut typist, 2); |
| 2956 | assert_eq!(typist.value(), "a\u{FFFC}b"); |
| 2957 | assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]); |
| 2958 | let outgoing = typist.outgoing(); |
| 2959 | assert_eq!(outgoing.images.len(), 1); |
| 2960 | assert_eq!( |
| 2961 | outgoing.html(), |
| 2962 | "a<img src=\"../hostedContents/1/$value\">b" |
| 2963 | ); |
| 2964 | let composer = typist.composer.clone(); |
| 2965 | assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips())); |
| 2966 | } |
| 2967 | |
| 2968 | fn wide_png_bytes() -> Vec<u8> { |
| 2969 | let mut bytes = Vec::new(); |
| 2970 | image::RgbaImage::new(600, 300) |
| 2971 | .write_to( |
| 2972 | &mut std::io::Cursor::new(&mut bytes), |
| 2973 | image::ImageFormat::Png, |
| 2974 | ) |
| 2975 | .unwrap(); |
| 2976 | bytes |
| 2977 | } |
| 2978 | |
| 2979 | fn caret_is_visible(typist: &mut Typist<'_>) -> bool { |
| 2980 | let composer = typist.composer.clone(); |
| 2981 | typist.cx.update(|cx| { |
| 2982 | let state = composer.read(cx).input.read(cx); |
| 2983 | let cursor = state.cursor(); |
| 2984 | let caret = state.range_to_bounds(&(cursor..cursor)).unwrap(); |
| 2985 | let viewport = state.input_bounds(); |
| 2986 | caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom() |
| 2987 | }) |
| 2988 | } |
| 2989 | |
| 2990 | #[gpui_kit::test] |
| 2991 | fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) { |
| 2992 | let mut typist = typist(cx); |
| 2993 | typist.type_text("look at this "); |
| 2994 | typist.cx.write_to_clipboard(gpui_kit::ClipboardItem { |
| 2995 | entries: vec![gpui_kit::ClipboardEntry::Image( |
| 2996 | gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()), |
| 2997 | )], |
| 2998 | }); |
| 2999 | typist.press("ctrl-v"); |
| 3000 | typist.act(|window, _| window.refresh()); |
| 3001 | typist.type_text("and then more text"); |
| 3002 | typist.act(|window, _| window.refresh()); |
| 3003 | assert!(caret_is_visible(&mut typist)); |
| 3004 | } |
| 3005 | |
| 3006 | #[gpui_kit::test] |
| 3007 | fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) { |
| 3008 | let mut typist = typist(cx); |
| 3009 | typist.type_text("ab"); |
| 3010 | typist.press("left"); |
| 3011 | paste_image(&mut typist, 2); |
| 3012 | typist.press("backspace"); |
| 3013 | assert_eq!(typist.value(), "ab"); |
| 3014 | assert!(image_tokens(&mut typist).is_empty()); |
| 3015 | let outgoing = typist.outgoing(); |
| 3016 | assert!(outgoing.images.is_empty()); |
| 3017 | assert_eq!(outgoing.html(), "ab"); |
| 3018 | typist.press("ctrl-z"); |
| 3019 | assert_eq!(typist.value(), "a\u{FFFC}b"); |
| 3020 | assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]); |
| 3021 | assert_eq!(typist.outgoing().images.len(), 1); |
| 3022 | } |
| 3023 | |
| 3024 | #[gpui_kit::test] |
| 3025 | fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) { |
| 3026 | let mut typist = typist(cx); |
| 3027 | typist.type_text("ab"); |
| 3028 | paste_image(&mut typist, 2); |
| 3029 | typist.type_text("cd"); |
| 3030 | let composer = typist.composer.clone(); |
| 3031 | let id = typist.cx.update(|cx| { |
| 3032 | let state = composer.read(cx).input.read(cx); |
| 3033 | super::super::image_id(state.tokens()[0].token()).unwrap() |
| 3034 | }); |
| 3035 | typist.act(|window, cx| { |
| 3036 | composer.update(cx, |composer, cx| { |
| 3037 | composer.remove_image_token(id, window, cx) |
| 3038 | }); |
| 3039 | }); |
| 3040 | assert_eq!(typist.value(), "abcd"); |
| 3041 | assert!(image_tokens(&mut typist).is_empty()); |
| 3042 | assert!(typist.outgoing().images.is_empty()); |
| 3043 | typist.press("ctrl-z"); |
| 3044 | assert_eq!(typist.value(), "ab\u{FFFC}cd"); |
| 3045 | assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]); |
| 3046 | assert_eq!(typist.outgoing().images.len(), 1); |
| 3047 | } |
| 3048 | |
| 3049 | #[gpui_kit::test] |
| 3050 | fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) { |
| 3051 | let mut typist = typist(cx); |
| 3052 | typist.type_text("x"); |
| 3053 | paste_image(&mut typist, 2); |
| 3054 | typist.type_text("y"); |
| 3055 | typist.press("ctrl-home"); |
| 3056 | paste_image(&mut typist, 4); |
| 3057 | assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y"); |
| 3058 | let outgoing = typist.outgoing(); |
| 3059 | let dimensions: Vec<_> = outgoing |
| 3060 | .images |
| 3061 | .iter() |
| 3062 | .map(|image| image.dimensions) |
| 3063 | .collect(); |
| 3064 | assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]); |
| 3065 | assert_eq!( |
| 3066 | outgoing.html(), |
| 3067 | "<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y" |
| 3068 | ); |
| 3069 | } |
| 3070 | |
| 3071 | #[gpui_kit::test] |
| 3072 | fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) { |
| 3073 | let mut typist = typist(cx); |
| 3074 | paste_image(&mut typist, 2); |
| 3075 | let composer = typist.composer.clone(); |
| 3076 | assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx))); |
| 3077 | let outgoing = typist.outgoing(); |
| 3078 | assert_eq!(outgoing.text(), ""); |
| 3079 | assert_eq!(outgoing.images.len(), 1); |
| 3080 | typist.type_text("hi"); |
| 3081 | typist.press("ctrl-a ctrl-c"); |
| 3082 | let copied = typist.cx.read_from_clipboard().and_then(|item| item.text()); |
| 3083 | assert_eq!(copied.as_deref(), Some("hi")); |
| 3084 | } |
| 3085 | |
| 3086 | #[gpui_kit::test] |
| 3087 | fn pasted_text_loses_object_marks(cx: &mut TestAppContext) { |
| 3088 | let mut typist = typist(cx); |
| 3089 | typist |
| 3090 | .cx |
| 3091 | .write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned())); |
| 3092 | typist.press("ctrl-v"); |
| 3093 | assert_eq!(typist.value(), "ab"); |
| 3094 | } |
| 3095 | |
| 3096 | #[gpui_kit::test] |
| 3097 | fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) { |
| 3098 | let mut typist = typist(cx); |
| 3099 | let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]); |
| 3100 | let composer = typist.composer.clone(); |
| 3101 | typist.act(|window, cx| { |
| 3102 | composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); |
| 3103 | }); |
| 3104 | assert_eq!(typist.value(), "x\u{FFFC}y"); |
| 3105 | assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]); |
| 3106 | let again = typist.outgoing(); |
| 3107 | assert_eq!(again.images, outgoing.images); |
| 3108 | assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y"); |
| 3109 | } |
| 3110 | |
| 3111 | #[gpui_kit::test] |
| 3112 | fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) { |
| 3113 | use teams_core::{FormatState, MarkKind}; |
| 3114 | |
| 3115 | let mut typist = typist(cx); |
| 3116 | typist.type_text("a **bold**"); |
| 3117 | assert_eq!(typist.value(), "a bold"); |
| 3118 | assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On); |
| 3119 | typist.press("backspace"); |
| 3120 | assert_eq!(typist.value(), "a **bold**"); |
| 3121 | assert!(typist.draft().marks().is_empty()); |
| 3122 | let composer = typist.composer.clone(); |
| 3123 | assert_eq!( |
| 3124 | typist |
| 3125 | .cx |
| 3126 | .update(|cx| composer.read(cx).input.read(cx).cursor()), |
| 3127 | 10 |
| 3128 | ); |
| 3129 | typist.press("backspace"); |
| 3130 | typist.type_text("* x"); |
| 3131 | assert_eq!(typist.value(), "a bold x"); |
| 3132 | assert_eq!( |
| 3133 | typist.draft().state(6..8, &MarkKind::Bold), |
| 3134 | FormatState::Off |
| 3135 | ); |
| 3136 | } |
| 3137 | |
| 3138 | #[gpui_kit::test] |
| 3139 | fn typed_url_is_linked_and_backspace_takes_the_link_back(cx: &mut TestAppContext) { |
| 3140 | use teams_core::{Mark, MarkKind}; |
| 3141 | |
| 3142 | let mut typist = typist(cx); |
| 3143 | typist.type_text("see https://a.b "); |
| 3144 | assert_eq!(typist.value(), "see https://a.b "); |
| 3145 | assert_eq!( |
| 3146 | typist.draft().marks(), |
| 3147 | [Mark { |
| 3148 | range: 4..15, |
| 3149 | kind: MarkKind::Link("https://a.b".into()) |
| 3150 | }] |
| 3151 | ); |
| 3152 | typist.press("backspace"); |
| 3153 | assert_eq!(typist.value(), "see https://a.b "); |
| 3154 | assert!(typist.draft().marks().is_empty()); |
| 3155 | } |
| 3156 | |
| 3157 | #[gpui_kit::test] |
| 3158 | fn ctrl_z_takes_an_autolink_back(cx: &mut TestAppContext) { |
| 3159 | let mut typist = typist(cx); |
| 3160 | typist.type_text("https://a.b "); |
| 3161 | assert_eq!(typist.draft().marks().len(), 1); |
| 3162 | typist.press("ctrl-z"); |
| 3163 | assert!(typist.draft().marks().is_empty()); |
| 3164 | } |
| 3165 | |
| 3166 | #[gpui_kit::test] |
| 3167 | fn pasted_url_is_linked_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) { |
| 3168 | use teams_core::{Mark, MarkKind}; |
| 3169 | |
| 3170 | let mut typist = typist(cx); |
| 3171 | typist |
| 3172 | .cx |
| 3173 | .write_to_clipboard(gpui_kit::ClipboardItem::new_string( |
| 3174 | "x https://a.b y".to_owned(), |
| 3175 | )); |
| 3176 | typist.press("ctrl-v"); |
| 3177 | assert_eq!(typist.value(), "x https://a.b y"); |
| 3178 | assert_eq!( |
| 3179 | typist.draft().marks(), |
| 3180 | [Mark { |
| 3181 | range: 2..13, |
| 3182 | kind: MarkKind::Link("https://a.b".into()) |
| 3183 | }] |
| 3184 | ); |
| 3185 | typist.press("ctrl-z"); |
| 3186 | assert_eq!(typist.value(), "x https://a.b y"); |
| 3187 | assert!(typist.draft().marks().is_empty()); |
| 3188 | } |
| 3189 | |
| 3190 | #[gpui_kit::test] |
| 3191 | fn the_link_editor_changes_and_removes_an_autolink(cx: &mut TestAppContext) { |
| 3192 | use teams_core::{Mark, MarkKind}; |
| 3193 | |
| 3194 | let mut typist = typist(cx); |
| 3195 | typist.type_text("https://a.b x"); |
| 3196 | typist.press("home"); |
| 3197 | typist.press("shift-right ".repeat(11).trim_end()); |
| 3198 | typist.press("ctrl-k"); |
| 3199 | typist.type_text("other.de"); |
| 3200 | typist.press("enter"); |
| 3201 | assert_eq!( |
| 3202 | typist.draft().marks(), |
| 3203 | [Mark { |
| 3204 | range: 0..11, |
| 3205 | kind: MarkKind::Link("https://other.de".into()) |
| 3206 | }] |
| 3207 | ); |
| 3208 | typist.press("ctrl-k backspace enter"); |
| 3209 | assert!(typist.draft().marks().is_empty()); |
| 3210 | assert_eq!(typist.value(), "https://a.b x"); |
| 3211 | } |
| 3212 | |
| 3213 | #[gpui_kit::test] |
| 3214 | fn enter_in_a_list_links_the_url_before_the_cursor(cx: &mut TestAppContext) { |
| 3215 | use teams_core::{Mark, MarkKind}; |
| 3216 | |
| 3217 | let mut typist = typist(cx); |
| 3218 | typist.type_text("- https://a.b"); |
| 3219 | typist.press("enter"); |
| 3220 | assert_eq!(typist.value(), "• https://a.b\n• "); |
| 3221 | assert_eq!( |
| 3222 | typist.draft().marks(), |
| 3223 | [Mark { |
| 3224 | range: 4..15, |
| 3225 | kind: MarkKind::Link("https://a.b".into()) |
| 3226 | }] |
| 3227 | ); |
| 3228 | } |
| 3229 | |
| 3230 | #[gpui_kit::test] |
| 3231 | fn a_url_only_paste_links_without_the_paste_hint(cx: &mut TestAppContext) { |
| 3232 | let mut typist = typist(cx); |
| 3233 | typist |
| 3234 | .cx |
| 3235 | .write_to_clipboard(gpui_kit::ClipboardItem::new_string( |
| 3236 | "x https://a.b y".to_owned(), |
| 3237 | )); |
| 3238 | typist.press("ctrl-v"); |
| 3239 | assert_eq!(typist.draft().marks().len(), 1); |
| 3240 | let composer = typist.composer.clone(); |
| 3241 | assert!( |
| 3242 | typist |
| 3243 | .cx |
| 3244 | .update(|cx| composer.read(cx).paste_hint.is_none()) |
| 3245 | ); |
| 3246 | typist.press("ctrl-z"); |
| 3247 | assert!(typist.draft().marks().is_empty()); |
| 3248 | } |
| 3249 | |
| 3250 | #[gpui_kit::test] |
| 3251 | fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) { |
| 3252 | let mut typist = typist(cx); |
| 3253 | typist.type_text("1. one"); |
| 3254 | typist.press("enter"); |
| 3255 | typist.type_text("two"); |
| 3256 | assert_eq!(typist.value(), "1. one\n2. two"); |
| 3257 | typist.press("enter enter"); |
| 3258 | assert_eq!(typist.value(), "1. one\n2. two\n"); |
| 3259 | typist.type_text("after"); |
| 3260 | typist.press("enter"); |
| 3261 | assert_eq!(typist.value(), ""); |
| 3262 | } |
| 3263 | |
| 3264 | #[gpui_kit::test] |
| 3265 | fn tab_nests_a_list_item(cx: &mut TestAppContext) { |
| 3266 | let mut typist = typist(cx); |
| 3267 | typist.type_text("- a"); |
| 3268 | typist.press("enter tab"); |
| 3269 | typist.type_text("b"); |
| 3270 | assert_eq!(typist.value(), "• a\n◦ b"); |
| 3271 | typist.press("shift-tab"); |
| 3272 | assert_eq!(typist.value(), "• a\n• b"); |
| 3273 | } |
| 3274 | |
| 3275 | #[gpui_kit::test] |
| 3276 | fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) { |
| 3277 | use teams_core::{FormatState, MarkKind}; |
| 3278 | |
| 3279 | let mut typist = typist(cx); |
| 3280 | typist.type_text("hello"); |
| 3281 | typist.press("shift-left shift-left ctrl-b"); |
| 3282 | assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On); |
| 3283 | assert_eq!( |
| 3284 | typist.draft().state(0..5, &MarkKind::Bold), |
| 3285 | FormatState::Mixed |
| 3286 | ); |
| 3287 | typist.press("ctrl-b"); |
| 3288 | assert!(typist.draft().marks().is_empty()); |
| 3289 | typist.press("end ctrl-i"); |
| 3290 | typist.type_text("!"); |
| 3291 | assert_eq!(typist.outgoing().html(), "hello<i>!</i>"); |
| 3292 | } |
| 3293 | |
| 3294 | #[gpui_kit::test] |
| 3295 | fn script_shortcuts_exclude_each_other_and_send_teams_html(cx: &mut TestAppContext) { |
| 3296 | let mut typist = typist(cx); |
| 3297 | typist.type_text("x2"); |
| 3298 | typist.press("shift-left ctrl-shift-="); |
| 3299 | assert_eq!(typist.outgoing().html(), "x<sup>2</sup>"); |
| 3300 | typist.press("ctrl-="); |
| 3301 | assert_eq!(typist.outgoing().html(), "x<sub>2</sub>"); |
| 3302 | } |
| 3303 | |
| 3304 | #[gpui_kit::test] |
| 3305 | fn the_toolbar_state_follows_the_selection(cx: &mut TestAppContext) { |
| 3306 | use teams_core::FormatState; |
| 3307 | |
| 3308 | use super::super::FormatButton; |
| 3309 | |
| 3310 | let mut typist = typist(cx); |
| 3311 | typist.type_text("big small"); |
| 3312 | typist.press("shift-left shift-left shift-left shift-left shift-left"); |
| 3313 | let composer = typist.composer.clone(); |
| 3314 | typist.act(|window, cx| { |
| 3315 | composer.update(cx, |composer, cx| { |
| 3316 | composer.press_format(FormatButton::SizeSmall, window, cx) |
| 3317 | }) |
| 3318 | }); |
| 3319 | let states = |typist: &mut Typist<'_>, range: std::ops::Range<usize>| { |
| 3320 | let composer = typist.composer.clone(); |
| 3321 | typist.cx.update(|cx| { |
| 3322 | let composer = composer.read(cx); |
| 3323 | [ |
| 3324 | FormatButton::SizeSmall, |
| 3325 | FormatButton::SizeNormal, |
| 3326 | FormatButton::SizeLarge, |
| 3327 | ] |
| 3328 | .map(|button| composer.format_state(button, &range)) |
| 3329 | }) |
| 3330 | }; |
| 3331 | assert_eq!( |
| 3332 | states(&mut typist, 4..9), |
| 3333 | [FormatState::On, FormatState::Off, FormatState::Off] |
| 3334 | ); |
| 3335 | assert_eq!( |
| 3336 | states(&mut typist, 0..9), |
| 3337 | [FormatState::Mixed, FormatState::Off, FormatState::Off] |
| 3338 | ); |
| 3339 | assert_eq!( |
| 3340 | states(&mut typist, 0..3), |
| 3341 | [FormatState::Off, FormatState::On, FormatState::Off] |
| 3342 | ); |
| 3343 | assert_eq!( |
| 3344 | typist.outgoing().html(), |
| 3345 | "big <span style=\"font-size:xx-small;\">small</span>" |
| 3346 | ); |
| 3347 | } |
| 3348 | |
| 3349 | #[gpui_kit::test] |
| 3350 | fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) { |
| 3351 | let mut typist = typist(cx); |
| 3352 | typist |
| 3353 | .cx |
| 3354 | .write_to_clipboard(gpui_kit::ClipboardItem::new_string( |
| 3355 | "**hi** there".to_owned(), |
| 3356 | )); |
| 3357 | typist.press("ctrl-v"); |
| 3358 | assert_eq!(typist.value(), "hi there"); |
| 3359 | let composer = typist.composer.clone(); |
| 3360 | assert!( |
| 3361 | typist |
| 3362 | .cx |
| 3363 | .update(|cx| composer.read(cx).paste_hint.is_some()) |
| 3364 | ); |
| 3365 | typist.press("ctrl-z"); |
| 3366 | assert_eq!(typist.value(), "**hi** there"); |
| 3367 | assert!(typist.draft().marks().is_empty()); |
| 3368 | } |
| 3369 | |
| 3370 | #[gpui_kit::test] |
| 3371 | fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) { |
| 3372 | use teams_core::{FormatState, MarkKind}; |
| 3373 | |
| 3374 | let mut typist = typist(cx); |
| 3375 | typist.type_text("`code` "); |
| 3376 | typist.press("ctrl-a ctrl-c end ctrl-v"); |
| 3377 | assert_eq!(typist.value(), "code code "); |
| 3378 | assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On); |
| 3379 | } |
| 3380 | |
| 3381 | #[gpui_kit::test] |
| 3382 | fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) { |
| 3383 | use teams_core::{FormatState, MarkKind}; |
| 3384 | |
| 3385 | let mut typist = typist(cx); |
| 3386 | typist.type_text("~~old~~"); |
| 3387 | typist.press("ctrl-a"); |
| 3388 | typist.type_text("new"); |
| 3389 | typist.press("ctrl-z ctrl-z"); |
| 3390 | assert_eq!(typist.value(), "old"); |
| 3391 | assert_eq!( |
| 3392 | typist.draft().state(0..3, &MarkKind::Strike), |
| 3393 | FormatState::On |
| 3394 | ); |
| 3395 | } |
| 3396 | |
| 3397 | #[gpui_kit::test] |
| 3398 | fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) { |
| 3399 | let mut typist = typist(cx); |
| 3400 | typist.type_text("see docs"); |
| 3401 | typist.press("shift-left shift-left shift-left shift-left ctrl-k"); |
| 3402 | let composer = typist.composer.clone(); |
| 3403 | assert!( |
| 3404 | typist |
| 3405 | .cx |
| 3406 | .update(|cx| composer.read(cx).link_editor.is_some()) |
| 3407 | ); |
| 3408 | typist.type_text("example.com"); |
| 3409 | typist.press("enter"); |
| 3410 | assert!( |
| 3411 | typist |
| 3412 | .cx |
| 3413 | .update(|cx| composer.read(cx).link_editor.is_none()) |
| 3414 | ); |
| 3415 | assert_eq!( |
| 3416 | typist.outgoing().html(), |
| 3417 | "see <a href=\"https://example.com\">docs</a>" |
| 3418 | ); |
| 3419 | } |
| 3420 | |
| 3421 | #[gpui_kit::test] |
| 3422 | fn ctrl_z_takes_back_bold_before_the_typing_and_ctrl_y_redoes_it(cx: &mut TestAppContext) { |
| 3423 | use teams_core::{FormatState, MarkKind}; |
| 3424 | |
| 3425 | let mut typist = typist(cx); |
| 3426 | typist.type_text("hello"); |
| 3427 | typist.press("shift-left shift-left ctrl-b"); |
| 3428 | typist.press("ctrl-z"); |
| 3429 | assert_eq!(typist.value(), "hello"); |
| 3430 | assert!(typist.draft().marks().is_empty()); |
| 3431 | typist.press("ctrl-y"); |
| 3432 | assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On); |
| 3433 | } |
| 3434 | |
| 3435 | #[gpui_kit::test] |
| 3436 | fn undo_after_typing_undoes_the_typing_not_an_older_bold(cx: &mut TestAppContext) { |
| 3437 | use teams_core::{FormatState, MarkKind}; |
| 3438 | |
| 3439 | let mut typist = typist(cx); |
| 3440 | typist.type_text("hello"); |
| 3441 | typist.press("shift-left shift-left ctrl-b end"); |
| 3442 | typist.type_text(" x"); |
| 3443 | typist.press("backspace backspace"); |
| 3444 | assert_eq!(typist.value(), "hello"); |
| 3445 | typist.press("ctrl-z"); |
| 3446 | assert_ne!(typist.value(), "hello"); |
| 3447 | assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On); |
| 3448 | } |
| 3449 | |
| 3450 | #[gpui_kit::test] |
| 3451 | fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) { |
| 3452 | let mut typist = typist(cx); |
| 3453 | typist.type_text("```"); |
| 3454 | typist.press("enter"); |
| 3455 | typist.type_text("a"); |
| 3456 | typist.press("enter"); |
| 3457 | typist.type_text("b"); |
| 3458 | typist.press("up end delete"); |
| 3459 | assert_eq!(typist.outgoing().html(), "<pre>ab</pre>"); |
| 3460 | } |
| 3461 | |
| 3462 | #[gpui_kit::test] |
| 3463 | fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) { |
| 3464 | let mut typist = typist(cx); |
| 3465 | typist.type_text("```"); |
| 3466 | typist.press("enter"); |
| 3467 | typist.type_text(" x"); |
| 3468 | typist.press("ctrl-a ctrl-c"); |
| 3469 | let text = typist.cx.read_from_clipboard().and_then(|item| item.text()); |
| 3470 | assert_eq!(text.as_deref(), Some(" x")); |
| 3471 | } |
| 3472 | |
| 3473 | #[gpui_kit::test] |
| 3474 | fn a_refused_link_keeps_the_field_open_and_says_why(cx: &mut TestAppContext) { |
| 3475 | let mut typist = typist(cx); |
| 3476 | typist.type_text("docs"); |
| 3477 | typist.press("ctrl-a ctrl-k"); |
| 3478 | typist.type_text("javascript:alert(1)"); |
| 3479 | typist.press("enter"); |
| 3480 | let composer = typist.composer.clone(); |
| 3481 | assert!(typist.cx.update(|cx| { |
| 3482 | composer |
| 3483 | .read(cx) |
| 3484 | .link_editor |
| 3485 | .as_ref() |
| 3486 | .is_some_and(|editor| editor.refused) |
| 3487 | })); |
| 3488 | assert!(typist.draft().marks().is_empty()); |
| 3489 | typist.type_text("x"); |
| 3490 | assert!(typist.cx.update(|cx| { |
| 3491 | composer |
| 3492 | .read(cx) |
| 3493 | .link_editor |
| 3494 | .as_ref() |
| 3495 | .is_some_and(|editor| !editor.refused) |
| 3496 | })); |
| 3497 | } |
| 3498 | |
| 3499 | #[gpui_kit::test] |
| 3500 | fn undo_takes_back_a_list_toggle_then_the_bold_before_it(cx: &mut TestAppContext) { |
| 3501 | use teams_core::{FormatState, LineKind, MarkKind}; |
| 3502 | |
| 3503 | let mut typist = typist(cx); |
| 3504 | typist.type_text("hello"); |
| 3505 | typist.press("ctrl-a ctrl-b"); |
| 3506 | let composer = typist.composer.clone(); |
| 3507 | typist.act(|window, cx| { |
| 3508 | composer.update(cx, |composer, cx| { |
| 3509 | composer.press_format(super::super::FormatButton::Bulleted, window, cx) |
| 3510 | }) |
| 3511 | }); |
| 3512 | assert_eq!(typist.value(), "• hello"); |
| 3513 | typist.press("ctrl-z"); |
| 3514 | assert_eq!(typist.value(), "hello"); |
| 3515 | assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On); |
| 3516 | typist.press("ctrl-z"); |
| 3517 | assert!(typist.draft().marks().is_empty()); |
| 3518 | assert_eq!(typist.draft().lines(), [LineKind::Text]); |
| 3519 | } |
| 3520 | |
| 3521 | #[gpui_kit::test] |
| 3522 | fn redo_brings_back_typing_and_bold_in_order(cx: &mut TestAppContext) { |
| 3523 | use teams_core::{FormatState, MarkKind}; |
| 3524 | |
| 3525 | let mut typist = typist(cx); |
| 3526 | typist.type_text("hello"); |
| 3527 | typist.press("ctrl-a ctrl-b ctrl-z ctrl-z"); |
| 3528 | assert_eq!(typist.value(), ""); |
| 3529 | typist.press("ctrl-y"); |
| 3530 | assert_eq!(typist.value(), "hello"); |
| 3531 | assert!(typist.draft().marks().is_empty()); |
| 3532 | typist.press("ctrl-y"); |
| 3533 | assert_eq!(typist.draft().state(0..5, &MarkKind::Bold), FormatState::On); |
| 3534 | } |
| 3535 | |
| 3536 | fn cursor(typist: &mut Typist<'_>) -> usize { |
| 3537 | let composer = typist.composer.clone(); |
| 3538 | typist |
| 3539 | .cx |
| 3540 | .update(|cx| composer.read(cx).input.read(cx).cursor()) |
| 3541 | } |
| 3542 | |
| 3543 | #[gpui_kit::test] |
| 3544 | fn typing_elsewhere_is_its_own_undo_step_and_undo_puts_the_caret_there( |
| 3545 | cx: &mut TestAppContext, |
| 3546 | ) { |
| 3547 | let mut typist = typist(cx); |
| 3548 | typist.type_text("hello"); |
| 3549 | typist.press("home"); |
| 3550 | typist.type_text("X"); |
| 3551 | typist.press("end ctrl-z"); |
| 3552 | assert_eq!(typist.value(), "hello"); |
| 3553 | assert_eq!(cursor(&mut typist), 0); |
| 3554 | typist.press("ctrl-y"); |
| 3555 | assert_eq!(typist.value(), "Xhello"); |
| 3556 | assert_eq!(cursor(&mut typist), 1); |
| 3557 | } |
| 3558 | |
| 3559 | #[gpui_kit::test] |
| 3560 | fn undo_keeps_the_scroll_position(cx: &mut TestAppContext) { |
| 3561 | let mut typist = typist(cx); |
| 3562 | for line in 0..14 { |
| 3563 | typist.type_text(&format!("line {line}")); |
| 3564 | typist.press("shift-enter"); |
| 3565 | } |
| 3566 | typist.type_text("end"); |
| 3567 | let composer = typist.composer.clone(); |
| 3568 | let scroll = |typist: &mut Typist<'_>| { |
| 3569 | typist |
| 3570 | .cx |
| 3571 | .update(|cx| composer.read(cx).input.read(cx).scroll_offset().y) |
| 3572 | }; |
| 3573 | typist.act(|window, cx| window.render_frame(cx)); |
| 3574 | let before = scroll(&mut typist); |
| 3575 | assert!(before < gpui_kit::px(0.)); |
| 3576 | typist.press("ctrl-z"); |
| 3577 | typist.act(|window, cx| window.render_frame(cx)); |
| 3578 | assert_eq!(scroll(&mut typist), before); |
| 3579 | } |
| 3580 | |
| 3581 | #[gpui_kit::test] |
| 3582 | fn a_smiley_taken_back_with_ctrl_z_is_sent_as_typed(cx: &mut TestAppContext) { |
| 3583 | let mut typist = typist(cx); |
| 3584 | typist.type_text("ok :) "); |
| 3585 | assert!(typist.value().contains('🙂')); |
| 3586 | typist.press("ctrl-z"); |
| 3587 | assert_eq!(typist.value(), "ok :) "); |
| 3588 | assert_eq!(typist.outgoing().text(), "ok :)"); |
| 3589 | } |
| 3590 | |
| 3591 | #[gpui_kit::test] |
| 3592 | fn an_undo_with_nothing_to_undo_leaves_conversions_working(cx: &mut TestAppContext) { |
| 3593 | let mut typist = typist(cx); |
| 3594 | typist.press("ctrl-z"); |
| 3595 | typist.type_text("**a**"); |
| 3596 | assert_eq!(typist.value(), "a"); |
| 3597 | } |
| 3598 | |
| 3599 | #[gpui_kit::test] |
| 3600 | fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) { |
| 3601 | let mut typist = typist(cx); |
| 3602 | typist.type_text("```"); |
| 3603 | typist.press("enter"); |
| 3604 | typist.type_text(":) "); |
| 3605 | typist |
| 3606 | .cx |
| 3607 | .write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned())); |
| 3608 | typist.press("ctrl-v"); |
| 3609 | assert_eq!(typist.value(), ":) **x**"); |
| 3610 | let composer = typist.composer.clone(); |
| 3611 | assert!( |
| 3612 | typist |
| 3613 | .cx |
| 3614 | .update(|cx| composer.read(cx).paste_hint.is_none()) |
| 3615 | ); |
| 3616 | let outgoing = typist.outgoing(); |
| 3617 | assert_eq!(outgoing.html(), "<pre>:) **x**</pre>"); |
| 3618 | } |
| 3619 | |
| 3620 | #[gpui_kit::test] |
| 3621 | fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) { |
| 3622 | let mut typist = typist(cx); |
| 3623 | typist.type_text("> quoted"); |
| 3624 | typist.press("shift-enter"); |
| 3625 | typist.type_text("more"); |
| 3626 | let outgoing = typist.outgoing(); |
| 3627 | assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>"); |
| 3628 | assert_eq!(outgoing.text(), "quoted\nmore"); |
| 3629 | } |
| 3630 | |
| 3631 | #[gpui_kit::test] |
| 3632 | fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) { |
| 3633 | cx.update(gpui_kit::init); |
| 3634 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 3635 | let mode = Mode { |
| 3636 | demo: true, |
| 3637 | read_only: false, |
| 3638 | demo_sync: None, |
| 3639 | }; |
| 3640 | let (handle, composer) = cx.update(|cx| { |
| 3641 | let app = cx.new(|_| AppState::new(store, mode)); |
| 3642 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 3643 | cx.new(|cx| Composer::new(app, window, cx)) |
| 3644 | }) |
| 3645 | .unwrap() |
| 3646 | }); |
| 3647 | let directory = tempfile::tempdir().unwrap(); |
| 3648 | let path = directory.path().join("plan.pdf"); |
| 3649 | std::fs::write(&path, b"%PDF-1.7").unwrap(); |
| 3650 | cx.update_window(handle, |_, window, cx| { |
| 3651 | composer.update(cx, |composer, cx| { |
| 3652 | composer.set_conversation("demo-chat", "Demo", window, cx); |
| 3653 | composer.add_paths(vec![path], window, cx); |
| 3654 | }); |
| 3655 | }) |
| 3656 | .unwrap(); |
| 3657 | cx.run_until_parked(); |
| 3658 | cx.update(|cx| { |
| 3659 | let composer = composer.read(cx); |
| 3660 | assert!(composer.tray.blocks_send()); |
| 3661 | assert!(!composer.can_send(cx)); |
| 3662 | }); |
| 3663 | cx.executor() |
| 3664 | .advance_clock(std::time::Duration::from_secs(3)); |
| 3665 | cx.run_until_parked(); |
| 3666 | cx.update(|cx| { |
| 3667 | let composer = composer.read(cx); |
| 3668 | assert!(composer.can_send(cx)); |
| 3669 | let outgoing = composer |
| 3670 | .outgoing(cx) |
| 3671 | .expect("an attachment alone is a message"); |
| 3672 | assert_eq!(outgoing.text(), ""); |
| 3673 | assert_eq!(outgoing.files.len(), 1); |
| 3674 | assert_eq!(outgoing.files[0].name, "plan.pdf"); |
| 3675 | }); |
| 3676 | } |
| 3677 | |
| 3678 | #[gpui_kit::test] |
| 3679 | fn attachments_are_dropped_when_the_conversation_changes(cx: &mut TestAppContext) { |
| 3680 | cx.update(gpui_kit::init); |
| 3681 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 3682 | let mode = Mode { |
| 3683 | demo: true, |
| 3684 | read_only: false, |
| 3685 | demo_sync: None, |
| 3686 | }; |
| 3687 | let (handle, composer) = cx.update(|cx| { |
| 3688 | let app = cx.new(|_| AppState::new(store, mode)); |
| 3689 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 3690 | cx.new(|cx| Composer::new(app, window, cx)) |
| 3691 | }) |
| 3692 | .unwrap() |
| 3693 | }); |
| 3694 | let directory = tempfile::tempdir().unwrap(); |
| 3695 | let path = directory.path().join("plan.pdf"); |
| 3696 | std::fs::write(&path, b"%PDF-1.7").unwrap(); |
| 3697 | cx.update_window(handle, |_, window, cx| { |
| 3698 | composer.update(cx, |composer, cx| { |
| 3699 | composer.set_conversation("demo-chat", "Demo", window, cx); |
| 3700 | composer.add_paths(vec![path], window, cx); |
| 3701 | }); |
| 3702 | }) |
| 3703 | .unwrap(); |
| 3704 | cx.run_until_parked(); |
| 3705 | cx.update_window(handle, |_, window, cx| { |
| 3706 | composer.update(cx, |composer, cx| { |
| 3707 | composer.set_conversation("other-chat", "Other", window, cx) |
| 3708 | }); |
| 3709 | }) |
| 3710 | .unwrap(); |
| 3711 | cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty())); |
| 3712 | } |
| 3713 | |
| 3714 | fn demo_composer( |
| 3715 | cx: &mut TestAppContext, |
| 3716 | ) -> (gpui_kit::AnyWindowHandle, gpui_kit::Entity<Composer>) { |
| 3717 | cx.update(gpui_kit::init); |
| 3718 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 3719 | let mode = Mode { |
| 3720 | demo: true, |
| 3721 | read_only: false, |
| 3722 | demo_sync: None, |
| 3723 | }; |
| 3724 | let (handle, composer) = cx.update(|cx| { |
| 3725 | let app = cx.new(|_| AppState::new(store, mode)); |
| 3726 | gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { |
| 3727 | cx.new(|cx| Composer::new(app, window, cx)) |
| 3728 | }) |
| 3729 | .unwrap() |
| 3730 | }); |
| 3731 | (handle, composer) |
| 3732 | } |
| 3733 | |
| 3734 | fn small_png(directory: &std::path::Path) -> std::path::PathBuf { |
| 3735 | let path = directory.join("dot.png"); |
| 3736 | image::RgbaImage::new(2, 2).save(&path).unwrap(); |
| 3737 | path |
| 3738 | } |
| 3739 | |
| 3740 | #[gpui_kit::test] |
| 3741 | fn editing_keeps_the_attachments_and_hides_them_from_the_edit(cx: &mut TestAppContext) { |
| 3742 | use super::super::{EditPreview, Outgoing}; |
| 3743 | |
| 3744 | let (handle, composer) = demo_composer(cx); |
| 3745 | let directory = tempfile::tempdir().unwrap(); |
| 3746 | let path = directory.path().join("plan.pdf"); |
| 3747 | std::fs::write(&path, b"%PDF-1.7").unwrap(); |
| 3748 | cx.update_window(handle, |_, window, cx| { |
| 3749 | composer.update(cx, |composer, cx| { |
| 3750 | composer.set_conversation("demo-chat", "Demo", window, cx); |
| 3751 | composer.add_paths(vec![path], window, cx); |
| 3752 | }); |
| 3753 | }) |
| 3754 | .unwrap(); |
| 3755 | cx.run_until_parked(); |
| 3756 | cx.executor() |
| 3757 | .advance_clock(std::time::Duration::from_secs(3)); |
| 3758 | cx.run_until_parked(); |
| 3759 | cx.update_window(handle, |_, window, cx| { |
| 3760 | composer.update(cx, |composer, cx| { |
| 3761 | let draft = Outgoing { |
| 3762 | draft: teams_core::Draft::plain("old"), |
| 3763 | mentions: Vec::new(), |
| 3764 | link_preview: None, |
| 3765 | reply: None, |
| 3766 | edit: Some(EditPreview { |
| 3767 | message_id: "m1".into(), |
| 3768 | excerpt: "old".into(), |
| 3769 | }), |
| 3770 | images: Vec::new(), |
| 3771 | files: Vec::new(), |
| 3772 | }; |
| 3773 | composer.begin_edit(draft, window, cx); |
| 3774 | }); |
| 3775 | }) |
| 3776 | .unwrap(); |
| 3777 | cx.update(|cx| { |
| 3778 | let composer = composer.read(cx); |
| 3779 | assert_eq!(composer.tray.items().len(), 1); |
| 3780 | let outgoing = composer.outgoing(cx).unwrap(); |
| 3781 | assert!(outgoing.files.is_empty()); |
| 3782 | assert_eq!(outgoing.text(), "old"); |
| 3783 | }); |
| 3784 | cx.update_window(handle, |_, window, cx| { |
| 3785 | composer.update(cx, |composer, cx| composer.cancel_edit(window, cx)); |
| 3786 | }) |
| 3787 | .unwrap(); |
| 3788 | cx.update(|cx| { |
| 3789 | let composer = composer.read(cx); |
| 3790 | assert_eq!(composer.tray.items().len(), 1); |
| 3791 | assert!(composer.can_send(cx)); |
| 3792 | }); |
| 3793 | } |
| 3794 | |
| 3795 | #[gpui_kit::test] |
| 3796 | fn draft_images_follow_only_into_the_chat_that_was_chosen(cx: &mut TestAppContext) { |
| 3797 | let (handle, composer) = demo_composer(cx); |
| 3798 | let directory = tempfile::tempdir().unwrap(); |
| 3799 | let path = small_png(directory.path()); |
| 3800 | for (carry, chosen, expected) in [ |
| 3801 | (Some("chat-a"), "chat-a", 1), |
| 3802 | (None, "chat-b", 0), |
| 3803 | (Some("chat-a"), "chat-b", 0), |
| 3804 | ] { |
| 3805 | cx.update_window(handle, |_, window, cx| { |
| 3806 | composer.update(cx, |composer, cx| { |
| 3807 | composer.set_conversation("", "", window, cx); |
| 3808 | composer.add_paths(vec![path.clone()], window, cx); |
| 3809 | }); |
| 3810 | }) |
| 3811 | .unwrap(); |
| 3812 | cx.run_until_parked(); |
| 3813 | cx.update_window(handle, |_, window, cx| { |
| 3814 | composer.update(cx, |composer, cx| { |
| 3815 | if let Some(chat) = carry { |
| 3816 | composer.carry_images_into(chat.to_owned()); |
| 3817 | } |
| 3818 | composer.set_conversation(chosen, "Chat", window, cx); |
| 3819 | }); |
| 3820 | }) |
| 3821 | .unwrap(); |
| 3822 | cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), expected)); |
| 3823 | } |
| 3824 | } |
| 3825 | |
| 3826 | #[gpui_kit::test] |
| 3827 | fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images( |
| 3828 | cx: &mut TestAppContext, |
| 3829 | ) { |
| 3830 | let (handle, composer) = demo_composer(cx); |
| 3831 | let directory = tempfile::tempdir().unwrap(); |
| 3832 | let png = small_png(directory.path()); |
| 3833 | let pdf = directory.path().join("plan.pdf"); |
| 3834 | std::fs::write(&pdf, b"%PDF-1.7").unwrap(); |
| 3835 | cx.update_window(handle, |_, window, cx| { |
| 3836 | composer.update(cx, |composer, cx| { |
| 3837 | composer.set_conversation("bob-chat", "Bob", window, cx); |
| 3838 | composer.add_paths(vec![png, pdf], window, cx); |
| 3839 | }); |
| 3840 | }) |
| 3841 | .unwrap(); |
| 3842 | cx.run_until_parked(); |
| 3843 | cx.update(|cx| assert_eq!(composer.read(cx).tray.items().len(), 2)); |
| 3844 | cx.update_window(handle, |_, window, cx| { |
| 3845 | composer.update(cx, |composer, cx| { |
| 3846 | composer.carry_images_into(String::new()); |
| 3847 | composer.set_conversation("", "", window, cx); |
| 3848 | }); |
| 3849 | }) |
| 3850 | .unwrap(); |
| 3851 | cx.update(|cx| { |
| 3852 | let composer = composer.read(cx); |
| 3853 | assert_eq!(composer.tray.items().len(), 1); |
| 3854 | assert_eq!(composer.tray.items()[0].name, "dot.png"); |
| 3855 | assert!(!composer.files_allowed()); |
| 3856 | }); |
| 3857 | } |
| 3858 | } |
| 3859 | } |