BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / card_inputs.rs

card_inputs.rs

d39bdfed History
card_inputs.rs 20.2 KiB Download Raw
1use std::time::Duration;
2
3use gpui_kit::component::IndexPath;
4use gpui_kit::component::calendar::Matcher;
5use gpui_kit::component::date_picker::{DatePickerEvent, DatePickerState};
6use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
7use gpui_kit::component::searchable_list::{
8 SearchableListDelegate, SearchableListItem, SearchableVec,
9};
10use gpui_kit::component::select::{SelectEvent, SelectState};
11use gpui_kit::component::time_field::{TimeFieldEvent, TimeFieldState};
12use gpui_kit::*;
13use regex::Regex;
14use teams_core::{
15 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceQuery,
16 ChoiceStyle, InputChoice, TextStyle, collect_input_values, format_date, format_time,
17};
18use tokio::sync::oneshot;
19
20use crate::app_state::{AppHandle, AppState};
21use crate::card_actions::CardTask;
22use crate::card_state::{CardScope, Surface, short_reason};
23use crate::runtime;
24
25const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
26const AREA_MIN_ROWS: usize = 3;
27const AREA_MAX_ROWS: usize = 8;
28const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
29const NOT_CONNECTED: &str = "Not connected";
30const READ_ONLY: &str = "Read-only mode";
31const SEARCH_FAILED: &str = "Search failed";
32const INLINE_ACTION_SUFFIX: &str = "inline";
33
34pub type SearchAnswer = Result<Vec<InputChoice>, String>;
35
36#[derive(Clone)]
37pub struct ChoiceItem {
38 pub title: SharedString,
39 pub value: String,
40}
41
42impl 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
54pub struct RemoteSearch {
55 scope: CardScope,
56 key: String,
57 query: ChoiceQuery,
58}
59
60pub struct ChoiceList {
61 items: SearchableVec<ChoiceItem>,
62 remote: Option<RemoteSearch>,
63 search_task: Task<()>,
64}
65
66impl 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
80impl 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
140pub type ChoiceSelect = SelectState<ChoiceList>;
141
142#[derive(Clone)]
143pub enum InputField {
144 Line(Entity<InputState>),
145 Area(Entity<TextareaState>),
146 Select(Entity<ChoiceSelect>),
147 Date(Entity<DatePickerState>),
148 Time(Entity<TimeFieldState>),
149}
150
151impl 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
164pub struct FieldHandle {
165 pub field: InputField,
166 _subscriptions: Vec<Subscription>,
167}
168
169fn 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
179pub 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
200pub fn uses_select(choice: &ChoiceInput) -> bool {
201 choice.query.is_some() || (!choice.multi && choice.style != ChoiceStyle::Expanded)
202}
203
204pub fn length_pattern(max_length: usize) -> Option<Regex> {
205 Regex::new(&format!("^(?s:.{{0,{max_length}}})$")).ok()
206}
207
208pub fn inline_action_key(input_key: &str) -> String {
209 format!("{input_key}-{INLINE_ACTION_SUFFIX}")
210}
211
212impl 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}