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