BlueGit

ict rusty-teams

Files

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

card_inputs.rs

card_inputs.rs 14.9 KiB Download Raw
1use gpui_kit::component::IndexPath;
2use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
3use gpui_kit::component::searchable_list::{SearchableListItem, SearchableVec};
4use gpui_kit::component::select::{SelectEvent, SelectState};
5use gpui_kit::*;
6use regex::Regex;
7use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceStyle,
9 DATE_PLACEHOLDER, TIME_PLACEHOLDER, TextStyle, collect_input_values,
10};
11
12use crate::app_state::AppState;
13use crate::card_actions::CardTask;
14use crate::card_state::{CardScope, Surface};
15
16const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
17const AREA_MIN_ROWS: usize = 3;
18const AREA_MAX_ROWS: usize = 8;
19
20#[derive(Clone)]
21pub struct ChoiceItem {
22 pub title: SharedString,
23 pub value: String,
24}
25
26impl SearchableListItem for ChoiceItem {
27 type Value = String;
28
29 fn title(&self) -> SharedString {
30 self.title.clone()
31 }
32
33 fn value(&self) -> &String {
34 &self.value
35 }
36}
37
38pub type ChoiceSelect = SelectState<SearchableVec<ChoiceItem>>;
39
40#[derive(Clone)]
41pub enum InputField {
42 Line(Entity<InputState>),
43 Area(Entity<TextareaState>),
44 Select(Entity<ChoiceSelect>),
45}
46
47impl InputField {
48 pub fn text(&self, cx: &App) -> String {
49 match self {
50 InputField::Line(state) => state.read(cx).value().to_string(),
51 InputField::Area(state) => state.read(cx).value().to_string(),
52 InputField::Select(state) => {
53 state.read(cx).selected_value().cloned().unwrap_or_default()
54 }
55 }
56 }
57}
58
59pub struct FieldHandle {
60 pub field: InputField,
61 _subscription: Subscription,
62}
63
64pub fn choice_items(choice: &ChoiceInput) -> SearchableVec<ChoiceItem> {
65 SearchableVec::new(
66 choice
67 .choices
68 .iter()
69 .map(|choice| ChoiceItem {
70 title: choice.title.clone().into(),
71 value: choice.value.clone(),
72 })
73 .collect::<Vec<_>>(),
74 )
75}
76
77pub fn uses_select(choice: &ChoiceInput) -> bool {
78 !choice.multi && choice.style != ChoiceStyle::Expanded
79}
80
81impl AppState {
82 pub fn ensure_card_inputs(
83 &mut self,
84 scope: &CardScope,
85 card: &AdaptiveCard,
86 window: &mut Window,
87 cx: &mut Context<Self>,
88 ) {
89 for input in card.all_inputs() {
90 let key = scope.input_key(&input.id);
91 if self.cards.has_input(&key) {
92 continue;
93 }
94 let handle = Self::create_field(scope, &key, &input, window, cx);
95 self.cards.seed_input(key, input.initial_value(), handle);
96 }
97 }
98
99 fn create_field(
100 scope: &CardScope,
101 key: &str,
102 input: &CardInput,
103 window: &mut Window,
104 cx: &mut Context<Self>,
105 ) -> Option<FieldHandle> {
106 let value = input.initial_value();
107 let (scope, key) = (scope.clone(), key.to_owned());
108 match &input.kind {
109 CardInputKind::Text(text) if text.multiline => {
110 let placeholder = text.placeholder.clone().unwrap_or_default();
111 let state = cx.new(|cx| {
112 TextareaState::new(window, cx)
113 .auto_grow(AREA_MIN_ROWS, AREA_MAX_ROWS)
114 .placeholder(placeholder)
115 .default_value(value)
116 });
117 let subscription =
118 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
119 if matches!(event, InputEvent::Change) {
120 let text = state.read(cx).value().to_string();
121 this.edit_card_input(&scope, &key, text, cx);
122 }
123 });
124 Some(FieldHandle {
125 field: InputField::Area(state),
126 _subscription: subscription,
127 })
128 }
129 CardInputKind::Text(_)
130 | CardInputKind::Number(_)
131 | CardInputKind::Date(_)
132 | CardInputKind::Time(_) => {
133 let (placeholder, masked, numeric) = match &input.kind {
134 CardInputKind::Text(text) => (
135 text.placeholder.clone(),
136 text.style == TextStyle::Password,
137 false,
138 ),
139 CardInputKind::Number(number) => (number.placeholder.clone(), false, true),
140 CardInputKind::Date(_) => (Some(DATE_PLACEHOLDER.to_owned()), false, false),
141 _ => (Some(TIME_PLACEHOLDER.to_owned()), false, false),
142 };
143 let state = cx.new(|cx| {
144 let line = InputState::new(window, cx)
145 .placeholder(placeholder.unwrap_or_default())
146 .masked(masked)
147 .default_value(value);
148 match Regex::new(NUMBER_PATTERN) {
149 Ok(pattern) if numeric => line.pattern(pattern),
150 _ => line,
151 }
152 });
153 let subscription =
154 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
155 if matches!(event, InputEvent::Change) {
156 let text = state.read(cx).value().to_string();
157 this.edit_card_input(&scope, &key, text, cx);
158 }
159 });
160 Some(FieldHandle {
161 field: InputField::Line(state),
162 _subscription: subscription,
163 })
164 }
165 CardInputKind::Choice(choice) if uses_select(choice) => {
166 let searchable = choice.style == ChoiceStyle::Filtered;
167 let selected = choice
168 .choices
169 .iter()
170 .position(|candidate| candidate.value == value)
171 .map(|row| IndexPath::default().row(row));
172 let state = cx.new(|cx| {
173 SelectState::new(choice_items(choice), selected, window, cx)
174 .searchable(searchable)
175 });
176 let subscription = cx.subscribe(
177 &state,
178 move |this, _, event: &SelectEvent<SearchableVec<ChoiceItem>>, cx| {
179 let SelectEvent::Confirm(picked) = event;
180 this.pick_card_input(&scope, &key, picked.clone().unwrap_or_default(), cx);
181 },
182 );
183 Some(FieldHandle {
184 field: InputField::Select(state),
185 _subscription: subscription,
186 })
187 }
188 CardInputKind::Choice(_) | CardInputKind::Toggle(_) => None,
189 }
190 }
191
192 pub fn edit_card_input(
193 &mut self,
194 scope: &CardScope,
195 key: &str,
196 value: String,
197 cx: &mut Context<Self>,
198 ) {
199 if self.cards.set_input_value(key, value) {
200 self.announce_cards(scope, cx);
201 }
202 }
203
204 pub fn pick_card_input(
205 &mut self,
206 scope: &CardScope,
207 key: &str,
208 value: String,
209 cx: &mut Context<Self>,
210 ) {
211 self.cards.set_input_value(key, value);
212 self.announce_cards(scope, cx);
213 }
214
215 pub fn card_task(
216 &mut self,
217 scope: &CardScope,
218 action: CardAction,
219 inputs: &[CardInput],
220 cx: &mut Context<Self>,
221 ) -> Option<CardTask> {
222 let submits = matches!(
223 action.kind,
224 CardActionKind::Submit(_) | CardActionKind::Execute(_)
225 );
226 let values = if submits && action.collects_inputs {
227 let keys: Vec<String> = inputs
228 .iter()
229 .map(|input| scope.input_key(&input.id))
230 .collect();
231 self.cards.clear_input_errors(&keys);
232 let collected = collect_input_values(inputs, |input| {
233 self.cards.input_text(&scope.input_key(&input.id), cx)
234 });
235 match collected {
236 Ok(values) => values,
237 Err(errors) => {
238 for error in errors {
239 self.cards
240 .set_input_error(&scope.input_key(&error.id), error.message);
241 }
242 self.announce_cards(scope, cx);
243 return None;
244 }
245 }
246 } else {
247 serde_json::Map::new()
248 };
249 let action = action.with_inputs(&values);
250 Some(match (&scope.surface, &action.kind) {
251 (Surface::Dialog, CardActionKind::Submit(submit)) => {
252 CardTask::Submit(submit.data.clone())
253 }
254 _ => CardTask::Action(action),
255 })
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use std::sync::Arc;
262
263 use gpui_kit::{
264 AppContext as _, Context, Entity, IntoElement, Render, TestAppContext, VisualTestContext,
265 Window,
266 };
267 use serde_json::json;
268 use store::Store;
269 use teams_core::AdaptiveCard;
270
271 use super::InputField;
272 use crate::app_state::{AppHandle, AppState, Mode};
273 use crate::card_actions::CardTask;
274 use crate::card_state::{CardScope, Surface};
275 use crate::views::adaptive_card::card_view;
276
277 struct Harness {
278 app: Entity<AppState>,
279 scope: CardScope,
280 card: AdaptiveCard,
281 }
282
283 impl Render for Harness {
284 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
285 self.app.update(cx, |state, cx| {
286 state.ensure_card_inputs(&self.scope, &self.card, window, cx)
287 });
288 card_view(&self.card, &self.scope, cx)
289 }
290 }
291
292 fn form_card() -> AdaptiveCard {
293 let card = json!({
294 "body": [
295 {"type": "Input.Text", "id": "name", "label": "Name", "isRequired": true, "errorMessage": "Name needed"},
296 {"type": "Input.Toggle", "id": "agree", "title": "Agree"}
297 ],
298 "actions": [
299 {"type": "Action.Submit", "title": "Save", "data": {"action": "save"}},
300 {"type": "Action.Submit", "title": "Skip", "associatedInputs": "none", "data": {"action": "skip"}}
301 ]
302 });
303 AdaptiveCard::parse(&card.to_string()).unwrap()
304 }
305
306 fn open(
307 cx: &mut TestAppContext,
308 surface: Surface,
309 ) -> (
310 &mut VisualTestContext,
311 Entity<AppState>,
312 CardScope,
313 AdaptiveCard,
314 ) {
315 cx.update(gpui_kit::init);
316 let store = Arc::new(Store::open_in_memory().unwrap());
317 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
318 cx.update(|cx| cx.set_global(AppHandle(app.clone())));
319 let scope = CardScope {
320 surface,
321 ..CardScope::message("19:chat@thread.v2", "m1", 0)
322 };
323 let card = form_card();
324 let (_, window_cx) = cx.add_window_view({
325 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
326 move |_, _| Harness { app, scope, card }
327 });
328 window_cx.update(|window, cx| window.draw(cx).clear(cx));
329 (window_cx, app, scope, card)
330 }
331
332 fn focus_name_field(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
333 let key = scope.input_key("name");
334 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
335 let Some(InputField::Line(line)) = field else {
336 panic!("name is a single line field");
337 };
338 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
339 }
340
341 fn task_for(
342 cx: &mut VisualTestContext,
343 app: &Entity<AppState>,
344 scope: &CardScope,
345 card: &AdaptiveCard,
346 action_index: usize,
347 ) -> Option<CardTask> {
348 let action = card.actions[action_index].clone();
349 let inputs = card.own_inputs();
350 cx.update(|_, cx| app.update(cx, |state, cx| state.card_task(scope, action, &inputs, cx)))
351 }
352
353 fn object(pairs: &[(&str, &str)]) -> serde_json::Value {
354 serde_json::Value::Object(
355 pairs
356 .iter()
357 .map(|(key, value)| ((*key).to_owned(), serde_json::Value::from(*value)))
358 .collect(),
359 )
360 }
361
362 fn error_of(cx: &mut VisualTestContext, app: &Entity<AppState>, key: &str) -> Option<String> {
363 cx.update(|_, cx| app.read(cx).cards.input_error(key).map(str::to_owned))
364 }
365
366 fn type_name(
367 cx: &mut VisualTestContext,
368 app: &Entity<AppState>,
369 scope: &CardScope,
370 text: &str,
371 ) {
372 focus_name_field(cx, app, scope);
373 cx.simulate_input(text);
374 }
375
376 fn switch_agree(cx: &mut VisualTestContext, app: &Entity<AppState>, scope: &CardScope) {
377 let key = scope.input_key("agree");
378 cx.update(|_, cx| {
379 app.update(cx, |state, cx| {
380 state.pick_card_input(scope, &key, "true".into(), cx)
381 })
382 });
383 }
384
385 fn sent_value(task: Option<CardTask>) -> serde_json::Value {
386 match task {
387 Some(CardTask::Action(action)) => action.invoke_payload().unwrap().value,
388 Some(CardTask::Submit(data)) => data,
389 None => serde_json::Value::Null,
390 }
391 }
392
393 #[gpui_kit::test]
394 fn typed_text_and_toggle_are_sent_with_the_action_data(cx: &mut TestAppContext) {
395 let (cx, app, scope, card) = open(cx, Surface::Message);
396 type_name(cx, &app, &scope, "Ada");
397 switch_agree(cx, &app, &scope);
398 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
399 assert_eq!(
400 sent,
401 object(&[("action", "save"), ("name", "Ada"), ("agree", "true")])
402 );
403 }
404
405 #[gpui_kit::test]
406 fn an_empty_required_input_blocks_the_send_until_it_changes(cx: &mut TestAppContext) {
407 let (cx, app, scope, card) = open(cx, Surface::Message);
408 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
409 let key = scope.input_key("name");
410 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Name needed"));
411 type_name(cx, &app, &scope, "A");
412 assert_eq!(error_of(cx, &app, &key), None);
413 assert!(task_for(cx, &app, &scope, &card, 0).is_some());
414 }
415
416 #[gpui_kit::test]
417 fn associated_inputs_none_skips_collection_and_validation(cx: &mut TestAppContext) {
418 let (cx, app, scope, card) = open(cx, Surface::Message);
419 let sent = sent_value(task_for(cx, &app, &scope, &card, 1));
420 assert_eq!(sent, object(&[("action", "skip")]));
421 }
422
423 #[gpui_kit::test]
424 fn a_dialog_submit_carries_the_collected_values(cx: &mut TestAppContext) {
425 let (cx, app, scope, card) = open(cx, Surface::Dialog);
426 type_name(cx, &app, &scope, "Ada");
427 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
428 assert_eq!(
429 sent,
430 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
431 );
432 }
433}