BlueGit

ict rusty-teams

feat(cards): input fields in Adaptive Cards and card dialogs

- Input.Text (multiline, password, regex), Number, Date, Time, Toggle, ChoiceSet (dropdown, radios, checkboxes)
- Labels with required marker; isRequired, regex, min/max and format are checked before sending, errors show under the field
- Submit and Execute merge the values of the card and its parent cards into the action data; associatedInputs none is honoured
- Card task dialogs get the same fields; a replaced card resets its values

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
dd09cfbec36f9ce5fd5f4c494af80ba7e09814a1
Parent
14aa9993
18 files changed +1646 −26
Cargo.lock +1 −0
@@ -266,6 +266,7 @@ dependencies = [
266 266 "graph",
267 267 "image",
268 268 "raw-window-handle",
269 "regex",
269 270 "rodio",
270 271 "serde",
271 272 "serde_json",
@@ -266,6 +266,7 @@ dependencies = [
266 "graph",
266 "graph",
267 "image",
267 "image",
268 "raw-window-handle",
268 "raw-window-handle",
269 "regex",
269 "rodio",
270 "rodio",
270 "serde",
271 "serde",
271 "serde_json",
272 "serde_json",
README.md +1 −1
@@ -15,7 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15 15 - Send, edit, delete, react, quote-reply, @mentions
16 16 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17 17 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; task dialogs)
18 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19 19 - Read receipts, presence (last known status shown at start), unread jump
20 20 - Select and copy message text, `Ctrl+A` in the composer
21 21 - Local full-text search and a `Ctrl+K` switcher, served from the cache
@@ -15,7 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15- Send, edit, delete, react, quote-reply, @mentions
15- Send, edit, delete, react, quote-reply, @mentions
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; task dialogs)
18- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19- Read receipts, presence (last known status shown at start), unread jump
19- Read receipts, presence (last known status shown at start), unread jump
20- Select and copy message text, `Ctrl+A` in the composer
20- Select and copy message text, `Ctrl+A` in the composer
21- Local full-text search and a `Ctrl+K` switcher, served from the cache
21- Local full-text search and a `Ctrl+K` switcher, served from the cache
ROADMAP.md +1 −1
@@ -75,7 +75,7 @@ Feature parity with the Microsoft Teams desktop client.
75 75 | Unread jump with New divider | Done | |
76 76 | Read receipts | Done | |
77 77 | Select and copy message text | Done | |
78 | Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Missing: input fields |
78 | Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
79 79 | Typing indicator | Missing | Event arrives, ignored |
80 80 | Link previews | Missing | |
81 81 | Loop components | Missing | |
@@ -75,7 +75,7 @@ Feature parity with the Microsoft Teams desktop client.
75| Unread jump with New divider | Done | |
75| Unread jump with New divider | Done | |
76| Read receipts | Done | |
76| Read receipts | Done | |
77| Select and copy message text | Done | |
77| Select and copy message text | Done | |
78| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Missing: input fields |
78| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
79| Typing indicator | Missing | Event arrives, ignored |
79| Typing indicator | Missing | Event arrives, ignored |
80| Link previews | Missing | |
80| Link previews | Missing | |
81| Loop components | Missing | |
81| Loop components | Missing | |
crates/app/Cargo.toml +1 −0
@@ -22,6 +22,7 @@ chatsvc.workspace = true
22 22 chrono.workspace = true
23 23 directories.workspace = true
24 24 gpui-kit.workspace = true
25 regex.workspace = true
25 26 reqwest_client.workspace = true
26 27 graph.workspace = true
27 28 serde.workspace = true
@@ -22,6 +22,7 @@ chatsvc.workspace = true
22chrono.workspace = true
22chrono.workspace = true
23directories.workspace = true
23directories.workspace = true
24gpui-kit.workspace = true
24gpui-kit.workspace = true
25regex.workspace = true
25reqwest_client.workspace = true
26reqwest_client.workspace = true
26graph.workspace = true
27graph.workspace = true
27serde.workspace = true
28serde.workspace = true
crates/app/src/card_actions.rs +8 −9
@@ -1,7 +1,7 @@
1 1 use gpui_kit::*;
2 2 use serde_json::Value;
3 3 use teams_core::{
4 AdaptiveCard, CardAction, CardActionKind, CardActionOutcome, ChatApp, TaskDialog,
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog,
5 5 TaskDialogKind, adaptive_cards,
6 6 };
7 7 use tokio::sync::oneshot;
@@ -33,17 +33,15 @@ impl AppState {
33 33 scope: CardScope,
34 34 action_key: String,
35 35 action: CardAction,
36 inputs: Vec<CardInput>,
36 37 cx: &mut Context<Self>,
37 38 ) {
38 let task = match (&scope.surface, &action.kind) {
39 (Surface::Dialog, CardActionKind::Submit(submit)) => {
40 CardTask::Submit(submit.data.clone())
41 }
42 _ => CardTask::Action(action),
43 };
44 39 if self.cards.is_busy(&action_key) {
45 40 return;
46 41 }
42 let Some(task) = self.card_task(&scope, action, &inputs, cx) else {
43 return;
44 };
47 45 self.cards.set_phase(&action_key, ActionPhase::Busy);
48 46 self.cards.clear_note(&scope.card_key());
49 47 self.announce_cards(&scope, cx);
@@ -224,7 +222,7 @@ impl AppState {
224 222 .detach();
225 223 }
226 224
227 fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
225 pub(crate) fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
228 226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
229 227 cx.notify();
230 228 }
@@ -233,6 +231,7 @@ impl AppState {
233 231 let Some(card) = AdaptiveCard::parse(json) else {
234 232 return false;
235 233 };
234 self.cards.clear_card(&scope.card_key());
236 235 if scope.surface == Surface::Dialog {
237 236 if let Some(dialog) = self.task_dialog.as_mut() {
238 237 dialog.card = card;
@@ -283,7 +282,7 @@ impl AppState {
283 282 let Some(card) = AdaptiveCard::parse(&json) else {
284 283 return;
285 284 };
286 self.cards.clear_card(&scope.card_key());
285 self.cards.clear_card(&CardScope::dialog_key());
287 286 self.task_dialog = Some(TaskDialogState {
288 287 title,
289 288 card,
@@ -1,7 +1,7 @@
1use gpui_kit::*;
1use gpui_kit::*;
2use serde_json::Value;
2use serde_json::Value;
3use teams_core::{
3use teams_core::{
4 AdaptiveCard, CardAction, CardActionKind, CardActionOutcome, ChatApp, TaskDialog,
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog,
5 TaskDialogKind, adaptive_cards,
5 TaskDialogKind, adaptive_cards,
6};
6};
7use tokio::sync::oneshot;
7use tokio::sync::oneshot;
@@ -33,17 +33,15 @@ impl AppState {
33 scope: CardScope,
33 scope: CardScope,
34 action_key: String,
34 action_key: String,
35 action: CardAction,
35 action: CardAction,
36 inputs: Vec<CardInput>,
36 cx: &mut Context<Self>,
37 cx: &mut Context<Self>,
37 ) {
38 ) {
38 let task = match (&scope.surface, &action.kind) {
39 (Surface::Dialog, CardActionKind::Submit(submit)) => {
40 CardTask::Submit(submit.data.clone())
41 }
42 _ => CardTask::Action(action),
43 };
44 if self.cards.is_busy(&action_key) {
39 if self.cards.is_busy(&action_key) {
45 return;
40 return;
46 }
41 }
42 let Some(task) = self.card_task(&scope, action, &inputs, cx) else {
43 return;
44 };
47 self.cards.set_phase(&action_key, ActionPhase::Busy);
45 self.cards.set_phase(&action_key, ActionPhase::Busy);
48 self.cards.clear_note(&scope.card_key());
46 self.cards.clear_note(&scope.card_key());
49 self.announce_cards(&scope, cx);
47 self.announce_cards(&scope, cx);
@@ -224,7 +222,7 @@ impl AppState {
224 .detach();
222 .detach();
225 }
223 }
226
224
227 fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
225 pub(crate) fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
228 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
229 cx.notify();
227 cx.notify();
230 }
228 }
@@ -233,6 +231,7 @@ impl AppState {
233 let Some(card) = AdaptiveCard::parse(json) else {
231 let Some(card) = AdaptiveCard::parse(json) else {
234 return false;
232 return false;
235 };
233 };
234 self.cards.clear_card(&scope.card_key());
236 if scope.surface == Surface::Dialog {
235 if scope.surface == Surface::Dialog {
237 if let Some(dialog) = self.task_dialog.as_mut() {
236 if let Some(dialog) = self.task_dialog.as_mut() {
238 dialog.card = card;
237 dialog.card = card;
@@ -283,7 +282,7 @@ impl AppState {
283 let Some(card) = AdaptiveCard::parse(&json) else {
282 let Some(card) = AdaptiveCard::parse(&json) else {
284 return;
283 return;
285 };
284 };
286 self.cards.clear_card(&scope.card_key());
285 self.cards.clear_card(&CardScope::dialog_key());
287 self.task_dialog = Some(TaskDialogState {
286 self.task_dialog = Some(TaskDialogState {
288 title,
287 title,
289 card,
288 card,
crates/app/src/card_inputs.rs added +433 −0
@@ -0,0 +1,433 @@
1 use gpui_kit::component::IndexPath;
2 use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
3 use gpui_kit::component::searchable_list::{SearchableListItem, SearchableVec};
4 use gpui_kit::component::select::{SelectEvent, SelectState};
5 use gpui_kit::*;
6 use regex::Regex;
7 use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceStyle,
9 DATE_PLACEHOLDER, TIME_PLACEHOLDER, TextStyle, collect_input_values,
10 };
11
12 use crate::app_state::AppState;
13 use crate::card_actions::CardTask;
14 use crate::card_state::{CardScope, Surface};
15
16 const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
17 const AREA_MIN_ROWS: usize = 3;
18 const AREA_MAX_ROWS: usize = 8;
19
20 #[derive(Clone)]
21 pub struct ChoiceItem {
22 pub title: SharedString,
23 pub value: String,
24 }
25
26 impl 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
38 pub type ChoiceSelect = SelectState<SearchableVec<ChoiceItem>>;
39
40 #[derive(Clone)]
41 pub enum InputField {
42 Line(Entity<InputState>),
43 Area(Entity<TextareaState>),
44 Select(Entity<ChoiceSelect>),
45 }
46
47 impl 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
59 pub struct FieldHandle {
60 pub field: InputField,
61 _subscription: Subscription,
62 }
63
64 pub 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
77 pub fn uses_select(choice: &ChoiceInput) -> bool {
78 !choice.multi && choice.style != ChoiceStyle::Expanded
79 }
80
81 impl 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)]
260 mod 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 }
@@ -0,0 +1,433 @@
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}
crates/app/src/card_state.rs +61 −0
@@ -3,6 +3,10 @@ use std::time::Duration;
3 3
4 4 use teams_core::AdaptiveCard;
5 5
6 use gpui_kit::App;
7
8 use crate::card_inputs::{FieldHandle, InputField};
9
6 10 const DIALOG_KEY: &str = "task-dialog";
7 11 pub const DONE_HOLD: Duration = Duration::from_millis(1600);
8 12 pub const MAX_REASON_CHARS: usize = 160;
@@ -66,6 +70,10 @@ impl CardScope {
66 70 }
67 71 }
68 72
73 pub fn input_key(&self, input_id: &str) -> String {
74 format!("{}/{input_id}", self.card_key())
75 }
76
69 77 pub fn dialog_key() -> String {
70 78 DIALOG_KEY.to_owned()
71 79 }
@@ -78,6 +86,9 @@ pub struct CardState {
78 86 open_cards: HashMap<String, usize>,
79 87 notes: HashMap<String, String>,
80 88 overrides: HashMap<(String, String), CardOverride>,
89 input_values: HashMap<String, String>,
90 input_errors: HashMap<String, String>,
91 input_fields: HashMap<String, FieldHandle>,
81 92 }
82 93
83 94 impl CardState {
@@ -104,6 +115,56 @@ impl CardState {
104 115 self.visibility.retain(|key, _| !key.starts_with(card_key));
105 116 self.open_cards.retain(|key, _| !key.starts_with(card_key));
106 117 self.notes.remove(card_key);
118 self.input_values.retain(|key, _| !key.starts_with(card_key));
119 self.input_errors.retain(|key, _| !key.starts_with(card_key));
120 self.input_fields.retain(|key, _| !key.starts_with(card_key));
121 }
122
123 pub fn has_input(&self, input_key: &str) -> bool {
124 self.input_values.contains_key(input_key)
125 }
126
127 pub fn seed_input(&mut self, input_key: String, value: String, field: Option<FieldHandle>) {
128 if let Some(field) = field {
129 self.input_fields.insert(input_key.clone(), field);
130 }
131 self.input_values.insert(input_key, value);
132 }
133
134 pub fn input_value(&self, input_key: &str) -> &str {
135 self.input_values
136 .get(input_key)
137 .map_or("", String::as_str)
138 }
139
140 pub fn input_text(&self, input_key: &str, cx: &App) -> String {
141 match self.input_fields.get(input_key) {
142 Some(handle) => handle.field.text(cx),
143 None => self.input_value(input_key).to_owned(),
144 }
145 }
146
147 pub fn input_field(&self, input_key: &str) -> Option<&InputField> {
148 self.input_fields.get(input_key).map(|handle| &handle.field)
149 }
150
151 pub fn set_input_value(&mut self, input_key: &str, value: String) -> bool {
152 self.input_values.insert(input_key.to_owned(), value);
153 self.input_errors.remove(input_key).is_some()
154 }
155
156 pub fn input_error(&self, input_key: &str) -> Option<&str> {
157 self.input_errors.get(input_key).map(String::as_str)
158 }
159
160 pub fn set_input_error(&mut self, input_key: &str, message: String) {
161 self.input_errors.insert(input_key.to_owned(), message);
162 }
163
164 pub fn clear_input_errors(&mut self, input_keys: &[String]) {
165 for input_key in input_keys {
166 self.input_errors.remove(input_key);
167 }
107 168 }
108 169
109 170 pub fn is_visible(&self, element_key: &str, initial: bool) -> bool {
@@ -3,6 +3,10 @@ use std::time::Duration;
3
3
4use teams_core::AdaptiveCard;
4use teams_core::AdaptiveCard;
5
5
6use gpui_kit::App;
7
8use crate::card_inputs::{FieldHandle, InputField};
9
6const DIALOG_KEY: &str = "task-dialog";
10const DIALOG_KEY: &str = "task-dialog";
7pub const DONE_HOLD: Duration = Duration::from_millis(1600);
11pub const DONE_HOLD: Duration = Duration::from_millis(1600);
8pub const MAX_REASON_CHARS: usize = 160;
12pub const MAX_REASON_CHARS: usize = 160;
@@ -66,6 +70,10 @@ impl CardScope {
66 }
70 }
67 }
71 }
68
72
73 pub fn input_key(&self, input_id: &str) -> String {
74 format!("{}/{input_id}", self.card_key())
75 }
76
69 pub fn dialog_key() -> String {
77 pub fn dialog_key() -> String {
70 DIALOG_KEY.to_owned()
78 DIALOG_KEY.to_owned()
71 }
79 }
@@ -78,6 +86,9 @@ pub struct CardState {
78 open_cards: HashMap<String, usize>,
86 open_cards: HashMap<String, usize>,
79 notes: HashMap<String, String>,
87 notes: HashMap<String, String>,
80 overrides: HashMap<(String, String), CardOverride>,
88 overrides: HashMap<(String, String), CardOverride>,
89 input_values: HashMap<String, String>,
90 input_errors: HashMap<String, String>,
91 input_fields: HashMap<String, FieldHandle>,
81}
92}
82
93
83impl CardState {
94impl CardState {
@@ -104,6 +115,56 @@ impl CardState {
104 self.visibility.retain(|key, _| !key.starts_with(card_key));
115 self.visibility.retain(|key, _| !key.starts_with(card_key));
105 self.open_cards.retain(|key, _| !key.starts_with(card_key));
116 self.open_cards.retain(|key, _| !key.starts_with(card_key));
106 self.notes.remove(card_key);
117 self.notes.remove(card_key);
118 self.input_values.retain(|key, _| !key.starts_with(card_key));
119 self.input_errors.retain(|key, _| !key.starts_with(card_key));
120 self.input_fields.retain(|key, _| !key.starts_with(card_key));
121 }
122
123 pub fn has_input(&self, input_key: &str) -> bool {
124 self.input_values.contains_key(input_key)
125 }
126
127 pub fn seed_input(&mut self, input_key: String, value: String, field: Option<FieldHandle>) {
128 if let Some(field) = field {
129 self.input_fields.insert(input_key.clone(), field);
130 }
131 self.input_values.insert(input_key, value);
132 }
133
134 pub fn input_value(&self, input_key: &str) -> &str {
135 self.input_values
136 .get(input_key)
137 .map_or("", String::as_str)
138 }
139
140 pub fn input_text(&self, input_key: &str, cx: &App) -> String {
141 match self.input_fields.get(input_key) {
142 Some(handle) => handle.field.text(cx),
143 None => self.input_value(input_key).to_owned(),
144 }
145 }
146
147 pub fn input_field(&self, input_key: &str) -> Option<&InputField> {
148 self.input_fields.get(input_key).map(|handle| &handle.field)
149 }
150
151 pub fn set_input_value(&mut self, input_key: &str, value: String) -> bool {
152 self.input_values.insert(input_key.to_owned(), value);
153 self.input_errors.remove(input_key).is_some()
154 }
155
156 pub fn input_error(&self, input_key: &str) -> Option<&str> {
157 self.input_errors.get(input_key).map(String::as_str)
158 }
159
160 pub fn set_input_error(&mut self, input_key: &str, message: String) {
161 self.input_errors.insert(input_key.to_owned(), message);
162 }
163
164 pub fn clear_input_errors(&mut self, input_keys: &[String]) {
165 for input_key in input_keys {
166 self.input_errors.remove(input_key);
167 }
107 }
168 }
108
169
109 pub fn is_visible(&self, element_key: &str, initial: bool) -> bool {
170 pub fn is_visible(&self, element_key: &str, initial: bool) -> bool {
crates/app/src/demo.rs +53 −5
@@ -717,6 +717,13 @@ fn bot_messages() -> Vec<MessageRecord> {
717 717 ]}
718 718 ]
719 719 });
720 vec![
721 bot_card_message("b1", at(0, 13, 45), &card),
722 bot_card_message("b2", at(0, 13, 52), &input_card()),
723 ]
724 }
725
726 fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
720 727 let attachments = serde_json::json!([{
721 728 "content_type": "application/vnd.microsoft.card.adaptive",
722 729 "name": null,
@@ -727,11 +734,11 @@ fn bot_messages() -> Vec<MessageRecord> {
727 734 let mut record = with_attachments(
728 735 message(
729 736 BOT_CHAT,
730 "b1",
737 id,
731 738 None,
732 739 ("", BOT_NAME),
733 at(0, 13, 45),
734 "<attachment id=\"b1\"></attachment>",
740 time,
741 &format!("<attachment id=\"{id}\"></attachment>"),
735 742 "[]",
736 743 false,
737 744 ),
@@ -739,7 +746,44 @@ fn bot_messages() -> Vec<MessageRecord> {
739 746 );
740 747 record.sender_id = None;
741 748 record.sender_application_id = Some(BOT_ID.to_owned());
742 vec![record]
749 record
750 }
751
752 fn input_card() -> serde_json::Value {
753 serde_json::json!({
754 "type": "AdaptiveCard",
755 "body": [
756 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
757 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
758 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
759 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
760 {"type": "ColumnSet", "columns": [
761 {"type": "Column", "width": "stretch", "items": [
762 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
763 ]},
764 {"type": "Column", "width": "stretch", "items": [
765 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
766 ]},
767 {"type": "Column", "width": "stretch", "items": [
768 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
769 ]}
770 ]},
771 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
772 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
773 ]},
774 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
775 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
776 ]},
777 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
778 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
779 ]},
780 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
781 ],
782 "actions": [
783 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
784 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
785 ]
786 })
743 787 }
744 788
745 789 fn bot_app() -> ChatApp {
@@ -788,7 +832,11 @@ fn settings_card() -> serde_json::Value {
788 832 "type": "AdaptiveCard",
789 833 "body": [
790 834 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
791 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."}
835 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
836 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
837 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
838 ]},
839 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
792 840 ],
793 841 "actions": [
794 842 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
@@ -717,6 +717,13 @@ fn bot_messages() -> Vec<MessageRecord> {
717 ]}
717 ]}
718 ]
718 ]
719 });
719 });
720 vec![
721 bot_card_message("b1", at(0, 13, 45), &card),
722 bot_card_message("b2", at(0, 13, 52), &input_card()),
723 ]
724}
725
726fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
720 let attachments = serde_json::json!([{
727 let attachments = serde_json::json!([{
721 "content_type": "application/vnd.microsoft.card.adaptive",
728 "content_type": "application/vnd.microsoft.card.adaptive",
722 "name": null,
729 "name": null,
@@ -727,11 +734,11 @@ fn bot_messages() -> Vec<MessageRecord> {
727 let mut record = with_attachments(
734 let mut record = with_attachments(
728 message(
735 message(
729 BOT_CHAT,
736 BOT_CHAT,
730 "b1",
737 id,
731 None,
738 None,
732 ("", BOT_NAME),
739 ("", BOT_NAME),
733 at(0, 13, 45),
740 time,
734 "<attachment id=\"b1\"></attachment>",
741 &format!("<attachment id=\"{id}\"></attachment>"),
735 "[]",
742 "[]",
736 false,
743 false,
737 ),
744 ),
@@ -739,7 +746,44 @@ fn bot_messages() -> Vec<MessageRecord> {
739 );
746 );
740 record.sender_id = None;
747 record.sender_id = None;
741 record.sender_application_id = Some(BOT_ID.to_owned());
748 record.sender_application_id = Some(BOT_ID.to_owned());
742 vec![record]
749 record
750}
751
752fn input_card() -> serde_json::Value {
753 serde_json::json!({
754 "type": "AdaptiveCard",
755 "body": [
756 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
757 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
758 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
759 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
760 {"type": "ColumnSet", "columns": [
761 {"type": "Column", "width": "stretch", "items": [
762 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
763 ]},
764 {"type": "Column", "width": "stretch", "items": [
765 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
766 ]},
767 {"type": "Column", "width": "stretch", "items": [
768 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
769 ]}
770 ]},
771 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
772 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
773 ]},
774 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
775 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
776 ]},
777 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
778 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
779 ]},
780 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
781 ],
782 "actions": [
783 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
784 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
785 ]
786 })
743}
787}
744
788
745fn bot_app() -> ChatApp {
789fn bot_app() -> ChatApp {
@@ -788,7 +832,11 @@ fn settings_card() -> serde_json::Value {
788 "type": "AdaptiveCard",
832 "type": "AdaptiveCard",
789 "body": [
833 "body": [
790 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
834 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
791 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."}
835 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
836 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
837 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
838 ]},
839 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
792 ],
840 ],
793 "actions": [
841 "actions": [
794 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
842 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
crates/app/src/main.rs +1 −0
@@ -9,6 +9,7 @@ mod assets;
9 9 mod avatar_image;
10 10 mod backend;
11 11 mod card_actions;
12 mod card_inputs;
12 13 mod chat_actions;
13 14 mod crash_log;
14 15 mod card_state;
@@ -9,6 +9,7 @@ mod assets;
9mod avatar_image;
9mod avatar_image;
10mod backend;
10mod backend;
11mod card_actions;
11mod card_actions;
12mod card_inputs;
12mod chat_actions;
13mod chat_actions;
13mod crash_log;
14mod crash_log;
14mod card_state;
15mod card_state;
crates/app/src/views/adaptive_card.rs +52 −8
@@ -1,16 +1,18 @@
1 1 use std::collections::HashMap;
2 use std::rc::Rc;
2 3
3 4 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4 5 use gpui_kit::prelude::FluentBuilder as _;
5 6 use gpui_kit::*;
6 7 use teams_core::{
7 8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
8 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 10 VerticalAlignment,
10 11 };
11 12
13 use super::card_input::input_view;
12 14 use super::widgets::symbol;
13 use crate::app_state::AppHandle;
15 use crate::app_state::{AppHandle, AppState};
14 16 use crate::card_state::{ActionPhase, CardScope, CardState};
15 17 use crate::render::{layout_blocks, render_blocks};
16 18 use crate::theme;
@@ -49,7 +51,8 @@ struct CardContext<'a> {
49 51 scope: &'a CardScope,
50 52 state: &'a CardState,
51 53 root_key: String,
52 initial_visibility: HashMap<String, bool>,
54 initial_visibility: Rc<HashMap<String, bool>>,
55 inputs: Vec<CardInput>,
53 56 }
54 57
55 58 impl<'a> CardContext<'a> {
@@ -59,7 +62,21 @@ impl<'a> CardContext<'a> {
59 62 scope,
60 63 state: &cx.global::<AppHandle>().0.read(cx).cards,
61 64 root_key: scope.card_key(),
62 initial_visibility: card.element_visibility(),
65 initial_visibility: Rc::new(card.element_visibility()),
66 inputs: card.own_inputs(),
67 }
68 }
69
70 fn nested(&self, card: &AdaptiveCard) -> CardContext<'a> {
71 let mut inputs = self.inputs.clone();
72 inputs.extend(card.own_inputs());
73 CardContext {
74 cx: self.cx,
75 scope: self.scope,
76 state: self.state,
77 root_key: self.root_key.clone(),
78 initial_visibility: self.initial_visibility.clone(),
79 inputs,
63 80 }
64 81 }
65 82
@@ -89,6 +106,25 @@ pub fn cards_view(
89 106 .collect()
90 107 }
91 108
109 pub fn ensure_cards_inputs(
110 app: &Entity<AppState>,
111 cards: &[AdaptiveCard],
112 conversation_id: &str,
113 message_id: &str,
114 window: &mut Window,
115 cx: &mut App,
116 ) {
117 if cards.is_empty() {
118 return;
119 }
120 app.update(cx, |state, cx| {
121 for (index, card) in cards.iter().enumerate() {
122 let scope = CardScope::message(conversation_id, message_id, index);
123 state.ensure_card_inputs(&scope, card, window, cx);
124 }
125 });
126 }
127
92 128 pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
93 129 let context = CardContext::new(card, scope, cx);
94 130 let id = scope.card_key();
@@ -196,6 +232,7 @@ fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyEl
196 232 }
197 233 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
198 234 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
235 CardElement::Input(input) => input_view(input, context.scope, context.state),
199 236 }
200 237 }
201 238
@@ -387,6 +424,7 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
387 424 )
388 425 .when_some(open_card, |column, card| {
389 426 let nested_id = format!("{id}-show");
427 let nested_context = context.nested(card);
390 428 column.child(
391 429 v_flex()
392 430 .w_full()
@@ -394,12 +432,12 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
394 432 .gap(px(ACTION_GAP))
395 433 .rounded(px(CONTAINER_RADIUS))
396 434 .bg(theme::surface_raised())
397 .child(items_view(&card.items, &nested_id, context))
435 .child(items_view(&card.items, &nested_id, &nested_context))
398 436 .when(!card.actions.is_empty(), |nested| {
399 437 nested.child(actions_view(
400 438 &card.actions,
401 439 &format!("{nested_id}-actions"),
402 context,
440 &nested_context,
403 441 ))
404 442 }),
405 443 )
@@ -464,11 +502,17 @@ fn action_button(
464 502 }
465 503 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
466 504 let action = action.clone();
505 let inputs = context.inputs.clone();
467 506 enabled.on_click(move |_, _, cx| {
468 507 cx.stop_propagation();
469 let (scope, action, button_id) = (scope.clone(), action.clone(), button_id.clone());
508 let (scope, action, button_id, inputs) = (
509 scope.clone(),
510 action.clone(),
511 button_id.clone(),
512 inputs.clone(),
513 );
470 514 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
471 state.run_card_action(scope, button_id, action, cx)
515 state.run_card_action(scope, button_id, action, inputs, cx)
472 516 });
473 517 })
474 518 }
@@ -1,16 +1,18 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::rc::Rc;
2
3
3use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use gpui_kit::*;
6use teams_core::{
7use teams_core::{
7 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
8 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 VerticalAlignment,
10 VerticalAlignment,
10};
11};
11
12
13use super::card_input::input_view;
12use super::widgets::symbol;
14use super::widgets::symbol;
13use crate::app_state::AppHandle;
15use crate::app_state::{AppHandle, AppState};
14use crate::card_state::{ActionPhase, CardScope, CardState};
16use crate::card_state::{ActionPhase, CardScope, CardState};
15use crate::render::{layout_blocks, render_blocks};
17use crate::render::{layout_blocks, render_blocks};
16use crate::theme;
18use crate::theme;
@@ -49,7 +51,8 @@ struct CardContext<'a> {
49 scope: &'a CardScope,
51 scope: &'a CardScope,
50 state: &'a CardState,
52 state: &'a CardState,
51 root_key: String,
53 root_key: String,
52 initial_visibility: HashMap<String, bool>,
54 initial_visibility: Rc<HashMap<String, bool>>,
55 inputs: Vec<CardInput>,
53}
56}
54
57
55impl<'a> CardContext<'a> {
58impl<'a> CardContext<'a> {
@@ -59,7 +62,21 @@ impl<'a> CardContext<'a> {
59 scope,
62 scope,
60 state: &cx.global::<AppHandle>().0.read(cx).cards,
63 state: &cx.global::<AppHandle>().0.read(cx).cards,
61 root_key: scope.card_key(),
64 root_key: scope.card_key(),
62 initial_visibility: card.element_visibility(),
65 initial_visibility: Rc::new(card.element_visibility()),
66 inputs: card.own_inputs(),
67 }
68 }
69
70 fn nested(&self, card: &AdaptiveCard) -> CardContext<'a> {
71 let mut inputs = self.inputs.clone();
72 inputs.extend(card.own_inputs());
73 CardContext {
74 cx: self.cx,
75 scope: self.scope,
76 state: self.state,
77 root_key: self.root_key.clone(),
78 initial_visibility: self.initial_visibility.clone(),
79 inputs,
63 }
80 }
64 }
81 }
65
82
@@ -89,6 +106,25 @@ pub fn cards_view(
89 .collect()
106 .collect()
90}
107}
91
108
109pub fn ensure_cards_inputs(
110 app: &Entity<AppState>,
111 cards: &[AdaptiveCard],
112 conversation_id: &str,
113 message_id: &str,
114 window: &mut Window,
115 cx: &mut App,
116) {
117 if cards.is_empty() {
118 return;
119 }
120 app.update(cx, |state, cx| {
121 for (index, card) in cards.iter().enumerate() {
122 let scope = CardScope::message(conversation_id, message_id, index);
123 state.ensure_card_inputs(&scope, card, window, cx);
124 }
125 });
126}
127
92pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
128pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
93 let context = CardContext::new(card, scope, cx);
129 let context = CardContext::new(card, scope, cx);
94 let id = scope.card_key();
130 let id = scope.card_key();
@@ -196,6 +232,7 @@ fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyEl
196 }
232 }
197 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
233 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
198 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
234 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
235 CardElement::Input(input) => input_view(input, context.scope, context.state),
199 }
236 }
200}
237}
201
238
@@ -387,6 +424,7 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
387 )
424 )
388 .when_some(open_card, |column, card| {
425 .when_some(open_card, |column, card| {
389 let nested_id = format!("{id}-show");
426 let nested_id = format!("{id}-show");
427 let nested_context = context.nested(card);
390 column.child(
428 column.child(
391 v_flex()
429 v_flex()
392 .w_full()
430 .w_full()
@@ -394,12 +432,12 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
394 .gap(px(ACTION_GAP))
432 .gap(px(ACTION_GAP))
395 .rounded(px(CONTAINER_RADIUS))
433 .rounded(px(CONTAINER_RADIUS))
396 .bg(theme::surface_raised())
434 .bg(theme::surface_raised())
397 .child(items_view(&card.items, &nested_id, context))
435 .child(items_view(&card.items, &nested_id, &nested_context))
398 .when(!card.actions.is_empty(), |nested| {
436 .when(!card.actions.is_empty(), |nested| {
399 nested.child(actions_view(
437 nested.child(actions_view(
400 &card.actions,
438 &card.actions,
401 &format!("{nested_id}-actions"),
439 &format!("{nested_id}-actions"),
402 context,
440 &nested_context,
403 ))
441 ))
404 }),
442 }),
405 )
443 )
@@ -464,11 +502,17 @@ fn action_button(
464 }
502 }
465 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
503 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
466 let action = action.clone();
504 let action = action.clone();
505 let inputs = context.inputs.clone();
467 enabled.on_click(move |_, _, cx| {
506 enabled.on_click(move |_, _, cx| {
468 cx.stop_propagation();
507 cx.stop_propagation();
469 let (scope, action, button_id) = (scope.clone(), action.clone(), button_id.clone());
508 let (scope, action, button_id, inputs) = (
509 scope.clone(),
510 action.clone(),
511 button_id.clone(),
512 inputs.clone(),
513 );
470 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
514 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
471 state.run_card_action(scope, button_id, action, cx)
515 state.run_card_action(scope, button_id, action, inputs, cx)
472 });
516 });
473 })
517 })
474 }
518 }
crates/app/src/views/card_input.rs added +159 −0
@@ -0,0 +1,159 @@
1 use gpui_kit::component::checkbox::Checkbox;
2 use gpui_kit::component::input::{Input, Textarea};
3 use gpui_kit::component::radio::{Radio, RadioGroup};
4 use gpui_kit::component::select::Select;
5 use gpui_kit::component::v_flex;
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8 use teams_core::{CardInput, CardInputKind, ChoiceInput, ToggleInput};
9
10 use crate::app_state::AppHandle;
11 use crate::card_inputs::{InputField, uses_select};
12 use crate::card_state::{CardScope, CardState};
13 use crate::theme;
14
15 const INPUT_GAP: f32 = 4.;
16 const LABEL_SIZE: f32 = 12.5;
17 const ERROR_SIZE: f32 = 12.;
18 const FIELD_RADIUS: f32 = 6.;
19 const CHOICE_GAP: f32 = 6.;
20
21 pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> AnyElement {
22 let key = scope.input_key(&input.id);
23 let error = state.input_error(&key).map(str::to_owned);
24 let label = input
25 .label
26 .as_deref()
27 .filter(|label| !label.trim().is_empty());
28 v_flex()
29 .id(ElementId::Name(format!("{key}-input").into()))
30 .w_full()
31 .gap(px(INPUT_GAP))
32 .on_click(|_, _, cx| cx.stop_propagation())
33 .when_some(label, |column, label| {
34 column.child(
35 div()
36 .text_size(px(LABEL_SIZE))
37 .font_weight(FontWeight::SEMIBOLD)
38 .text_color(theme::text_strong())
39 .child(if input.required {
40 format!("{label} *")
41 } else {
42 label.to_owned()
43 }),
44 )
45 })
46 .child(
47 div()
48 .w_full()
49 .rounded(px(FIELD_RADIUS))
50 .border_1()
51 .border_color(if error.is_some() {
52 theme::red()
53 } else {
54 transparent_black()
55 })
56 .child(control_view(input, &key, scope, state)),
57 )
58 .when_some(error, |column, error| {
59 column.child(
60 div()
61 .text_size(px(ERROR_SIZE))
62 .text_color(theme::red_soft())
63 .child(error),
64 )
65 })
66 .into_any_element()
67 }
68
69 fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardState) -> AnyElement {
70 let current = state.input_value(key).to_owned();
71 match &input.kind {
72 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
73 CardInputKind::Choice(choice) if !uses_select(choice) => {
74 choices_view(choice, key, &current, scope)
75 }
76 _ => match state.input_field(key) {
77 Some(InputField::Line(field)) => Input::new(field).into_any_element(),
78 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
79 Some(InputField::Select(field)) => {
80 let placeholder = match &input.kind {
81 CardInputKind::Choice(choice) => choice.placeholder.clone(),
82 _ => None,
83 };
84 Select::new(field)
85 .w_full()
86 .when_some(placeholder, |select, placeholder| {
87 select.placeholder(placeholder)
88 })
89 .into_any_element()
90 }
91 None => div().into_any_element(),
92 },
93 }
94 }
95
96 fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
97 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
98 let (scope, input_key) = (scope.clone(), key.to_owned());
99 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
100 .label(toggle.title.clone())
101 .checked(toggle.is_on(current))
102 .on_click(move |checked, _, cx| {
103 let value = if *checked { &value_on } else { &value_off };
104 pick(&scope, &input_key, value.clone(), cx);
105 })
106 .into_any_element()
107 }
108
109 fn choices_view(choice: &ChoiceInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
110 let (scope, input_key) = (scope.clone(), key.to_owned());
111 if choice.multi {
112 return v_flex()
113 .gap(px(CHOICE_GAP))
114 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
115 let (choice, scope, input_key, current, value) = (
116 choice.clone(),
117 scope.clone(),
118 input_key.clone(),
119 current.to_owned(),
120 candidate.value.clone(),
121 );
122 Checkbox::new(ElementId::Name(format!("{key}-choice-{index}").into()))
123 .label(candidate.title.clone())
124 .checked(choice.is_selected(&current, &value))
125 .on_click(move |_, _, cx| {
126 pick(&scope, &input_key, choice.toggled(&current, &value), cx)
127 })
128 }))
129 .into_any_element();
130 }
131 let selected = choice
132 .choices
133 .iter()
134 .position(|candidate| candidate.value == current);
135 let values: Vec<String> = choice
136 .choices
137 .iter()
138 .map(|candidate| candidate.value.clone())
139 .collect();
140 RadioGroup::new(ElementId::Name(format!("{key}-choices").into()))
141 .selected_index(selected)
142 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
143 Radio::new(ElementId::Name(format!("{key}-choice-{index}").into()))
144 .label(candidate.title.clone())
145 }))
146 .on_click(move |index, _, cx| {
147 if let Some(value) = values.get(*index) {
148 pick(&scope, &input_key, value.clone(), cx);
149 }
150 })
151 .into_any_element()
152 }
153
154 fn pick(scope: &CardScope, key: &str, value: String, cx: &mut App) {
155 cx.global::<AppHandle>()
156 .0
157 .clone()
158 .update(cx, |state, cx| state.pick_card_input(scope, key, value, cx));
159 }
@@ -0,0 +1,159 @@
1use gpui_kit::component::checkbox::Checkbox;
2use gpui_kit::component::input::{Input, Textarea};
3use gpui_kit::component::radio::{Radio, RadioGroup};
4use gpui_kit::component::select::Select;
5use gpui_kit::component::v_flex;
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{CardInput, CardInputKind, ChoiceInput, ToggleInput};
9
10use crate::app_state::AppHandle;
11use crate::card_inputs::{InputField, uses_select};
12use crate::card_state::{CardScope, CardState};
13use crate::theme;
14
15const INPUT_GAP: f32 = 4.;
16const LABEL_SIZE: f32 = 12.5;
17const ERROR_SIZE: f32 = 12.;
18const FIELD_RADIUS: f32 = 6.;
19const CHOICE_GAP: f32 = 6.;
20
21pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> AnyElement {
22 let key = scope.input_key(&input.id);
23 let error = state.input_error(&key).map(str::to_owned);
24 let label = input
25 .label
26 .as_deref()
27 .filter(|label| !label.trim().is_empty());
28 v_flex()
29 .id(ElementId::Name(format!("{key}-input").into()))
30 .w_full()
31 .gap(px(INPUT_GAP))
32 .on_click(|_, _, cx| cx.stop_propagation())
33 .when_some(label, |column, label| {
34 column.child(
35 div()
36 .text_size(px(LABEL_SIZE))
37 .font_weight(FontWeight::SEMIBOLD)
38 .text_color(theme::text_strong())
39 .child(if input.required {
40 format!("{label} *")
41 } else {
42 label.to_owned()
43 }),
44 )
45 })
46 .child(
47 div()
48 .w_full()
49 .rounded(px(FIELD_RADIUS))
50 .border_1()
51 .border_color(if error.is_some() {
52 theme::red()
53 } else {
54 transparent_black()
55 })
56 .child(control_view(input, &key, scope, state)),
57 )
58 .when_some(error, |column, error| {
59 column.child(
60 div()
61 .text_size(px(ERROR_SIZE))
62 .text_color(theme::red_soft())
63 .child(error),
64 )
65 })
66 .into_any_element()
67}
68
69fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardState) -> AnyElement {
70 let current = state.input_value(key).to_owned();
71 match &input.kind {
72 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
73 CardInputKind::Choice(choice) if !uses_select(choice) => {
74 choices_view(choice, key, &current, scope)
75 }
76 _ => match state.input_field(key) {
77 Some(InputField::Line(field)) => Input::new(field).into_any_element(),
78 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
79 Some(InputField::Select(field)) => {
80 let placeholder = match &input.kind {
81 CardInputKind::Choice(choice) => choice.placeholder.clone(),
82 _ => None,
83 };
84 Select::new(field)
85 .w_full()
86 .when_some(placeholder, |select, placeholder| {
87 select.placeholder(placeholder)
88 })
89 .into_any_element()
90 }
91 None => div().into_any_element(),
92 },
93 }
94}
95
96fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
97 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
98 let (scope, input_key) = (scope.clone(), key.to_owned());
99 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
100 .label(toggle.title.clone())
101 .checked(toggle.is_on(current))
102 .on_click(move |checked, _, cx| {
103 let value = if *checked { &value_on } else { &value_off };
104 pick(&scope, &input_key, value.clone(), cx);
105 })
106 .into_any_element()
107}
108
109fn choices_view(choice: &ChoiceInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
110 let (scope, input_key) = (scope.clone(), key.to_owned());
111 if choice.multi {
112 return v_flex()
113 .gap(px(CHOICE_GAP))
114 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
115 let (choice, scope, input_key, current, value) = (
116 choice.clone(),
117 scope.clone(),
118 input_key.clone(),
119 current.to_owned(),
120 candidate.value.clone(),
121 );
122 Checkbox::new(ElementId::Name(format!("{key}-choice-{index}").into()))
123 .label(candidate.title.clone())
124 .checked(choice.is_selected(&current, &value))
125 .on_click(move |_, _, cx| {
126 pick(&scope, &input_key, choice.toggled(&current, &value), cx)
127 })
128 }))
129 .into_any_element();
130 }
131 let selected = choice
132 .choices
133 .iter()
134 .position(|candidate| candidate.value == current);
135 let values: Vec<String> = choice
136 .choices
137 .iter()
138 .map(|candidate| candidate.value.clone())
139 .collect();
140 RadioGroup::new(ElementId::Name(format!("{key}-choices").into()))
141 .selected_index(selected)
142 .children(choice.choices.iter().enumerate().map(|(index, candidate)| {
143 Radio::new(ElementId::Name(format!("{key}-choice-{index}").into()))
144 .label(candidate.title.clone())
145 }))
146 .on_click(move |index, _, cx| {
147 if let Some(value) = values.get(*index) {
148 pick(&scope, &input_key, value.clone(), cx);
149 }
150 })
151 .into_any_element()
152}
153
154fn pick(scope: &CardScope, key: &str, value: String, cx: &mut App) {
155 cx.global::<AppHandle>()
156 .0
157 .clone()
158 .update(cx, |state, cx| state.pick_card_input(scope, key, value, cx));
159}
crates/app/src/views/conversation.rs +9 −0
@@ -22,6 +22,7 @@ use super::attachments::FileActions;
22 22 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23 23 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24 24 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25 use super::adaptive_card::ensure_cards_inputs;
25 26 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26 27 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27 28 use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -2709,6 +2710,14 @@ impl Render for ConversationView {
2709 2710 }
2710 2711 known
2711 2712 });
2713 ensure_cards_inputs(
2714 &app,
2715 &message.adaptive_cards,
2716 &message.conversation_id,
2717 &message.key,
2718 window,
2719 cx,
2720 );
2712 2721 let state = app.read(cx);
2713 2722 render_message_row(
2714 2723 message,
@@ -22,6 +22,7 @@ use super::attachments::FileActions;
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
22use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
23use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
24use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
24use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
25use super::adaptive_card::ensure_cards_inputs;
25use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26use super::message_row::{RowActions, render_message_row, render_skeleton_row};
26use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
27use super::reaction_picker::{PickHandler, ReactionPicker};
28use super::reaction_picker::{PickHandler, ReactionPicker};
@@ -2709,6 +2710,14 @@ impl Render for ConversationView {
2709 }
2710 }
2710 known
2711 known
2711 });
2712 });
2713 ensure_cards_inputs(
2714 &app,
2715 &message.adaptive_cards,
2716 &message.conversation_id,
2717 &message.key,
2718 window,
2719 cx,
2720 );
2712 let state = app.read(cx);
2721 let state = app.read(cx);
2713 render_message_row(
2722 render_message_row(
2714 message,
2723 message,
crates/app/src/views/mod.rs +1 −0
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3 3 pub mod attachment_tray;
4 4 pub mod attachments;
5 5 pub mod avatar;
6 pub mod card_input;
6 7 pub mod composer;
7 8 pub mod conversation;
8 9 pub mod dialog_overlay;
@@ -3,6 +3,7 @@ pub mod adaptive_card;
3pub mod attachment_tray;
3pub mod attachment_tray;
4pub mod attachments;
4pub mod attachments;
5pub mod avatar;
5pub mod avatar;
6pub mod card_input;
6pub mod composer;
7pub mod composer;
7pub mod conversation;
8pub mod conversation;
8pub mod dialog_overlay;
9pub mod dialog_overlay;
crates/app/src/views/shell.rs +12 −1
@@ -286,7 +286,18 @@ impl AppShell {
286 286 }
287 287
288 288 impl Render for AppShell {
289 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
289 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
290 if let Some(dialog) = self
291 .state
292 .read(cx)
293 .task_dialog
294 .as_ref()
295 .map(|dialog| (dialog.scope.clone(), dialog.card.clone()))
296 {
297 self.state.update(cx, |state, cx| {
298 state.ensure_card_inputs(&dialog.0, &dialog.1, window, cx)
299 });
300 }
290 301 if let Some(me) = self.state.read(cx).directory.me.clone() {
291 302 let app = self.state.clone();
292 303 cx.defer(move |cx| {
@@ -286,7 +286,18 @@ impl AppShell {
286}
286}
287
287
288impl Render for AppShell {
288impl Render for AppShell {
289 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
289 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
290 if let Some(dialog) = self
291 .state
292 .read(cx)
293 .task_dialog
294 .as_ref()
295 .map(|dialog| (dialog.scope.clone(), dialog.card.clone()))
296 {
297 self.state.update(cx, |state, cx| {
298 state.ensure_card_inputs(&dialog.0, &dialog.1, window, cx)
299 });
300 }
290 if let Some(me) = self.state.read(cx).directory.me.clone() {
301 if let Some(me) = self.state.read(cx).directory.me.clone() {
291 let app = self.state.clone();
302 let app = self.state.clone();
292 cx.defer(move |cx| {
303 cx.defer(move |cx| {
crates/core/src/adaptive_card.rs +99 −1
@@ -2,6 +2,7 @@ use std::collections::HashMap;
2 2
3 3 use serde_json::{Map, Value, json};
4 4
5 use crate::card_inputs::{CardInput, merge_input_data, parse_input};
5 6 use crate::markdown::markdown_to_html;
6 7 use crate::spans::{Span, html_to_spans};
7 8 use crate::stored::push_plain;
@@ -9,6 +10,7 @@ use crate::stored::push_plain;
9 10 const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
10 11 const IMAGE_URL_SCHEME: &str = "https://";
11 12 const ACTION_TYPE_PREFIX: &str = "Action.";
13 const INPUT_TYPE_PREFIX: &str = "Input.";
12 14 const OPEN_URL_ACTION: &str = "Action.OpenUrl";
13 15 const SUBMIT_ACTION: &str = "Action.Submit";
14 16 const EXECUTE_ACTION: &str = "Action.Execute";
@@ -49,6 +51,7 @@ pub enum CardElement {
49 51 },
50 52 Facts(Vec<CardFact>),
51 53 Actions(Vec<CardAction>),
54 Input(CardInput),
52 55 }
53 56
54 57 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -155,6 +158,7 @@ pub struct CardAction {
155 158 pub kind: CardActionKind,
156 159 pub enabled: bool,
157 160 pub visible: bool,
161 pub collects_inputs: bool,
158 162 }
159 163
160 164 #[derive(Debug, Clone, PartialEq)]
@@ -192,6 +196,27 @@ pub struct InvokePayload {
192 196 }
193 197
194 198 impl SubmitAction {
199 pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction {
200 let mut data = merge_input_data(&self.data, values);
201 if !values.is_empty() && self.is_message_back() {
202 let mut sent = data.as_object().cloned().unwrap_or_default();
203 sent.remove(TEAMS_SETTINGS_KEY);
204 if let Some(settings) = data
205 .get_mut(TEAMS_SETTINGS_KEY)
206 .and_then(Value::as_object_mut)
207 {
208 settings.insert("value".to_owned(), Value::Object(sent));
209 }
210 }
211 SubmitAction { data }
212 }
213
214 fn is_message_back(&self) -> bool {
215 self.teams_settings()
216 .and_then(|settings| string_field(settings, "type"))
217 .is_some_and(|kind| kind.eq_ignore_ascii_case("messageBack"))
218 }
219
195 220 fn teams_settings(&self) -> Option<&Value> {
196 221 self.data.get(TEAMS_SETTINGS_KEY)
197 222 }
@@ -248,6 +273,23 @@ pub fn task_value(data: Value) -> Value {
248 273 }
249 274
250 275 impl CardAction {
276 pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction {
277 let kind = match &self.kind {
278 CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)),
279 CardActionKind::Execute(execute) => {
280 CardActionKind::Execute(ExecuteAction {
281 data: merge_input_data(&execute.data, values),
282 ..execute.clone()
283 })
284 }
285 other => other.clone(),
286 };
287 CardAction {
288 kind,
289 ..self.clone()
290 }
291 }
292
251 293 pub fn invoke_payload(&self) -> Option<InvokePayload> {
252 294 match &self.kind {
253 295 CardActionKind::Submit(submit) => Some(submit.payload()),
@@ -296,6 +338,28 @@ impl AdaptiveCard {
296 338 visibility
297 339 }
298 340
341 pub fn own_inputs(&self) -> Vec<CardInput> {
342 let mut inputs = Vec::new();
343 collect_inputs(&self.items, &mut inputs);
344 inputs
345 }
346
347 pub fn all_inputs(&self) -> Vec<CardInput> {
348 let mut inputs = self.own_inputs();
349 for action in self.all_actions() {
350 if let CardActionKind::ShowCard(card) = &action.kind {
351 inputs.extend(card.all_inputs());
352 }
353 }
354 inputs
355 }
356
357 fn all_actions(&self) -> Vec<&CardAction> {
358 let mut actions: Vec<&CardAction> = self.actions.iter().collect();
359 collect_item_actions(&self.items, &mut actions);
360 actions
361 }
362
299 363 pub fn plain_text(&self) -> Option<String> {
300 364 let mut lines = Vec::new();
301 365 collect_lines(&self.items, &mut lines);
@@ -331,6 +395,32 @@ fn collect_visibility(
331 395 }
332 396 }
333 397
398 fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) {
399 for item in items {
400 match &item.element {
401 CardElement::Input(input) => inputs.push(input.clone()),
402 CardElement::Columns(columns) => columns
403 .iter()
404 .for_each(|column| collect_inputs(&column.items, inputs)),
405 CardElement::Container { items, .. } => collect_inputs(items, inputs),
406 _ => {}
407 }
408 }
409 }
410
411 fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) {
412 for item in items {
413 match &item.element {
414 CardElement::Actions(set) => actions.extend(set),
415 CardElement::Columns(columns) => columns
416 .iter()
417 .for_each(|column| collect_item_actions(&column.items, actions)),
418 CardElement::Container { items, .. } => collect_item_actions(items, actions),
419 _ => {}
420 }
421 }
422 }
423
334 424 pub fn card_content_text(content: &str) -> Option<String> {
335 425 AdaptiveCard::parse(content)?.plain_text()
336 426 }
@@ -350,7 +440,10 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
350 440 lines.push(line.trim().to_owned());
351 441 }
352 442 }
353 CardElement::Image(_) | CardElement::ImageSet(_) | CardElement::Actions(_) => {}
443 CardElement::Image(_)
444 | CardElement::ImageSet(_)
445 | CardElement::Actions(_)
446 | CardElement::Input(_) => {}
354 447 }
355 448 }
356 449 }
@@ -388,6 +481,9 @@ fn parse_item(value: &Value) -> Option<CardItem> {
388 481 "Container" => parse_container(value),
389 482 "FactSet" => parse_fact_set(value),
390 483 "ActionSet" => parse_action_set(value),
484 input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => {
485 parse_input(value, input_type).map(CardElement::Input)
486 }
391 487 _ => None,
392 488 };
393 489 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
@@ -620,6 +716,8 @@ fn parse_action(value: &Value) -> Option<CardAction> {
620 716 .and_then(Value::as_bool)
621 717 .unwrap_or(true),
622 718 visible,
719 collects_inputs: !string_field(value, "associatedInputs")
720 .is_some_and(|mode| mode.eq_ignore_ascii_case("none")),
623 721 })
624 722 }
625 723
@@ -2,6 +2,7 @@ use std::collections::HashMap;
2
2
3use serde_json::{Map, Value, json};
3use serde_json::{Map, Value, json};
4
4
5use crate::card_inputs::{CardInput, merge_input_data, parse_input};
5use crate::markdown::markdown_to_html;
6use crate::markdown::markdown_to_html;
6use crate::spans::{Span, html_to_spans};
7use crate::spans::{Span, html_to_spans};
7use crate::stored::push_plain;
8use crate::stored::push_plain;
@@ -9,6 +10,7 @@ use crate::stored::push_plain;
9const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
10const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
10const IMAGE_URL_SCHEME: &str = "https://";
11const IMAGE_URL_SCHEME: &str = "https://";
11const ACTION_TYPE_PREFIX: &str = "Action.";
12const ACTION_TYPE_PREFIX: &str = "Action.";
13const INPUT_TYPE_PREFIX: &str = "Input.";
12const OPEN_URL_ACTION: &str = "Action.OpenUrl";
14const OPEN_URL_ACTION: &str = "Action.OpenUrl";
13const SUBMIT_ACTION: &str = "Action.Submit";
15const SUBMIT_ACTION: &str = "Action.Submit";
14const EXECUTE_ACTION: &str = "Action.Execute";
16const EXECUTE_ACTION: &str = "Action.Execute";
@@ -49,6 +51,7 @@ pub enum CardElement {
49 },
51 },
50 Facts(Vec<CardFact>),
52 Facts(Vec<CardFact>),
51 Actions(Vec<CardAction>),
53 Actions(Vec<CardAction>),
54 Input(CardInput),
52}
55}
53
56
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -155,6 +158,7 @@ pub struct CardAction {
155 pub kind: CardActionKind,
158 pub kind: CardActionKind,
156 pub enabled: bool,
159 pub enabled: bool,
157 pub visible: bool,
160 pub visible: bool,
161 pub collects_inputs: bool,
158}
162}
159
163
160#[derive(Debug, Clone, PartialEq)]
164#[derive(Debug, Clone, PartialEq)]
@@ -192,6 +196,27 @@ pub struct InvokePayload {
192}
196}
193
197
194impl SubmitAction {
198impl SubmitAction {
199 pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction {
200 let mut data = merge_input_data(&self.data, values);
201 if !values.is_empty() && self.is_message_back() {
202 let mut sent = data.as_object().cloned().unwrap_or_default();
203 sent.remove(TEAMS_SETTINGS_KEY);
204 if let Some(settings) = data
205 .get_mut(TEAMS_SETTINGS_KEY)
206 .and_then(Value::as_object_mut)
207 {
208 settings.insert("value".to_owned(), Value::Object(sent));
209 }
210 }
211 SubmitAction { data }
212 }
213
214 fn is_message_back(&self) -> bool {
215 self.teams_settings()
216 .and_then(|settings| string_field(settings, "type"))
217 .is_some_and(|kind| kind.eq_ignore_ascii_case("messageBack"))
218 }
219
195 fn teams_settings(&self) -> Option<&Value> {
220 fn teams_settings(&self) -> Option<&Value> {
196 self.data.get(TEAMS_SETTINGS_KEY)
221 self.data.get(TEAMS_SETTINGS_KEY)
197 }
222 }
@@ -248,6 +273,23 @@ pub fn task_value(data: Value) -> Value {
248}
273}
249
274
250impl CardAction {
275impl CardAction {
276 pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction {
277 let kind = match &self.kind {
278 CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)),
279 CardActionKind::Execute(execute) => {
280 CardActionKind::Execute(ExecuteAction {
281 data: merge_input_data(&execute.data, values),
282 ..execute.clone()
283 })
284 }
285 other => other.clone(),
286 };
287 CardAction {
288 kind,
289 ..self.clone()
290 }
291 }
292
251 pub fn invoke_payload(&self) -> Option<InvokePayload> {
293 pub fn invoke_payload(&self) -> Option<InvokePayload> {
252 match &self.kind {
294 match &self.kind {
253 CardActionKind::Submit(submit) => Some(submit.payload()),
295 CardActionKind::Submit(submit) => Some(submit.payload()),
@@ -296,6 +338,28 @@ impl AdaptiveCard {
296 visibility
338 visibility
297 }
339 }
298
340
341 pub fn own_inputs(&self) -> Vec<CardInput> {
342 let mut inputs = Vec::new();
343 collect_inputs(&self.items, &mut inputs);
344 inputs
345 }
346
347 pub fn all_inputs(&self) -> Vec<CardInput> {
348 let mut inputs = self.own_inputs();
349 for action in self.all_actions() {
350 if let CardActionKind::ShowCard(card) = &action.kind {
351 inputs.extend(card.all_inputs());
352 }
353 }
354 inputs
355 }
356
357 fn all_actions(&self) -> Vec<&CardAction> {
358 let mut actions: Vec<&CardAction> = self.actions.iter().collect();
359 collect_item_actions(&self.items, &mut actions);
360 actions
361 }
362
299 pub fn plain_text(&self) -> Option<String> {
363 pub fn plain_text(&self) -> Option<String> {
300 let mut lines = Vec::new();
364 let mut lines = Vec::new();
301 collect_lines(&self.items, &mut lines);
365 collect_lines(&self.items, &mut lines);
@@ -331,6 +395,32 @@ fn collect_visibility(
331 }
395 }
332}
396}
333
397
398fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) {
399 for item in items {
400 match &item.element {
401 CardElement::Input(input) => inputs.push(input.clone()),
402 CardElement::Columns(columns) => columns
403 .iter()
404 .for_each(|column| collect_inputs(&column.items, inputs)),
405 CardElement::Container { items, .. } => collect_inputs(items, inputs),
406 _ => {}
407 }
408 }
409}
410
411fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) {
412 for item in items {
413 match &item.element {
414 CardElement::Actions(set) => actions.extend(set),
415 CardElement::Columns(columns) => columns
416 .iter()
417 .for_each(|column| collect_item_actions(&column.items, actions)),
418 CardElement::Container { items, .. } => collect_item_actions(items, actions),
419 _ => {}
420 }
421 }
422}
423
334pub fn card_content_text(content: &str) -> Option<String> {
424pub fn card_content_text(content: &str) -> Option<String> {
335 AdaptiveCard::parse(content)?.plain_text()
425 AdaptiveCard::parse(content)?.plain_text()
336}
426}
@@ -350,7 +440,10 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
350 lines.push(line.trim().to_owned());
440 lines.push(line.trim().to_owned());
351 }
441 }
352 }
442 }
353 CardElement::Image(_) | CardElement::ImageSet(_) | CardElement::Actions(_) => {}
443 CardElement::Image(_)
444 | CardElement::ImageSet(_)
445 | CardElement::Actions(_)
446 | CardElement::Input(_) => {}
354 }
447 }
355 }
448 }
356}
449}
@@ -388,6 +481,9 @@ fn parse_item(value: &Value) -> Option<CardItem> {
388 "Container" => parse_container(value),
481 "Container" => parse_container(value),
389 "FactSet" => parse_fact_set(value),
482 "FactSet" => parse_fact_set(value),
390 "ActionSet" => parse_action_set(value),
483 "ActionSet" => parse_action_set(value),
484 input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => {
485 parse_input(value, input_type).map(CardElement::Input)
486 }
391 _ => None,
487 _ => None,
392 };
488 };
393 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
489 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
@@ -620,6 +716,8 @@ fn parse_action(value: &Value) -> Option<CardAction> {
620 .and_then(Value::as_bool)
716 .and_then(Value::as_bool)
621 .unwrap_or(true),
717 .unwrap_or(true),
622 visible,
718 visible,
719 collects_inputs: !string_field(value, "associatedInputs")
720 .is_some_and(|mode| mode.eq_ignore_ascii_case("none")),
623 })
721 })
624}
722}
625
723
crates/core/src/card_inputs.rs added +386 −0
@@ -0,0 +1,386 @@
1 use chrono::{NaiveDate, NaiveTime};
2 use regex::Regex;
3 use serde_json::{Map, Value};
4
5 const DATE_FORMAT: &str = "%Y-%m-%d";
6 const TIME_FORMAT: &str = "%H:%M";
7 const DEFAULT_VALUE_ON: &str = "true";
8 const DEFAULT_VALUE_OFF: &str = "false";
9 const CHOICE_SEPARATOR: char = ',';
10 const REQUIRED_MESSAGE: &str = "Required";
11 const INVALID_MESSAGE: &str = "Invalid value";
12 pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD";
13 pub const TIME_PLACEHOLDER: &str = "HH:MM";
14
15 #[derive(Debug, Clone, PartialEq)]
16 pub struct CardInput {
17 pub id: String,
18 pub label: Option<String>,
19 pub required: bool,
20 pub error_message: Option<String>,
21 pub kind: CardInputKind,
22 }
23
24 #[derive(Debug, Clone, PartialEq)]
25 pub enum CardInputKind {
26 Text(TextInput),
27 Number(NumberInput),
28 Date(MomentInput),
29 Time(MomentInput),
30 Toggle(ToggleInput),
31 Choice(ChoiceInput),
32 }
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35 pub enum TextStyle {
36 Text,
37 Tel,
38 Url,
39 Email,
40 Password,
41 }
42
43 #[derive(Debug, Clone, PartialEq)]
44 pub struct TextInput {
45 pub placeholder: Option<String>,
46 pub value: String,
47 pub multiline: bool,
48 pub max_length: Option<usize>,
49 pub style: TextStyle,
50 pub regex: Option<String>,
51 }
52
53 #[derive(Debug, Clone, PartialEq)]
54 pub struct NumberInput {
55 pub placeholder: Option<String>,
56 pub value: String,
57 pub min: Option<f64>,
58 pub max: Option<f64>,
59 }
60
61 #[derive(Debug, Clone, PartialEq)]
62 pub struct MomentInput {
63 pub value: String,
64 pub min: Option<String>,
65 pub max: Option<String>,
66 }
67
68 #[derive(Debug, Clone, PartialEq)]
69 pub struct ToggleInput {
70 pub title: String,
71 pub value: String,
72 pub value_on: String,
73 pub value_off: String,
74 }
75
76 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
77 pub enum ChoiceStyle {
78 Compact,
79 Expanded,
80 Filtered,
81 }
82
83 #[derive(Debug, Clone, PartialEq)]
84 pub struct ChoiceInput {
85 pub choices: Vec<InputChoice>,
86 pub multi: bool,
87 pub style: ChoiceStyle,
88 pub placeholder: Option<String>,
89 pub value: String,
90 }
91
92 #[derive(Debug, Clone, PartialEq, Eq)]
93 pub struct InputChoice {
94 pub title: String,
95 pub value: String,
96 }
97
98 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct InputError {
100 pub id: String,
101 pub message: String,
102 }
103
104 impl TextStyle {
105 fn parse(value: Option<&str>) -> Self {
106 match value.map(str::to_ascii_lowercase).as_deref() {
107 Some("tel") => TextStyle::Tel,
108 Some("url") => TextStyle::Url,
109 Some("email") => TextStyle::Email,
110 Some("password") => TextStyle::Password,
111 _ => TextStyle::Text,
112 }
113 }
114 }
115
116 impl ChoiceStyle {
117 fn parse(value: Option<&str>) -> Self {
118 match value.map(str::to_ascii_lowercase).as_deref() {
119 Some("expanded") => ChoiceStyle::Expanded,
120 Some("filtered") => ChoiceStyle::Filtered,
121 _ => ChoiceStyle::Compact,
122 }
123 }
124 }
125
126 impl ToggleInput {
127 pub fn is_on(&self, current: &str) -> bool {
128 current == self.value_on
129 }
130
131 pub fn flipped(&self, current: &str) -> String {
132 if self.is_on(current) {
133 self.value_off.clone()
134 } else {
135 self.value_on.clone()
136 }
137 }
138 }
139
140 impl ChoiceInput {
141 pub fn selected<'current>(&self, current: &'current str) -> Vec<&'current str> {
142 if self.multi {
143 current
144 .split(CHOICE_SEPARATOR)
145 .map(str::trim)
146 .filter(|value| !value.is_empty())
147 .collect()
148 } else {
149 Some(current)
150 .filter(|value| !value.is_empty())
151 .into_iter()
152 .collect()
153 }
154 }
155
156 pub fn is_selected(&self, current: &str, choice_value: &str) -> bool {
157 self.selected(current).contains(&choice_value)
158 }
159
160 pub fn toggled(&self, current: &str, choice_value: &str) -> String {
161 if !self.multi {
162 return choice_value.to_owned();
163 }
164 let selected = self.selected(current);
165 let keep = |choice: &&InputChoice| {
166 (choice.value == choice_value) != selected.contains(&choice.value.as_str())
167 };
168 self.choices
169 .iter()
170 .filter(keep)
171 .map(|choice| choice.value.as_str())
172 .collect::<Vec<_>>()
173 .join(&CHOICE_SEPARATOR.to_string())
174 }
175 }
176
177 impl CardInput {
178 pub fn initial_value(&self) -> String {
179 match &self.kind {
180 CardInputKind::Text(text) => text.value.clone(),
181 CardInputKind::Number(number) => number.value.clone(),
182 CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(),
183 CardInputKind::Toggle(toggle) => toggle.value.clone(),
184 CardInputKind::Choice(choice) => choice.value.clone(),
185 }
186 }
187
188 pub fn validate(&self, value: &str) -> Option<String> {
189 let message = || {
190 self.error_message
191 .clone()
192 .filter(|message| !message.trim().is_empty())
193 };
194 if value.is_empty() {
195 return (self.required)
196 .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned()));
197 }
198 let valid = match &self.kind {
199 CardInputKind::Text(text) => text.accepts(value),
200 CardInputKind::Number(number) => number.accepts(value),
201 CardInputKind::Date(moment) => moment.accepts(value, parse_date),
202 CardInputKind::Time(moment) => moment.accepts(value, parse_time),
203 CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value),
204 CardInputKind::Choice(_) => true,
205 };
206 (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned()))
207 }
208 }
209
210 impl TextInput {
211 fn accepts(&self, value: &str) -> bool {
212 self.max_length
213 .is_none_or(|max_length| value.chars().count() <= max_length)
214 && self
215 .regex
216 .as_deref()
217 .is_none_or(|pattern| Regex::new(pattern).is_ok_and(|regex| regex.is_match(value)))
218 }
219 }
220
221 impl NumberInput {
222 fn accepts(&self, value: &str) -> bool {
223 let Ok(number) = value.trim().parse::<f64>() else {
224 return false;
225 };
226 number.is_finite()
227 && self.min.is_none_or(|min| number >= min)
228 && self.max.is_none_or(|max| number <= max)
229 }
230 }
231
232 impl MomentInput {
233 fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool {
234 let Some(moment) = parse(value) else {
235 return false;
236 };
237 self.min
238 .as_deref()
239 .and_then(parse)
240 .is_none_or(|min| moment >= min)
241 && self
242 .max
243 .as_deref()
244 .and_then(parse)
245 .is_none_or(|max| moment <= max)
246 }
247 }
248
249 fn parse_date(value: &str) -> Option<NaiveDate> {
250 NaiveDate::parse_from_str(value, DATE_FORMAT).ok()
251 }
252
253 fn parse_time(value: &str) -> Option<NaiveTime> {
254 NaiveTime::parse_from_str(value, TIME_FORMAT).ok()
255 }
256
257 pub fn collect_input_values(
258 inputs: &[CardInput],
259 value_of: impl Fn(&CardInput) -> String,
260 ) -> Result<Map<String, Value>, Vec<InputError>> {
261 let mut values = Map::new();
262 let mut errors = Vec::new();
263 for input in inputs {
264 let value = value_of(input);
265 match input.validate(&value) {
266 Some(message) => errors.push(InputError {
267 id: input.id.clone(),
268 message,
269 }),
270 None => {
271 values.insert(input.id.clone(), Value::String(value));
272 }
273 }
274 }
275 if errors.is_empty() {
276 Ok(values)
277 } else {
278 Err(errors)
279 }
280 }
281
282 pub fn merge_input_data(data: &Value, values: &Map<String, Value>) -> Value {
283 match data {
284 Value::Object(object) => {
285 let mut merged = object.clone();
286 merged.extend(values.clone());
287 Value::Object(merged)
288 }
289 Value::Null => Value::Object(values.clone()),
290 other => other.clone(),
291 }
292 }
293
294 pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> {
295 let id = text_field(value, "id")?;
296 let placeholder = text_field(value, "placeholder");
297 let kind = match input_type {
298 "Input.Text" => CardInputKind::Text(TextInput {
299 placeholder,
300 value: text_field(value, "value").unwrap_or_default(),
301 multiline: bool_field(value, "isMultiline"),
302 max_length: value
303 .get("maxLength")
304 .and_then(Value::as_u64)
305 .filter(|max_length| *max_length > 0)
306 .map(|max_length| max_length as usize),
307 style: TextStyle::parse(value.get("style").and_then(Value::as_str)),
308 regex: text_field(value, "regex"),
309 }),
310 "Input.Number" => CardInputKind::Number(NumberInput {
311 placeholder,
312 value: number_text(value.get("value")),
313 min: value.get("min").and_then(Value::as_f64),
314 max: value.get("max").and_then(Value::as_f64),
315 }),
316 "Input.Date" => CardInputKind::Date(parse_moment(value)),
317 "Input.Time" => CardInputKind::Time(parse_moment(value)),
318 "Input.Toggle" => {
319 let value_on =
320 text_field(value, "valueOn").unwrap_or_else(|| DEFAULT_VALUE_ON.to_owned());
321 let value_off =
322 text_field(value, "valueOff").unwrap_or_else(|| DEFAULT_VALUE_OFF.to_owned());
323 CardInputKind::Toggle(ToggleInput {
324 title: text_field(value, "title").unwrap_or_default(),
325 value: text_field(value, "value").unwrap_or_else(|| value_off.clone()),
326 value_on,
327 value_off,
328 })
329 }
330 "Input.ChoiceSet" => {
331 let choices: Vec<InputChoice> = value
332 .get("choices")?
333 .as_array()?
334 .iter()
335 .filter_map(|choice| {
336 Some(InputChoice {
337 title: text_field(choice, "title")?,
338 value: text_field(choice, "value")?,
339 })
340 })
341 .collect();
342 if choices.is_empty() {
343 return None;
344 }
345 CardInputKind::Choice(ChoiceInput {
346 choices,
347 multi: bool_field(value, "isMultiSelect"),
348 style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)),
349 placeholder,
350 value: text_field(value, "value").unwrap_or_default(),
351 })
352 }
353 _ => return None,
354 };
355 Some(CardInput {
356 id,
357 label: text_field(value, "label"),
358 required: bool_field(value, "isRequired"),
359 error_message: text_field(value, "errorMessage"),
360 kind,
361 })
362 }
363
364 fn parse_moment(value: &Value) -> MomentInput {
365 MomentInput {
366 value: text_field(value, "value").unwrap_or_default(),
367 min: text_field(value, "min"),
368 max: text_field(value, "max"),
369 }
370 }
371
372 fn text_field(value: &Value, key: &str) -> Option<String> {
373 value.get(key)?.as_str().map(str::to_owned)
374 }
375
376 fn bool_field(value: &Value, key: &str) -> bool {
377 value.get(key).and_then(Value::as_bool).unwrap_or(false)
378 }
379
380 fn number_text(value: Option<&Value>) -> String {
381 match value {
382 Some(Value::Number(number)) => number.to_string(),
383 Some(Value::String(text)) => text.clone(),
384 _ => String::new(),
385 }
386 }
@@ -0,0 +1,386 @@
1use chrono::{NaiveDate, NaiveTime};
2use regex::Regex;
3use serde_json::{Map, Value};
4
5const DATE_FORMAT: &str = "%Y-%m-%d";
6const TIME_FORMAT: &str = "%H:%M";
7const DEFAULT_VALUE_ON: &str = "true";
8const DEFAULT_VALUE_OFF: &str = "false";
9const CHOICE_SEPARATOR: char = ',';
10const REQUIRED_MESSAGE: &str = "Required";
11const INVALID_MESSAGE: &str = "Invalid value";
12pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD";
13pub const TIME_PLACEHOLDER: &str = "HH:MM";
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct CardInput {
17 pub id: String,
18 pub label: Option<String>,
19 pub required: bool,
20 pub error_message: Option<String>,
21 pub kind: CardInputKind,
22}
23
24#[derive(Debug, Clone, PartialEq)]
25pub enum CardInputKind {
26 Text(TextInput),
27 Number(NumberInput),
28 Date(MomentInput),
29 Time(MomentInput),
30 Toggle(ToggleInput),
31 Choice(ChoiceInput),
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum TextStyle {
36 Text,
37 Tel,
38 Url,
39 Email,
40 Password,
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct TextInput {
45 pub placeholder: Option<String>,
46 pub value: String,
47 pub multiline: bool,
48 pub max_length: Option<usize>,
49 pub style: TextStyle,
50 pub regex: Option<String>,
51}
52
53#[derive(Debug, Clone, PartialEq)]
54pub struct NumberInput {
55 pub placeholder: Option<String>,
56 pub value: String,
57 pub min: Option<f64>,
58 pub max: Option<f64>,
59}
60
61#[derive(Debug, Clone, PartialEq)]
62pub struct MomentInput {
63 pub value: String,
64 pub min: Option<String>,
65 pub max: Option<String>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct ToggleInput {
70 pub title: String,
71 pub value: String,
72 pub value_on: String,
73 pub value_off: String,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum ChoiceStyle {
78 Compact,
79 Expanded,
80 Filtered,
81}
82
83#[derive(Debug, Clone, PartialEq)]
84pub struct ChoiceInput {
85 pub choices: Vec<InputChoice>,
86 pub multi: bool,
87 pub style: ChoiceStyle,
88 pub placeholder: Option<String>,
89 pub value: String,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct InputChoice {
94 pub title: String,
95 pub value: String,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct InputError {
100 pub id: String,
101 pub message: String,
102}
103
104impl TextStyle {
105 fn parse(value: Option<&str>) -> Self {
106 match value.map(str::to_ascii_lowercase).as_deref() {
107 Some("tel") => TextStyle::Tel,
108 Some("url") => TextStyle::Url,
109 Some("email") => TextStyle::Email,
110 Some("password") => TextStyle::Password,
111 _ => TextStyle::Text,
112 }
113 }
114}
115
116impl ChoiceStyle {
117 fn parse(value: Option<&str>) -> Self {
118 match value.map(str::to_ascii_lowercase).as_deref() {
119 Some("expanded") => ChoiceStyle::Expanded,
120 Some("filtered") => ChoiceStyle::Filtered,
121 _ => ChoiceStyle::Compact,
122 }
123 }
124}
125
126impl ToggleInput {
127 pub fn is_on(&self, current: &str) -> bool {
128 current == self.value_on
129 }
130
131 pub fn flipped(&self, current: &str) -> String {
132 if self.is_on(current) {
133 self.value_off.clone()
134 } else {
135 self.value_on.clone()
136 }
137 }
138}
139
140impl ChoiceInput {
141 pub fn selected<'current>(&self, current: &'current str) -> Vec<&'current str> {
142 if self.multi {
143 current
144 .split(CHOICE_SEPARATOR)
145 .map(str::trim)
146 .filter(|value| !value.is_empty())
147 .collect()
148 } else {
149 Some(current)
150 .filter(|value| !value.is_empty())
151 .into_iter()
152 .collect()
153 }
154 }
155
156 pub fn is_selected(&self, current: &str, choice_value: &str) -> bool {
157 self.selected(current).contains(&choice_value)
158 }
159
160 pub fn toggled(&self, current: &str, choice_value: &str) -> String {
161 if !self.multi {
162 return choice_value.to_owned();
163 }
164 let selected = self.selected(current);
165 let keep = |choice: &&InputChoice| {
166 (choice.value == choice_value) != selected.contains(&choice.value.as_str())
167 };
168 self.choices
169 .iter()
170 .filter(keep)
171 .map(|choice| choice.value.as_str())
172 .collect::<Vec<_>>()
173 .join(&CHOICE_SEPARATOR.to_string())
174 }
175}
176
177impl CardInput {
178 pub fn initial_value(&self) -> String {
179 match &self.kind {
180 CardInputKind::Text(text) => text.value.clone(),
181 CardInputKind::Number(number) => number.value.clone(),
182 CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(),
183 CardInputKind::Toggle(toggle) => toggle.value.clone(),
184 CardInputKind::Choice(choice) => choice.value.clone(),
185 }
186 }
187
188 pub fn validate(&self, value: &str) -> Option<String> {
189 let message = || {
190 self.error_message
191 .clone()
192 .filter(|message| !message.trim().is_empty())
193 };
194 if value.is_empty() {
195 return (self.required)
196 .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned()));
197 }
198 let valid = match &self.kind {
199 CardInputKind::Text(text) => text.accepts(value),
200 CardInputKind::Number(number) => number.accepts(value),
201 CardInputKind::Date(moment) => moment.accepts(value, parse_date),
202 CardInputKind::Time(moment) => moment.accepts(value, parse_time),
203 CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value),
204 CardInputKind::Choice(_) => true,
205 };
206 (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned()))
207 }
208}
209
210impl TextInput {
211 fn accepts(&self, value: &str) -> bool {
212 self.max_length
213 .is_none_or(|max_length| value.chars().count() <= max_length)
214 && self
215 .regex
216 .as_deref()
217 .is_none_or(|pattern| Regex::new(pattern).is_ok_and(|regex| regex.is_match(value)))
218 }
219}
220
221impl NumberInput {
222 fn accepts(&self, value: &str) -> bool {
223 let Ok(number) = value.trim().parse::<f64>() else {
224 return false;
225 };
226 number.is_finite()
227 && self.min.is_none_or(|min| number >= min)
228 && self.max.is_none_or(|max| number <= max)
229 }
230}
231
232impl MomentInput {
233 fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool {
234 let Some(moment) = parse(value) else {
235 return false;
236 };
237 self.min
238 .as_deref()
239 .and_then(parse)
240 .is_none_or(|min| moment >= min)
241 && self
242 .max
243 .as_deref()
244 .and_then(parse)
245 .is_none_or(|max| moment <= max)
246 }
247}
248
249fn parse_date(value: &str) -> Option<NaiveDate> {
250 NaiveDate::parse_from_str(value, DATE_FORMAT).ok()
251}
252
253fn parse_time(value: &str) -> Option<NaiveTime> {
254 NaiveTime::parse_from_str(value, TIME_FORMAT).ok()
255}
256
257pub fn collect_input_values(
258 inputs: &[CardInput],
259 value_of: impl Fn(&CardInput) -> String,
260) -> Result<Map<String, Value>, Vec<InputError>> {
261 let mut values = Map::new();
262 let mut errors = Vec::new();
263 for input in inputs {
264 let value = value_of(input);
265 match input.validate(&value) {
266 Some(message) => errors.push(InputError {
267 id: input.id.clone(),
268 message,
269 }),
270 None => {
271 values.insert(input.id.clone(), Value::String(value));
272 }
273 }
274 }
275 if errors.is_empty() {
276 Ok(values)
277 } else {
278 Err(errors)
279 }
280}
281
282pub fn merge_input_data(data: &Value, values: &Map<String, Value>) -> Value {
283 match data {
284 Value::Object(object) => {
285 let mut merged = object.clone();
286 merged.extend(values.clone());
287 Value::Object(merged)
288 }
289 Value::Null => Value::Object(values.clone()),
290 other => other.clone(),
291 }
292}
293
294pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> {
295 let id = text_field(value, "id")?;
296 let placeholder = text_field(value, "placeholder");
297 let kind = match input_type {
298 "Input.Text" => CardInputKind::Text(TextInput {
299 placeholder,
300 value: text_field(value, "value").unwrap_or_default(),
301 multiline: bool_field(value, "isMultiline"),
302 max_length: value
303 .get("maxLength")
304 .and_then(Value::as_u64)
305 .filter(|max_length| *max_length > 0)
306 .map(|max_length| max_length as usize),
307 style: TextStyle::parse(value.get("style").and_then(Value::as_str)),
308 regex: text_field(value, "regex"),
309 }),
310 "Input.Number" => CardInputKind::Number(NumberInput {
311 placeholder,
312 value: number_text(value.get("value")),
313 min: value.get("min").and_then(Value::as_f64),
314 max: value.get("max").and_then(Value::as_f64),
315 }),
316 "Input.Date" => CardInputKind::Date(parse_moment(value)),
317 "Input.Time" => CardInputKind::Time(parse_moment(value)),
318 "Input.Toggle" => {
319 let value_on =
320 text_field(value, "valueOn").unwrap_or_else(|| DEFAULT_VALUE_ON.to_owned());
321 let value_off =
322 text_field(value, "valueOff").unwrap_or_else(|| DEFAULT_VALUE_OFF.to_owned());
323 CardInputKind::Toggle(ToggleInput {
324 title: text_field(value, "title").unwrap_or_default(),
325 value: text_field(value, "value").unwrap_or_else(|| value_off.clone()),
326 value_on,
327 value_off,
328 })
329 }
330 "Input.ChoiceSet" => {
331 let choices: Vec<InputChoice> = value
332 .get("choices")?
333 .as_array()?
334 .iter()
335 .filter_map(|choice| {
336 Some(InputChoice {
337 title: text_field(choice, "title")?,
338 value: text_field(choice, "value")?,
339 })
340 })
341 .collect();
342 if choices.is_empty() {
343 return None;
344 }
345 CardInputKind::Choice(ChoiceInput {
346 choices,
347 multi: bool_field(value, "isMultiSelect"),
348 style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)),
349 placeholder,
350 value: text_field(value, "value").unwrap_or_default(),
351 })
352 }
353 _ => return None,
354 };
355 Some(CardInput {
356 id,
357 label: text_field(value, "label"),
358 required: bool_field(value, "isRequired"),
359 error_message: text_field(value, "errorMessage"),
360 kind,
361 })
362}
363
364fn parse_moment(value: &Value) -> MomentInput {
365 MomentInput {
366 value: text_field(value, "value").unwrap_or_default(),
367 min: text_field(value, "min"),
368 max: text_field(value, "max"),
369 }
370}
371
372fn text_field(value: &Value, key: &str) -> Option<String> {
373 value.get(key)?.as_str().map(str::to_owned)
374}
375
376fn bool_field(value: &Value, key: &str) -> bool {
377 value.get(key).and_then(Value::as_bool).unwrap_or(false)
378}
379
380fn number_text(value: Option<&Value>) -> String {
381 match value {
382 Some(Value::Number(number)) => number.to_string(),
383 Some(Value::String(text)) => text.clone(),
384 _ => String::new(),
385 }
386}
crates/core/src/lib.rs +6 −0
@@ -2,6 +2,7 @@ mod actions;
2 2 mod adaptive_card;
3 3 mod avatars;
4 4 mod card_actions;
5 mod card_inputs;
5 6 mod channel_sync;
6 7 mod download;
7 8 mod draft;
@@ -32,6 +33,11 @@ pub use adaptive_card::{
32 33 };
33 34 pub use avatars::Avatar;
34 35 pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
36 pub use card_inputs::{
37 CardInput, CardInputKind, ChoiceInput, ChoiceStyle, DATE_PLACEHOLDER, InputChoice, InputError,
38 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
39 collect_input_values, merge_input_data,
40 };
35 41 pub use chatsvc::ChatApp;
36 42 pub use draft::{
37 43 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -2,6 +2,7 @@ mod actions;
2mod adaptive_card;
2mod adaptive_card;
3mod avatars;
3mod avatars;
4mod card_actions;
4mod card_actions;
5mod card_inputs;
5mod channel_sync;
6mod channel_sync;
6mod download;
7mod download;
7mod draft;
8mod draft;
@@ -32,6 +33,11 @@ pub use adaptive_card::{
32};
33};
33pub use avatars::Avatar;
34pub use avatars::Avatar;
34pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
35pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
36pub use card_inputs::{
37 CardInput, CardInputKind, ChoiceInput, ChoiceStyle, DATE_PLACEHOLDER, InputChoice, InputError,
38 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
39 collect_input_values, merge_input_data,
40};
35pub use chatsvc::ChatApp;
41pub use chatsvc::ChatApp;
36pub use draft::{
42pub use draft::{
37 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
43 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
crates/core/tests/card_inputs.rs added +362 −0
@@ -0,0 +1,362 @@
1 use serde_json::{Value, json};
2 use teams_core::{
3 AdaptiveCard, CardAction, CardActionKind, CardElement, CardInput, CardInputKind, ChoiceStyle,
4 TextStyle, collect_input_values, merge_input_data,
5 };
6
7 fn card(body: Value, actions: Value) -> AdaptiveCard {
8 AdaptiveCard::parse(&json!({"body": body, "actions": actions}).to_string()).unwrap()
9 }
10
11 fn inputs(body: Value) -> Vec<CardInput> {
12 card(body, json!([])).own_inputs()
13 }
14
15 fn one(body: Value) -> CardInput {
16 let mut parsed = inputs(json!([body]));
17 assert_eq!(parsed.len(), 1);
18 parsed.remove(0)
19 }
20
21 fn submit(data: Value, associated: Option<&str>) -> CardAction {
22 let mut action = json!({"type": "Action.Submit", "title": "Go", "data": data});
23 if let Some(associated) = associated {
24 action["associatedInputs"] = json!(associated);
25 }
26 card(json!([{"type": "TextBlock", "text": "x"}]), json!([action]))
27 .actions
28 .remove(0)
29 }
30
31 fn values(pairs: Value) -> serde_json::Map<String, Value> {
32 pairs.as_object().unwrap().clone()
33 }
34
35 #[test]
36 fn text_input_keeps_every_field() {
37 let input = one(json!({
38 "type": "Input.Text", "id": "name", "label": "Name", "placeholder": "Your name",
39 "value": "Ada", "isMultiline": true, "maxLength": 20, "style": "Password",
40 "regex": "^[A-Z]", "isRequired": true, "errorMessage": "Start with a capital"
41 }));
42 assert_eq!(input.id, "name");
43 assert_eq!(input.label.as_deref(), Some("Name"));
44 assert!(input.required);
45 assert_eq!(input.error_message.as_deref(), Some("Start with a capital"));
46 let CardInputKind::Text(text) = &input.kind else {
47 panic!("text input expected");
48 };
49 assert_eq!(text.placeholder.as_deref(), Some("Your name"));
50 assert_eq!(text.value, "Ada");
51 assert!(text.multiline);
52 assert_eq!(text.max_length, Some(20));
53 assert_eq!(text.style, TextStyle::Password);
54 assert_eq!(text.regex.as_deref(), Some("^[A-Z]"));
55 }
56
57 #[test]
58 fn number_input_reads_numeric_value_and_range() {
59 let input = one(json!({"type": "Input.Number", "id": "n", "value": 5, "min": 1, "max": 10.5}));
60 let CardInputKind::Number(number) = &input.kind else {
61 panic!("number input expected");
62 };
63 assert_eq!(number.value, "5");
64 assert_eq!((number.min, number.max), (Some(1.), Some(10.5)));
65 }
66
67 #[test]
68 fn date_and_time_inputs_keep_their_bounds() {
69 let date = one(
70 json!({"type": "Input.Date", "id": "d", "value": "2026-01-02", "min": "2026-01-01", "max": "2026-12-31"}),
71 );
72 let CardInputKind::Date(moment) = &date.kind else {
73 panic!("date input expected");
74 };
75 assert_eq!(moment.value, "2026-01-02");
76 assert_eq!(moment.min.as_deref(), Some("2026-01-01"));
77 let time = one(json!({"type": "Input.Time", "id": "t", "value": "09:30"}));
78 assert!(matches!(time.kind, CardInputKind::Time(_)));
79 assert_eq!(time.initial_value(), "09:30");
80 }
81
82 #[test]
83 fn toggle_defaults_to_true_false_and_off() {
84 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "Agree"}));
85 let CardInputKind::Toggle(toggle) = &input.kind else {
86 panic!("toggle expected");
87 };
88 assert_eq!(toggle.title, "Agree");
89 assert_eq!(
90 (toggle.value_on.as_str(), toggle.value_off.as_str()),
91 ("true", "false")
92 );
93 assert_eq!(input.initial_value(), "false");
94 assert_eq!(toggle.flipped("false"), "true");
95 assert_eq!(toggle.flipped("true"), "false");
96 }
97
98 #[test]
99 fn toggle_with_custom_values_starts_on_its_value() {
100 let input = one(
101 json!({"type": "Input.Toggle", "id": "t", "title": "x", "valueOn": "yes", "valueOff": "no", "value": "yes"}),
102 );
103 assert_eq!(input.initial_value(), "yes");
104 }
105
106 #[test]
107 fn choice_set_parses_style_and_multi_select() {
108 let input = one(json!({
109 "type": "Input.ChoiceSet", "id": "c", "style": "expanded", "isMultiSelect": true,
110 "value": "a,b", "placeholder": "Pick",
111 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}, {"title": "C", "value": "c"}]
112 }));
113 let CardInputKind::Choice(choice) = &input.kind else {
114 panic!("choice set expected");
115 };
116 assert_eq!(choice.style, ChoiceStyle::Expanded);
117 assert!(choice.multi);
118 assert_eq!(choice.choices.len(), 3);
119 assert_eq!(choice.selected("a,b"), vec!["a", "b"]);
120 assert_eq!(choice.toggled("a,b", "c"), "a,b,c");
121 assert_eq!(choice.toggled("a,b", "a"), "b");
122 assert_eq!(choice.toggled("", "b"), "b");
123 }
124
125 #[test]
126 fn single_choice_replaces_the_selection() {
127 let input = one(json!({
128 "type": "Input.ChoiceSet", "id": "c", "style": "filtered",
129 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}]
130 }));
131 let CardInputKind::Choice(choice) = &input.kind else {
132 panic!("choice set expected");
133 };
134 assert_eq!(choice.style, ChoiceStyle::Filtered);
135 assert_eq!(choice.toggled("a", "b"), "b");
136 assert!(choice.selected("").is_empty());
137 }
138
139 #[test]
140 fn inputs_without_id_or_choices_and_unknown_types_fall_back() {
141 let parsed = card(
142 json!([
143 {"type": "Input.Text"},
144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
145 {"type": "Input.Rating", "id": "r", "fallbackText": "Rating is not supported"}
146 ]),
147 json!([]),
148 );
149 assert!(parsed.own_inputs().is_empty());
150 assert_eq!(parsed.items.len(), 1);
151 assert!(matches!(parsed.items[0].element, CardElement::Text(_)));
152 }
153
154 #[test]
155 fn nested_inputs_are_found_in_containers_and_columns_but_not_show_cards() {
156 let parsed = card(
157 json!([
158 {"type": "Input.Text", "id": "a"},
159 {"type": "Container", "items": [{"type": "Input.Text", "id": "b"}]},
160 {"type": "ColumnSet", "columns": [{"type": "Column", "items": [{"type": "Input.Text", "id": "c"}]}]},
161 {"type": "ActionSet", "actions": [
162 {"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "Input.Text", "id": "d"}]}}
163 ]}
164 ]),
165 json!([]),
166 );
167 let own: Vec<String> = parsed
168 .own_inputs()
169 .into_iter()
170 .map(|input| input.id)
171 .collect();
172 assert_eq!(own, ["a", "b", "c"]);
173 let all: Vec<String> = parsed
174 .all_inputs()
175 .into_iter()
176 .map(|input| input.id)
177 .collect();
178 assert_eq!(all, ["a", "b", "c", "d"]);
179 }
180
181 #[test]
182 fn required_input_rejects_empty_with_default_or_custom_message() {
183 let plain = one(json!({"type": "Input.Text", "id": "a", "isRequired": true}));
184 assert_eq!(plain.validate("").as_deref(), Some("Required"));
185 assert_eq!(plain.validate("x"), None);
186 let custom = one(
187 json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Tell us"}),
188 );
189 assert_eq!(custom.validate("").as_deref(), Some("Tell us"));
190 let optional = one(json!({"type": "Input.Text", "id": "a"}));
191 assert_eq!(optional.validate(""), None);
192 }
193
194 #[test]
195 fn text_regex_and_max_length_are_validated() {
196 let input = one(json!({"type": "Input.Text", "id": "a", "regex": "^\\d+$", "maxLength": 3}));
197 assert_eq!(input.validate("12"), None);
198 assert_eq!(input.validate("ab").as_deref(), Some("Invalid value"));
199 assert_eq!(input.validate("1234").as_deref(), Some("Invalid value"));
200 }
201
202 #[test]
203 fn number_range_and_format_are_validated() {
204 let input = one(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 10}));
205 assert_eq!(input.validate("5.5"), None);
206 assert_eq!(input.validate("0").as_deref(), Some("Invalid value"));
207 assert_eq!(input.validate("11").as_deref(), Some("Invalid value"));
208 assert_eq!(input.validate("abc").as_deref(), Some("Invalid value"));
209 }
210
211 #[test]
212 fn date_and_time_format_and_bounds_are_validated() {
213 let date =
214 one(json!({"type": "Input.Date", "id": "d", "min": "2026-01-10", "max": "2026-01-20"}));
215 assert_eq!(date.validate("2026-01-15"), None);
216 assert!(date.validate("2026-01-09").is_some());
217 assert!(date.validate("2026-01-21").is_some());
218 assert!(date.validate("15.01.2026").is_some());
219 assert!(date.validate("2026-02-30").is_some());
220 let time = one(json!({"type": "Input.Time", "id": "t", "min": "09:00", "max": "17:00"}));
221 assert_eq!(time.validate("09:30"), None);
222 assert!(time.validate("08:59").is_some());
223 assert!(time.validate("25:00").is_some());
224 }
225
226 #[test]
227 fn required_toggle_must_be_on() {
228 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "x", "isRequired": true}));
229 assert_eq!(input.validate("false").as_deref(), Some("Invalid value"));
230 assert_eq!(input.validate("true"), None);
231 }
232
233 #[test]
234 fn collecting_returns_every_error_or_all_values() {
235 let parsed = inputs(json!([
236 {"type": "Input.Text", "id": "a", "isRequired": true},
237 {"type": "Input.Text", "id": "b", "isRequired": true, "errorMessage": "Needed"},
238 {"type": "Input.Text", "id": "c"}
239 ]));
240 let errors = collect_input_values(&parsed, |input| {
241 if input.id == "c" {
242 "x".into()
243 } else {
244 String::new()
245 }
246 })
247 .unwrap_err();
248 assert_eq!(errors.len(), 2);
249 assert_eq!(errors[0].id, "a");
250 assert_eq!(errors[1].message, "Needed");
251 let collected = collect_input_values(&parsed, |input| format!("v-{}", input.id)).unwrap();
252 assert_eq!(
253 Value::Object(collected),
254 json!({"a": "v-a", "b": "v-b", "c": "v-c"})
255 );
256 }
257
258 #[test]
259 fn merge_keeps_string_data_and_builds_objects_otherwise() {
260 let inputs = values(json!({"a": "1"}));
261 assert_eq!(
262 merge_input_data(&json!({"k": 1, "a": "old"}), &inputs),
263 json!({"k": 1, "a": "1"})
264 );
265 assert_eq!(merge_input_data(&Value::Null, &inputs), json!({"a": "1"}));
266 assert_eq!(merge_input_data(&json!("plain"), &inputs), json!("plain"));
267 }
268
269 #[test]
270 fn submit_payload_carries_the_merged_inputs() {
271 let action = submit(json!({"action": "save"}), None);
272 assert!(action.collects_inputs);
273 let payload = action
274 .with_inputs(&values(json!({"name": "Ada"})))
275 .invoke_payload()
276 .unwrap();
277 assert_eq!(payload.name, "messageback");
278 assert_eq!(payload.value, json!({"action": "save", "name": "Ada"}));
279 }
280
281 #[test]
282 fn submit_without_data_becomes_the_input_object() {
283 let action = card(
284 json!([{"type": "TextBlock", "text": "x"}]),
285 json!([{"type": "Action.Submit", "title": "Go"}]),
286 )
287 .actions
288 .remove(0);
289 let payload = action
290 .with_inputs(&values(json!({"name": "Ada"})))
291 .invoke_payload()
292 .unwrap();
293 assert_eq!(payload.value, json!({"name": "Ada"}));
294 }
295
296 #[test]
297 fn submit_with_string_data_ignores_the_inputs() {
298 let action = submit(json!("go"), None);
299 let payload = action
300 .with_inputs(&values(json!({"name": "Ada"})))
301 .invoke_payload()
302 .unwrap();
303 assert_eq!(payload.value, json!("go"));
304 }
305
306 #[test]
307 fn associated_inputs_none_is_parsed() {
308 assert!(!submit(json!({}), Some("none")).collects_inputs);
309 assert!(submit(json!({}), Some("auto")).collects_inputs);
310 }
311
312 #[test]
313 fn message_back_sends_the_merged_object_as_value() {
314 let action = submit(
315 json!({"id": 7, "msteams": {"type": "messageBack", "text": "hi", "value": "old"}}),
316 None,
317 );
318 let payload = action
319 .with_inputs(&values(json!({"name": "Ada"})))
320 .invoke_payload()
321 .unwrap();
322 assert_eq!(payload.value, json!({"id": 7, "name": "Ada"}));
323 let without = action
324 .with_inputs(&values(json!({})))
325 .invoke_payload()
326 .unwrap();
327 assert_eq!(without.value, json!("old"));
328 }
329
330 #[test]
331 fn task_fetch_merges_inputs_and_drops_the_settings() {
332 let action = submit(json!({"msteams": {"type": "task/fetch"}, "k": 1}), None);
333 let payload = action
334 .with_inputs(&values(json!({"name": "Ada"})))
335 .invoke_payload()
336 .unwrap();
337 assert_eq!(payload.name, "task/fetch");
338 assert_eq!(
339 payload.value,
340 json!({"data": {"k": 1, "name": "Ada", "type": "task/fetch"}, "context": {"theme": "dark"}})
341 );
342 }
343
344 #[test]
345 fn execute_merges_inputs_into_the_action_data() {
346 let action = card(
347 json!([{"type": "TextBlock", "text": "x"}]),
348 json!([{"type": "Action.Execute", "title": "Go", "verb": "save", "data": {"k": 1}}]),
349 )
350 .actions
351 .remove(0);
352 let sent = action.with_inputs(&values(json!({"name": "Ada"})));
353 let CardActionKind::Execute(execute) = &sent.kind else {
354 panic!("execute expected");
355 };
356 assert_eq!(execute.data, json!({"k": 1, "name": "Ada"}));
357 let payload = sent.invoke_payload().unwrap();
358 assert_eq!(
359 payload.value["action"]["data"],
360 json!({"k": 1, "name": "Ada"})
361 );
362 }
@@ -0,0 +1,362 @@
1use serde_json::{Value, json};
2use teams_core::{
3 AdaptiveCard, CardAction, CardActionKind, CardElement, CardInput, CardInputKind, ChoiceStyle,
4 TextStyle, collect_input_values, merge_input_data,
5};
6
7fn card(body: Value, actions: Value) -> AdaptiveCard {
8 AdaptiveCard::parse(&json!({"body": body, "actions": actions}).to_string()).unwrap()
9}
10
11fn inputs(body: Value) -> Vec<CardInput> {
12 card(body, json!([])).own_inputs()
13}
14
15fn one(body: Value) -> CardInput {
16 let mut parsed = inputs(json!([body]));
17 assert_eq!(parsed.len(), 1);
18 parsed.remove(0)
19}
20
21fn submit(data: Value, associated: Option<&str>) -> CardAction {
22 let mut action = json!({"type": "Action.Submit", "title": "Go", "data": data});
23 if let Some(associated) = associated {
24 action["associatedInputs"] = json!(associated);
25 }
26 card(json!([{"type": "TextBlock", "text": "x"}]), json!([action]))
27 .actions
28 .remove(0)
29}
30
31fn values(pairs: Value) -> serde_json::Map<String, Value> {
32 pairs.as_object().unwrap().clone()
33}
34
35#[test]
36fn text_input_keeps_every_field() {
37 let input = one(json!({
38 "type": "Input.Text", "id": "name", "label": "Name", "placeholder": "Your name",
39 "value": "Ada", "isMultiline": true, "maxLength": 20, "style": "Password",
40 "regex": "^[A-Z]", "isRequired": true, "errorMessage": "Start with a capital"
41 }));
42 assert_eq!(input.id, "name");
43 assert_eq!(input.label.as_deref(), Some("Name"));
44 assert!(input.required);
45 assert_eq!(input.error_message.as_deref(), Some("Start with a capital"));
46 let CardInputKind::Text(text) = &input.kind else {
47 panic!("text input expected");
48 };
49 assert_eq!(text.placeholder.as_deref(), Some("Your name"));
50 assert_eq!(text.value, "Ada");
51 assert!(text.multiline);
52 assert_eq!(text.max_length, Some(20));
53 assert_eq!(text.style, TextStyle::Password);
54 assert_eq!(text.regex.as_deref(), Some("^[A-Z]"));
55}
56
57#[test]
58fn number_input_reads_numeric_value_and_range() {
59 let input = one(json!({"type": "Input.Number", "id": "n", "value": 5, "min": 1, "max": 10.5}));
60 let CardInputKind::Number(number) = &input.kind else {
61 panic!("number input expected");
62 };
63 assert_eq!(number.value, "5");
64 assert_eq!((number.min, number.max), (Some(1.), Some(10.5)));
65}
66
67#[test]
68fn date_and_time_inputs_keep_their_bounds() {
69 let date = one(
70 json!({"type": "Input.Date", "id": "d", "value": "2026-01-02", "min": "2026-01-01", "max": "2026-12-31"}),
71 );
72 let CardInputKind::Date(moment) = &date.kind else {
73 panic!("date input expected");
74 };
75 assert_eq!(moment.value, "2026-01-02");
76 assert_eq!(moment.min.as_deref(), Some("2026-01-01"));
77 let time = one(json!({"type": "Input.Time", "id": "t", "value": "09:30"}));
78 assert!(matches!(time.kind, CardInputKind::Time(_)));
79 assert_eq!(time.initial_value(), "09:30");
80}
81
82#[test]
83fn toggle_defaults_to_true_false_and_off() {
84 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "Agree"}));
85 let CardInputKind::Toggle(toggle) = &input.kind else {
86 panic!("toggle expected");
87 };
88 assert_eq!(toggle.title, "Agree");
89 assert_eq!(
90 (toggle.value_on.as_str(), toggle.value_off.as_str()),
91 ("true", "false")
92 );
93 assert_eq!(input.initial_value(), "false");
94 assert_eq!(toggle.flipped("false"), "true");
95 assert_eq!(toggle.flipped("true"), "false");
96}
97
98#[test]
99fn toggle_with_custom_values_starts_on_its_value() {
100 let input = one(
101 json!({"type": "Input.Toggle", "id": "t", "title": "x", "valueOn": "yes", "valueOff": "no", "value": "yes"}),
102 );
103 assert_eq!(input.initial_value(), "yes");
104}
105
106#[test]
107fn choice_set_parses_style_and_multi_select() {
108 let input = one(json!({
109 "type": "Input.ChoiceSet", "id": "c", "style": "expanded", "isMultiSelect": true,
110 "value": "a,b", "placeholder": "Pick",
111 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}, {"title": "C", "value": "c"}]
112 }));
113 let CardInputKind::Choice(choice) = &input.kind else {
114 panic!("choice set expected");
115 };
116 assert_eq!(choice.style, ChoiceStyle::Expanded);
117 assert!(choice.multi);
118 assert_eq!(choice.choices.len(), 3);
119 assert_eq!(choice.selected("a,b"), vec!["a", "b"]);
120 assert_eq!(choice.toggled("a,b", "c"), "a,b,c");
121 assert_eq!(choice.toggled("a,b", "a"), "b");
122 assert_eq!(choice.toggled("", "b"), "b");
123}
124
125#[test]
126fn single_choice_replaces_the_selection() {
127 let input = one(json!({
128 "type": "Input.ChoiceSet", "id": "c", "style": "filtered",
129 "choices": [{"title": "A", "value": "a"}, {"title": "B", "value": "b"}]
130 }));
131 let CardInputKind::Choice(choice) = &input.kind else {
132 panic!("choice set expected");
133 };
134 assert_eq!(choice.style, ChoiceStyle::Filtered);
135 assert_eq!(choice.toggled("a", "b"), "b");
136 assert!(choice.selected("").is_empty());
137}
138
139#[test]
140fn inputs_without_id_or_choices_and_unknown_types_fall_back() {
141 let parsed = card(
142 json!([
143 {"type": "Input.Text"},
144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
145 {"type": "Input.Rating", "id": "r", "fallbackText": "Rating is not supported"}
146 ]),
147 json!([]),
148 );
149 assert!(parsed.own_inputs().is_empty());
150 assert_eq!(parsed.items.len(), 1);
151 assert!(matches!(parsed.items[0].element, CardElement::Text(_)));
152}
153
154#[test]
155fn nested_inputs_are_found_in_containers_and_columns_but_not_show_cards() {
156 let parsed = card(
157 json!([
158 {"type": "Input.Text", "id": "a"},
159 {"type": "Container", "items": [{"type": "Input.Text", "id": "b"}]},
160 {"type": "ColumnSet", "columns": [{"type": "Column", "items": [{"type": "Input.Text", "id": "c"}]}]},
161 {"type": "ActionSet", "actions": [
162 {"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "Input.Text", "id": "d"}]}}
163 ]}
164 ]),
165 json!([]),
166 );
167 let own: Vec<String> = parsed
168 .own_inputs()
169 .into_iter()
170 .map(|input| input.id)
171 .collect();
172 assert_eq!(own, ["a", "b", "c"]);
173 let all: Vec<String> = parsed
174 .all_inputs()
175 .into_iter()
176 .map(|input| input.id)
177 .collect();
178 assert_eq!(all, ["a", "b", "c", "d"]);
179}
180
181#[test]
182fn required_input_rejects_empty_with_default_or_custom_message() {
183 let plain = one(json!({"type": "Input.Text", "id": "a", "isRequired": true}));
184 assert_eq!(plain.validate("").as_deref(), Some("Required"));
185 assert_eq!(plain.validate("x"), None);
186 let custom = one(
187 json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Tell us"}),
188 );
189 assert_eq!(custom.validate("").as_deref(), Some("Tell us"));
190 let optional = one(json!({"type": "Input.Text", "id": "a"}));
191 assert_eq!(optional.validate(""), None);
192}
193
194#[test]
195fn text_regex_and_max_length_are_validated() {
196 let input = one(json!({"type": "Input.Text", "id": "a", "regex": "^\\d+$", "maxLength": 3}));
197 assert_eq!(input.validate("12"), None);
198 assert_eq!(input.validate("ab").as_deref(), Some("Invalid value"));
199 assert_eq!(input.validate("1234").as_deref(), Some("Invalid value"));
200}
201
202#[test]
203fn number_range_and_format_are_validated() {
204 let input = one(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 10}));
205 assert_eq!(input.validate("5.5"), None);
206 assert_eq!(input.validate("0").as_deref(), Some("Invalid value"));
207 assert_eq!(input.validate("11").as_deref(), Some("Invalid value"));
208 assert_eq!(input.validate("abc").as_deref(), Some("Invalid value"));
209}
210
211#[test]
212fn date_and_time_format_and_bounds_are_validated() {
213 let date =
214 one(json!({"type": "Input.Date", "id": "d", "min": "2026-01-10", "max": "2026-01-20"}));
215 assert_eq!(date.validate("2026-01-15"), None);
216 assert!(date.validate("2026-01-09").is_some());
217 assert!(date.validate("2026-01-21").is_some());
218 assert!(date.validate("15.01.2026").is_some());
219 assert!(date.validate("2026-02-30").is_some());
220 let time = one(json!({"type": "Input.Time", "id": "t", "min": "09:00", "max": "17:00"}));
221 assert_eq!(time.validate("09:30"), None);
222 assert!(time.validate("08:59").is_some());
223 assert!(time.validate("25:00").is_some());
224}
225
226#[test]
227fn required_toggle_must_be_on() {
228 let input = one(json!({"type": "Input.Toggle", "id": "t", "title": "x", "isRequired": true}));
229 assert_eq!(input.validate("false").as_deref(), Some("Invalid value"));
230 assert_eq!(input.validate("true"), None);
231}
232
233#[test]
234fn collecting_returns_every_error_or_all_values() {
235 let parsed = inputs(json!([
236 {"type": "Input.Text", "id": "a", "isRequired": true},
237 {"type": "Input.Text", "id": "b", "isRequired": true, "errorMessage": "Needed"},
238 {"type": "Input.Text", "id": "c"}
239 ]));
240 let errors = collect_input_values(&parsed, |input| {
241 if input.id == "c" {
242 "x".into()
243 } else {
244 String::new()
245 }
246 })
247 .unwrap_err();
248 assert_eq!(errors.len(), 2);
249 assert_eq!(errors[0].id, "a");
250 assert_eq!(errors[1].message, "Needed");
251 let collected = collect_input_values(&parsed, |input| format!("v-{}", input.id)).unwrap();
252 assert_eq!(
253 Value::Object(collected),
254 json!({"a": "v-a", "b": "v-b", "c": "v-c"})
255 );
256}
257
258#[test]
259fn merge_keeps_string_data_and_builds_objects_otherwise() {
260 let inputs = values(json!({"a": "1"}));
261 assert_eq!(
262 merge_input_data(&json!({"k": 1, "a": "old"}), &inputs),
263 json!({"k": 1, "a": "1"})
264 );
265 assert_eq!(merge_input_data(&Value::Null, &inputs), json!({"a": "1"}));
266 assert_eq!(merge_input_data(&json!("plain"), &inputs), json!("plain"));
267}
268
269#[test]
270fn submit_payload_carries_the_merged_inputs() {
271 let action = submit(json!({"action": "save"}), None);
272 assert!(action.collects_inputs);
273 let payload = action
274 .with_inputs(&values(json!({"name": "Ada"})))
275 .invoke_payload()
276 .unwrap();
277 assert_eq!(payload.name, "messageback");
278 assert_eq!(payload.value, json!({"action": "save", "name": "Ada"}));
279}
280
281#[test]
282fn submit_without_data_becomes_the_input_object() {
283 let action = card(
284 json!([{"type": "TextBlock", "text": "x"}]),
285 json!([{"type": "Action.Submit", "title": "Go"}]),
286 )
287 .actions
288 .remove(0);
289 let payload = action
290 .with_inputs(&values(json!({"name": "Ada"})))
291 .invoke_payload()
292 .unwrap();
293 assert_eq!(payload.value, json!({"name": "Ada"}));
294}
295
296#[test]
297fn submit_with_string_data_ignores_the_inputs() {
298 let action = submit(json!("go"), None);
299 let payload = action
300 .with_inputs(&values(json!({"name": "Ada"})))
301 .invoke_payload()
302 .unwrap();
303 assert_eq!(payload.value, json!("go"));
304}
305
306#[test]
307fn associated_inputs_none_is_parsed() {
308 assert!(!submit(json!({}), Some("none")).collects_inputs);
309 assert!(submit(json!({}), Some("auto")).collects_inputs);
310}
311
312#[test]
313fn message_back_sends_the_merged_object_as_value() {
314 let action = submit(
315 json!({"id": 7, "msteams": {"type": "messageBack", "text": "hi", "value": "old"}}),
316 None,
317 );
318 let payload = action
319 .with_inputs(&values(json!({"name": "Ada"})))
320 .invoke_payload()
321 .unwrap();
322 assert_eq!(payload.value, json!({"id": 7, "name": "Ada"}));
323 let without = action
324 .with_inputs(&values(json!({})))
325 .invoke_payload()
326 .unwrap();
327 assert_eq!(without.value, json!("old"));
328}
329
330#[test]
331fn task_fetch_merges_inputs_and_drops_the_settings() {
332 let action = submit(json!({"msteams": {"type": "task/fetch"}, "k": 1}), None);
333 let payload = action
334 .with_inputs(&values(json!({"name": "Ada"})))
335 .invoke_payload()
336 .unwrap();
337 assert_eq!(payload.name, "task/fetch");
338 assert_eq!(
339 payload.value,
340 json!({"data": {"k": 1, "name": "Ada", "type": "task/fetch"}, "context": {"theme": "dark"}})
341 );
342}
343
344#[test]
345fn execute_merges_inputs_into_the_action_data() {
346 let action = card(
347 json!([{"type": "TextBlock", "text": "x"}]),
348 json!([{"type": "Action.Execute", "title": "Go", "verb": "save", "data": {"k": 1}}]),
349 )
350 .actions
351 .remove(0);
352 let sent = action.with_inputs(&values(json!({"name": "Ada"})));
353 let CardActionKind::Execute(execute) = &sent.kind else {
354 panic!("execute expected");
355 };
356 assert_eq!(execute.data, json!({"k": 1, "name": "Ada"}));
357 let payload = sent.invoke_payload().unwrap();
358 assert_eq!(
359 payload.value["action"]["data"],
360 json!({"k": 1, "name": "Ada"})
361 );
362}