| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use serde_json::{Map, Value, json}; |
| 4 | |
| 5 | use crate::card_inputs::{CardInput, merge_input_data, parse_input}; |
| 6 | use crate::markdown::markdown_to_html; |
| 7 | use crate::spans::{Span, html_to_spans}; |
| 8 | use crate::stored::push_plain; |
| 9 | |
| 10 | const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"]; |
| 11 | const IMAGE_URL_SCHEME: &str = "https://"; |
| 12 | const ACTION_TYPE_PREFIX: &str = "Action."; |
| 13 | const INPUT_TYPE_PREFIX: &str = "Input."; |
| 14 | const OPEN_URL_ACTION: &str = "Action.OpenUrl"; |
| 15 | const SUBMIT_ACTION: &str = "Action.Submit"; |
| 16 | const EXECUTE_ACTION: &str = "Action.Execute"; |
| 17 | const SHOW_CARD_ACTION: &str = "Action.ShowCard"; |
| 18 | const TOGGLE_VISIBILITY_ACTION: &str = "Action.ToggleVisibility"; |
| 19 | const TEAMS_SETTINGS_KEY: &str = "msteams"; |
| 20 | pub const CARD_THEME: &str = "dark"; |
| 21 | const MESSAGE_BACK_NAME: &str = "messageback"; |
| 22 | const TASK_FETCH_NAME: &str = "task/fetch"; |
| 23 | const EXECUTE_NAME: &str = "adaptiveCard/action"; |
| 24 | const PIXEL_SUFFIX: &str = "px"; |
| 25 | |
| 26 | #[derive(Debug, Clone, PartialEq)] |
| 27 | pub struct AdaptiveCard { |
| 28 | pub full_width: bool, |
| 29 | pub items: Vec<CardItem>, |
| 30 | pub actions: Vec<CardAction>, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, PartialEq)] |
| 34 | pub struct CardItem { |
| 35 | pub id: Option<String>, |
| 36 | pub visible: bool, |
| 37 | pub separator: bool, |
| 38 | pub spacing: CardSpacing, |
| 39 | pub element: CardElement, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, PartialEq)] |
| 43 | pub enum CardElement { |
| 44 | Text(CardText), |
| 45 | Image(CardImage), |
| 46 | ImageSet(Vec<CardImage>), |
| 47 | Columns(Vec<CardColumn>), |
| 48 | Container { |
| 49 | style: ContainerStyle, |
| 50 | items: Vec<CardItem>, |
| 51 | }, |
| 52 | Facts(Vec<CardFact>), |
| 53 | Actions(Vec<CardAction>), |
| 54 | Input(CardInput), |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 58 | pub enum CardSpacing { |
| 59 | None, |
| 60 | Small, |
| 61 | Default, |
| 62 | Medium, |
| 63 | Large, |
| 64 | ExtraLarge, |
| 65 | Padding, |
| 66 | } |
| 67 | |
| 68 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 69 | pub enum TextSize { |
| 70 | Small, |
| 71 | Default, |
| 72 | Medium, |
| 73 | Large, |
| 74 | ExtraLarge, |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 78 | pub enum TextColor { |
| 79 | Default, |
| 80 | Dark, |
| 81 | Light, |
| 82 | Accent, |
| 83 | Good, |
| 84 | Warning, |
| 85 | Attention, |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 89 | pub enum ImageSize { |
| 90 | Auto, |
| 91 | Stretch, |
| 92 | Small, |
| 93 | Medium, |
| 94 | Large, |
| 95 | } |
| 96 | |
| 97 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 98 | pub enum ContainerStyle { |
| 99 | Default, |
| 100 | Emphasis, |
| 101 | Accent, |
| 102 | Good, |
| 103 | Warning, |
| 104 | Attention, |
| 105 | } |
| 106 | |
| 107 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 108 | pub enum VerticalAlignment { |
| 109 | Top, |
| 110 | Center, |
| 111 | Bottom, |
| 112 | } |
| 113 | |
| 114 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 115 | pub enum ColumnWidth { |
| 116 | Auto, |
| 117 | Stretch, |
| 118 | Weighted(f32), |
| 119 | Pixels(f32), |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, PartialEq)] |
| 123 | pub struct CardText { |
| 124 | pub spans: Vec<Span>, |
| 125 | pub size: TextSize, |
| 126 | pub bold: bool, |
| 127 | pub color: TextColor, |
| 128 | pub subtle: bool, |
| 129 | pub wrap: bool, |
| 130 | } |
| 131 | |
| 132 | #[derive(Debug, Clone, PartialEq)] |
| 133 | pub struct CardImage { |
| 134 | pub url: String, |
| 135 | pub size: ImageSize, |
| 136 | pub width: Option<f32>, |
| 137 | pub height: Option<f32>, |
| 138 | pub person: bool, |
| 139 | } |
| 140 | |
| 141 | #[derive(Debug, Clone, PartialEq)] |
| 142 | pub struct CardColumn { |
| 143 | pub width: ColumnWidth, |
| 144 | pub vertical_alignment: VerticalAlignment, |
| 145 | pub items: Vec<CardItem>, |
| 146 | } |
| 147 | |
| 148 | #[derive(Debug, Clone, PartialEq)] |
| 149 | pub struct CardFact { |
| 150 | pub title: String, |
| 151 | pub value: Vec<Span>, |
| 152 | } |
| 153 | |
| 154 | #[derive(Debug, Clone, PartialEq)] |
| 155 | pub struct CardAction { |
| 156 | pub id: Option<String>, |
| 157 | pub title: String, |
| 158 | pub kind: CardActionKind, |
| 159 | pub enabled: bool, |
| 160 | pub visible: bool, |
| 161 | pub collects_inputs: bool, |
| 162 | } |
| 163 | |
| 164 | #[derive(Debug, Clone, PartialEq)] |
| 165 | pub enum CardActionKind { |
| 166 | OpenUrl(String), |
| 167 | Submit(SubmitAction), |
| 168 | Execute(ExecuteAction), |
| 169 | ShowCard(Box<AdaptiveCard>), |
| 170 | ToggleVisibility(Vec<ToggleTarget>), |
| 171 | Unsupported, |
| 172 | } |
| 173 | |
| 174 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 175 | pub struct SubmitAction { |
| 176 | pub data: Value, |
| 177 | } |
| 178 | |
| 179 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 180 | pub struct ExecuteAction { |
| 181 | pub id: Option<String>, |
| 182 | pub verb: String, |
| 183 | pub data: Value, |
| 184 | } |
| 185 | |
| 186 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 187 | pub struct ToggleTarget { |
| 188 | pub element_id: String, |
| 189 | pub visible: Option<bool>, |
| 190 | } |
| 191 | |
| 192 | #[derive(Debug, Clone, PartialEq)] |
| 193 | pub struct InvokePayload { |
| 194 | pub name: &'static str, |
| 195 | pub value: Value, |
| 196 | } |
| 197 | |
| 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 | |
| 220 | fn teams_settings(&self) -> Option<&Value> { |
| 221 | self.data.get(TEAMS_SETTINGS_KEY) |
| 222 | } |
| 223 | |
| 224 | pub fn is_task_fetch(&self) -> bool { |
| 225 | self.teams_settings() |
| 226 | .and_then(|settings| string_field(settings, "type")) |
| 227 | .is_some_and(|kind| kind == TASK_FETCH_NAME) |
| 228 | } |
| 229 | |
| 230 | pub fn payload(&self) -> InvokePayload { |
| 231 | if self.is_task_fetch() { |
| 232 | let mut data = self.data.as_object().cloned().unwrap_or_default(); |
| 233 | data.remove(TEAMS_SETTINGS_KEY); |
| 234 | data.insert("type".to_owned(), json!(TASK_FETCH_NAME)); |
| 235 | return InvokePayload { |
| 236 | name: TASK_FETCH_NAME, |
| 237 | value: task_value(Value::Object(data)), |
| 238 | }; |
| 239 | } |
| 240 | let message_back = self |
| 241 | .teams_settings() |
| 242 | .filter(|settings| { |
| 243 | string_field(settings, "type").is_some_and(|kind| { |
| 244 | kind.eq_ignore_ascii_case("messageBack") || kind.eq_ignore_ascii_case("imBack") |
| 245 | }) |
| 246 | }) |
| 247 | .and_then(|settings| settings.get("value")); |
| 248 | InvokePayload { |
| 249 | name: MESSAGE_BACK_NAME, |
| 250 | value: message_back.unwrap_or(&self.data).clone(), |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | impl ExecuteAction { |
| 256 | pub fn payload(&self) -> InvokePayload { |
| 257 | let mut action = Map::new(); |
| 258 | action.insert("type".to_owned(), json!(EXECUTE_ACTION)); |
| 259 | if let Some(id) = &self.id { |
| 260 | action.insert("id".to_owned(), json!(id)); |
| 261 | } |
| 262 | action.insert("verb".to_owned(), json!(self.verb)); |
| 263 | action.insert("data".to_owned(), self.data.clone()); |
| 264 | InvokePayload { |
| 265 | name: EXECUTE_NAME, |
| 266 | value: json!({"action": action, "trigger": "manual"}), |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | pub fn task_value(data: Value) -> Value { |
| 272 | json!({"data": data, "context": {"theme": CARD_THEME}}) |
| 273 | } |
| 274 | |
| 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 | |
| 293 | pub fn invoke_payload(&self) -> Option<InvokePayload> { |
| 294 | match &self.kind { |
| 295 | CardActionKind::Submit(submit) => Some(submit.payload()), |
| 296 | CardActionKind::Execute(execute) => Some(execute.payload()), |
| 297 | _ => None, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | pub fn is_clickable(&self) -> bool { |
| 302 | self.enabled && !matches!(self.kind, CardActionKind::Unsupported) |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | impl AdaptiveCard { |
| 307 | pub fn parse(content: &str) -> Option<AdaptiveCard> { |
| 308 | Self::from_value(&serde_json::from_str(content).ok()?) |
| 309 | } |
| 310 | |
| 311 | fn from_value(root: &Value) -> Option<AdaptiveCard> { |
| 312 | let object = root.as_object()?; |
| 313 | let mut items = parse_items(object.get("body")); |
| 314 | let actions = parse_actions(object.get("actions")); |
| 315 | if items.is_empty() |
| 316 | && let Some(item) = fallback_item(root) |
| 317 | { |
| 318 | items.push(item); |
| 319 | } |
| 320 | if items.is_empty() && actions.is_empty() { |
| 321 | return None; |
| 322 | } |
| 323 | let full_width = object |
| 324 | .get("msTeams") |
| 325 | .and_then(|settings| string_field(settings, "width")) |
| 326 | .is_some_and(|width| width.eq_ignore_ascii_case("full")); |
| 327 | Some(AdaptiveCard { |
| 328 | full_width, |
| 329 | items, |
| 330 | actions, |
| 331 | }) |
| 332 | } |
| 333 | |
| 334 | /// Initial visibility of every element and action that has an id, nested cards included. |
| 335 | pub fn element_visibility(&self) -> HashMap<String, bool> { |
| 336 | let mut visibility = HashMap::new(); |
| 337 | collect_visibility(&self.items, &self.actions, &mut visibility); |
| 338 | visibility |
| 339 | } |
| 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 | |
| 363 | pub fn plain_text(&self) -> Option<String> { |
| 364 | let mut lines = Vec::new(); |
| 365 | collect_lines(&self.items, &mut lines); |
| 366 | (!lines.is_empty()).then(|| lines.join("\n")) |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | fn collect_visibility( |
| 371 | items: &[CardItem], |
| 372 | actions: &[CardAction], |
| 373 | visibility: &mut HashMap<String, bool>, |
| 374 | ) { |
| 375 | for item in items { |
| 376 | if let Some(id) = &item.id { |
| 377 | visibility.insert(id.clone(), item.visible); |
| 378 | } |
| 379 | match &item.element { |
| 380 | CardElement::Columns(columns) => columns |
| 381 | .iter() |
| 382 | .for_each(|column| collect_visibility(&column.items, &[], visibility)), |
| 383 | CardElement::Container { items, .. } => collect_visibility(items, &[], visibility), |
| 384 | CardElement::Actions(actions) => collect_visibility(&[], actions, visibility), |
| 385 | _ => {} |
| 386 | } |
| 387 | } |
| 388 | for action in actions { |
| 389 | if let Some(id) = &action.id { |
| 390 | visibility.insert(id.clone(), action.visible); |
| 391 | } |
| 392 | if let CardActionKind::ShowCard(card) = &action.kind { |
| 393 | collect_visibility(&card.items, &card.actions, visibility); |
| 394 | } |
| 395 | } |
| 396 | } |
| 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 | |
| 424 | pub fn card_content_text(content: &str) -> Option<String> { |
| 425 | AdaptiveCard::parse(content)?.plain_text() |
| 426 | } |
| 427 | |
| 428 | fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) { |
| 429 | for item in items.iter().filter(|item| item.visible) { |
| 430 | match &item.element { |
| 431 | CardElement::Text(text) => push_line(lines, &text.spans), |
| 432 | CardElement::Columns(columns) => columns |
| 433 | .iter() |
| 434 | .for_each(|column| collect_lines(&column.items, lines)), |
| 435 | CardElement::Container { items, .. } => collect_lines(items, lines), |
| 436 | CardElement::Facts(facts) => { |
| 437 | for fact in facts { |
| 438 | let mut line = format!("{}: ", fact.title); |
| 439 | push_plain(&mut line, &fact.value); |
| 440 | lines.push(line.trim().to_owned()); |
| 441 | } |
| 442 | } |
| 443 | CardElement::Image(_) |
| 444 | | CardElement::ImageSet(_) |
| 445 | | CardElement::Actions(_) |
| 446 | | CardElement::Input(_) => {} |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn push_line(lines: &mut Vec<String>, spans: &[Span]) { |
| 452 | let mut line = String::new(); |
| 453 | push_plain(&mut line, spans); |
| 454 | let line = line.trim(); |
| 455 | if !line.is_empty() { |
| 456 | lines.push(line.to_owned()); |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | fn parse_items(value: Option<&Value>) -> Vec<CardItem> { |
| 461 | value |
| 462 | .and_then(Value::as_array) |
| 463 | .into_iter() |
| 464 | .flatten() |
| 465 | .filter_map(parse_item) |
| 466 | .collect() |
| 467 | } |
| 468 | |
| 469 | fn parse_item(value: &Value) -> Option<CardItem> { |
| 470 | let id = string_field(value, "id").map(str::to_owned); |
| 471 | let visible = is_visible(value); |
| 472 | if !visible && id.is_none() { |
| 473 | return None; |
| 474 | } |
| 475 | let element = match string_field(value, "type")? { |
| 476 | "TextBlock" => parse_text_block(value), |
| 477 | "RichTextBlock" => parse_rich_text_block(value), |
| 478 | "Image" => parse_image(value).map(CardElement::Image), |
| 479 | "ImageSet" => parse_image_set(value), |
| 480 | "ColumnSet" => parse_column_set(value), |
| 481 | "Container" => parse_container(value), |
| 482 | "FactSet" => parse_fact_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 | } |
| 487 | _ => None, |
| 488 | }; |
| 489 | let element = element.or_else(|| fallback_item(value).map(|item| item.element))?; |
| 490 | Some(CardItem { |
| 491 | id, |
| 492 | visible, |
| 493 | separator: value |
| 494 | .get("separator") |
| 495 | .and_then(Value::as_bool) |
| 496 | .unwrap_or(false), |
| 497 | spacing: parse_spacing(string_field(value, "spacing")), |
| 498 | element, |
| 499 | }) |
| 500 | } |
| 501 | |
| 502 | fn fallback_item(value: &Value) -> Option<CardItem> { |
| 503 | let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?; |
| 504 | Some(CardItem { |
| 505 | id: None, |
| 506 | visible: true, |
| 507 | separator: false, |
| 508 | spacing: CardSpacing::Default, |
| 509 | element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])), |
| 510 | }) |
| 511 | } |
| 512 | |
| 513 | fn plain_text_block(spans: Vec<Span>) -> CardText { |
| 514 | CardText { |
| 515 | spans, |
| 516 | size: TextSize::Default, |
| 517 | bold: false, |
| 518 | color: TextColor::Default, |
| 519 | subtle: false, |
| 520 | wrap: true, |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | fn parse_text_block(value: &Value) -> Option<CardElement> { |
| 525 | let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?; |
| 526 | Some(CardElement::Text(CardText { |
| 527 | spans: html_to_spans(&markdown_to_html(text)), |
| 528 | size: parse_text_size(string_field(value, "size")), |
| 529 | bold: string_field(value, "weight").is_some_and(is_bold_weight), |
| 530 | color: parse_text_color(string_field(value, "color")), |
| 531 | subtle: bool_field(value, "isSubtle"), |
| 532 | wrap: bool_field(value, "wrap"), |
| 533 | })) |
| 534 | } |
| 535 | |
| 536 | fn parse_rich_text_block(value: &Value) -> Option<CardElement> { |
| 537 | let spans: Vec<Span> = value |
| 538 | .get("inlines")? |
| 539 | .as_array()? |
| 540 | .iter() |
| 541 | .filter_map(parse_text_run) |
| 542 | .collect(); |
| 543 | (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans))) |
| 544 | } |
| 545 | |
| 546 | fn parse_text_run(value: &Value) -> Option<Span> { |
| 547 | let text = value |
| 548 | .as_str() |
| 549 | .or_else(|| string_field(value, "text")) |
| 550 | .filter(|text| !text.is_empty())?; |
| 551 | let mut span = Span::Text(text.to_owned()); |
| 552 | if string_field(value, "weight").is_some_and(is_bold_weight) { |
| 553 | span = Span::Bold(vec![span]); |
| 554 | } |
| 555 | if bool_field(value, "italic") { |
| 556 | span = Span::Italic(vec![span]); |
| 557 | } |
| 558 | if bool_field(value, "strikethrough") { |
| 559 | span = Span::Strike(vec![span]); |
| 560 | } |
| 561 | if bool_field(value, "underline") { |
| 562 | span = Span::Underline(vec![span]); |
| 563 | } |
| 564 | let url = value |
| 565 | .get("selectAction") |
| 566 | .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION)) |
| 567 | .and_then(|action| string_field(action, "url")) |
| 568 | .filter(|url| is_supported_url(url)); |
| 569 | Some(match url { |
| 570 | Some(url) => Span::Link { |
| 571 | url: url.to_owned(), |
| 572 | children: vec![span], |
| 573 | }, |
| 574 | None => span, |
| 575 | }) |
| 576 | } |
| 577 | |
| 578 | fn parse_image(value: &Value) -> Option<CardImage> { |
| 579 | let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?; |
| 580 | Some(CardImage { |
| 581 | url: url.to_owned(), |
| 582 | size: parse_image_size(string_field(value, "size")), |
| 583 | width: pixel_field(value, "width"), |
| 584 | height: pixel_field(value, "height"), |
| 585 | person: string_field(value, "style") |
| 586 | .is_some_and(|style| style.eq_ignore_ascii_case("person")), |
| 587 | }) |
| 588 | } |
| 589 | |
| 590 | fn parse_image_set(value: &Value) -> Option<CardElement> { |
| 591 | let size = parse_image_size(string_field(value, "imageSize")); |
| 592 | let images: Vec<CardImage> = value |
| 593 | .get("images")? |
| 594 | .as_array()? |
| 595 | .iter() |
| 596 | .filter(|image| is_visible(image)) |
| 597 | .filter_map(parse_image) |
| 598 | .map(|image| match image.size { |
| 599 | ImageSize::Auto => CardImage { size, ..image }, |
| 600 | _ => image, |
| 601 | }) |
| 602 | .collect(); |
| 603 | (!images.is_empty()).then_some(CardElement::ImageSet(images)) |
| 604 | } |
| 605 | |
| 606 | fn parse_column_set(value: &Value) -> Option<CardElement> { |
| 607 | let columns: Vec<CardColumn> = value |
| 608 | .get("columns")? |
| 609 | .as_array()? |
| 610 | .iter() |
| 611 | .filter(|column| is_visible(column)) |
| 612 | .filter_map(|column| { |
| 613 | let items = parse_items(column.get("items")); |
| 614 | (!items.is_empty()).then(|| CardColumn { |
| 615 | width: parse_column_width(column.get("width")), |
| 616 | vertical_alignment: parse_vertical_alignment(string_field( |
| 617 | column, |
| 618 | "verticalContentAlignment", |
| 619 | )), |
| 620 | items, |
| 621 | }) |
| 622 | }) |
| 623 | .collect(); |
| 624 | (!columns.is_empty()).then_some(CardElement::Columns(columns)) |
| 625 | } |
| 626 | |
| 627 | fn parse_container(value: &Value) -> Option<CardElement> { |
| 628 | let items = parse_items(value.get("items")); |
| 629 | (!items.is_empty()).then(|| CardElement::Container { |
| 630 | style: parse_container_style(string_field(value, "style")), |
| 631 | items, |
| 632 | }) |
| 633 | } |
| 634 | |
| 635 | fn parse_fact_set(value: &Value) -> Option<CardElement> { |
| 636 | let facts: Vec<CardFact> = value |
| 637 | .get("facts")? |
| 638 | .as_array()? |
| 639 | .iter() |
| 640 | .filter_map(|fact| { |
| 641 | let title = string_field(fact, "title")?; |
| 642 | let text = string_field(fact, "value").unwrap_or_default(); |
| 643 | Some(CardFact { |
| 644 | title: title.to_owned(), |
| 645 | value: html_to_spans(&markdown_to_html(text)), |
| 646 | }) |
| 647 | }) |
| 648 | .collect(); |
| 649 | (!facts.is_empty()).then_some(CardElement::Facts(facts)) |
| 650 | } |
| 651 | |
| 652 | fn parse_action_set(value: &Value) -> Option<CardElement> { |
| 653 | let actions = parse_actions(value.get("actions")); |
| 654 | (!actions.is_empty()).then_some(CardElement::Actions(actions)) |
| 655 | } |
| 656 | |
| 657 | fn parse_actions(value: Option<&Value>) -> Vec<CardAction> { |
| 658 | value |
| 659 | .and_then(Value::as_array) |
| 660 | .into_iter() |
| 661 | .flatten() |
| 662 | .filter_map(parse_action) |
| 663 | .collect() |
| 664 | } |
| 665 | |
| 666 | fn parse_action(value: &Value) -> Option<CardAction> { |
| 667 | let id = string_field(value, "id").map(str::to_owned); |
| 668 | let visible = is_visible(value); |
| 669 | if !visible && id.is_none() { |
| 670 | return None; |
| 671 | } |
| 672 | let action_type = string_field(value, "type")?; |
| 673 | if !action_type.starts_with(ACTION_TYPE_PREFIX) { |
| 674 | return None; |
| 675 | } |
| 676 | let title = string_field(value, "title") |
| 677 | .map(str::trim) |
| 678 | .filter(|title| !title.is_empty())?; |
| 679 | let data = || value.get("data").cloned().unwrap_or(Value::Null); |
| 680 | let kind = match action_type { |
| 681 | OPEN_URL_ACTION => string_field(value, "url") |
| 682 | .filter(|url| is_supported_url(url)) |
| 683 | .map_or(CardActionKind::Unsupported, |url| { |
| 684 | CardActionKind::OpenUrl(url.to_owned()) |
| 685 | }), |
| 686 | SUBMIT_ACTION => CardActionKind::Submit(SubmitAction { data: data() }), |
| 687 | EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| { |
| 688 | CardActionKind::Execute(ExecuteAction { |
| 689 | id: id.clone(), |
| 690 | verb: verb.to_owned(), |
| 691 | data: data(), |
| 692 | }) |
| 693 | }), |
| 694 | SHOW_CARD_ACTION => value |
| 695 | .get("card") |
| 696 | .and_then(AdaptiveCard::from_value) |
| 697 | .map_or(CardActionKind::Unsupported, |card| { |
| 698 | CardActionKind::ShowCard(Box::new(card)) |
| 699 | }), |
| 700 | TOGGLE_VISIBILITY_ACTION => { |
| 701 | let targets = parse_toggle_targets(value.get("targetElements")); |
| 702 | if targets.is_empty() { |
| 703 | CardActionKind::Unsupported |
| 704 | } else { |
| 705 | CardActionKind::ToggleVisibility(targets) |
| 706 | } |
| 707 | } |
| 708 | _ => CardActionKind::Unsupported, |
| 709 | }; |
| 710 | Some(CardAction { |
| 711 | id, |
| 712 | title: title.to_owned(), |
| 713 | kind, |
| 714 | enabled: value |
| 715 | .get("isEnabled") |
| 716 | .and_then(Value::as_bool) |
| 717 | .unwrap_or(true), |
| 718 | visible, |
| 719 | collects_inputs: !string_field(value, "associatedInputs") |
| 720 | .is_some_and(|mode| mode.eq_ignore_ascii_case("none")), |
| 721 | }) |
| 722 | } |
| 723 | |
| 724 | fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> { |
| 725 | value |
| 726 | .and_then(Value::as_array) |
| 727 | .into_iter() |
| 728 | .flatten() |
| 729 | .filter_map(|target| match target.as_str() { |
| 730 | Some(element_id) => Some(ToggleTarget { |
| 731 | element_id: element_id.to_owned(), |
| 732 | visible: None, |
| 733 | }), |
| 734 | None => Some(ToggleTarget { |
| 735 | element_id: string_field(target, "elementId")?.to_owned(), |
| 736 | visible: target.get("isVisible").and_then(Value::as_bool), |
| 737 | }), |
| 738 | }) |
| 739 | .collect() |
| 740 | } |
| 741 | |
| 742 | fn is_bold_weight(weight: &str) -> bool { |
| 743 | weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold") |
| 744 | } |
| 745 | |
| 746 | fn is_supported_url(url: &str) -> bool { |
| 747 | SUPPORTED_URL_SCHEMES |
| 748 | .iter() |
| 749 | .any(|scheme| url.starts_with(scheme)) |
| 750 | } |
| 751 | |
| 752 | fn is_visible(value: &Value) -> bool { |
| 753 | value |
| 754 | .get("isVisible") |
| 755 | .and_then(Value::as_bool) |
| 756 | .unwrap_or(true) |
| 757 | } |
| 758 | |
| 759 | fn bool_field(value: &Value, key: &str) -> bool { |
| 760 | value.get(key).and_then(Value::as_bool).unwrap_or(false) |
| 761 | } |
| 762 | |
| 763 | fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> { |
| 764 | value.get(key)?.as_str() |
| 765 | } |
| 766 | |
| 767 | fn pixel_field(value: &Value, key: &str) -> Option<f32> { |
| 768 | let field = value.get(key)?; |
| 769 | let pixels = match field.as_str() { |
| 770 | Some(text) => text |
| 771 | .trim() |
| 772 | .strip_suffix(PIXEL_SUFFIX)? |
| 773 | .trim() |
| 774 | .parse() |
| 775 | .ok()?, |
| 776 | None => field.as_f64()? as f32, |
| 777 | }; |
| 778 | (pixels > 0.).then_some(pixels) |
| 779 | } |
| 780 | |
| 781 | fn parse_column_width(value: Option<&Value>) -> ColumnWidth { |
| 782 | let Some(value) = value else { |
| 783 | return ColumnWidth::Stretch; |
| 784 | }; |
| 785 | if let Some(weight) = value.as_f64() { |
| 786 | return ColumnWidth::Weighted(weight as f32); |
| 787 | } |
| 788 | let Some(text) = value.as_str().map(str::trim) else { |
| 789 | return ColumnWidth::Stretch; |
| 790 | }; |
| 791 | if text.eq_ignore_ascii_case("auto") { |
| 792 | return ColumnWidth::Auto; |
| 793 | } |
| 794 | if let Some(pixels) = text |
| 795 | .strip_suffix(PIXEL_SUFFIX) |
| 796 | .and_then(|number| number.trim().parse().ok()) |
| 797 | { |
| 798 | return ColumnWidth::Pixels(pixels); |
| 799 | } |
| 800 | text.parse() |
| 801 | .map(ColumnWidth::Weighted) |
| 802 | .unwrap_or(ColumnWidth::Stretch) |
| 803 | } |
| 804 | |
| 805 | fn parse_spacing(value: Option<&str>) -> CardSpacing { |
| 806 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 807 | Some("none") => CardSpacing::None, |
| 808 | Some("small") => CardSpacing::Small, |
| 809 | Some("medium") => CardSpacing::Medium, |
| 810 | Some("large") => CardSpacing::Large, |
| 811 | Some("extralarge") => CardSpacing::ExtraLarge, |
| 812 | Some("padding") => CardSpacing::Padding, |
| 813 | _ => CardSpacing::Default, |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | fn parse_text_size(value: Option<&str>) -> TextSize { |
| 818 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 819 | Some("small") => TextSize::Small, |
| 820 | Some("medium") => TextSize::Medium, |
| 821 | Some("large") => TextSize::Large, |
| 822 | Some("extralarge") => TextSize::ExtraLarge, |
| 823 | _ => TextSize::Default, |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | fn parse_text_color(value: Option<&str>) -> TextColor { |
| 828 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 829 | Some("dark") => TextColor::Dark, |
| 830 | Some("light") => TextColor::Light, |
| 831 | Some("accent") => TextColor::Accent, |
| 832 | Some("good") => TextColor::Good, |
| 833 | Some("warning") => TextColor::Warning, |
| 834 | Some("attention") => TextColor::Attention, |
| 835 | _ => TextColor::Default, |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | fn parse_image_size(value: Option<&str>) -> ImageSize { |
| 840 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 841 | Some("stretch") => ImageSize::Stretch, |
| 842 | Some("small") => ImageSize::Small, |
| 843 | Some("medium") => ImageSize::Medium, |
| 844 | Some("large") => ImageSize::Large, |
| 845 | _ => ImageSize::Auto, |
| 846 | } |
| 847 | } |
| 848 | |
| 849 | fn parse_container_style(value: Option<&str>) -> ContainerStyle { |
| 850 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 851 | Some("emphasis") => ContainerStyle::Emphasis, |
| 852 | Some("accent") => ContainerStyle::Accent, |
| 853 | Some("good") => ContainerStyle::Good, |
| 854 | Some("warning") => ContainerStyle::Warning, |
| 855 | Some("attention") => ContainerStyle::Attention, |
| 856 | _ => ContainerStyle::Default, |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment { |
| 861 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 862 | Some("center") => VerticalAlignment::Center, |
| 863 | Some("bottom") => VerticalAlignment::Bottom, |
| 864 | _ => VerticalAlignment::Top, |
| 865 | } |
| 866 | } |