| 1 | use std::rc::Rc; |
| 2 | |
| 3 | use gpui::prelude::FluentBuilder as _; |
| 4 | use gpui::{ |
| 5 | AccessibleAction, AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Hsla, |
| 6 | InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Rems, RenderOnce, Role, |
| 7 | SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, TextAlign, TouchPhase, |
| 8 | Window, div, px, relative, |
| 9 | }; |
| 10 | |
| 11 | use crate::button::{Button, ButtonRounded, ButtonVariants as _}; |
| 12 | use crate::input::clear_button; |
| 13 | use crate::native_menu::NativeMenu; |
| 14 | use crate::spinner::Spinner; |
| 15 | use crate::touch_selection::{EditMenuItem, TouchSelectionOverlay}; |
| 16 | use crate::{ActiveTheme, Colorize, v_flex}; |
| 17 | use crate::{IconName, Size}; |
| 18 | use crate::{RoleOverride, Selectable, StyledExt, h_flex}; |
| 19 | use crate::{Sizable, StyleSized}; |
| 20 | use gpui_base::InputBase as BaseInput; |
| 21 | use rust_i18n::t; |
| 22 | |
| 23 | use super::state::{TextInputState, sync_focused_input_registry}; |
| 24 | use super::{InputContentType, InputState, sync_native_content_type}; |
| 25 | use crate::ThemeStyled as _; |
| 26 | |
| 27 | fn accessibility_role( |
| 28 | is_multi_line: bool, |
| 29 | content_type: Option<InputContentType>, |
| 30 | role: RoleOverride, |
| 31 | ) -> Option<Role> { |
| 32 | role.resolve(|| { |
| 33 | if is_multi_line { |
| 34 | return Role::MultilineTextInput; |
| 35 | } |
| 36 | |
| 37 | match content_type { |
| 38 | None => Role::TextInput, |
| 39 | Some(InputContentType::TelephoneNumber) => Role::PhoneNumberInput, |
| 40 | Some(InputContentType::EmailAddress) => Role::EmailInput, |
| 41 | Some(InputContentType::Url) => Role::UrlInput, |
| 42 | Some(InputContentType::Password | InputContentType::NewPassword) => Role::PasswordInput, |
| 43 | Some(InputContentType::DateTime) => Role::DateTimeInput, |
| 44 | Some(InputContentType::Birthdate) => Role::DateInput, |
| 45 | Some( |
| 46 | InputContentType::Name |
| 47 | | InputContentType::NamePrefix |
| 48 | | InputContentType::GivenName |
| 49 | | InputContentType::MiddleName |
| 50 | | InputContentType::FamilyName |
| 51 | | InputContentType::NameSuffix |
| 52 | | InputContentType::Nickname |
| 53 | | InputContentType::JobTitle |
| 54 | | InputContentType::OrganizationName |
| 55 | | InputContentType::Location |
| 56 | | InputContentType::FullStreetAddress |
| 57 | | InputContentType::StreetAddressLine1 |
| 58 | | InputContentType::StreetAddressLine2 |
| 59 | | InputContentType::AddressCity |
| 60 | | InputContentType::AddressState |
| 61 | | InputContentType::AddressCityAndState |
| 62 | | InputContentType::Sublocality |
| 63 | | InputContentType::CountryName |
| 64 | | InputContentType::PostalCode |
| 65 | | InputContentType::CreditCardNumber |
| 66 | | InputContentType::CreditCardName |
| 67 | | InputContentType::CreditCardGivenName |
| 68 | | InputContentType::CreditCardMiddleName |
| 69 | | InputContentType::CreditCardFamilyName |
| 70 | | InputContentType::CreditCardSecurityCode |
| 71 | | InputContentType::CreditCardExpiration |
| 72 | | InputContentType::CreditCardExpirationMonth |
| 73 | | InputContentType::CreditCardExpirationYear |
| 74 | | InputContentType::CreditCardType |
| 75 | | InputContentType::Username |
| 76 | | InputContentType::OneTimeCode |
| 77 | | InputContentType::ShipmentTrackingNumber |
| 78 | | InputContentType::FlightNumber |
| 79 | | InputContentType::BirthdateDay |
| 80 | | InputContentType::BirthdateMonth |
| 81 | | InputContentType::BirthdateYear |
| 82 | | InputContentType::CellularEid |
| 83 | | InputContentType::CellularImei, |
| 84 | ) => Role::TextInput, |
| 85 | } |
| 86 | }) |
| 87 | } |
| 88 | |
| 89 | fn exposes_accessibility_value(masked: bool, content_type: Option<InputContentType>) -> bool { |
| 90 | !masked |
| 91 | && !matches!( |
| 92 | content_type, |
| 93 | Some(InputContentType::Password | InputContentType::NewPassword) |
| 94 | ) |
| 95 | } |
| 96 | |
| 97 | /// Returns `(background, foreground)` colors for input-like components. |
| 98 | pub(crate) fn input_style(disabled: bool, cx: &App) -> (Hsla, Hsla) { |
| 99 | if disabled { |
| 100 | ( |
| 101 | cx.theme().input.mix_oklab(cx.theme().transparent, 0.8), |
| 102 | cx.theme().muted_foreground, |
| 103 | ) |
| 104 | } else { |
| 105 | (cx.theme().input_background(), cx.theme().foreground) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// A text input element bind to an [`InputState`]. |
| 110 | #[derive(IntoElement)] |
| 111 | pub struct Input { |
| 112 | token_renderer: Option<gpui_base::input::InlineTokenRenderer>, |
| 113 | token_click_listener: Option<gpui_base::input::InlineTokenClickListener>, |
| 114 | token_hover_listener: Option<gpui_base::input::InlineTokenHoverListener>, |
| 115 | id: Option<ElementId>, |
| 116 | state: TextInputState, |
| 117 | style: StyleRefinement, |
| 118 | size: Size, |
| 119 | prefix: Option<AnyElement>, |
| 120 | suffix: Option<AnyElement>, |
| 121 | height: Option<DefiniteLength>, |
| 122 | line_box_height: Option<Pixels>, |
| 123 | appearance: bool, |
| 124 | cleanable: bool, |
| 125 | mask_toggle: bool, |
| 126 | disabled: bool, |
| 127 | readonly: bool, |
| 128 | bordered: bool, |
| 129 | focus_bordered: bool, |
| 130 | tab_index: isize, |
| 131 | selected: bool, |
| 132 | content_type: Option<InputContentType>, |
| 133 | role: RoleOverride, |
| 134 | accessibility_id: Option<SharedString>, |
| 135 | aria_label: Option<SharedString>, |
| 136 | |
| 137 | /// An optional context menu builder to allow a custom context menu on the input. |
| 138 | /// |
| 139 | /// If set, this overrides the built-in context menu. |
| 140 | context_menu_builder: Option<Rc<dyn Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu>>, |
| 141 | |
| 142 | /// An optional paste handler. If set, it is invoked with the clipboard item |
| 143 | /// before the default text insertion. Return `true` if handled. |
| 144 | paste_handler: Option<Rc<dyn Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool>>, |
| 145 | } |
| 146 | |
| 147 | impl Sizable for Input { |
| 148 | fn with_size(mut self, size: impl Into<Size>) -> Self { |
| 149 | self.size = size.into(); |
| 150 | self |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl Selectable for Input { |
| 155 | fn selected(mut self, selected: bool) -> Self { |
| 156 | self.selected = selected; |
| 157 | self |
| 158 | } |
| 159 | |
| 160 | fn is_selected(&self) -> bool { |
| 161 | self.selected |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | impl crate::FocusableExt for Input { |
| 166 | fn focus_ring(mut self, enabled: bool) -> Self { |
| 167 | self.focus_bordered = enabled; |
| 168 | self |
| 169 | } |
| 170 | |
| 171 | fn is_focus_ring_enabled(&self) -> bool { |
| 172 | self.focus_bordered |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | impl Input { |
| 177 | /// The element each atomic inline token renders as, in place of the default |
| 178 | /// [`InputToken`](super::InputToken); editing and history stay |
| 179 | /// with the input. |
| 180 | pub fn token<R: IntoElement>( |
| 181 | mut self, |
| 182 | render: impl Fn(&super::InlineTokenContext, &mut Window, &mut App) -> R + 'static, |
| 183 | ) -> Self { |
| 184 | self.token_renderer = Some(Rc::new(move |token, window, cx| { |
| 185 | render(token, window, cx).into_any_element() |
| 186 | })); |
| 187 | self |
| 188 | } |
| 189 | /// Open a reference after a completed, unconsumed token click. |
| 190 | pub fn on_token_click( |
| 191 | mut self, |
| 192 | listener: impl Fn(&super::InlineTokenClickEvent, &mut Window, &mut App) + 'static, |
| 193 | ) -> Self { |
| 194 | self.token_click_listener = Some(Rc::new(listener)); |
| 195 | self |
| 196 | } |
| 197 | /// Report pointer presence over a token so the application can show a |
| 198 | /// tooltip or run custom logic. Hover never selects or edits. |
| 199 | pub fn on_token_hover( |
| 200 | mut self, |
| 201 | listener: impl Fn(&super::InlineTokenHoverEvent, &mut Window, &mut App) + 'static, |
| 202 | ) -> Self { |
| 203 | self.token_hover_listener = Some(Rc::new(listener)); |
| 204 | self |
| 205 | } |
| 206 | |
| 207 | /// Sets the GPUI identity of the input frame. By default it uses the state entity ID. |
| 208 | pub fn id(mut self, id: impl Into<ElementId>) -> Self { |
| 209 | self.id = Some(id.into()); |
| 210 | self |
| 211 | } |
| 212 | |
| 213 | /// Create a new [`Input`] element bind to the [`InputState`]. |
| 214 | pub fn new(state: &Entity<InputState>) -> Self { |
| 215 | Self::with_state(state.clone().into()) |
| 216 | } |
| 217 | |
| 218 | /// Builds an input renderer around a state of any kind. |
| 219 | /// |
| 220 | /// `Textarea` and `Editor` render through this. Application code uses |
| 221 | /// [`Input::new`], [`super::Textarea`], or [`super::Editor`]. |
| 222 | pub(crate) fn from_state(state: impl Into<TextInputState>) -> Self { |
| 223 | Self::with_state(state.into()) |
| 224 | } |
| 225 | |
| 226 | fn with_state(state: TextInputState) -> Self { |
| 227 | Self { |
| 228 | id: None, |
| 229 | state, |
| 230 | size: Size::default(), |
| 231 | style: StyleRefinement::default(), |
| 232 | prefix: None, |
| 233 | suffix: None, |
| 234 | height: None, |
| 235 | appearance: true, |
| 236 | cleanable: false, |
| 237 | mask_toggle: false, |
| 238 | disabled: false, |
| 239 | readonly: false, |
| 240 | bordered: true, |
| 241 | focus_bordered: true, |
| 242 | tab_index: 0, |
| 243 | selected: false, |
| 244 | content_type: None, |
| 245 | role: RoleOverride::default(), |
| 246 | accessibility_id: None, |
| 247 | aria_label: None, |
| 248 | context_menu_builder: None, |
| 249 | paste_handler: None, |
| 250 | line_box_height: None, |
| 251 | token_renderer: None, |
| 252 | token_click_listener: None, |
| 253 | token_hover_listener: None, |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | /// Set the developer-assigned identifier exposed to accessibility clients. |
| 258 | /// The state this input renders; a compound control reads focus and |
| 259 | /// presentation from it. |
| 260 | pub(crate) fn state(&self) -> &TextInputState { |
| 261 | &self.state |
| 262 | } |
| 263 | |
| 264 | pub(crate) fn is_disabled(&self) -> bool { |
| 265 | self.disabled |
| 266 | } |
| 267 | |
| 268 | pub fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self { |
| 269 | self.accessibility_id = Some(id.into()); |
| 270 | self |
| 271 | } |
| 272 | |
| 273 | pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self { |
| 274 | self.aria_label = Some(label.into()); |
| 275 | self |
| 276 | } |
| 277 | |
| 278 | pub fn prefix(mut self, prefix: impl IntoElement) -> Self { |
| 279 | self.prefix = Some(prefix.into_any_element()); |
| 280 | self |
| 281 | } |
| 282 | |
| 283 | pub fn suffix(mut self, suffix: impl IntoElement) -> Self { |
| 284 | self.suffix = Some(suffix.into_any_element()); |
| 285 | self |
| 286 | } |
| 287 | |
| 288 | /// Set full height of the input (Multi-line only). |
| 289 | pub fn h_full(mut self) -> Self { |
| 290 | self.height = Some(relative(1.)); |
| 291 | self |
| 292 | } |
| 293 | |
| 294 | /// Set height of the input (Multi-line only). |
| 295 | pub fn h(mut self, height: impl Into<DefiniteLength>) -> Self { |
| 296 | self.height = Some(height.into()); |
| 297 | self |
| 298 | } |
| 299 | |
| 300 | /// Center each text line of a multi-line input in a box this tall, in |
| 301 | /// place of the size's vertical padding, so a single line is exactly this |
| 302 | /// tall and lines up with controls of the same height beside it. |
| 303 | pub fn line_box_height(mut self, height: Pixels) -> Self { |
| 304 | self.line_box_height = Some(height); |
| 305 | self |
| 306 | } |
| 307 | |
| 308 | /// Set the appearance of the input field, if false the input field will no border, background. |
| 309 | pub fn appearance(mut self, appearance: bool) -> Self { |
| 310 | self.appearance = appearance; |
| 311 | self |
| 312 | } |
| 313 | |
| 314 | /// Set the bordered for the input, default: true |
| 315 | pub fn bordered(mut self, bordered: bool) -> Self { |
| 316 | self.bordered = bordered; |
| 317 | self |
| 318 | } |
| 319 | |
| 320 | /// Set focus border for the input, default is true. |
| 321 | pub fn focus_bordered(mut self, bordered: bool) -> Self { |
| 322 | self.focus_bordered = bordered; |
| 323 | self |
| 324 | } |
| 325 | |
| 326 | /// Set whether to show the clear button when the input field is not empty, default is false. |
| 327 | pub fn cleanable(mut self, cleanable: bool) -> Self { |
| 328 | self.cleanable = cleanable; |
| 329 | self |
| 330 | } |
| 331 | |
| 332 | /// Set to enable toggle button for password mask state. |
| 333 | pub fn mask_toggle(mut self) -> Self { |
| 334 | self.mask_toggle = true; |
| 335 | self |
| 336 | } |
| 337 | |
| 338 | /// Set the semantic content type for password managers and autofill. |
| 339 | /// |
| 340 | /// This is a component-level semantic hint. It does not change the text |
| 341 | /// value or masked rendering state. |
| 342 | pub fn content_type(mut self, content_type: InputContentType) -> Self { |
| 343 | self.content_type = Some(content_type); |
| 344 | self |
| 345 | } |
| 346 | |
| 347 | /// Override the accessible role for the input. |
| 348 | /// |
| 349 | /// If unset, the role is inferred from multi-line mode and content type. |
| 350 | pub fn role(mut self, role: impl Into<RoleOverride>) -> Self { |
| 351 | self.role = role.into(); |
| 352 | self |
| 353 | } |
| 354 | |
| 355 | /// Set to disable the input field. |
| 356 | pub fn disabled(mut self, disabled: bool) -> Self { |
| 357 | self.disabled = disabled; |
| 358 | self |
| 359 | } |
| 360 | |
| 361 | /// Set the input field to read-only, default is `false`. |
| 362 | /// |
| 363 | /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance |
| 364 | /// and still can be focused, selected and copied, it only rejects the changes |
| 365 | /// made by the user. |
| 366 | pub fn readonly(mut self, readonly: bool) -> Self { |
| 367 | self.readonly = readonly; |
| 368 | self |
| 369 | } |
| 370 | |
| 371 | /// Set the tab index for the input, default is 0. |
| 372 | pub fn tab_index(mut self, index: isize) -> Self { |
| 373 | self.tab_index = index; |
| 374 | self |
| 375 | } |
| 376 | |
| 377 | /// Sets a custom context menu builder for the input, shown as a native OS menu. |
| 378 | /// |
| 379 | /// If set, this overrides the built-in right-click context menu. It shows |
| 380 | /// only while the state's context menu is enabled, which is the default. |
| 381 | pub fn context_menu( |
| 382 | mut self, |
| 383 | f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static, |
| 384 | ) -> Self { |
| 385 | self.context_menu_builder = Some(Rc::new(f)); |
| 386 | self |
| 387 | } |
| 388 | |
| 389 | /// Intercept paste payloads (images, files) before the default text insertion. |
| 390 | /// |
| 391 | /// The handler receives the clipboard item and returns whether it took the |
| 392 | /// paste: `true` stops the `input::Paste` action so the input inserts |
| 393 | /// nothing, `false` lets it reach the engine, which inserts |
| 394 | /// `clipboard.text()` as today. Text stays in the `Rope`; images and |
| 395 | /// copied files (`ClipboardEntry::Image`, `ClipboardEntry::ExternalPaths`) |
| 396 | /// belong in app-owned state beside the input (e.g. `Attachment`s), never |
| 397 | /// inside it. |
| 398 | /// |
| 399 | /// Known limit: on web `read_from_clipboard()` is `None`, so the handler |
| 400 | /// is skipped there and the input inserts the plain text itself (a |
| 401 | /// keyboard paste arrives through the platform input handler, a menu |
| 402 | /// paste through the asynchronous clipboard read); image paste there |
| 403 | /// needs `read_from_clipboard_async` and permission, out of scope here. |
| 404 | pub fn on_paste( |
| 405 | mut self, |
| 406 | handler: impl Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool + 'static, |
| 407 | ) -> Self { |
| 408 | self.paste_handler = Some(Rc::new(handler)); |
| 409 | self |
| 410 | } |
| 411 | |
| 412 | /// The handles and the edit menu of the selection a long press made. |
| 413 | /// |
| 414 | /// The menu offers what the native context menu would: Cut, Copy, Paste |
| 415 | /// and Select All, leaving out what cannot apply right now rather than |
| 416 | /// disabling it. Cut, Copy and Paste go through the input's actions, so a |
| 417 | /// custom key binding or an open completion menu sees them the same way. |
| 418 | fn render_touch_selection( |
| 419 | state: &TextInputState, |
| 420 | window: &Window, |
| 421 | cx: &App, |
| 422 | ) -> Vec<AnyElement> { |
| 423 | if state.touch_selection(cx).is_none() { |
| 424 | return Vec::new(); |
| 425 | } |
| 426 | let capabilities = state.context_menu_capabilities(cx); |
| 427 | let editable = capabilities.is_editable(); |
| 428 | let copyable = capabilities.is_copyable(); |
| 429 | // Offered whenever the text can change, without peeking at the |
| 430 | // clipboard: on iOS every read of it shows the system's paste banner, |
| 431 | // and an empty clipboard pastes nothing. |
| 432 | let pasteable = editable; |
| 433 | let selectable = state.text(cx).len() > 0 && !state.is_all_selected(cx); |
| 434 | let focus_handle = state.presentation(cx).focus_handle().clone(); |
| 435 | |
| 436 | let dispatch = { |
| 437 | let focus_handle = focus_handle.clone(); |
| 438 | move |action: &dyn gpui::Action, window: &mut Window, cx: &mut App| { |
| 439 | focus_handle.dispatch_action(action, window, cx); |
| 440 | } |
| 441 | }; |
| 442 | let mut items = Vec::with_capacity(4); |
| 443 | if editable && copyable { |
| 444 | let dispatch = dispatch.clone(); |
| 445 | items.push(EditMenuItem::new(t!("Input.Cut"), move |window, cx| { |
| 446 | dispatch(&gpui_base::input::Cut, window, cx); |
| 447 | })); |
| 448 | } |
| 449 | if copyable { |
| 450 | let dispatch = dispatch.clone(); |
| 451 | let state = state.clone(); |
| 452 | items.push(EditMenuItem::new(t!("Input.Copy"), move |window, cx| { |
| 453 | dispatch(&gpui_base::input::Copy, window, cx); |
| 454 | state.close_edit_menu(cx); |
| 455 | })); |
| 456 | } |
| 457 | if pasteable { |
| 458 | let dispatch = dispatch.clone(); |
| 459 | items.push(EditMenuItem::new(t!("Input.Paste"), move |window, cx| { |
| 460 | dispatch(&gpui_base::input::Paste, window, cx); |
| 461 | })); |
| 462 | } |
| 463 | if selectable { |
| 464 | let state = state.clone(); |
| 465 | items.push(EditMenuItem::new( |
| 466 | t!("Input.Select All"), |
| 467 | move |window, cx| state.select_all_from_edit_menu(window, cx), |
| 468 | )); |
| 469 | } |
| 470 | |
| 471 | let drag_state = state.clone(); |
| 472 | let source_state = state.clone(); |
| 473 | TouchSelectionOverlay::new( |
| 474 | ("input-touch-selection", state.entity_id()), |
| 475 | move |_, cx| source_state.touch_selection(cx), |
| 476 | ) |
| 477 | .handles(move |edge, phase, position, _, cx| match phase { |
| 478 | TouchPhase::Started => drag_state.begin_edge_drag(edge, position, cx), |
| 479 | TouchPhase::Moved => drag_state.update_edge_drag(position, cx), |
| 480 | TouchPhase::Ended | TouchPhase::Cancelled => drag_state.end_edge_drag(cx), |
| 481 | }) |
| 482 | .items(items) |
| 483 | .into_elements(window, cx) |
| 484 | } |
| 485 | |
| 486 | fn render_toggle_mask_button(state: &TextInputState, cx: &App) -> impl IntoElement { |
| 487 | let masked = state.presentation(cx).is_masked(); |
| 488 | Button::new("toggle-mask") |
| 489 | .icon(if masked { |
| 490 | IconName::Eye |
| 491 | } else { |
| 492 | IconName::EyeOff |
| 493 | }) |
| 494 | .xsmall() |
| 495 | .text() |
| 496 | .tab_stop(false) |
| 497 | .on_click({ |
| 498 | let state = state.clone(); |
| 499 | move |_, window, cx| state.toggle_masked(window, cx) |
| 500 | }) |
| 501 | } |
| 502 | |
| 503 | fn handle_accessibility_set_value( |
| 504 | state: &TextInputState, |
| 505 | data: Option<&gpui::accesskit::ActionData>, |
| 506 | window: &mut Window, |
| 507 | cx: &mut App, |
| 508 | ) { |
| 509 | let Some(gpui::accesskit::ActionData::Value(value)) = data else { |
| 510 | return; |
| 511 | }; |
| 512 | if !state.presentation(cx).is_editable() { |
| 513 | return; |
| 514 | } |
| 515 | state.replace_all(value.to_string(), window, cx); |
| 516 | } |
| 517 | |
| 518 | fn handle_accessibility_focus(state: &TextInputState, window: &mut Window, cx: &mut App) { |
| 519 | if !state.presentation(cx).is_disabled() { |
| 520 | state.focus(window, cx); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | /// This method must after the refine_style. |
| 525 | fn render_editor( |
| 526 | input_state: TextInputState, |
| 527 | search_panel: Option<AnyElement>, |
| 528 | _: &Window, |
| 529 | ) -> impl IntoElement { |
| 530 | v_flex().size_full().children(search_panel).child( |
| 531 | div() |
| 532 | .relative() |
| 533 | .flex_1() |
| 534 | .child(input_state.into_any_element()), |
| 535 | ) |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | impl Styled for Input { |
| 540 | fn style(&mut self) -> &mut StyleRefinement { |
| 541 | &mut self.style |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | impl RenderOnce for Input { |
| 546 | fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { |
| 547 | const LINE_HEIGHT: Rems = Rems(1.25); |
| 548 | let text_align = self.style.text.text_align.unwrap_or(TextAlign::Left); |
| 549 | let state = self.state.clone(); |
| 550 | state.install_token_presentation( |
| 551 | Some(self.token_renderer.unwrap_or_else(|| { |
| 552 | Rc::new(|token, _, _| super::InputToken::new(token).into_any_element()) |
| 553 | })), |
| 554 | self.token_click_listener, |
| 555 | matches!( |
| 556 | self.content_type, |
| 557 | Some(InputContentType::Password | InputContentType::NewPassword) |
| 558 | ), |
| 559 | cx, |
| 560 | ); |
| 561 | state.install_token_hover_presentation(self.token_hover_listener, cx); |
| 562 | // Which kind of input this registers as follows from the state itself. |
| 563 | sync_focused_input_registry(&state, window, cx); |
| 564 | |
| 565 | state.ensure_highlighter_factory(crate::highlighter::input_highlighter_factory(), cx); |
| 566 | state.set_editor_style( |
| 567 | gpui_base::input::InputEditorStyle { |
| 568 | foreground: cx.theme().foreground, |
| 569 | muted_foreground: cx.theme().muted_foreground, |
| 570 | background: cx.theme().editor_background(), |
| 571 | border: cx.theme().border, |
| 572 | selection: cx.theme().selection, |
| 573 | caret: cx.theme().caret, |
| 574 | diagnostics: gpui_base::input::DiagnosticColors { |
| 575 | error: cx.theme().highlight_theme.style.status.error(cx), |
| 576 | warning: cx.theme().highlight_theme.style.status.warning(cx), |
| 577 | info: cx.theme().highlight_theme.style.status.info(cx), |
| 578 | hint: cx.theme().highlight_theme.style.status.hint(cx), |
| 579 | }, |
| 580 | highlight_styles: cx.theme().highlight_theme.clone(), |
| 581 | editor_invisible: cx.theme().highlight_theme.style.editor_invisible, |
| 582 | editor_active_line: cx.theme().highlight_theme.style.editor_active_line, |
| 583 | editor_gutter_background: cx.theme().highlight_theme.style.editor_gutter_background, |
| 584 | fold_icon_renderer: Some(Rc::new(|ix, is_folded| { |
| 585 | Button::new(("fold-icon", ix)) |
| 586 | .ghost() |
| 587 | .icon(if is_folded { |
| 588 | IconName::ChevronRight |
| 589 | } else { |
| 590 | IconName::ChevronDown |
| 591 | }) |
| 592 | .xsmall() |
| 593 | .rounded(ButtonRounded::Small) |
| 594 | .size(px(14.)) |
| 595 | .selected(is_folded) |
| 596 | .into_any_element() |
| 597 | })), |
| 598 | }, |
| 599 | cx, |
| 600 | ); |
| 601 | let padding_y = self.line_box_height.map_or(self.size.input_py(), |height| { |
| 602 | ((height - LINE_HEIGHT.to_pixels(window.rem_size())) / 2.).max(px(0.)) |
| 603 | }); |
| 604 | state.set_editor_paddings( |
| 605 | if state.presentation(cx).is_multi_line() { |
| 606 | Edges { |
| 607 | top: padding_y, |
| 608 | right: self.size.input_px(), |
| 609 | bottom: padding_y, |
| 610 | left: if state.presentation(cx).is_code_editor() { |
| 611 | self.size.input_px().min(px(6.)) |
| 612 | } else { |
| 613 | self.size.input_px() |
| 614 | }, |
| 615 | } |
| 616 | } else { |
| 617 | Edges::default() |
| 618 | }, |
| 619 | cx, |
| 620 | ); |
| 621 | state.set_disabled(self.disabled, cx); |
| 622 | state.set_readonly(self.readonly, cx); |
| 623 | state.set_text_align(text_align, cx); |
| 624 | let custom = self.context_menu_builder.clone(); |
| 625 | state.on_context_menu( |
| 626 | Rc::new(move |_, capabilities, position, window, cx| { |
| 627 | let menu = if let Some(custom) = custom.as_ref() { |
| 628 | custom(NativeMenu::new(), window, cx) |
| 629 | } else { |
| 630 | let enabled = !capabilities.is_disabled(); |
| 631 | // A read-only input can still navigate the code, it only |
| 632 | // rejects the items that would change the text. |
| 633 | let editable = enabled && !capabilities.is_readonly(); |
| 634 | let mut menu = NativeMenu::new(); |
| 635 | if capabilities.is_code_editor() { |
| 636 | menu = menu |
| 637 | .menu_with_disabled( |
| 638 | t!("Input.Go to Definition"), |
| 639 | !(enabled && capabilities.has_definition()), |
| 640 | Box::new(gpui_base::input::GoToDefinition), |
| 641 | ) |
| 642 | .menu_with_disabled( |
| 643 | t!("Input.Show Code Actions"), |
| 644 | !(editable && capabilities.has_code_actions()), |
| 645 | Box::new(gpui_base::input::ToggleCodeActions), |
| 646 | ) |
| 647 | .separator(); |
| 648 | } |
| 649 | menu.menu_with_disabled( |
| 650 | t!("Input.Cut"), |
| 651 | !(editable && capabilities.is_copyable()), |
| 652 | Box::new(gpui_base::input::Cut), |
| 653 | ) |
| 654 | .menu_with_disabled( |
| 655 | t!("Input.Copy"), |
| 656 | !capabilities.is_copyable(), |
| 657 | Box::new(gpui_base::input::Copy), |
| 658 | ) |
| 659 | // Offered whenever the text can change, without peeking |
| 660 | // at the clipboard: the synchronous read is always empty |
| 661 | // on the web, and an empty clipboard pastes nothing. |
| 662 | .menu_with_disabled( |
| 663 | t!("Input.Paste"), |
| 664 | !editable, |
| 665 | Box::new(gpui_base::input::Paste), |
| 666 | ) |
| 667 | .separator() |
| 668 | .menu( |
| 669 | t!("Input.Select All"), |
| 670 | Box::new(gpui_base::input::SelectAll), |
| 671 | ) |
| 672 | }; |
| 673 | menu.show(position, window, cx); |
| 674 | }), |
| 675 | cx, |
| 676 | ); |
| 677 | // The engine ignores `Paste` on a read-only or disabled input; the hook |
| 678 | // must not see a paste the input itself would refuse. |
| 679 | let paste_handler = self |
| 680 | .paste_handler |
| 681 | .clone() |
| 682 | .filter(|_| state.presentation(cx).is_editable()); |
| 683 | let mut overlays = state.render_overlays(window, cx); |
| 684 | overlays |
| 685 | .floating |
| 686 | .extend(Self::render_touch_selection(&state, window, cx)); |
| 687 | |
| 688 | let presentation = state.presentation(cx); |
| 689 | let content_type = self.content_type; |
| 690 | let disabled = self.disabled; |
| 691 | let is_multi_line = presentation.is_multi_line(); |
| 692 | let accessibility_role = accessibility_role(is_multi_line, content_type, self.role); |
| 693 | let accessibility_state = state.clone(); |
| 694 | // Tests read the same accessibility value as assistive technology. |
| 695 | // Avoid materializing the rope in normal builds without a client. |
| 696 | let accessibility_value = ((window.is_a11y_active() || cfg!(feature = "test-support")) |
| 697 | && exposes_accessibility_value(presentation.is_masked(), content_type)) |
| 698 | .then(|| state.text(cx).to_string()); |
| 699 | let input_focused = |
| 700 | presentation.focus_handle().is_focused(window) && !presentation.is_disabled(); |
| 701 | if input_focused { |
| 702 | sync_native_content_type(window, content_type, presentation.is_editable()); |
| 703 | } |
| 704 | let frame_focus_handle = window |
| 705 | .use_keyed_state(("input-frame-focus", state.entity_id()), cx, |_, cx| { |
| 706 | cx.focus_handle() |
| 707 | }) |
| 708 | .read(cx) |
| 709 | .clone(); |
| 710 | let focused = input_focused |
| 711 | || (frame_focus_handle.contains_focused(window, cx) && !presentation.is_disabled()); |
| 712 | |
| 713 | let gap_x = match self.size { |
| 714 | Size::Small => px(4.), |
| 715 | Size::Large => px(8.), |
| 716 | _ => px(6.), |
| 717 | }; |
| 718 | |
| 719 | let (bg, _) = input_style(presentation.is_disabled(), cx); |
| 720 | let bg = if presentation.is_code_editor() { |
| 721 | cx.theme().editor_background() |
| 722 | } else { |
| 723 | bg |
| 724 | }; |
| 725 | let bg = if presentation.is_disabled() { |
| 726 | bg.opacity(0.5) |
| 727 | } else { |
| 728 | bg |
| 729 | }; |
| 730 | let prefix = self.prefix; |
| 731 | let suffix = self.suffix; |
| 732 | let show_clear_button = self.cleanable |
| 733 | && presentation.is_editable() |
| 734 | && !presentation.is_loading() |
| 735 | && state.text(cx).len() > 0 |
| 736 | && !presentation.is_multi_line(); |
| 737 | let has_suffix = |
| 738 | suffix.is_some() || presentation.is_loading() || self.mask_toggle || show_clear_button; |
| 739 | |
| 740 | let placeholder = Some(presentation.placeholder().clone()).filter(|p| !p.is_empty()); |
| 741 | |
| 742 | // Don't use a mask-derived placeholder ("(___)___-___") as an aria_label fallback. |
| 743 | let placeholder_is_mask = presentation.mask_placeholder() == placeholder.as_deref(); |
| 744 | |
| 745 | let aria_label = match self.aria_label { |
| 746 | Some(label) => Some(label), |
| 747 | None if placeholder_is_mask => None, |
| 748 | None => placeholder.clone(), |
| 749 | }; |
| 750 | let id = self |
| 751 | .id |
| 752 | .unwrap_or_else(|| ("input", state.entity_id()).into()); |
| 753 | BaseInput::new(id) |
| 754 | .focused(focused) |
| 755 | .disabled(disabled) |
| 756 | .track_focus(&frame_focus_handle) |
| 757 | .when(disabled, |this| { |
| 758 | this.capture_any_mouse_down(|_, _, cx| cx.stop_propagation()) |
| 759 | }) |
| 760 | .styles(|styles| { |
| 761 | styles.focused(|style| { |
| 762 | style.when( |
| 763 | self.appearance && self.bordered && self.focus_bordered, |
| 764 | |style| style.border_1().border_color(cx.theme().ring), |
| 765 | ) |
| 766 | }) |
| 767 | }) |
| 768 | .role(accessibility_role) |
| 769 | .when_some(self.accessibility_id, |this, id| this.accessibility_id(id)) |
| 770 | .when_some(aria_label, |this, label| this.aria_label(label)) |
| 771 | .when_some(placeholder, |this, placeholder| { |
| 772 | this.aria_placeholder(placeholder) |
| 773 | }) |
| 774 | .when_some(accessibility_value, |this, value| this.aria_value(value)) |
| 775 | .on_a11y_action(AccessibleAction::Focus, { |
| 776 | let state = state.clone(); |
| 777 | move |_, window, cx| Self::handle_accessibility_focus(&state, window, cx) |
| 778 | }) |
| 779 | .when(presentation.is_editable(), |this| { |
| 780 | this.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| { |
| 781 | Self::handle_accessibility_set_value(&accessibility_state, data, window, cx); |
| 782 | }) |
| 783 | }) |
| 784 | .flex() |
| 785 | .size_full() |
| 786 | .line_height(LINE_HEIGHT) |
| 787 | .when(!is_multi_line, |this| { |
| 788 | this.input_px(self.size).input_py(self.size) |
| 789 | }) |
| 790 | .input_h(self.size) |
| 791 | .input_text_size(self.size) |
| 792 | .items_center() |
| 793 | .when(presentation.is_multi_line(), |this| { |
| 794 | this.h_auto() |
| 795 | .when_some(self.height, |this, height| this.h(height)) |
| 796 | }) |
| 797 | .when(self.appearance, |this| { |
| 798 | this.bg(bg) |
| 799 | .rounded(cx.theme().radius) |
| 800 | .when(self.bordered, |this| { |
| 801 | this.border_1().border_color(cx.theme().input) |
| 802 | }) |
| 803 | }) |
| 804 | .items_center() |
| 805 | .gap(gap_x) |
| 806 | .refine_style(&self.style) |
| 807 | .when( |
| 808 | focused && self.appearance && self.bordered && self.focus_bordered, |
| 809 | |this| this.focus_ring_style(window, cx), |
| 810 | ) |
| 811 | .children(prefix.map(|p| { |
| 812 | div() |
| 813 | .when(presentation.is_disabled(), |this| this.opacity(0.5)) |
| 814 | .child(p) |
| 815 | })) |
| 816 | .when(presentation.is_multi_line(), |this| { |
| 817 | this.child(Self::render_editor(state.clone(), overlays.search, window)) |
| 818 | }) |
| 819 | .when(!presentation.is_multi_line(), |this| { |
| 820 | this.child(state.clone().into_any_element()) |
| 821 | }) |
| 822 | .when(has_suffix, |this| { |
| 823 | this.pr(self.size.input_px()).child( |
| 824 | h_flex() |
| 825 | .id("suffix") |
| 826 | .gap(gap_x) |
| 827 | .items_center() |
| 828 | .cursor_default() |
| 829 | .when(presentation.is_disabled(), |this| this.opacity(0.5)) |
| 830 | .when(presentation.is_loading(), |this| { |
| 831 | this.child(Spinner::new().color(cx.theme().muted_foreground)) |
| 832 | }) |
| 833 | .when(self.mask_toggle, |this| { |
| 834 | this.child(Self::render_toggle_mask_button(&state, cx)) |
| 835 | }) |
| 836 | .when(show_clear_button, |this| { |
| 837 | this.child(clear_button(cx).on_click({ |
| 838 | let state = state.clone(); |
| 839 | move |_, window, cx| { |
| 840 | state.clean(window, cx); |
| 841 | state.focus(window, cx); |
| 842 | } |
| 843 | })) |
| 844 | }) |
| 845 | .children(suffix), |
| 846 | ) |
| 847 | }) |
| 848 | .relative() |
| 849 | .children(overlays.floating) |
| 850 | .when_some(paste_handler, |this, handler| { |
| 851 | this.capture_action(move |_: &gpui_base::input::Paste, window, cx| { |
| 852 | if let Some(clipboard) = cx.read_from_clipboard() { |
| 853 | if handler(&clipboard, window, cx) { |
| 854 | cx.stop_propagation(); |
| 855 | } |
| 856 | } |
| 857 | }) |
| 858 | }) |
| 859 | .render(window, cx) |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | #[cfg(test)] |
| 864 | mod tests { |
| 865 | use super::*; |
| 866 | use crate::input::AnyInputState; |
| 867 | |
| 868 | #[test] |
| 869 | fn content_types_map_to_accessibility_roles() { |
| 870 | let cases = [ |
| 871 | (None, Role::TextInput), |
| 872 | (Some(InputContentType::Name), Role::TextInput), |
| 873 | (Some(InputContentType::NamePrefix), Role::TextInput), |
| 874 | (Some(InputContentType::GivenName), Role::TextInput), |
| 875 | (Some(InputContentType::MiddleName), Role::TextInput), |
| 876 | (Some(InputContentType::FamilyName), Role::TextInput), |
| 877 | (Some(InputContentType::NameSuffix), Role::TextInput), |
| 878 | (Some(InputContentType::Nickname), Role::TextInput), |
| 879 | (Some(InputContentType::JobTitle), Role::TextInput), |
| 880 | (Some(InputContentType::OrganizationName), Role::TextInput), |
| 881 | (Some(InputContentType::Location), Role::TextInput), |
| 882 | (Some(InputContentType::FullStreetAddress), Role::TextInput), |
| 883 | (Some(InputContentType::StreetAddressLine1), Role::TextInput), |
| 884 | (Some(InputContentType::StreetAddressLine2), Role::TextInput), |
| 885 | (Some(InputContentType::AddressCity), Role::TextInput), |
| 886 | (Some(InputContentType::AddressState), Role::TextInput), |
| 887 | (Some(InputContentType::AddressCityAndState), Role::TextInput), |
| 888 | (Some(InputContentType::Sublocality), Role::TextInput), |
| 889 | (Some(InputContentType::CountryName), Role::TextInput), |
| 890 | (Some(InputContentType::PostalCode), Role::TextInput), |
| 891 | ( |
| 892 | Some(InputContentType::TelephoneNumber), |
| 893 | Role::PhoneNumberInput, |
| 894 | ), |
| 895 | (Some(InputContentType::EmailAddress), Role::EmailInput), |
| 896 | (Some(InputContentType::Url), Role::UrlInput), |
| 897 | (Some(InputContentType::CreditCardNumber), Role::TextInput), |
| 898 | (Some(InputContentType::CreditCardName), Role::TextInput), |
| 899 | (Some(InputContentType::CreditCardGivenName), Role::TextInput), |
| 900 | ( |
| 901 | Some(InputContentType::CreditCardMiddleName), |
| 902 | Role::TextInput, |
| 903 | ), |
| 904 | ( |
| 905 | Some(InputContentType::CreditCardFamilyName), |
| 906 | Role::TextInput, |
| 907 | ), |
| 908 | ( |
| 909 | Some(InputContentType::CreditCardSecurityCode), |
| 910 | Role::TextInput, |
| 911 | ), |
| 912 | ( |
| 913 | Some(InputContentType::CreditCardExpiration), |
| 914 | Role::TextInput, |
| 915 | ), |
| 916 | ( |
| 917 | Some(InputContentType::CreditCardExpirationMonth), |
| 918 | Role::TextInput, |
| 919 | ), |
| 920 | ( |
| 921 | Some(InputContentType::CreditCardExpirationYear), |
| 922 | Role::TextInput, |
| 923 | ), |
| 924 | (Some(InputContentType::CreditCardType), Role::TextInput), |
| 925 | (Some(InputContentType::Username), Role::TextInput), |
| 926 | (Some(InputContentType::Password), Role::PasswordInput), |
| 927 | (Some(InputContentType::NewPassword), Role::PasswordInput), |
| 928 | (Some(InputContentType::OneTimeCode), Role::TextInput), |
| 929 | ( |
| 930 | Some(InputContentType::ShipmentTrackingNumber), |
| 931 | Role::TextInput, |
| 932 | ), |
| 933 | (Some(InputContentType::FlightNumber), Role::TextInput), |
| 934 | (Some(InputContentType::DateTime), Role::DateTimeInput), |
| 935 | (Some(InputContentType::Birthdate), Role::DateInput), |
| 936 | (Some(InputContentType::BirthdateDay), Role::TextInput), |
| 937 | (Some(InputContentType::BirthdateMonth), Role::TextInput), |
| 938 | (Some(InputContentType::BirthdateYear), Role::TextInput), |
| 939 | (Some(InputContentType::CellularEid), Role::TextInput), |
| 940 | (Some(InputContentType::CellularImei), Role::TextInput), |
| 941 | ]; |
| 942 | |
| 943 | for (content_type, role) in cases { |
| 944 | assert_eq!( |
| 945 | accessibility_role(false, content_type, RoleOverride::Implicit), |
| 946 | Some(role) |
| 947 | ); |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | #[test] |
| 952 | fn multiline_inputs_keep_multiline_accessibility_role() { |
| 953 | assert_eq!( |
| 954 | accessibility_role( |
| 955 | true, |
| 956 | Some(InputContentType::Password), |
| 957 | RoleOverride::Implicit |
| 958 | ), |
| 959 | Some(Role::MultilineTextInput) |
| 960 | ); |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn explicit_accessibility_role_overrides_defaults() { |
| 965 | assert_eq!( |
| 966 | accessibility_role( |
| 967 | false, |
| 968 | Some(InputContentType::Password), |
| 969 | Role::TextInput.into() |
| 970 | ), |
| 971 | Some(Role::TextInput) |
| 972 | ); |
| 973 | assert_eq!( |
| 974 | accessibility_role( |
| 975 | true, |
| 976 | Some(InputContentType::Password), |
| 977 | Role::TextInput.into() |
| 978 | ), |
| 979 | Some(Role::TextInput) |
| 980 | ); |
| 981 | } |
| 982 | |
| 983 | #[test] |
| 984 | fn presentational_role_emits_no_accessibility_node() { |
| 985 | assert_eq!( |
| 986 | accessibility_role( |
| 987 | false, |
| 988 | Some(InputContentType::Password), |
| 989 | RoleOverride::Presentational |
| 990 | ), |
| 991 | None |
| 992 | ); |
| 993 | assert_eq!( |
| 994 | accessibility_role(true, None, RoleOverride::Presentational), |
| 995 | None |
| 996 | ); |
| 997 | } |
| 998 | |
| 999 | #[test] |
| 1000 | fn role_option_converts_to_the_matching_override() { |
| 1001 | assert_eq!( |
| 1002 | RoleOverride::from(Some(Role::Button)), |
| 1003 | RoleOverride::Role(Role::Button) |
| 1004 | ); |
| 1005 | assert_eq!(RoleOverride::from(None), RoleOverride::Presentational); |
| 1006 | } |
| 1007 | |
| 1008 | #[gpui::test] |
| 1009 | fn test_on_paste_builder(cx: &mut gpui::TestAppContext) { |
| 1010 | use gpui::{AppContext as _, Render}; |
| 1011 | |
| 1012 | struct Probe; |
| 1013 | impl Render for Probe { |
| 1014 | fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement { |
| 1015 | div() |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | cx.update(crate::init); |
| 1020 | let _ = cx.add_window_view(|window, cx| { |
| 1021 | let state = cx.new(|cx| InputState::new(window, cx)); |
| 1022 | |
| 1023 | assert!(Input::new(&state).paste_handler.is_none()); |
| 1024 | let input = Input::new(&state).on_paste(|_, _, _| true); |
| 1025 | assert!(input.paste_handler.is_some()); |
| 1026 | Probe |
| 1027 | }); |
| 1028 | } |
| 1029 | |
| 1030 | #[gpui::test] |
| 1031 | fn test_on_token_hover_builder(cx: &mut gpui::TestAppContext) { |
| 1032 | use gpui::{AppContext as _, Render}; |
| 1033 | |
| 1034 | struct Probe; |
| 1035 | impl Render for Probe { |
| 1036 | fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement { |
| 1037 | div() |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | cx.update(crate::init); |
| 1042 | let _ = cx.add_window_view(|window, cx| { |
| 1043 | let state = cx.new(|cx| InputState::new(window, cx)); |
| 1044 | |
| 1045 | assert!(Input::new(&state).token_hover_listener.is_none()); |
| 1046 | let input = Input::new(&state).on_token_hover(|_, _, _| {}); |
| 1047 | assert!(input.token_hover_listener.is_some()); |
| 1048 | Probe |
| 1049 | }); |
| 1050 | } |
| 1051 | |
| 1052 | #[gpui::test] |
| 1053 | fn editable_input_offers_accessibility_write_action(cx: &mut gpui::TestAppContext) { |
| 1054 | use crate::ElementExt as _; |
| 1055 | use gpui::{AppContext as _, Element as _, IntoElement as _, Render}; |
| 1056 | use std::sync::{Arc, Mutex}; |
| 1057 | |
| 1058 | type EmittedState = Option<(Option<String>, bool)>; |
| 1059 | |
| 1060 | struct InputA11yProbe { |
| 1061 | state: Entity<InputState>, |
| 1062 | emitted: Arc<Mutex<EmittedState>>, |
| 1063 | } |
| 1064 | |
| 1065 | impl Render for InputA11yProbe { |
| 1066 | fn render( |
| 1067 | &mut self, |
| 1068 | _window: &mut Window, |
| 1069 | _cx: &mut gpui::Context<Self>, |
| 1070 | ) -> impl IntoElement { |
| 1071 | let state = self.state.clone(); |
| 1072 | let emitted = self.emitted.clone(); |
| 1073 | div() |
| 1074 | .child(Input::new(&state)) |
| 1075 | .on_prepaint(move |_, window, cx| { |
| 1076 | let input = Input::new(&state).render(window, cx).into_element(); |
| 1077 | let mut node = gpui::accesskit::Node::new(Role::TextInput); |
| 1078 | input.write_a11y_info(&mut node); |
| 1079 | *emitted.lock().unwrap() = Some(( |
| 1080 | node.value().map(ToOwned::to_owned), |
| 1081 | node.supports_action(AccessibleAction::SetValue), |
| 1082 | )); |
| 1083 | }) |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | cx.update(crate::init); |
| 1088 | let emitted = Arc::new(Mutex::new(None)); |
| 1089 | let captured = emitted.clone(); |
| 1090 | let (probe, cx) = cx.add_window_view(move |window, cx| InputA11yProbe { |
| 1091 | state: cx.new(|cx| InputState::new(window, cx).default_value("initial")), |
| 1092 | emitted, |
| 1093 | }); |
| 1094 | cx.update(|window, cx| { |
| 1095 | let _ = window.draw(cx); |
| 1096 | }); |
| 1097 | // Normal builds leave the value lazy without an accessibility client; |
| 1098 | // test-support reads that same production value path eagerly. |
| 1099 | let expected_value = cfg!(feature = "test-support").then(|| "initial".to_owned()); |
| 1100 | assert_eq!(*captured.lock().unwrap(), Some((expected_value, true))); |
| 1101 | |
| 1102 | let state = probe.read_with(cx, |probe, _| probe.state.clone()); |
| 1103 | let base: TextInputState = state.clone().into(); |
| 1104 | cx.update(|window, cx| { |
| 1105 | Input::handle_accessibility_set_value(&base, None, window, cx); |
| 1106 | Input::handle_accessibility_focus(&base, window, cx); |
| 1107 | assert!(base.presentation(cx).focus_handle().is_focused(window)); |
| 1108 | window.draw(cx).clear(cx); |
| 1109 | }); |
| 1110 | assert_eq!(state.read_with(cx, |state, _| state.value()), "initial"); |
| 1111 | |
| 1112 | let changes = std::rc::Rc::new(std::cell::Cell::new(0)); |
| 1113 | let observed = changes.clone(); |
| 1114 | let _subscription = cx.update(|_, cx| { |
| 1115 | cx.subscribe(&state, move |_, event: &super::super::InputEvent, _| { |
| 1116 | if matches!(event, super::super::InputEvent::Change) { |
| 1117 | observed.set(observed.get() + 1); |
| 1118 | } |
| 1119 | }) |
| 1120 | }); |
| 1121 | let action = gpui::accesskit::ActionData::Value("updated🦀".into()); |
| 1122 | cx.update(|window, cx| { |
| 1123 | Input::handle_accessibility_set_value(&base, Some(&action), window, cx); |
| 1124 | }); |
| 1125 | assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀"); |
| 1126 | assert_eq!(changes.get(), 1); |
| 1127 | for disabled in [false, true] { |
| 1128 | cx.update(|window, cx| { |
| 1129 | base.set_disabled(disabled, cx); |
| 1130 | base.set_readonly(!disabled, cx); |
| 1131 | window.blur(cx); |
| 1132 | Input::handle_accessibility_focus(&base, window, cx); |
| 1133 | assert_eq!( |
| 1134 | base.presentation(cx).focus_handle().is_focused(window), |
| 1135 | !disabled |
| 1136 | ); |
| 1137 | let action = gpui::accesskit::ActionData::Value("rejected".into()); |
| 1138 | Input::handle_accessibility_set_value(&base, Some(&action), window, cx); |
| 1139 | }); |
| 1140 | assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀"); |
| 1141 | assert_eq!(changes.get(), 1); |
| 1142 | } |
| 1143 | cx.update(|window, cx| { |
| 1144 | base.set_disabled(false, cx); |
| 1145 | base.set_readonly(false, cx); |
| 1146 | Input::handle_accessibility_focus(&base, window, cx); |
| 1147 | window.draw(cx).clear(cx); |
| 1148 | window.dispatch_action(Box::new(super::super::Undo), cx); |
| 1149 | }); |
| 1150 | assert_eq!(state.read_with(cx, |state, _| state.value()), "initial"); |
| 1151 | cx.update(|window, cx| { |
| 1152 | state.update(cx, |state, cx| state.set_masked(true, window, cx)); |
| 1153 | Input::handle_accessibility_set_value(&base, Some(&action), window, cx); |
| 1154 | window.draw(cx).clear(cx); |
| 1155 | }); |
| 1156 | assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀"); |
| 1157 | assert_eq!(*captured.lock().unwrap(), Some((None, true))); |
| 1158 | } |
| 1159 | |
| 1160 | #[gpui::test] |
| 1161 | fn accessibility_set_value_preserves_exact_editor_text(cx: &mut gpui::TestAppContext) { |
| 1162 | use gpui::{AppContext as _, Render}; |
| 1163 | |
| 1164 | struct Probe(Entity<crate::input::EditorState>); |
| 1165 | |
| 1166 | impl Render for Probe { |
| 1167 | fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement { |
| 1168 | div().child(crate::input::Editor::new(&self.0)) |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | cx.update(crate::init); |
| 1173 | let (probe, cx) = cx.add_window_view(|window, cx| { |
| 1174 | Probe(cx.new(|cx| crate::input::EditorState::new(window, cx).language("rust"))) |
| 1175 | }); |
| 1176 | let editor = probe.read_with(cx, |probe, _| probe.0.clone()); |
| 1177 | let state: TextInputState = editor.clone().into(); |
| 1178 | let action = gpui::accesskit::ActionData::Value("(".into()); |
| 1179 | |
| 1180 | cx.update(|window, cx| { |
| 1181 | Input::handle_accessibility_set_value(&state, Some(&action), window, cx) |
| 1182 | }); |
| 1183 | assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "("); |
| 1184 | } |
| 1185 | |
| 1186 | #[gpui::test] |
| 1187 | fn input_emits_accessibility_id(cx: &mut gpui::TestAppContext) { |
| 1188 | use crate::ElementExt as _; |
| 1189 | use gpui::{AppContext as _, Element as _, IntoElement as _, Render}; |
| 1190 | use std::sync::{Arc, Mutex}; |
| 1191 | |
| 1192 | type EmittedIds = Vec<Option<String>>; |
| 1193 | |
| 1194 | struct InputA11yProbe { |
| 1195 | state: Entity<InputState>, |
| 1196 | emitted: Arc<Mutex<EmittedIds>>, |
| 1197 | } |
| 1198 | |
| 1199 | impl Render for InputA11yProbe { |
| 1200 | fn render( |
| 1201 | &mut self, |
| 1202 | _window: &mut Window, |
| 1203 | _cx: &mut gpui::Context<Self>, |
| 1204 | ) -> impl IntoElement { |
| 1205 | let state = self.state.clone(); |
| 1206 | let emitted = self.emitted.clone(); |
| 1207 | div().on_prepaint(move |_, window, cx| { |
| 1208 | let mut author_id_of = |input: Input| { |
| 1209 | let mut node = gpui::accesskit::Node::new(Role::TextInput); |
| 1210 | input |
| 1211 | .render(window, cx) |
| 1212 | .into_element() |
| 1213 | .write_a11y_info(&mut node); |
| 1214 | node.author_id().map(ToOwned::to_owned) |
| 1215 | }; |
| 1216 | |
| 1217 | *emitted.lock().unwrap() = vec![ |
| 1218 | author_id_of(Input::new(&state)), |
| 1219 | author_id_of(Input::new(&state).accessibility_id("search.query")), |
| 1220 | ]; |
| 1221 | }) |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | cx.update(crate::init); |
| 1226 | let emitted = Arc::new(Mutex::new(Vec::new())); |
| 1227 | let captured = emitted.clone(); |
| 1228 | let (_, cx) = cx.add_window_view(move |window, cx| InputA11yProbe { |
| 1229 | state: cx.new(|cx| InputState::new(window, cx)), |
| 1230 | emitted, |
| 1231 | }); |
| 1232 | cx.update(|window, cx| { |
| 1233 | let _ = window.draw(cx); |
| 1234 | }); |
| 1235 | |
| 1236 | assert_eq!( |
| 1237 | *captured.lock().unwrap(), |
| 1238 | vec![None, Some("search.query".into())] |
| 1239 | ); |
| 1240 | } |
| 1241 | |
| 1242 | #[test] |
| 1243 | fn accessibility_value_is_hidden_for_secret_inputs() { |
| 1244 | assert!(exposes_accessibility_value(false, None)); |
| 1245 | assert!(!exposes_accessibility_value(true, None)); |
| 1246 | assert!(!exposes_accessibility_value( |
| 1247 | false, |
| 1248 | Some(InputContentType::Password) |
| 1249 | )); |
| 1250 | assert!(!exposes_accessibility_value( |
| 1251 | false, |
| 1252 | Some(InputContentType::NewPassword) |
| 1253 | )); |
| 1254 | } |
| 1255 | |
| 1256 | #[gpui::test] |
| 1257 | fn focused_input_registry_tracks_focus_and_blur(cx: &mut gpui::TestAppContext) { |
| 1258 | use crate::{Root, WindowExt as _}; |
| 1259 | use gpui::{AppContext as _, Render}; |
| 1260 | |
| 1261 | struct Probe { |
| 1262 | input: Entity<InputState>, |
| 1263 | textarea: Entity<crate::input::TextareaState>, |
| 1264 | editor: Entity<crate::input::EditorState>, |
| 1265 | otp: Entity<gpui_base::OtpState>, |
| 1266 | other: gpui::FocusHandle, |
| 1267 | } |
| 1268 | impl Render for Probe { |
| 1269 | fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement { |
| 1270 | div() |
| 1271 | .child(div().track_focus(&self.other)) |
| 1272 | .child(Input::new(&self.input)) |
| 1273 | .child(crate::input::Textarea::new(&self.textarea)) |
| 1274 | .child(crate::input::Editor::new(&self.editor)) |
| 1275 | .child(crate::input::OtpInput::new(&self.otp)) |
| 1276 | } |
| 1277 | } |
| 1278 | |
| 1279 | cx.update(crate::init); |
| 1280 | let mut input = None; |
| 1281 | let mut textarea = None; |
| 1282 | let mut editor = None; |
| 1283 | let mut other_focus = None; |
| 1284 | let mut otp = None; |
| 1285 | let window = cx.update(|cx| { |
| 1286 | cx.open_window(Default::default(), |window, cx| { |
| 1287 | let state = cx.new(|cx| InputState::new(window, cx)); |
| 1288 | let textarea_state = cx.new(|cx| crate::input::TextareaState::new(window, cx)); |
| 1289 | let editor_state = |
| 1290 | cx.new(|cx| crate::input::EditorState::new(window, cx).language("rust")); |
| 1291 | let otp_state = cx.new(|cx| gpui_base::OtpState::new(6, window, cx)); |
| 1292 | input = Some(state.clone()); |
| 1293 | textarea = Some(textarea_state.clone()); |
| 1294 | editor = Some(editor_state.clone()); |
| 1295 | otp = Some(otp_state.clone()); |
| 1296 | let other = cx.focus_handle(); |
| 1297 | other_focus = Some(other.clone()); |
| 1298 | let probe = cx.new(|_| Probe { |
| 1299 | input: state, |
| 1300 | textarea: textarea_state, |
| 1301 | editor: editor_state, |
| 1302 | otp: otp_state, |
| 1303 | other, |
| 1304 | }); |
| 1305 | cx.new(|cx| Root::new(probe, window, cx)) |
| 1306 | }) |
| 1307 | .unwrap() |
| 1308 | }); |
| 1309 | let input = input.unwrap(); |
| 1310 | let textarea = textarea.unwrap(); |
| 1311 | let editor = editor.unwrap(); |
| 1312 | let otp = otp.unwrap(); |
| 1313 | let other_focus = other_focus.unwrap(); |
| 1314 | let mut cx = gpui::VisualTestContext::from_window(window.into(), cx); |
| 1315 | |
| 1316 | // Focusing each kind of input registers it, and blurring clears it. |
| 1317 | let cases: Vec<AnyInputState> = vec![ |
| 1318 | input.clone().into(), |
| 1319 | textarea.clone().into(), |
| 1320 | editor.clone().into(), |
| 1321 | otp.clone().into(), |
| 1322 | ]; |
| 1323 | for expected in cases { |
| 1324 | cx.update(|window, cx| { |
| 1325 | let _ = window.draw(cx); |
| 1326 | }); |
| 1327 | cx.update(|window, cx| expected.focus_handle(cx).focus(window, cx)); |
| 1328 | cx.run_until_parked(); |
| 1329 | cx.update(|window, cx| { |
| 1330 | let _ = window.draw(cx); |
| 1331 | }); |
| 1332 | assert_eq!( |
| 1333 | cx.update(|window, cx| window.focused_input(cx)), |
| 1334 | Some(expected) |
| 1335 | ); |
| 1336 | |
| 1337 | cx.update(|window, cx| other_focus.clone().focus(window, cx)); |
| 1338 | cx.run_until_parked(); |
| 1339 | cx.update(|window, cx| { |
| 1340 | let _ = window.draw(cx); |
| 1341 | }); |
| 1342 | assert_eq!(cx.update(|window, cx| window.focused_input(cx)), None); |
| 1343 | } |
| 1344 | } |
| 1345 | |
| 1346 | #[gpui::test] |
| 1347 | fn focused_input_registry_ignores_input_removed_while_focused(cx: &mut gpui::TestAppContext) { |
| 1348 | use crate::{Root, WindowExt as _}; |
| 1349 | use gpui::{AppContext as _, Render}; |
| 1350 | |
| 1351 | struct Probe { |
| 1352 | input: Entity<InputState>, |
| 1353 | show_input: bool, |
| 1354 | other: gpui::FocusHandle, |
| 1355 | } |
| 1356 | impl Render for Probe { |
| 1357 | fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement { |
| 1358 | let base = div().child(div().track_focus(&self.other)); |
| 1359 | if self.show_input { |
| 1360 | base.child(Input::new(&self.input)) |
| 1361 | } else { |
| 1362 | base |
| 1363 | } |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | cx.update(crate::init); |
| 1368 | let mut input = None; |
| 1369 | let mut other_focus = None; |
| 1370 | let mut probe_entity = None; |
| 1371 | let window = cx.update(|cx| { |
| 1372 | cx.open_window(Default::default(), |window, cx| { |
| 1373 | let state = cx.new(|cx| InputState::new(window, cx)); |
| 1374 | input = Some(state.clone()); |
| 1375 | let other = cx.focus_handle(); |
| 1376 | other_focus = Some(other.clone()); |
| 1377 | let probe = cx.new(|_| Probe { |
| 1378 | input: state, |
| 1379 | show_input: true, |
| 1380 | other, |
| 1381 | }); |
| 1382 | probe_entity = Some(probe.clone()); |
| 1383 | cx.new(|cx| Root::new(probe, window, cx)) |
| 1384 | }) |
| 1385 | .unwrap() |
| 1386 | }); |
| 1387 | let input: AnyInputState = input.unwrap().into(); |
| 1388 | let other_focus = other_focus.unwrap(); |
| 1389 | let probe = probe_entity.unwrap(); |
| 1390 | let mut cx = gpui::VisualTestContext::from_window(window.into(), cx); |
| 1391 | |
| 1392 | cx.update(|window, cx| { |
| 1393 | let _ = window.draw(cx); |
| 1394 | }); |
| 1395 | cx.update(|window, cx| input.focus_handle(cx).focus(window, cx)); |
| 1396 | cx.run_until_parked(); |
| 1397 | cx.update(|window, cx| { |
| 1398 | let _ = window.draw(cx); |
| 1399 | }); |
| 1400 | assert_eq!( |
| 1401 | cx.update(|window, cx| window.focused_input(cx)), |
| 1402 | Some(input.clone()) |
| 1403 | ); |
| 1404 | |
| 1405 | // Remove the input from the tree while it holds focus and move focus |
| 1406 | // elsewhere in the same update (e.g. closing a sidebar containing the |
| 1407 | // input) — the input never re-renders to unregister itself. |
| 1408 | cx.update(|window, cx| { |
| 1409 | probe.update(cx, |probe, cx| { |
| 1410 | probe.show_input = false; |
| 1411 | cx.notify(); |
| 1412 | }); |
| 1413 | other_focus.focus(window, cx); |
| 1414 | }); |
| 1415 | cx.run_until_parked(); |
| 1416 | cx.update(|window, cx| { |
| 1417 | let _ = window.draw(cx); |
| 1418 | }); |
| 1419 | assert!(!cx.update(|window, cx| window.has_focused_input(cx))); |
| 1420 | assert_eq!(cx.update(|window, cx| window.focused_input(cx)), None); |
| 1421 | } |
| 1422 | } |