| 1 | use std::time::Duration; |
| 2 | |
| 3 | use gpui_kit::component::IndexPath; |
| 4 | use gpui_kit::component::calendar::Matcher; |
| 5 | use gpui_kit::component::date_picker::{DatePickerEvent, DatePickerState}; |
| 6 | use gpui_kit::component::input::{InputEvent, InputState, TextareaState}; |
| 7 | use gpui_kit::component::searchable_list::{ |
| 8 | SearchableListDelegate, SearchableListItem, SearchableVec, |
| 9 | }; |
| 10 | use gpui_kit::component::select::{SelectEvent, SelectState}; |
| 11 | use gpui_kit::component::time_field::{TimeFieldEvent, TimeFieldState}; |
| 12 | use gpui_kit::*; |
| 13 | use regex::Regex; |
| 14 | use teams_core::{ |
| 15 | AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceQuery, |
| 16 | ChoiceStyle, InputChoice, TextStyle, collect_input_values, format_date, format_time, |
| 17 | }; |
| 18 | use tokio::sync::oneshot; |
| 19 | |
| 20 | use crate::app_state::{AppHandle, AppState}; |
| 21 | use crate::card_actions::CardTask; |
| 22 | use crate::card_state::{CardScope, Surface, short_reason}; |
| 23 | use crate::runtime; |
| 24 | |
| 25 | const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$"; |
| 26 | const AREA_MIN_ROWS: usize = 3; |
| 27 | const AREA_MAX_ROWS: usize = 8; |
| 28 | const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300); |
| 29 | const NOT_CONNECTED: &str = "Not connected"; |
| 30 | const READ_ONLY: &str = "Read-only mode"; |
| 31 | const SEARCH_FAILED: &str = "Search failed"; |
| 32 | const INLINE_ACTION_SUFFIX: &str = "inline"; |
| 33 | |
| 34 | pub type SearchAnswer = Result<Vec<InputChoice>, String>; |
| 35 | |
| 36 | #[derive(Clone)] |
| 37 | pub struct ChoiceItem { |
| 38 | pub title: SharedString, |
| 39 | pub value: String, |
| 40 | } |
| 41 | |
| 42 | impl SearchableListItem for ChoiceItem { |
| 43 | type Value = String; |
| 44 | |
| 45 | fn title(&self) -> SharedString { |
| 46 | self.title.clone() |
| 47 | } |
| 48 | |
| 49 | fn value(&self) -> &String { |
| 50 | &self.value |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub struct RemoteSearch { |
| 55 | scope: CardScope, |
| 56 | key: String, |
| 57 | query: ChoiceQuery, |
| 58 | } |
| 59 | |
| 60 | pub struct ChoiceList { |
| 61 | items: SearchableVec<ChoiceItem>, |
| 62 | remote: Option<RemoteSearch>, |
| 63 | search_task: Task<()>, |
| 64 | } |
| 65 | |
| 66 | impl ChoiceList { |
| 67 | fn new(items: Vec<ChoiceItem>, remote: Option<RemoteSearch>) -> Self { |
| 68 | ChoiceList { |
| 69 | items: SearchableVec::new(items), |
| 70 | remote, |
| 71 | search_task: Task::ready(()), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn found(choices: Vec<InputChoice>, remote: Option<RemoteSearch>) -> Self { |
| 76 | ChoiceList::new(choice_item_list(&choices), remote) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl SearchableListDelegate for ChoiceList { |
| 81 | type Item = ChoiceItem; |
| 82 | |
| 83 | fn items_count(&self, section: usize) -> usize { |
| 84 | self.items.items_count(section) |
| 85 | } |
| 86 | |
| 87 | fn item(&self, ix: IndexPath) -> Option<&ChoiceItem> { |
| 88 | self.items.item(ix) |
| 89 | } |
| 90 | |
| 91 | fn position<V>(&self, value: &V) -> Option<IndexPath> |
| 92 | where |
| 93 | ChoiceItem: SearchableListItem<Value = V>, |
| 94 | V: PartialEq, |
| 95 | { |
| 96 | self.items.position(value) |
| 97 | } |
| 98 | |
| 99 | fn perform_search(&mut self, query: &str, window: &mut Window, cx: &mut App) -> Task<()> { |
| 100 | let Some(remote) = &self.remote else { |
| 101 | return self.items.perform_search(query, window, cx); |
| 102 | }; |
| 103 | if query.is_empty() { |
| 104 | return Task::ready(()); |
| 105 | } |
| 106 | let (scope, key, choice_query, query_text) = ( |
| 107 | remote.scope.clone(), |
| 108 | remote.key.clone(), |
| 109 | remote.query.clone(), |
| 110 | query.to_owned(), |
| 111 | ); |
| 112 | self.search_task = window.spawn(cx, async move |cx| { |
| 113 | cx.background_executor().timer(SEARCH_DEBOUNCE).await; |
| 114 | let app = cx.update(|_, cx| cx.global::<AppHandle>().0.clone()).ok(); |
| 115 | let Some(app) = app else { |
| 116 | return; |
| 117 | }; |
| 118 | let receiver = cx |
| 119 | .update(|_, cx| { |
| 120 | app.update(cx, |state, _| { |
| 121 | state.card_choice_search(&scope, &choice_query, &query_text) |
| 122 | }) |
| 123 | }) |
| 124 | .ok(); |
| 125 | let answer = match receiver { |
| 126 | Some(receiver) => receiver.await.unwrap_or_else(|_| Err(SEARCH_FAILED.into())), |
| 127 | None => return, |
| 128 | }; |
| 129 | cx.update(|window, cx| { |
| 130 | app.update(cx, |state, cx| { |
| 131 | state.show_choice_results(&scope, &key, &choice_query, answer, window, cx) |
| 132 | }) |
| 133 | }) |
| 134 | .ok(); |
| 135 | }); |
| 136 | Task::ready(()) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | pub type ChoiceSelect = SelectState<ChoiceList>; |
| 141 | |
| 142 | #[derive(Clone)] |
| 143 | pub enum InputField { |
| 144 | Line(Entity<InputState>), |
| 145 | Area(Entity<TextareaState>), |
| 146 | Select(Entity<ChoiceSelect>), |
| 147 | Date(Entity<DatePickerState>), |
| 148 | Time(Entity<TimeFieldState>), |
| 149 | } |
| 150 | |
| 151 | impl InputField { |
| 152 | pub fn text(&self, cx: &App) -> Option<String> { |
| 153 | match self { |
| 154 | InputField::Line(state) => Some(state.read(cx).value().to_string()), |
| 155 | InputField::Area(state) => Some(state.read(cx).value().to_string()), |
| 156 | InputField::Select(state) => { |
| 157 | Some(state.read(cx).selected_value().cloned().unwrap_or_default()) |
| 158 | } |
| 159 | InputField::Date(_) | InputField::Time(_) => None, |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | pub struct FieldHandle { |
| 165 | pub field: InputField, |
| 166 | _subscriptions: Vec<Subscription>, |
| 167 | } |
| 168 | |
| 169 | fn choice_item_list(choices: &[InputChoice]) -> Vec<ChoiceItem> { |
| 170 | choices |
| 171 | .iter() |
| 172 | .map(|choice| ChoiceItem { |
| 173 | title: choice.title.clone().into(), |
| 174 | value: choice.value.clone(), |
| 175 | }) |
| 176 | .collect() |
| 177 | } |
| 178 | |
| 179 | pub fn choice_list(choice: &ChoiceInput, scope: &CardScope, key: &str) -> ChoiceList { |
| 180 | let remote = choice.query.clone().map(|query| RemoteSearch { |
| 181 | scope: scope.clone(), |
| 182 | key: key.to_owned(), |
| 183 | query, |
| 184 | }); |
| 185 | let mut choices = choice.choices.clone(); |
| 186 | if remote.is_some() && !choice.value.is_empty() { |
| 187 | let known = choices |
| 188 | .iter() |
| 189 | .any(|candidate| candidate.value == choice.value); |
| 190 | if !known { |
| 191 | choices.push(InputChoice { |
| 192 | title: choice.value.clone(), |
| 193 | value: choice.value.clone(), |
| 194 | }); |
| 195 | } |
| 196 | } |
| 197 | ChoiceList::found(choices, remote) |
| 198 | } |
| 199 | |
| 200 | pub fn uses_select(choice: &ChoiceInput) -> bool { |
| 201 | choice.query.is_some() || (!choice.multi && choice.style != ChoiceStyle::Expanded) |
| 202 | } |
| 203 | |
| 204 | pub fn length_pattern(max_length: usize) -> Option<Regex> { |
| 205 | Regex::new(&format!("^(?s:.{{0,{max_length}}})$")).ok() |
| 206 | } |
| 207 | |
| 208 | pub fn inline_action_key(input_key: &str) -> String { |
| 209 | format!("{input_key}-{INLINE_ACTION_SUFFIX}") |
| 210 | } |
| 211 | |
| 212 | impl AppState { |
| 213 | pub fn ensure_card_inputs( |
| 214 | &mut self, |
| 215 | scope: &CardScope, |
| 216 | card: &AdaptiveCard, |
| 217 | window: &mut Window, |
| 218 | cx: &mut Context<Self>, |
| 219 | ) { |
| 220 | let inputs = card.all_inputs(); |
| 221 | for input in &inputs { |
| 222 | let key = scope.input_key(&input.id); |
| 223 | if self.cards.has_input(&key) { |
| 224 | continue; |
| 225 | } |
| 226 | let handle = Self::create_field(scope, &key, input, &inputs, window, cx); |
| 227 | self.cards.seed_input(key, input.initial_value(), handle); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | fn create_field( |
| 232 | scope: &CardScope, |
| 233 | key: &str, |
| 234 | input: &CardInput, |
| 235 | inputs: &[CardInput], |
| 236 | window: &mut Window, |
| 237 | cx: &mut Context<Self>, |
| 238 | ) -> Option<FieldHandle> { |
| 239 | let value = input.initial_value(); |
| 240 | let (scope, key) = (scope.clone(), key.to_owned()); |
| 241 | let validated = input.clone(); |
| 242 | match &input.kind { |
| 243 | CardInputKind::Text(text) if text.multiline => { |
| 244 | let placeholder = text.placeholder.clone().unwrap_or_default(); |
| 245 | let max_length = text.max_length; |
| 246 | let state = cx.new(|cx| { |
| 247 | TextareaState::new(window, cx) |
| 248 | .auto_grow(AREA_MIN_ROWS, AREA_MAX_ROWS) |
| 249 | .placeholder(placeholder) |
| 250 | .default_value(value) |
| 251 | }); |
| 252 | let subscription = cx.subscribe_in(&state, window, { |
| 253 | let (scope, key) = (scope.clone(), key.clone()); |
| 254 | move |this, state, event: &InputEvent, window, cx| match event { |
| 255 | InputEvent::Change => { |
| 256 | let mut text = state.read(cx).value().to_string(); |
| 257 | if let Some(max_length) = max_length |
| 258 | && text.chars().count() > max_length |
| 259 | { |
| 260 | text = text.chars().take(max_length).collect(); |
| 261 | state.update(cx, |area, cx| { |
| 262 | area.set_value(text.clone(), window, cx) |
| 263 | }); |
| 264 | } |
| 265 | this.edit_card_input(&scope, &key, text, cx); |
| 266 | } |
| 267 | InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx), |
| 268 | _ => {} |
| 269 | } |
| 270 | }); |
| 271 | Some(FieldHandle { |
| 272 | field: InputField::Area(state), |
| 273 | _subscriptions: vec![subscription], |
| 274 | }) |
| 275 | } |
| 276 | CardInputKind::Text(_) | CardInputKind::Number(_) => { |
| 277 | let (placeholder, masked, pattern, inline_action) = match &input.kind { |
| 278 | CardInputKind::Text(text) => ( |
| 279 | text.placeholder.clone(), |
| 280 | text.style == TextStyle::Password, |
| 281 | text.max_length.and_then(length_pattern), |
| 282 | text.inline_action.clone(), |
| 283 | ), |
| 284 | CardInputKind::Number(number) => ( |
| 285 | number.placeholder.clone(), |
| 286 | false, |
| 287 | Regex::new(NUMBER_PATTERN).ok(), |
| 288 | None, |
| 289 | ), |
| 290 | _ => (None, false, None, None), |
| 291 | }; |
| 292 | let state = cx.new(|cx| { |
| 293 | let line = InputState::new(window, cx) |
| 294 | .placeholder(placeholder.unwrap_or_default()) |
| 295 | .masked(masked) |
| 296 | .default_value(value); |
| 297 | match pattern { |
| 298 | Some(pattern) => line.pattern(pattern), |
| 299 | None => line, |
| 300 | } |
| 301 | }); |
| 302 | let inputs = inputs.to_vec(); |
| 303 | let subscription = cx.subscribe(&state, { |
| 304 | let (scope, key) = (scope.clone(), key.clone()); |
| 305 | move |this, state, event: &InputEvent, cx| match event { |
| 306 | InputEvent::Change => { |
| 307 | let text = state.read(cx).value().to_string(); |
| 308 | this.edit_card_input(&scope, &key, text, cx); |
| 309 | } |
| 310 | InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx), |
| 311 | InputEvent::PressEnter { .. } => { |
| 312 | if let Some(inline) = &inline_action { |
| 313 | this.run_inline_action( |
| 314 | &scope, |
| 315 | inline_action_key(&key), |
| 316 | &inline.action, |
| 317 | &inputs, |
| 318 | cx, |
| 319 | ); |
| 320 | } |
| 321 | } |
| 322 | InputEvent::Focus => {} |
| 323 | } |
| 324 | }); |
| 325 | Some(FieldHandle { |
| 326 | field: InputField::Line(state), |
| 327 | _subscriptions: vec![subscription], |
| 328 | }) |
| 329 | } |
| 330 | CardInputKind::Date(moment) => { |
| 331 | let (min, max) = (moment.min_date(), moment.max_date()); |
| 332 | let initial = moment.initial_date(); |
| 333 | let state = cx.new(|cx| { |
| 334 | let mut picker = DatePickerState::new(window, cx).date_format("%Y-%m-%d"); |
| 335 | if min.is_some() || max.is_some() { |
| 336 | picker = picker.disabled_matcher(Matcher::interval(min, max)); |
| 337 | } |
| 338 | if let Some(date) = initial { |
| 339 | picker.set_date(date, window, cx); |
| 340 | } |
| 341 | picker |
| 342 | }); |
| 343 | let subscription = cx.subscribe(&state, { |
| 344 | move |this, _, event: &DatePickerEvent, cx| { |
| 345 | let DatePickerEvent::Change(picked) = event; |
| 346 | let text = picked.date().start().map(format_date).unwrap_or_default(); |
| 347 | this.pick_card_input(&scope, &key, text, cx); |
| 348 | this.validate_card_input(&scope, &key, &validated, cx); |
| 349 | } |
| 350 | }); |
| 351 | Some(FieldHandle { |
| 352 | field: InputField::Date(state), |
| 353 | _subscriptions: vec![subscription], |
| 354 | }) |
| 355 | } |
| 356 | CardInputKind::Time(moment) => { |
| 357 | let initial = moment.initial_time(); |
| 358 | let state = cx.new(|cx| { |
| 359 | let mut field = TimeFieldState::new(window, cx); |
| 360 | if let Some(time) = initial { |
| 361 | field.set_time(time, window, cx); |
| 362 | } |
| 363 | field |
| 364 | }); |
| 365 | let focus_handle = state.focus_handle(cx); |
| 366 | let changed = cx.subscribe(&state, { |
| 367 | let (scope, key) = (scope.clone(), key.clone()); |
| 368 | move |this, _, event: &TimeFieldEvent, cx| { |
| 369 | let TimeFieldEvent::Change(time) = event; |
| 370 | this.pick_card_input(&scope, &key, format_time(*time), cx); |
| 371 | } |
| 372 | }); |
| 373 | let blurred = cx.on_blur(&focus_handle, window, move |this, _, cx| { |
| 374 | this.validate_card_input(&scope, &key, &validated, cx) |
| 375 | }); |
| 376 | Some(FieldHandle { |
| 377 | field: InputField::Time(state), |
| 378 | _subscriptions: vec![changed, blurred], |
| 379 | }) |
| 380 | } |
| 381 | CardInputKind::Choice(choice) if uses_select(choice) => { |
| 382 | let searchable = choice.style == ChoiceStyle::Filtered || choice.query.is_some(); |
| 383 | let list = choice_list(choice, &scope, &key); |
| 384 | let selected = (0..list.items_count(0)) |
| 385 | .find(|row| { |
| 386 | list.item(IndexPath::default().row(*row)) |
| 387 | .is_some_and(|item| item.value == value) |
| 388 | }) |
| 389 | .map(|row| IndexPath::default().row(row)); |
| 390 | let state = cx |
| 391 | .new(|cx| SelectState::new(list, selected, window, cx).searchable(searchable)); |
| 392 | let subscription = cx.subscribe( |
| 393 | &state, |
| 394 | move |this, _, event: &SelectEvent<ChoiceList>, cx| { |
| 395 | let SelectEvent::Confirm(picked) = event; |
| 396 | this.pick_card_input(&scope, &key, picked.clone().unwrap_or_default(), cx); |
| 397 | }, |
| 398 | ); |
| 399 | Some(FieldHandle { |
| 400 | field: InputField::Select(state), |
| 401 | _subscriptions: vec![subscription], |
| 402 | }) |
| 403 | } |
| 404 | CardInputKind::Choice(_) | CardInputKind::Toggle(_) | CardInputKind::Rating(_) => None, |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | pub fn validate_card_input( |
| 409 | &mut self, |
| 410 | scope: &CardScope, |
| 411 | key: &str, |
| 412 | input: &CardInput, |
| 413 | cx: &mut Context<Self>, |
| 414 | ) { |
| 415 | let value = self.cards.input_text(key, cx); |
| 416 | match input.validate(&value) { |
| 417 | Some(message) => self.cards.set_input_error(key, message), |
| 418 | None => self.cards.clear_input_errors(&[key.to_owned()]), |
| 419 | } |
| 420 | self.announce_cards(scope, cx); |
| 421 | } |
| 422 | |
| 423 | pub fn run_inline_action( |
| 424 | &mut self, |
| 425 | scope: &CardScope, |
| 426 | action_key: String, |
| 427 | action: &CardAction, |
| 428 | inputs: &[CardInput], |
| 429 | cx: &mut Context<Self>, |
| 430 | ) { |
| 431 | match &action.kind { |
| 432 | CardActionKind::OpenUrl(url) => cx.open_url(url), |
| 433 | _ => self.run_card_action( |
| 434 | scope.clone(), |
| 435 | action_key, |
| 436 | action.clone(), |
| 437 | inputs.to_vec(), |
| 438 | cx, |
| 439 | ), |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | pub fn card_choice_search( |
| 444 | &self, |
| 445 | scope: &CardScope, |
| 446 | query: &ChoiceQuery, |
| 447 | query_text: &str, |
| 448 | ) -> oneshot::Receiver<SearchAnswer> { |
| 449 | if self.mode.demo { |
| 450 | let (dataset, query_text) = (query.dataset.clone(), query_text.to_owned()); |
| 451 | return runtime::spawn(async move { |
| 452 | Ok(crate::demo_input_cards::search(&dataset, &query_text)) |
| 453 | }); |
| 454 | } |
| 455 | if self.mode.read_only { |
| 456 | return runtime::spawn(async { Err(READ_ONLY.to_owned()) }); |
| 457 | } |
| 458 | let Some(engine) = self.engine.clone() else { |
| 459 | return runtime::spawn(async { Err(NOT_CONNECTED.to_owned()) }); |
| 460 | }; |
| 461 | let (conversation_id, message_id) = |
| 462 | (scope.conversation_id.clone(), scope.message_id.clone()); |
| 463 | let (query, query_text) = (query.clone(), query_text.to_owned()); |
| 464 | runtime::spawn(async move { |
| 465 | engine |
| 466 | .card_search(&conversation_id, &message_id, &query, &query_text) |
| 467 | .await |
| 468 | .map_err(|error| short_reason(&error.to_string())) |
| 469 | }) |
| 470 | } |
| 471 | |
| 472 | pub fn show_choice_results( |
| 473 | &mut self, |
| 474 | scope: &CardScope, |
| 475 | key: &str, |
| 476 | query: &ChoiceQuery, |
| 477 | answer: SearchAnswer, |
| 478 | window: &mut Window, |
| 479 | cx: &mut Context<Self>, |
| 480 | ) { |
| 481 | match answer { |
| 482 | Ok(choices) => { |
| 483 | if self.cards.input_error(key) == Some(SEARCH_FAILED) { |
| 484 | self.cards.clear_input_errors(&[key.to_owned()]); |
| 485 | self.announce_cards(scope, cx); |
| 486 | } |
| 487 | if let Some(InputField::Select(select)) = self.cards.input_field(key).cloned() { |
| 488 | let remote = RemoteSearch { |
| 489 | scope: scope.clone(), |
| 490 | key: key.to_owned(), |
| 491 | query: query.clone(), |
| 492 | }; |
| 493 | select.update(cx, |select, cx| { |
| 494 | select.set_items(ChoiceList::found(choices, Some(remote)), window, cx); |
| 495 | cx.notify(); |
| 496 | }); |
| 497 | } |
| 498 | } |
| 499 | Err(_) => { |
| 500 | self.cards.set_input_error(key, SEARCH_FAILED.to_owned()); |
| 501 | self.announce_cards(scope, cx); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | pub fn edit_card_input( |
| 507 | &mut self, |
| 508 | scope: &CardScope, |
| 509 | key: &str, |
| 510 | value: String, |
| 511 | cx: &mut Context<Self>, |
| 512 | ) { |
| 513 | if self.cards.set_input_value(key, value) { |
| 514 | self.announce_cards(scope, cx); |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | pub fn pick_card_input( |
| 519 | &mut self, |
| 520 | scope: &CardScope, |
| 521 | key: &str, |
| 522 | value: String, |
| 523 | cx: &mut Context<Self>, |
| 524 | ) { |
| 525 | self.cards.set_input_value(key, value); |
| 526 | self.announce_cards(scope, cx); |
| 527 | } |
| 528 | |
| 529 | pub fn card_task( |
| 530 | &mut self, |
| 531 | scope: &CardScope, |
| 532 | action: CardAction, |
| 533 | inputs: &[CardInput], |
| 534 | cx: &mut Context<Self>, |
| 535 | ) -> Option<CardTask> { |
| 536 | let submits = matches!( |
| 537 | action.kind, |
| 538 | CardActionKind::Submit(_) | CardActionKind::Execute(_) |
| 539 | ); |
| 540 | let values = if submits && action.collects_inputs { |
| 541 | let keys: Vec<String> = inputs |
| 542 | .iter() |
| 543 | .map(|input| scope.input_key(&input.id)) |
| 544 | .collect(); |
| 545 | self.cards.clear_input_errors(&keys); |
| 546 | let collected = collect_input_values(inputs, |input| { |
| 547 | self.cards.input_text(&scope.input_key(&input.id), cx) |
| 548 | }); |
| 549 | match collected { |
| 550 | Ok(values) => values, |
| 551 | Err(errors) => { |
| 552 | for error in errors { |
| 553 | self.cards |
| 554 | .set_input_error(&scope.input_key(&error.id), error.message); |
| 555 | } |
| 556 | self.announce_cards(scope, cx); |
| 557 | return None; |
| 558 | } |
| 559 | } |
| 560 | } else { |
| 561 | serde_json::Map::new() |
| 562 | }; |
| 563 | let action = action.with_inputs(&values); |
| 564 | Some(match (&scope.surface, &action.kind) { |
| 565 | (Surface::Dialog, CardActionKind::Submit(submit)) => { |
| 566 | CardTask::Submit(submit.data.clone()) |
| 567 | } |
| 568 | _ => CardTask::Action(action), |
| 569 | }) |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | #[cfg(test)] |
| 574 | mod tests { |
| 575 | use std::sync::Arc; |
| 576 | |
| 577 | use gpui_kit::{ |
| 578 | AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext, |
| 579 | Window, |
| 580 | }; |
| 581 | use serde_json::json; |
| 582 | use store::Store; |
| 583 | use teams_core::AdaptiveCard; |
| 584 | |
| 585 | use super::InputField; |
| 586 | use crate::app_state::{AppHandle, AppState, Mode}; |
| 587 | use crate::card_actions::CardTask; |
| 588 | use crate::card_state::{CardScope, Surface}; |
| 589 | use crate::views::adaptive_card::card_view; |
| 590 | |
| 591 | struct Harness { |
| 592 | app: Entity<AppState>, |
| 593 | scope: CardScope, |
| 594 | card: AdaptiveCard, |
| 595 | } |
| 596 | |
| 597 | impl Render for Harness { |
| 598 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 599 | self.app.update(cx, |state, cx| { |
| 600 | state.ensure_card_inputs(&self.scope, &self.card, window, cx) |
| 601 | }); |
| 602 | card_view(&self.card, &self.scope, cx) |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | fn form_card() -> AdaptiveCard { |
| 607 | let card = json!({ |
| 608 | "body": [ |
| 609 | {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"}, |
| 610 | {"type": "Input.Toggle", "id": "agree", "title": "Agree"} |
| 611 | ], |
| 612 | "actions": [ |
| 613 | {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}, |
| 614 | {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}} |
| 615 | ] |
| 616 | }); |
| 617 | AdaptiveCard::parse(&card.to_string()).unwrap() |
| 618 | } |
| 619 | |
| 620 | fn typed_card() -> AdaptiveCard { |
| 621 | let card = json!({ |
| 622 | "body": [ |
| 623 | {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"}, |
| 624 | {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"}, |
| 625 | {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"}, |
| 626 | {"type": "Input.Number", "id": "count", "value": 4}, |
| 627 | {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true} |
| 628 | ], |
| 629 | "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}] |
| 630 | }); |
| 631 | AdaptiveCard::parse(&card.to_string()).unwrap() |
| 632 | } |
| 633 | |
| 634 | fn open( |
| 635 | cx: &mut TestAppContext, |
| 636 | surface: Surface, |
| 637 | ) -> ( |
| 638 | &mut VisualTestContext, |
| 639 | Entity<AppState>, |
| 640 | CardScope, |
| 641 | AdaptiveCard, |
| 642 | ) { |
| 643 | open_card(cx, surface, form_card()) |
| 644 | } |
| 645 | |
| 646 | fn open_card( |
| 647 | cx: &mut TestAppContext, |
| 648 | surface: Surface, |
| 649 | card: AdaptiveCard, |
| 650 | ) -> ( |
| 651 | &mut VisualTestContext, |
| 652 | Entity<AppState>, |
| 653 | CardScope, |
| 654 | AdaptiveCard, |
| 655 | ) { |
| 656 | cx.update(gpui_kit::init); |
| 657 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 658 | let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default()))); |
| 659 | cx.update(|cx| cx.set_global(AppHandle(app.clone()))); |
| 660 | let scope = CardScope { |
| 661 | surface, |
| 662 | ..CardScope::message("19:chat@thread.v2", "m1", 0) |
| 663 | }; |
| 664 | let (_, window_cx) = cx.add_window_view({ |
| 665 | let (app, scope, card) = (app.clone(), scope.clone(), card.clone()); |
| 666 | move |_, _| Harness { app, scope, card } |
| 667 | }); |
| 668 | window_cx.update(|window, cx| window.draw(cx).clear(cx)); |
| 669 | (window_cx, app, scope, card) |
| 670 | } |
| 671 | |
| 672 | fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) { |
| 673 | let key = scope.input_key("name"); |
| 674 | let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned()); |
| 675 | let Some(InputField::Line(line)) = field else { |
| 676 | panic!("name is a single line field"); |
| 677 | }; |
| 678 | cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx))); |
| 679 | } |
| 680 | |
| 681 | fn task_for( |
| 682 | cx: &mut VisualTestContext, |
| 683 | app: &Entity<AppState>, |
| 684 | scope: &CardScope, |
| 685 | card: &AdaptiveCard, |
| 686 | action_index: usize, |
| 687 | ) -> Option<CardTask> { |
| 688 | let action = card.actions[action_index].clone(); |
| 689 | let inputs = card.own_inputs(); |
| 690 | cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx))) |
| 691 | } |
| 692 | |
| 693 | fn object(pairs: &[(&str, &str)]) -> serde_json::Value { |
| 694 | serde_json::Value::Object( |
| 695 | pairs |
| 696 | .iter() |
| 697 | .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value))) |
| 698 | .collect(), |
| 699 | ) |
| 700 | } |
| 701 | |
| 702 | fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> { |
| 703 | cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned)) |
| 704 | } |
| 705 | |
| 706 | fn type_name( |
| 707 | cx: &mut VisualTestContext, |
| 708 | app: &Entity<AppState>, |
| 709 | scope: &CardScope, |
| 710 | text: &str, |
| 711 | ) { |
| 712 | focus_name_field(cx, app, scope); |
| 713 | cx.simulate_input(text); |
| 714 | } |
| 715 | |
| 716 | fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) { |
| 717 | let key = scope.input_key("agree"); |
| 718 | cx.update(|_, cx| { |
| 719 | app.update(cx, |state, cx| { |
| 720 | state.pick_card_input(scope, &key, "true".into(), cx) |
| 721 | }) |
| 722 | }); |
| 723 | } |
| 724 | |
| 725 | fn sent_value(task: Option<CardTask>) -> serde_json::Value { |
| 726 | match task { |
| 727 | Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value, |
| 728 | Some(CardTask::Submit(data)) => data, |
| 729 | None => serde_json::Value::Null, |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | #[gpui_kit::test] |
| 734 | fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) { |
| 735 | let (cx, app, scope, card) = open(cx, Surface::Message); |
| 736 | type_name(cx, &app, &scope, "Ada"); |
| 737 | switch_agree(cx, &app, &scope); |
| 738 | let sent = sent_value(task_for(cx, &app, &scope, &card, 0)); |
| 739 | assert_eq!( |
| 740 | sent, |
| 741 | object(&[("action", "save"), ("name", "Ada"), ("agree", "true")]) |
| 742 | ); |
| 743 | } |
| 744 | |
| 745 | #[gpui_kit::test] |
| 746 | fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) { |
| 747 | let (cx, app, scope, card) = open(cx, Surface::Message); |
| 748 | assert!(task_for(cx, &app, &scope, &card, 0).is_none()); |
| 749 | let key = scope.input_key("name"); |
| 750 | assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed")); |
| 751 | type_name(cx, &app, &scope, "A"); |
| 752 | assert_eq!(error_of(cx, &app, &key), None); |
| 753 | assert!(task_for(cx, &app, &scope, &card, 0).is_some()); |
| 754 | } |
| 755 | |
| 756 | #[gpui_kit::test] |
| 757 | fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) { |
| 758 | let (cx, app, scope, card) = open(cx, Surface::Message); |
| 759 | let sent = sent_value(task_for(cx, &app, &scope, &card, 1)); |
| 760 | assert_eq!(sent, object(&[("action", "skip")])); |
| 761 | } |
| 762 | |
| 763 | #[gpui_kit::test] |
| 764 | fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) { |
| 765 | let (cx, app, scope, card) = open(cx, Surface::Dialog); |
| 766 | type_name(cx, &app, &scope, "Ada"); |
| 767 | let sent = sent_value(task_for(cx, &app, &scope, &card, 0)); |
| 768 | assert_eq!( |
| 769 | sent, |
| 770 | object(&[("action", "save"), ("name", "Ada"), ("agree", "false")]) |
| 771 | ); |
| 772 | } |
| 773 | |
| 774 | #[gpui_kit::test] |
| 775 | fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) { |
| 776 | let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card()); |
| 777 | let key = scope.input_key("code"); |
| 778 | let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned()); |
| 779 | let Some(InputField::Line(line)) = field else { |
| 780 | panic!("code is a single line field"); |
| 781 | }; |
| 782 | cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx))); |
| 783 | cx.simulate_input("abcdef"); |
| 784 | assert_eq!( |
| 785 | cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)), |
| 786 | "abc" |
| 787 | ); |
| 788 | } |
| 789 | |
| 790 | #[gpui_kit::test] |
| 791 | fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) { |
| 792 | let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card()); |
| 793 | let key = scope.input_key("code"); |
| 794 | let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned()); |
| 795 | let Some(InputField::Line(line)) = field else { |
| 796 | panic!("code is a single line field"); |
| 797 | }; |
| 798 | cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx))); |
| 799 | cx.simulate_input("AB"); |
| 800 | let input = card.own_inputs().remove(0); |
| 801 | cx.update(|_, cx| { |
| 802 | app.update(cx, |state, cx| { |
| 803 | state.validate_card_input(&scope, &key, &input, cx) |
| 804 | }) |
| 805 | }); |
| 806 | assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only")); |
| 807 | } |
| 808 | |
| 809 | #[gpui_kit::test] |
| 810 | fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) { |
| 811 | let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card()); |
| 812 | let hour_key = scope.input_key("hour"); |
| 813 | assert!(task_for(cx, &app, &scope, &card, 0).is_none()); |
| 814 | assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early")); |
| 815 | cx.update(|_, cx| { |
| 816 | app.update(cx, |state, cx| { |
| 817 | state.pick_card_input(&scope, &hour_key, "10:15".into(), cx); |
| 818 | state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx); |
| 819 | }) |
| 820 | }); |
| 821 | let sent = sent_value(task_for(cx, &app, &scope, &card, 0)); |
| 822 | assert_eq!( |
| 823 | sent, |
| 824 | json!({ |
| 825 | "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15", |
| 826 | "count": "4", "stars": 3.5 |
| 827 | }) |
| 828 | ); |
| 829 | } |
| 830 | } |