| 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 | } |