| 1 | use chrono::{NaiveDate, NaiveTime}; |
| 2 | use regex::Regex; |
| 3 | use serde_json::{Map, Number, Value, json}; |
| 4 | |
| 5 | use crate::adaptive_card::{CardAction, CardActionKind, parse_action}; |
| 6 | |
| 7 | const DATE_FORMAT: &str = "%Y-%m-%d"; |
| 8 | const TIME_FORMAT: &str = "%H:%M"; |
| 9 | const DEFAULT_VALUE_ON: &str = "true"; |
| 10 | const DEFAULT_VALUE_OFF: &str = "false"; |
| 11 | const CHOICE_SEPARATOR: char = ','; |
| 12 | const REQUIRED_MESSAGE: &str = "Required"; |
| 13 | const INVALID_MESSAGE: &str = "Invalid value"; |
| 14 | const INLINE_ACTION_TITLE: &str = "Go"; |
| 15 | const DEFAULT_SEARCH_COUNT: usize = 15; |
| 16 | const DEFAULT_RATING_MAX: u32 = 5; |
| 17 | const MAX_RATING_MAX: u32 = 10; |
| 18 | const WHOLE_NUMBER_LIMIT: f64 = 1e15; |
| 19 | const DATA_QUERY_TYPE: &str = "Data.Query"; |
| 20 | pub const SEARCH_INVOKE_NAME: &str = "application/search"; |
| 21 | pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD"; |
| 22 | pub const TIME_PLACEHOLDER: &str = "HH:MM"; |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq)] |
| 25 | pub struct CardInput { |
| 26 | pub id: String, |
| 27 | pub label: Option<String>, |
| 28 | pub required: bool, |
| 29 | pub error_message: Option<String>, |
| 30 | pub kind: CardInputKind, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, PartialEq)] |
| 34 | pub enum CardInputKind { |
| 35 | Text(TextInput), |
| 36 | Number(NumberInput), |
| 37 | Date(MomentInput), |
| 38 | Time(MomentInput), |
| 39 | Toggle(ToggleInput), |
| 40 | Choice(ChoiceInput), |
| 41 | Rating(RatingInput), |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 45 | pub enum TextStyle { |
| 46 | Text, |
| 47 | Tel, |
| 48 | Url, |
| 49 | Email, |
| 50 | Password, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone, PartialEq)] |
| 54 | pub struct TextInput { |
| 55 | pub placeholder: Option<String>, |
| 56 | pub value: String, |
| 57 | pub multiline: bool, |
| 58 | pub max_length: Option<usize>, |
| 59 | pub style: TextStyle, |
| 60 | pub regex: Option<String>, |
| 61 | pub inline_action: Option<Box<InlineAction>>, |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone, PartialEq)] |
| 65 | pub struct InlineAction { |
| 66 | pub action: CardAction, |
| 67 | pub icon_url: Option<String>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone, PartialEq)] |
| 71 | pub struct NumberInput { |
| 72 | pub placeholder: Option<String>, |
| 73 | pub value: String, |
| 74 | pub min: Option<f64>, |
| 75 | pub max: Option<f64>, |
| 76 | } |
| 77 | |
| 78 | #[derive(Debug, Clone, PartialEq)] |
| 79 | pub struct MomentInput { |
| 80 | pub value: String, |
| 81 | pub min: Option<String>, |
| 82 | pub max: Option<String>, |
| 83 | } |
| 84 | |
| 85 | #[derive(Debug, Clone, PartialEq)] |
| 86 | pub struct ToggleInput { |
| 87 | pub title: String, |
| 88 | pub value: String, |
| 89 | pub value_on: String, |
| 90 | pub value_off: String, |
| 91 | pub wrap: bool, |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 95 | pub enum ChoiceStyle { |
| 96 | Compact, |
| 97 | Expanded, |
| 98 | Filtered, |
| 99 | } |
| 100 | |
| 101 | #[derive(Debug, Clone, PartialEq)] |
| 102 | pub struct ChoiceInput { |
| 103 | pub choices: Vec<InputChoice>, |
| 104 | pub multi: bool, |
| 105 | pub style: ChoiceStyle, |
| 106 | pub placeholder: Option<String>, |
| 107 | pub value: String, |
| 108 | pub query: Option<ChoiceQuery>, |
| 109 | } |
| 110 | |
| 111 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 112 | pub struct ChoiceQuery { |
| 113 | pub dataset: String, |
| 114 | pub count: usize, |
| 115 | } |
| 116 | |
| 117 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 118 | pub enum RatingColor { |
| 119 | Neutral, |
| 120 | Marigold, |
| 121 | } |
| 122 | |
| 123 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 124 | pub enum RatingSize { |
| 125 | Medium, |
| 126 | Large, |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 130 | pub enum RatingStyle { |
| 131 | Default, |
| 132 | Compact, |
| 133 | } |
| 134 | |
| 135 | #[derive(Debug, Clone, PartialEq)] |
| 136 | pub struct RatingInput { |
| 137 | pub max: u32, |
| 138 | pub value: String, |
| 139 | pub color: RatingColor, |
| 140 | pub size: RatingSize, |
| 141 | pub allow_half: bool, |
| 142 | } |
| 143 | |
| 144 | #[derive(Debug, Clone, PartialEq)] |
| 145 | pub struct RatingDisplay { |
| 146 | pub value: f64, |
| 147 | pub max: u32, |
| 148 | pub count: Option<u64>, |
| 149 | pub size: RatingSize, |
| 150 | pub style: RatingStyle, |
| 151 | } |
| 152 | |
| 153 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 154 | pub struct InputChoice { |
| 155 | pub title: String, |
| 156 | pub value: String, |
| 157 | } |
| 158 | |
| 159 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 160 | pub struct InputError { |
| 161 | pub id: String, |
| 162 | pub message: String, |
| 163 | } |
| 164 | |
| 165 | impl TextStyle { |
| 166 | fn parse(value: Option<&str>) -> Self { |
| 167 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 168 | Some("tel") => TextStyle::Tel, |
| 169 | Some("url") => TextStyle::Url, |
| 170 | Some("email") => TextStyle::Email, |
| 171 | Some("password") => TextStyle::Password, |
| 172 | _ => TextStyle::Text, |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | impl ChoiceStyle { |
| 178 | fn parse(value: Option<&str>) -> Self { |
| 179 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 180 | Some("expanded") => ChoiceStyle::Expanded, |
| 181 | Some("filtered") => ChoiceStyle::Filtered, |
| 182 | _ => ChoiceStyle::Compact, |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | impl RatingColor { |
| 188 | fn parse(value: Option<&str>) -> Self { |
| 189 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 190 | Some("marigold") => RatingColor::Marigold, |
| 191 | _ => RatingColor::Neutral, |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | impl RatingSize { |
| 197 | fn parse(value: Option<&str>) -> Self { |
| 198 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 199 | Some("large") => RatingSize::Large, |
| 200 | _ => RatingSize::Medium, |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | impl RatingStyle { |
| 206 | fn parse(value: Option<&str>) -> Self { |
| 207 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 208 | Some("compact") => RatingStyle::Compact, |
| 209 | _ => RatingStyle::Default, |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | impl RatingInput { |
| 215 | pub fn rating(&self, current: &str) -> f64 { |
| 216 | current.trim().parse::<f64>().unwrap_or(0.) |
| 217 | } |
| 218 | |
| 219 | pub fn value_text(&self, rating: f64) -> String { |
| 220 | if rating <= 0. { |
| 221 | String::new() |
| 222 | } else { |
| 223 | number_value(rating.min(f64::from(self.max))).to_string() |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl ToggleInput { |
| 229 | pub fn is_on(&self, current: &str) -> bool { |
| 230 | current == self.value_on |
| 231 | } |
| 232 | |
| 233 | pub fn flipped(&self, current: &str) -> String { |
| 234 | if self.is_on(current) { |
| 235 | self.value_off.clone() |
| 236 | } else { |
| 237 | self.value_on.clone() |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | impl ChoiceInput { |
| 243 | pub fn selected<'current>(&self, current: &'current str) -> Vec<&'current str> { |
| 244 | if self.multi { |
| 245 | current |
| 246 | .split(CHOICE_SEPARATOR) |
| 247 | .map(str::trim) |
| 248 | .filter(|value| !value.is_empty()) |
| 249 | .collect() |
| 250 | } else { |
| 251 | Some(current) |
| 252 | .filter(|value| !value.is_empty()) |
| 253 | .into_iter() |
| 254 | .collect() |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | pub fn is_selected(&self, current: &str, choice_value: &str) -> bool { |
| 259 | self.selected(current).contains(&choice_value) |
| 260 | } |
| 261 | |
| 262 | pub fn toggled(&self, current: &str, choice_value: &str) -> String { |
| 263 | if !self.multi { |
| 264 | return choice_value.to_owned(); |
| 265 | } |
| 266 | let selected = self.selected(current); |
| 267 | let keep = |choice: &&InputChoice| { |
| 268 | (choice.value == choice_value) != selected.contains(&choice.value.as_str()) |
| 269 | }; |
| 270 | self.choices |
| 271 | .iter() |
| 272 | .filter(keep) |
| 273 | .map(|choice| choice.value.as_str()) |
| 274 | .collect::<Vec<_>>() |
| 275 | .join(&CHOICE_SEPARATOR.to_string()) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | impl CardInput { |
| 280 | pub fn initial_value(&self) -> String { |
| 281 | match &self.kind { |
| 282 | CardInputKind::Text(text) => text.value.clone(), |
| 283 | CardInputKind::Number(number) => number.value.clone(), |
| 284 | CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(), |
| 285 | CardInputKind::Toggle(toggle) => toggle.value.clone(), |
| 286 | CardInputKind::Choice(choice) => choice.value.clone(), |
| 287 | CardInputKind::Rating(rating) => rating.value.clone(), |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | pub fn submitted_value(&self, value: &str) -> Value { |
| 292 | match (&self.kind, value.trim().parse::<f64>()) { |
| 293 | (CardInputKind::Rating(_), Ok(number)) if number.is_finite() => { |
| 294 | Value::Number(number_value(number)) |
| 295 | } |
| 296 | _ => Value::String(value.to_owned()), |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | fn is_blank(&self, value: &str) -> bool { |
| 301 | match &self.kind { |
| 302 | CardInputKind::Rating(rating) => value.is_empty() || rating.rating(value) <= 0., |
| 303 | _ => value.is_empty(), |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | pub fn validate(&self, value: &str) -> Option<String> { |
| 308 | let message = || { |
| 309 | self.error_message |
| 310 | .clone() |
| 311 | .filter(|message| !message.trim().is_empty()) |
| 312 | }; |
| 313 | if self.is_blank(value) { |
| 314 | return (self.required) |
| 315 | .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned())); |
| 316 | } |
| 317 | let valid = match &self.kind { |
| 318 | CardInputKind::Text(text) => text.accepts(value), |
| 319 | CardInputKind::Number(number) => number.accepts(value), |
| 320 | CardInputKind::Date(moment) => moment.accepts(value, parse_date), |
| 321 | CardInputKind::Time(moment) => moment.accepts(value, parse_time), |
| 322 | CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value), |
| 323 | CardInputKind::Choice(_) => true, |
| 324 | CardInputKind::Rating(rating) => !self.required || rating.rating(value) > 0., |
| 325 | }; |
| 326 | (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned())) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | impl TextInput { |
| 331 | fn accepts(&self, value: &str) -> bool { |
| 332 | self.max_length |
| 333 | .is_none_or(|max_length| value.chars().count() <= max_length) |
| 334 | && self |
| 335 | .regex |
| 336 | .as_deref() |
| 337 | .is_none_or(|pattern| Regex::new(pattern).is_ok_and(|regex| regex.is_match(value))) |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | impl NumberInput { |
| 342 | fn accepts(&self, value: &str) -> bool { |
| 343 | let Ok(number) = value.trim().parse::<f64>() else { |
| 344 | return false; |
| 345 | }; |
| 346 | number.is_finite() |
| 347 | && self.min.is_none_or(|min| number >= min) |
| 348 | && self.max.is_none_or(|max| number <= max) |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | impl MomentInput { |
| 353 | pub fn initial_date(&self) -> Option<NaiveDate> { |
| 354 | parse_date(&self.value) |
| 355 | } |
| 356 | |
| 357 | pub fn min_date(&self) -> Option<NaiveDate> { |
| 358 | self.min.as_deref().and_then(parse_date) |
| 359 | } |
| 360 | |
| 361 | pub fn max_date(&self) -> Option<NaiveDate> { |
| 362 | self.max.as_deref().and_then(parse_date) |
| 363 | } |
| 364 | |
| 365 | pub fn initial_time(&self) -> Option<NaiveTime> { |
| 366 | parse_time(&self.value) |
| 367 | } |
| 368 | |
| 369 | fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool { |
| 370 | let Some(moment) = parse(value) else { |
| 371 | return false; |
| 372 | }; |
| 373 | self.min |
| 374 | .as_deref() |
| 375 | .and_then(parse) |
| 376 | .is_none_or(|min| moment >= min) |
| 377 | && self |
| 378 | .max |
| 379 | .as_deref() |
| 380 | .and_then(parse) |
| 381 | .is_none_or(|max| moment <= max) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | pub fn format_date(date: NaiveDate) -> String { |
| 386 | date.format(DATE_FORMAT).to_string() |
| 387 | } |
| 388 | |
| 389 | pub fn format_time(time: NaiveTime) -> String { |
| 390 | time.format(TIME_FORMAT).to_string() |
| 391 | } |
| 392 | |
| 393 | fn parse_date(value: &str) -> Option<NaiveDate> { |
| 394 | NaiveDate::parse_from_str(value, DATE_FORMAT).ok() |
| 395 | } |
| 396 | |
| 397 | fn parse_time(value: &str) -> Option<NaiveTime> { |
| 398 | NaiveTime::parse_from_str(value, TIME_FORMAT).ok() |
| 399 | } |
| 400 | |
| 401 | pub fn collect_input_values( |
| 402 | inputs: &[CardInput], |
| 403 | value_of: impl Fn(&CardInput) -> String, |
| 404 | ) -> Result<Map<String, Value>, Vec<InputError>> { |
| 405 | let mut values = Map::new(); |
| 406 | let mut errors = Vec::new(); |
| 407 | for input in inputs { |
| 408 | let value = value_of(input); |
| 409 | match input.validate(&value) { |
| 410 | Some(message) => errors.push(InputError { |
| 411 | id: input.id.clone(), |
| 412 | message, |
| 413 | }), |
| 414 | None => { |
| 415 | values.insert(input.id.clone(), input.submitted_value(&value)); |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | if errors.is_empty() { |
| 420 | Ok(values) |
| 421 | } else { |
| 422 | Err(errors) |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | pub fn merge_input_data(data: &Value, values: &Map<String, Value>) -> Value { |
| 427 | match data { |
| 428 | Value::Object(object) => { |
| 429 | let mut merged = object.clone(); |
| 430 | merged.extend(values.clone()); |
| 431 | Value::Object(merged) |
| 432 | } |
| 433 | Value::Null => Value::Object(values.clone()), |
| 434 | other => other.clone(), |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | pub fn search_request_value(query: &ChoiceQuery, query_text: &str) -> Value { |
| 439 | json!({ |
| 440 | "queryText": query_text, |
| 441 | "queryOptions": {"skip": 0, "top": query.count}, |
| 442 | "dataset": query.dataset, |
| 443 | }) |
| 444 | } |
| 445 | |
| 446 | pub fn parse_search_results(response_value: &Value) -> Vec<InputChoice> { |
| 447 | response_value |
| 448 | .get("results") |
| 449 | .and_then(Value::as_array) |
| 450 | .into_iter() |
| 451 | .flatten() |
| 452 | .filter_map(|result| { |
| 453 | Some(InputChoice { |
| 454 | title: text_field(result, "title")?, |
| 455 | value: text_field(result, "value")?, |
| 456 | }) |
| 457 | }) |
| 458 | .collect() |
| 459 | } |
| 460 | |
| 461 | pub(crate) fn parse_rating(value: &Value) -> RatingDisplay { |
| 462 | RatingDisplay { |
| 463 | value: value.get("value").and_then(Value::as_f64).unwrap_or(0.), |
| 464 | max: rating_max(value), |
| 465 | count: value.get("count").and_then(Value::as_u64), |
| 466 | size: RatingSize::parse(value.get("size").and_then(Value::as_str)), |
| 467 | style: RatingStyle::parse(value.get("style").and_then(Value::as_str)), |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | fn rating_max(value: &Value) -> u32 { |
| 472 | value |
| 473 | .get("max") |
| 474 | .and_then(Value::as_u64) |
| 475 | .map_or(DEFAULT_RATING_MAX, |max| { |
| 476 | max.clamp(1, MAX_RATING_MAX.into()) as u32 |
| 477 | }) |
| 478 | } |
| 479 | |
| 480 | fn parse_choice_query(value: &Value) -> Option<ChoiceQuery> { |
| 481 | let data = value.get("choices.data")?; |
| 482 | if text_field(data, "type")? != DATA_QUERY_TYPE { |
| 483 | return None; |
| 484 | } |
| 485 | Some(ChoiceQuery { |
| 486 | dataset: text_field(data, "dataset")?, |
| 487 | count: data |
| 488 | .get("count") |
| 489 | .and_then(Value::as_u64) |
| 490 | .filter(|count| *count > 0) |
| 491 | .map_or(DEFAULT_SEARCH_COUNT, |count| count as usize), |
| 492 | }) |
| 493 | } |
| 494 | |
| 495 | fn parse_inline_action(value: &Value) -> Option<Box<InlineAction>> { |
| 496 | let mut action_value = value.get("inlineAction")?.clone(); |
| 497 | if text_field(&action_value, "title").is_none_or(|title| title.trim().is_empty()) { |
| 498 | action_value["title"] = json!(INLINE_ACTION_TITLE); |
| 499 | } |
| 500 | let action = parse_action(&action_value)?; |
| 501 | matches!( |
| 502 | action.kind, |
| 503 | CardActionKind::Submit(_) | CardActionKind::Execute(_) | CardActionKind::OpenUrl(_) |
| 504 | ) |
| 505 | .then(|| { |
| 506 | Box::new(InlineAction { |
| 507 | action, |
| 508 | icon_url: text_field(&action_value, "iconUrl"), |
| 509 | }) |
| 510 | }) |
| 511 | } |
| 512 | |
| 513 | pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> { |
| 514 | let id = text_field(value, "id")?; |
| 515 | let placeholder = text_field(value, "placeholder"); |
| 516 | let kind = match input_type { |
| 517 | "Input.Text" => CardInputKind::Text(TextInput { |
| 518 | placeholder, |
| 519 | value: text_field(value, "value").unwrap_or_default(), |
| 520 | multiline: bool_field(value, "isMultiline"), |
| 521 | max_length: value |
| 522 | .get("maxLength") |
| 523 | .and_then(Value::as_u64) |
| 524 | .filter(|max_length| *max_length > 0) |
| 525 | .map(|max_length| max_length as usize), |
| 526 | style: TextStyle::parse(value.get("style").and_then(Value::as_str)), |
| 527 | regex: text_field(value, "regex"), |
| 528 | inline_action: parse_inline_action(value), |
| 529 | }), |
| 530 | "Input.Number" => CardInputKind::Number(NumberInput { |
| 531 | placeholder, |
| 532 | value: number_text(value.get("value")), |
| 533 | min: value.get("min").and_then(Value::as_f64), |
| 534 | max: value.get("max").and_then(Value::as_f64), |
| 535 | }), |
| 536 | "Input.Date" => CardInputKind::Date(parse_moment(value)), |
| 537 | "Input.Time" => CardInputKind::Time(parse_moment(value)), |
| 538 | "Input.Toggle" => { |
| 539 | let value_on = |
| 540 | text_field(value, "valueOn").unwrap_or_else(|| DEFAULT_VALUE_ON.to_owned()); |
| 541 | let value_off = |
| 542 | text_field(value, "valueOff").unwrap_or_else(|| DEFAULT_VALUE_OFF.to_owned()); |
| 543 | CardInputKind::Toggle(ToggleInput { |
| 544 | title: text_field(value, "title").unwrap_or_default(), |
| 545 | value: text_field(value, "value").unwrap_or_else(|| value_off.clone()), |
| 546 | value_on, |
| 547 | value_off, |
| 548 | wrap: bool_field(value, "wrap"), |
| 549 | }) |
| 550 | } |
| 551 | "Input.ChoiceSet" => { |
| 552 | let query = parse_choice_query(value); |
| 553 | let choices: Vec<InputChoice> = value |
| 554 | .get("choices") |
| 555 | .and_then(Value::as_array) |
| 556 | .into_iter() |
| 557 | .flatten() |
| 558 | .filter_map(|choice| { |
| 559 | Some(InputChoice { |
| 560 | title: text_field(choice, "title")?, |
| 561 | value: text_field(choice, "value")?, |
| 562 | }) |
| 563 | }) |
| 564 | .collect(); |
| 565 | if choices.is_empty() && query.is_none() { |
| 566 | return None; |
| 567 | } |
| 568 | CardInputKind::Choice(ChoiceInput { |
| 569 | choices, |
| 570 | multi: bool_field(value, "isMultiSelect"), |
| 571 | style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)), |
| 572 | placeholder, |
| 573 | value: text_field(value, "value").unwrap_or_default(), |
| 574 | query, |
| 575 | }) |
| 576 | } |
| 577 | "Input.Rating" => { |
| 578 | let max = rating_max(value); |
| 579 | let rating = RatingInput { |
| 580 | max, |
| 581 | value: String::new(), |
| 582 | color: RatingColor::parse(value.get("color").and_then(Value::as_str)), |
| 583 | size: RatingSize::parse(value.get("size").and_then(Value::as_str)), |
| 584 | allow_half: bool_field(value, "allowHalf"), |
| 585 | }; |
| 586 | let initial = value.get("value").and_then(Value::as_f64).unwrap_or(0.); |
| 587 | CardInputKind::Rating(RatingInput { |
| 588 | value: rating.value_text(initial), |
| 589 | ..rating |
| 590 | }) |
| 591 | } |
| 592 | _ => return None, |
| 593 | }; |
| 594 | Some(CardInput { |
| 595 | id, |
| 596 | label: text_field(value, "label"), |
| 597 | required: bool_field(value, "isRequired"), |
| 598 | error_message: text_field(value, "errorMessage"), |
| 599 | kind, |
| 600 | }) |
| 601 | } |
| 602 | |
| 603 | fn parse_moment(value: &Value) -> MomentInput { |
| 604 | MomentInput { |
| 605 | value: text_field(value, "value").unwrap_or_default(), |
| 606 | min: text_field(value, "min"), |
| 607 | max: text_field(value, "max"), |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | fn text_field(value: &Value, key: &str) -> Option<String> { |
| 612 | value.get(key)?.as_str().map(str::to_owned) |
| 613 | } |
| 614 | |
| 615 | fn bool_field(value: &Value, key: &str) -> bool { |
| 616 | value.get(key).and_then(Value::as_bool).unwrap_or(false) |
| 617 | } |
| 618 | |
| 619 | fn number_text(value: Option<&Value>) -> String { |
| 620 | match value { |
| 621 | Some(Value::Number(number)) => number.to_string(), |
| 622 | Some(Value::String(text)) => text.clone(), |
| 623 | _ => String::new(), |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | fn number_value(number: f64) -> Number { |
| 628 | if number.fract() == 0. && number.abs() < WHOLE_NUMBER_LIMIT { |
| 629 | Number::from(number as i64) |
| 630 | } else { |
| 631 | Number::from_f64(number).unwrap_or_else(|| Number::from(0)) |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | #[cfg(test)] |
| 636 | mod tests { |
| 637 | use serde_json::json; |
| 638 | |
| 639 | use super::*; |
| 640 | |
| 641 | fn input(value: Value) -> CardInput { |
| 642 | let input_type = value["type"].as_str().unwrap().to_owned(); |
| 643 | parse_input(&value, &input_type).unwrap() |
| 644 | } |
| 645 | |
| 646 | #[test] |
| 647 | fn required_empty_text_shows_the_error_message_or_a_default() { |
| 648 | let custom = input( |
| 649 | json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Fill me"}), |
| 650 | ); |
| 651 | assert_eq!(custom.validate("").as_deref(), Some("Fill me")); |
| 652 | let plain = input(json!({"type": "Input.Text", "id": "a", "isRequired": true})); |
| 653 | assert_eq!(plain.validate("").as_deref(), Some(REQUIRED_MESSAGE)); |
| 654 | assert_eq!(plain.validate("x"), None); |
| 655 | } |
| 656 | |
| 657 | #[test] |
| 658 | fn text_regex_and_max_length_are_checked() { |
| 659 | let ticket = input( |
| 660 | json!({"type": "Input.Text", "id": "t", "regex": "^[A-Z]{3}-\\d+$", "maxLength": 6, "errorMessage": "Bad ticket"}), |
| 661 | ); |
| 662 | assert_eq!(ticket.validate("ABC-12"), None); |
| 663 | assert_eq!(ticket.validate("abc-12").as_deref(), Some("Bad ticket")); |
| 664 | assert_eq!(ticket.validate("ABC-1234").as_deref(), Some("Bad ticket")); |
| 665 | assert_eq!(ticket.validate(""), None); |
| 666 | } |
| 667 | |
| 668 | #[test] |
| 669 | fn number_bounds_are_inclusive() { |
| 670 | let servers = input(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 20})); |
| 671 | assert_eq!(servers.validate("1"), None); |
| 672 | assert_eq!(servers.validate("20"), None); |
| 673 | assert_eq!(servers.validate("0").as_deref(), Some(INVALID_MESSAGE)); |
| 674 | assert_eq!(servers.validate("21").as_deref(), Some(INVALID_MESSAGE)); |
| 675 | assert_eq!(servers.validate("1.").as_deref(), None); |
| 676 | assert_eq!(servers.validate("-").as_deref(), Some(INVALID_MESSAGE)); |
| 677 | } |
| 678 | |
| 679 | #[test] |
| 680 | fn date_and_time_bounds_are_checked() { |
| 681 | let day = input( |
| 682 | json!({"type": "Input.Date", "id": "d", "min": "2026-10-01", "max": "2026-12-31"}), |
| 683 | ); |
| 684 | assert_eq!(day.validate("2026-10-01"), None); |
| 685 | assert_eq!(day.validate("2026-12-31"), None); |
| 686 | assert!(day.validate("2026-09-30").is_some()); |
| 687 | assert!(day.validate("2027-01-01").is_some()); |
| 688 | assert!(day.validate("tomorrow").is_some()); |
| 689 | let start = input(json!({"type": "Input.Time", "id": "s", "min": "06:00", "max": "20:00"})); |
| 690 | assert_eq!(start.validate("06:00"), None); |
| 691 | assert!(start.validate("05:59").is_some()); |
| 692 | assert!(start.validate("20:01").is_some()); |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn moments_are_formatted_as_the_bot_expects() { |
| 697 | let day = NaiveDate::from_ymd_opt(2026, 3, 7).unwrap(); |
| 698 | let time = NaiveTime::from_hms_opt(9, 5, 0).unwrap(); |
| 699 | assert_eq!(format_date(day), "2026-03-07"); |
| 700 | assert_eq!(format_time(time), "09:05"); |
| 701 | let moment = MomentInput { |
| 702 | value: "2026-03-07".into(), |
| 703 | min: Some("2026-03-01".into()), |
| 704 | max: None, |
| 705 | }; |
| 706 | assert_eq!(moment.initial_date(), Some(day)); |
| 707 | assert_eq!(moment.min_date(), NaiveDate::from_ymd_opt(2026, 3, 1)); |
| 708 | assert_eq!(moment.max_date(), None); |
| 709 | } |
| 710 | |
| 711 | #[test] |
| 712 | fn rating_parses_with_defaults_and_clamps_the_value() { |
| 713 | let rating = input( |
| 714 | json!({"type": "Input.Rating", "id": "r", "value": 9, "color": "marigold", "size": "large", "allowHalf": true}), |
| 715 | ); |
| 716 | let CardInputKind::Rating(parsed) = &rating.kind else { |
| 717 | panic!("rating expected"); |
| 718 | }; |
| 719 | assert_eq!(parsed.max, 5); |
| 720 | assert_eq!(parsed.value, "5"); |
| 721 | assert_eq!(parsed.color, RatingColor::Marigold); |
| 722 | assert_eq!(parsed.size, RatingSize::Large); |
| 723 | assert!(parsed.allow_half); |
| 724 | let ten = input(json!({"type": "Input.Rating", "id": "r", "max": 40})); |
| 725 | let CardInputKind::Rating(parsed) = &ten.kind else { |
| 726 | panic!("rating expected"); |
| 727 | }; |
| 728 | assert_eq!(parsed.max, MAX_RATING_MAX); |
| 729 | assert_eq!(parsed.value, ""); |
| 730 | } |
| 731 | |
| 732 | #[test] |
| 733 | fn rating_is_submitted_as_a_number_and_required_means_above_zero() { |
| 734 | let rating = input( |
| 735 | json!({"type": "Input.Rating", "id": "r", "isRequired": true, "allowHalf": true}), |
| 736 | ); |
| 737 | assert_eq!(rating.submitted_value("3"), json!(3)); |
| 738 | assert_eq!(rating.submitted_value("3.5"), json!(3.5)); |
| 739 | assert!(rating.validate("").is_some()); |
| 740 | assert!(rating.validate("0").is_some()); |
| 741 | assert_eq!(rating.validate("0.5"), None); |
| 742 | let CardInputKind::Rating(parsed) = &rating.kind else { |
| 743 | panic!("rating expected"); |
| 744 | }; |
| 745 | assert_eq!(parsed.value_text(2.5), "2.5"); |
| 746 | assert_eq!(parsed.value_text(0.), ""); |
| 747 | } |
| 748 | |
| 749 | #[test] |
| 750 | fn numbers_and_text_are_submitted_as_text() { |
| 751 | let count = input(json!({"type": "Input.Number", "id": "n"})); |
| 752 | assert_eq!(count.submitted_value("4"), json!("4")); |
| 753 | assert_eq!(count.submitted_value("4.25"), json!("4.25")); |
| 754 | assert_eq!(count.submitted_value(""), json!("")); |
| 755 | let text = input(json!({"type": "Input.Text", "id": "t"})); |
| 756 | assert_eq!(text.submitted_value("4"), json!("4")); |
| 757 | } |
| 758 | |
| 759 | #[test] |
| 760 | fn collected_values_use_their_submitted_types() { |
| 761 | let inputs = vec![ |
| 762 | input(json!({"type": "Input.Rating", "id": "r", "value": 4})), |
| 763 | input(json!({"type": "Input.Number", "id": "n", "value": 7})), |
| 764 | ]; |
| 765 | let values = collect_input_values(&inputs, CardInput::initial_value).unwrap(); |
| 766 | assert_eq!(Value::Object(values), json!({"r": 4, "n": "7"})); |
| 767 | } |
| 768 | |
| 769 | #[test] |
| 770 | fn data_query_choice_sets_keep_their_input_without_static_choices() { |
| 771 | let choice = input(json!({ |
| 772 | "type": "Input.ChoiceSet", "id": "c", |
| 773 | "choices.data": {"type": "Data.Query", "dataset": "people", "count": 7} |
| 774 | })); |
| 775 | let CardInputKind::Choice(parsed) = &choice.kind else { |
| 776 | panic!("choice set expected"); |
| 777 | }; |
| 778 | assert!(parsed.choices.is_empty()); |
| 779 | assert_eq!( |
| 780 | parsed.query, |
| 781 | Some(ChoiceQuery { |
| 782 | dataset: "people".into(), |
| 783 | count: 7 |
| 784 | }) |
| 785 | ); |
| 786 | assert!( |
| 787 | parse_input( |
| 788 | &json!({"type": "Input.ChoiceSet", "id": "c"}), |
| 789 | "Input.ChoiceSet" |
| 790 | ) |
| 791 | .is_none() |
| 792 | ); |
| 793 | } |
| 794 | |
| 795 | #[test] |
| 796 | fn search_request_carries_query_options_and_dataset() { |
| 797 | let query = ChoiceQuery { |
| 798 | dataset: "people".into(), |
| 799 | count: 15, |
| 800 | }; |
| 801 | assert_eq!( |
| 802 | search_request_value(&query, "ad"), |
| 803 | json!({"queryText": "ad", "queryOptions": {"skip": 0, "top": 15}, "dataset": "people"}) |
| 804 | ); |
| 805 | } |
| 806 | |
| 807 | #[test] |
| 808 | fn search_results_keep_only_complete_title_value_pairs() { |
| 809 | let response = json!({"results": [ |
| 810 | {"title": "Ada", "value": "ada"}, |
| 811 | {"title": "No value"}, |
| 812 | {"title": "Bob", "value": "bob"} |
| 813 | ]}); |
| 814 | let titles: Vec<String> = parse_search_results(&response) |
| 815 | .into_iter() |
| 816 | .map(|choice| choice.value) |
| 817 | .collect(); |
| 818 | assert_eq!(titles, ["ada", "bob"]); |
| 819 | assert!(parse_search_results(&Value::Null).is_empty()); |
| 820 | } |
| 821 | |
| 822 | #[test] |
| 823 | fn inline_action_defaults_its_title_and_rejects_other_kinds() { |
| 824 | let with_action = input(json!({ |
| 825 | "type": "Input.Text", "id": "t", |
| 826 | "inlineAction": {"type": "Action.Submit", "iconUrl": "https://example.com/i.png", "data": {"go": 1}} |
| 827 | })); |
| 828 | let CardInputKind::Text(text) = &with_action.kind else { |
| 829 | panic!("text expected"); |
| 830 | }; |
| 831 | let inline = text.inline_action.as_ref().unwrap(); |
| 832 | assert_eq!(inline.action.title, INLINE_ACTION_TITLE); |
| 833 | assert_eq!( |
| 834 | inline.icon_url.as_deref(), |
| 835 | Some("https://example.com/i.png") |
| 836 | ); |
| 837 | let toggling = input(json!({ |
| 838 | "type": "Input.Text", "id": "t", |
| 839 | "inlineAction": {"type": "Action.ToggleVisibility", "title": "x", "targetElements": ["a"]} |
| 840 | })); |
| 841 | let CardInputKind::Text(text) = &toggling.kind else { |
| 842 | panic!("text expected"); |
| 843 | }; |
| 844 | assert!(text.inline_action.is_none()); |
| 845 | } |
| 846 | |
| 847 | #[test] |
| 848 | fn toggle_wrap_is_parsed() { |
| 849 | let toggle = |
| 850 | input(json!({"type": "Input.Toggle", "id": "t", "title": "Long", "wrap": true})); |
| 851 | let CardInputKind::Toggle(parsed) = &toggle.kind else { |
| 852 | panic!("toggle expected"); |
| 853 | }; |
| 854 | assert!(parsed.wrap); |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn rating_element_reads_value_count_and_style() { |
| 859 | let display = parse_rating( |
| 860 | &json!({"type": "Rating", "value": 4.5, "count": 120, "style": "compact", "size": "large"}), |
| 861 | ); |
| 862 | assert_eq!(display.value, 4.5); |
| 863 | assert_eq!(display.max, 5); |
| 864 | assert_eq!(display.count, Some(120)); |
| 865 | assert_eq!(display.style, RatingStyle::Compact); |
| 866 | assert_eq!(display.size, RatingSize::Large); |
| 867 | } |
| 868 | } |