| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use serde_json::{Map, Value, json}; |
| 4 | |
| 5 | use crate::card_chart::{CardChart, is_chart_type, parse_chart}; |
| 6 | use crate::card_date::format_card_dates; |
| 7 | use crate::card_inputs::{CardInput, RatingDisplay, merge_input_data, parse_input, parse_rating}; |
| 8 | use crate::card_layout::{ |
| 9 | ContainerLayout, HorizontalAlignment, parse_color_hex, parse_horizontal_alignment, |
| 10 | }; |
| 11 | use crate::card_table::{CardTable, parse_table}; |
| 12 | use crate::card_widgets::{ |
| 13 | CardBadge, CardCarousel, CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, |
| 14 | parse_badge, parse_carousel, parse_code_block, parse_compound_button, parse_progress_bar, |
| 15 | parse_progress_ring, |
| 16 | }; |
| 17 | use crate::card_width::TargetWidth; |
| 18 | use crate::markdown::{card_markdown_to_html, split_mentions}; |
| 19 | use crate::spans::{FontSize, Span, html_to_spans}; |
| 20 | use crate::stored::push_plain; |
| 21 | |
| 22 | const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"]; |
| 23 | const IMAGE_URL_SCHEME: &str = "https://"; |
| 24 | const SUPPORTED_CARD_VERSION: (u32, u32) = (1, 6); |
| 25 | const ADAPTIVE_CARDS_FEATURE: &str = "adaptiveCards"; |
| 26 | const FALLBACK_DROP: &str = "drop"; |
| 27 | const MAX_PRIMARY_ACTIONS: usize = 6; |
| 28 | const ACCENT_RUN_COLOR: u32 = 0xe08a5c; |
| 29 | const GOOD_RUN_COLOR: u32 = 0x22c55e; |
| 30 | const WARNING_RUN_COLOR: u32 = 0xfbbf24; |
| 31 | const ATTENTION_RUN_COLOR: u32 = 0xf87171; |
| 32 | const SUBTLE_RUN_COLOR: u32 = 0xa1a1a6; |
| 33 | const HIGHLIGHT_BACKGROUND: u32 = 0xfacc15; |
| 34 | const HIGHLIGHT_FOREGROUND: u32 = 0x18181b; |
| 35 | const ACTION_TYPE_PREFIX: &str = "Action."; |
| 36 | const INPUT_TYPE_PREFIX: &str = "Input."; |
| 37 | const OPEN_URL_ACTION: &str = "Action.OpenUrl"; |
| 38 | const SUBMIT_ACTION: &str = "Action.Submit"; |
| 39 | const EXECUTE_ACTION: &str = "Action.Execute"; |
| 40 | const SHOW_CARD_ACTION: &str = "Action.ShowCard"; |
| 41 | const TOGGLE_VISIBILITY_ACTION: &str = "Action.ToggleVisibility"; |
| 42 | const TEAMS_SETTINGS_KEY: &str = "msteams"; |
| 43 | pub const CARD_THEME: &str = "dark"; |
| 44 | const MESSAGE_BACK_NAME: &str = "messageback"; |
| 45 | const TASK_FETCH_NAME: &str = "task/fetch"; |
| 46 | const EXECUTE_NAME: &str = "adaptiveCard/action"; |
| 47 | const INVOKE_TYPE: &str = "invoke"; |
| 48 | const SIGN_IN_TYPE: &str = "signin"; |
| 49 | const TAB_INFO_TYPE: &str = "tab/tabInfoAction"; |
| 50 | const ADD_APP_TYPES: [&str; 2] = ["appInstallToConversation", "addAppToConversation"]; |
| 51 | const ADD_APP_UNAVAILABLE: &str = "Adding apps is not supported"; |
| 52 | const AUTO_REFRESH_MEMBER_LIMIT: usize = 60; |
| 53 | const ICON_URL_PREFIX: &str = "icon:"; |
| 54 | const PIXEL_SUFFIX: &str = "px"; |
| 55 | |
| 56 | #[derive(Debug, Clone, PartialEq)] |
| 57 | pub struct AdaptiveCard { |
| 58 | pub full_width: bool, |
| 59 | pub items: Vec<CardItem>, |
| 60 | pub actions: Vec<CardAction>, |
| 61 | pub select_action: Option<CardAction>, |
| 62 | pub refresh: Option<CardRefresh>, |
| 63 | pub layout: ContainerLayout, |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug, Clone, PartialEq)] |
| 67 | pub struct CardRefresh { |
| 68 | pub action: ExecuteAction, |
| 69 | pub user_ids: Option<Vec<String>>, |
| 70 | } |
| 71 | |
| 72 | impl CardRefresh { |
| 73 | pub fn runs_automatically( |
| 74 | &self, |
| 75 | member_count: Option<usize>, |
| 76 | my_user_id: Option<&str>, |
| 77 | ) -> bool { |
| 78 | match &self.user_ids { |
| 79 | Some(user_ids) => my_user_id.is_some_and(|me| { |
| 80 | user_ids |
| 81 | .iter() |
| 82 | .any(|user_id| user_guid(user_id).eq_ignore_ascii_case(user_guid(me))) |
| 83 | }), |
| 84 | None => member_count.is_some_and(|count| count <= AUTO_REFRESH_MEMBER_LIMIT), |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn user_guid(user_id: &str) -> &str { |
| 90 | user_id.rsplit(':').next().unwrap_or(user_id) |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, Clone, PartialEq)] |
| 94 | pub struct CardItem { |
| 95 | pub id: Option<String>, |
| 96 | pub visible: bool, |
| 97 | pub separator: bool, |
| 98 | pub spacing: CardSpacing, |
| 99 | pub stretch: bool, |
| 100 | pub target_width: Option<TargetWidth>, |
| 101 | pub element: CardElement, |
| 102 | } |
| 103 | |
| 104 | #[derive(Debug, Clone, PartialEq)] |
| 105 | pub enum CardElement { |
| 106 | Text(CardText), |
| 107 | Image(CardImage), |
| 108 | ImageSet(Vec<CardImage>), |
| 109 | Columns { |
| 110 | columns: Vec<CardColumn>, |
| 111 | layout: ContainerLayout, |
| 112 | }, |
| 113 | Container { |
| 114 | layout: ContainerLayout, |
| 115 | items: Vec<CardItem>, |
| 116 | select_action: Option<CardAction>, |
| 117 | }, |
| 118 | Facts(Vec<CardFact>), |
| 119 | Media(CardMedia), |
| 120 | Icon(CardIcon), |
| 121 | Table(CardTable), |
| 122 | CodeBlock(CardCodeBlock), |
| 123 | Badge(CardBadge), |
| 124 | ProgressBar(CardProgressBar), |
| 125 | ProgressRing(CardProgressRing), |
| 126 | CompoundButton(CardCompoundButton), |
| 127 | Carousel(CardCarousel), |
| 128 | Actions(Vec<CardAction>), |
| 129 | Input(CardInput), |
| 130 | Rating(RatingDisplay), |
| 131 | Chart(CardChart), |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 135 | pub enum CardSpacing { |
| 136 | None, |
| 137 | Small, |
| 138 | Default, |
| 139 | Medium, |
| 140 | Large, |
| 141 | ExtraLarge, |
| 142 | Padding, |
| 143 | } |
| 144 | |
| 145 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 146 | pub enum TextSize { |
| 147 | Small, |
| 148 | Default, |
| 149 | Medium, |
| 150 | Large, |
| 151 | ExtraLarge, |
| 152 | } |
| 153 | |
| 154 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 155 | pub enum TextColor { |
| 156 | Default, |
| 157 | Dark, |
| 158 | Light, |
| 159 | Accent, |
| 160 | Good, |
| 161 | Warning, |
| 162 | Attention, |
| 163 | } |
| 164 | |
| 165 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 166 | pub enum ImageSize { |
| 167 | Auto, |
| 168 | Stretch, |
| 169 | Small, |
| 170 | Medium, |
| 171 | Large, |
| 172 | } |
| 173 | |
| 174 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 175 | pub enum IconSize { |
| 176 | ExtraExtraSmall, |
| 177 | ExtraSmall, |
| 178 | Small, |
| 179 | Standard, |
| 180 | Medium, |
| 181 | Large, |
| 182 | ExtraLarge, |
| 183 | ExtraExtraLarge, |
| 184 | } |
| 185 | |
| 186 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 187 | pub enum ContainerStyle { |
| 188 | #[default] |
| 189 | Default, |
| 190 | Emphasis, |
| 191 | Accent, |
| 192 | Good, |
| 193 | Warning, |
| 194 | Attention, |
| 195 | } |
| 196 | |
| 197 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 198 | pub enum VerticalAlignment { |
| 199 | #[default] |
| 200 | Top, |
| 201 | Center, |
| 202 | Bottom, |
| 203 | } |
| 204 | |
| 205 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 206 | pub enum ColumnWidth { |
| 207 | Auto, |
| 208 | Stretch, |
| 209 | Weighted(f32), |
| 210 | Pixels(f32), |
| 211 | } |
| 212 | |
| 213 | #[derive(Debug, Clone, PartialEq)] |
| 214 | pub struct CardText { |
| 215 | pub spans: Vec<Span>, |
| 216 | pub size: TextSize, |
| 217 | pub bold: bool, |
| 218 | pub color: TextColor, |
| 219 | pub subtle: bool, |
| 220 | pub wrap: bool, |
| 221 | pub max_lines: Option<usize>, |
| 222 | pub alignment: Option<HorizontalAlignment>, |
| 223 | pub monospace: bool, |
| 224 | } |
| 225 | |
| 226 | #[derive(Debug, Clone, PartialEq)] |
| 227 | pub struct CardImage { |
| 228 | pub url: String, |
| 229 | pub size: ImageSize, |
| 230 | pub width: Option<f32>, |
| 231 | pub height: Option<f32>, |
| 232 | pub person: bool, |
| 233 | pub alt_text: Option<String>, |
| 234 | pub alignment: HorizontalAlignment, |
| 235 | pub background_color: Option<u32>, |
| 236 | pub select_action: Option<CardAction>, |
| 237 | } |
| 238 | |
| 239 | #[derive(Debug, Clone, PartialEq)] |
| 240 | pub struct CardMedia { |
| 241 | pub poster_url: Option<String>, |
| 242 | pub source_url: String, |
| 243 | pub alt_text: Option<String>, |
| 244 | } |
| 245 | |
| 246 | #[derive(Debug, Clone, PartialEq)] |
| 247 | pub struct CardIcon { |
| 248 | pub name: String, |
| 249 | pub size: IconSize, |
| 250 | pub color: TextColor, |
| 251 | pub filled: bool, |
| 252 | pub select_action: Option<CardAction>, |
| 253 | } |
| 254 | |
| 255 | #[derive(Debug, Clone, PartialEq)] |
| 256 | pub struct CardColumn { |
| 257 | pub width: ColumnWidth, |
| 258 | pub layout: ContainerLayout, |
| 259 | pub target_width: Option<TargetWidth>, |
| 260 | pub items: Vec<CardItem>, |
| 261 | pub select_action: Option<CardAction>, |
| 262 | } |
| 263 | |
| 264 | #[derive(Debug, Clone, PartialEq)] |
| 265 | pub struct CardFact { |
| 266 | pub title: String, |
| 267 | pub value: Vec<Span>, |
| 268 | } |
| 269 | |
| 270 | #[derive(Debug, Clone, PartialEq)] |
| 271 | pub struct CardAction { |
| 272 | pub id: Option<String>, |
| 273 | pub title: String, |
| 274 | pub kind: CardActionKind, |
| 275 | pub enabled: bool, |
| 276 | pub visible: bool, |
| 277 | pub collects_inputs: bool, |
| 278 | pub icon: Option<CardActionIcon>, |
| 279 | pub secondary: bool, |
| 280 | pub tooltip: Option<String>, |
| 281 | } |
| 282 | |
| 283 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 284 | pub enum CardActionIcon { |
| 285 | Named(String), |
| 286 | Url(String), |
| 287 | } |
| 288 | |
| 289 | #[derive(Debug, Clone, PartialEq)] |
| 290 | pub enum CardActionKind { |
| 291 | OpenUrl(String), |
| 292 | Submit(SubmitAction), |
| 293 | Execute(ExecuteAction), |
| 294 | ShowCard(Box<AdaptiveCard>), |
| 295 | ToggleVisibility(Vec<ToggleTarget>), |
| 296 | Unavailable(&'static str), |
| 297 | Unsupported, |
| 298 | } |
| 299 | |
| 300 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 301 | pub struct SubmitAction { |
| 302 | pub data: Value, |
| 303 | } |
| 304 | |
| 305 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 306 | pub struct ExecuteAction { |
| 307 | pub id: Option<String>, |
| 308 | pub verb: String, |
| 309 | pub data: Value, |
| 310 | } |
| 311 | |
| 312 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 313 | pub struct ToggleTarget { |
| 314 | pub element_id: String, |
| 315 | pub visible: Option<bool>, |
| 316 | } |
| 317 | |
| 318 | #[derive(Debug, Clone, PartialEq)] |
| 319 | pub struct InvokePayload { |
| 320 | pub name: String, |
| 321 | pub value: Value, |
| 322 | } |
| 323 | |
| 324 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 325 | pub enum ExecuteTrigger { |
| 326 | Manual, |
| 327 | Automatic, |
| 328 | } |
| 329 | |
| 330 | impl ExecuteTrigger { |
| 331 | fn as_str(self) -> &'static str { |
| 332 | match self { |
| 333 | ExecuteTrigger::Manual => "manual", |
| 334 | ExecuteTrigger::Automatic => "automatic", |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | impl SubmitAction { |
| 340 | pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction { |
| 341 | let mut data = merge_input_data(&self.data, values); |
| 342 | if !values.is_empty() && self.is_message_back() { |
| 343 | let mut sent = data.as_object().cloned().unwrap_or_default(); |
| 344 | sent.remove(TEAMS_SETTINGS_KEY); |
| 345 | if let Some(settings) = data |
| 346 | .get_mut(TEAMS_SETTINGS_KEY) |
| 347 | .and_then(Value::as_object_mut) |
| 348 | { |
| 349 | settings.insert("value".to_owned(), Value::Object(sent)); |
| 350 | } |
| 351 | } |
| 352 | SubmitAction { data } |
| 353 | } |
| 354 | |
| 355 | fn is_message_back(&self) -> bool { |
| 356 | self.teams_settings() |
| 357 | .and_then(|settings| string_field(settings, "type")) |
| 358 | .is_some_and(|kind| kind.eq_ignore_ascii_case("messageBack")) |
| 359 | } |
| 360 | |
| 361 | fn teams_settings(&self) -> Option<&Value> { |
| 362 | self.data.get(TEAMS_SETTINGS_KEY) |
| 363 | } |
| 364 | |
| 365 | fn invoke_value(&self) -> Option<&Value> { |
| 366 | self.teams_settings() |
| 367 | .filter(|settings| { |
| 368 | string_field(settings, "type") |
| 369 | .is_some_and(|kind| kind.eq_ignore_ascii_case(INVOKE_TYPE)) |
| 370 | }) |
| 371 | .and_then(|settings| settings.get("value")) |
| 372 | } |
| 373 | |
| 374 | pub fn is_task_fetch(&self) -> bool { |
| 375 | self.teams_settings() |
| 376 | .and_then(|settings| string_field(settings, "type")) |
| 377 | .is_some_and(|kind| kind == TASK_FETCH_NAME) |
| 378 | } |
| 379 | |
| 380 | pub fn payload(&self) -> InvokePayload { |
| 381 | if self.is_task_fetch() { |
| 382 | let mut data = self.data.as_object().cloned().unwrap_or_default(); |
| 383 | data.remove(TEAMS_SETTINGS_KEY); |
| 384 | data.insert("type".to_owned(), json!(TASK_FETCH_NAME)); |
| 385 | return InvokePayload { |
| 386 | name: TASK_FETCH_NAME.to_owned(), |
| 387 | value: task_value(Value::Object(data)), |
| 388 | }; |
| 389 | } |
| 390 | if let Some((name, value)) = self.invoke_value().and_then(|value| { |
| 391 | let name = string_field(value, "type").filter(|name| !name.is_empty())?; |
| 392 | Some((name, value)) |
| 393 | }) { |
| 394 | return InvokePayload { |
| 395 | name: name.to_owned(), |
| 396 | value: value.clone(), |
| 397 | }; |
| 398 | } |
| 399 | let message_back = self |
| 400 | .teams_settings() |
| 401 | .filter(|settings| { |
| 402 | string_field(settings, "type").is_some_and(|kind| { |
| 403 | kind.eq_ignore_ascii_case("messageBack") || kind.eq_ignore_ascii_case("imBack") |
| 404 | }) |
| 405 | }) |
| 406 | .and_then(|settings| settings.get("value")); |
| 407 | InvokePayload { |
| 408 | name: MESSAGE_BACK_NAME.to_owned(), |
| 409 | value: message_back.unwrap_or(&self.data).clone(), |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | impl ExecuteAction { |
| 415 | pub fn payload(&self) -> InvokePayload { |
| 416 | self.payload_for(ExecuteTrigger::Manual) |
| 417 | } |
| 418 | |
| 419 | pub fn payload_for(&self, trigger: ExecuteTrigger) -> InvokePayload { |
| 420 | let mut action = Map::new(); |
| 421 | action.insert("type".to_owned(), json!(EXECUTE_ACTION)); |
| 422 | if let Some(id) = &self.id { |
| 423 | action.insert("id".to_owned(), json!(id)); |
| 424 | } |
| 425 | action.insert("verb".to_owned(), json!(self.verb)); |
| 426 | action.insert("data".to_owned(), self.data.clone()); |
| 427 | InvokePayload { |
| 428 | name: EXECUTE_NAME.to_owned(), |
| 429 | value: json!({"action": action, "trigger": trigger.as_str()}), |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | pub fn task_value(data: Value) -> Value { |
| 435 | json!({"data": data, "context": {"theme": CARD_THEME}}) |
| 436 | } |
| 437 | |
| 438 | impl CardAction { |
| 439 | pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction { |
| 440 | let kind = match &self.kind { |
| 441 | CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)), |
| 442 | CardActionKind::Execute(execute) => CardActionKind::Execute(ExecuteAction { |
| 443 | data: merge_input_data(&execute.data, values), |
| 444 | ..execute.clone() |
| 445 | }), |
| 446 | other => other.clone(), |
| 447 | }; |
| 448 | CardAction { |
| 449 | kind, |
| 450 | ..self.clone() |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | pub fn invoke_payload(&self) -> Option<InvokePayload> { |
| 455 | match &self.kind { |
| 456 | CardActionKind::Submit(submit) => Some(submit.payload()), |
| 457 | CardActionKind::Execute(execute) => Some(execute.payload()), |
| 458 | _ => None, |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | pub fn is_clickable(&self) -> bool { |
| 463 | self.enabled |
| 464 | && !matches!( |
| 465 | self.kind, |
| 466 | CardActionKind::Unsupported | CardActionKind::Unavailable(_) |
| 467 | ) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 472 | pub struct ActionSplit { |
| 473 | pub primary: Vec<usize>, |
| 474 | pub overflow: Vec<usize>, |
| 475 | } |
| 476 | |
| 477 | pub fn split_overflow( |
| 478 | actions: &[CardAction], |
| 479 | is_visible: impl Fn(&CardAction) -> bool, |
| 480 | ) -> ActionSplit { |
| 481 | let mut split = ActionSplit { |
| 482 | primary: Vec::new(), |
| 483 | overflow: Vec::new(), |
| 484 | }; |
| 485 | for (index, action) in actions |
| 486 | .iter() |
| 487 | .enumerate() |
| 488 | .filter(|(_, action)| is_visible(action)) |
| 489 | { |
| 490 | if action.secondary || split.primary.len() >= MAX_PRIMARY_ACTIONS { |
| 491 | split.overflow.push(index); |
| 492 | } else { |
| 493 | split.primary.push(index); |
| 494 | } |
| 495 | } |
| 496 | split |
| 497 | } |
| 498 | |
| 499 | impl AdaptiveCard { |
| 500 | pub fn parse(content: &str) -> Option<AdaptiveCard> { |
| 501 | Self::from_value(&serde_json::from_str(content).ok()?) |
| 502 | } |
| 503 | |
| 504 | fn from_value(root: &Value) -> Option<AdaptiveCard> { |
| 505 | if let Some(converted) = crate::legacy_card::as_adaptive_card(root) { |
| 506 | return Self::from_value(&converted); |
| 507 | } |
| 508 | let object = root.as_object()?; |
| 509 | let mut items = parse_items(object.get("body")); |
| 510 | let actions = parse_actions(object.get("actions")); |
| 511 | if items.is_empty() |
| 512 | && let Some(item) = fallback_item(root) |
| 513 | { |
| 514 | items.push(item); |
| 515 | } |
| 516 | if items.is_empty() && actions.is_empty() { |
| 517 | return None; |
| 518 | } |
| 519 | let full_width = object |
| 520 | .get("msTeams") |
| 521 | .and_then(|settings| string_field(settings, "width")) |
| 522 | .is_some_and(|width| width.eq_ignore_ascii_case("full")); |
| 523 | Some(AdaptiveCard { |
| 524 | full_width, |
| 525 | items, |
| 526 | actions, |
| 527 | select_action: parse_select_action(root), |
| 528 | refresh: parse_refresh(root), |
| 529 | layout: ContainerLayout::parse(root), |
| 530 | }) |
| 531 | } |
| 532 | |
| 533 | /// Initial visibility of every element and action that has an id, nested cards included. |
| 534 | pub fn element_visibility(&self) -> HashMap<String, bool> { |
| 535 | let mut visibility = HashMap::new(); |
| 536 | collect_visibility(&self.items, &self.actions, &mut visibility); |
| 537 | visibility |
| 538 | } |
| 539 | |
| 540 | pub fn own_inputs(&self) -> Vec<CardInput> { |
| 541 | let mut inputs = Vec::new(); |
| 542 | collect_inputs(&self.items, &mut inputs); |
| 543 | inputs |
| 544 | } |
| 545 | |
| 546 | pub fn all_inputs(&self) -> Vec<CardInput> { |
| 547 | let mut inputs = self.own_inputs(); |
| 548 | for action in self.all_actions() { |
| 549 | if let CardActionKind::ShowCard(card) = &action.kind { |
| 550 | inputs.extend(card.all_inputs()); |
| 551 | } |
| 552 | } |
| 553 | inputs |
| 554 | } |
| 555 | |
| 556 | fn all_actions(&self) -> Vec<&CardAction> { |
| 557 | let mut actions: Vec<&CardAction> = self.actions.iter().collect(); |
| 558 | collect_item_actions(&self.items, &mut actions); |
| 559 | actions |
| 560 | } |
| 561 | |
| 562 | pub fn plain_text(&self) -> Option<String> { |
| 563 | let mut lines = Vec::new(); |
| 564 | collect_lines(&self.items, &mut lines); |
| 565 | (!lines.is_empty()).then(|| lines.join("\n")) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | fn collect_visibility( |
| 570 | items: &[CardItem], |
| 571 | actions: &[CardAction], |
| 572 | visibility: &mut HashMap<String, bool>, |
| 573 | ) { |
| 574 | for item in items { |
| 575 | if let Some(id) = &item.id { |
| 576 | visibility.insert(id.clone(), item.visible); |
| 577 | } |
| 578 | for nested in item.element.nested_items() { |
| 579 | collect_visibility(nested, &[], visibility); |
| 580 | } |
| 581 | if let CardElement::Actions(actions) = &item.element { |
| 582 | collect_visibility(&[], actions, visibility); |
| 583 | } |
| 584 | } |
| 585 | for action in actions { |
| 586 | if let Some(id) = &action.id { |
| 587 | visibility.insert(id.clone(), action.visible); |
| 588 | } |
| 589 | if let CardActionKind::ShowCard(card) = &action.kind { |
| 590 | collect_visibility(&card.items, &card.actions, visibility); |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) { |
| 596 | for item in items { |
| 597 | if let CardElement::Input(input) = &item.element { |
| 598 | inputs.push(input.clone()); |
| 599 | } |
| 600 | for nested in item.element.nested_items() { |
| 601 | collect_inputs(nested, inputs); |
| 602 | } |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) { |
| 607 | for item in items { |
| 608 | if let CardElement::Actions(set) = &item.element { |
| 609 | actions.extend(set); |
| 610 | } |
| 611 | for nested in item.element.nested_items() { |
| 612 | collect_item_actions(nested, actions); |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | impl CardElement { |
| 618 | fn nested_items(&self) -> Vec<&[CardItem]> { |
| 619 | match self { |
| 620 | CardElement::Columns { columns, .. } => columns |
| 621 | .iter() |
| 622 | .map(|column| column.items.as_slice()) |
| 623 | .collect(), |
| 624 | CardElement::Container { items, .. } => vec![items.as_slice()], |
| 625 | CardElement::Table(table) => table |
| 626 | .rows |
| 627 | .iter() |
| 628 | .flat_map(|row| &row.cells) |
| 629 | .map(|cell| cell.items.as_slice()) |
| 630 | .collect(), |
| 631 | CardElement::Carousel(carousel) => carousel |
| 632 | .pages |
| 633 | .iter() |
| 634 | .map(|page| page.items.as_slice()) |
| 635 | .collect(), |
| 636 | _ => Vec::new(), |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | pub fn card_content_text(content: &str) -> Option<String> { |
| 642 | AdaptiveCard::parse(content)?.plain_text() |
| 643 | } |
| 644 | |
| 645 | fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) { |
| 646 | for item in items.iter().filter(|item| item.visible) { |
| 647 | match &item.element { |
| 648 | CardElement::Text(text) => push_line(lines, &text.spans), |
| 649 | CardElement::Facts(facts) => { |
| 650 | for fact in facts { |
| 651 | let mut line = format!("{}: ", fact.title); |
| 652 | push_plain(&mut line, &fact.value); |
| 653 | lines.push(line.trim().to_owned()); |
| 654 | } |
| 655 | } |
| 656 | CardElement::CodeBlock(block) => lines.push(block.code.clone()), |
| 657 | CardElement::Badge(badge) if !badge.text.is_empty() => lines.push(badge.text.clone()), |
| 658 | CardElement::CompoundButton(button) => { |
| 659 | lines.push(button.title.clone()); |
| 660 | lines.extend(button.description.clone()); |
| 661 | } |
| 662 | CardElement::ProgressRing(ring) => lines.extend(ring.label.clone()), |
| 663 | _ => {} |
| 664 | } |
| 665 | for nested in item.element.nested_items() { |
| 666 | collect_lines(nested, lines); |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | fn push_line(lines: &mut Vec<String>, spans: &[Span]) { |
| 672 | let mut line = String::new(); |
| 673 | push_plain(&mut line, spans); |
| 674 | let line = line.trim(); |
| 675 | if !line.is_empty() { |
| 676 | lines.push(line.to_owned()); |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | pub(crate) fn parse_items(value: Option<&Value>) -> Vec<CardItem> { |
| 681 | value |
| 682 | .and_then(Value::as_array) |
| 683 | .into_iter() |
| 684 | .flatten() |
| 685 | .filter_map(parse_item) |
| 686 | .collect() |
| 687 | } |
| 688 | |
| 689 | fn parse_item(value: &Value) -> Option<CardItem> { |
| 690 | let id = string_field(value, "id").map(str::to_owned); |
| 691 | let visible = is_visible(value); |
| 692 | if !visible && id.is_none() { |
| 693 | return None; |
| 694 | } |
| 695 | let element = parse_element(value).or_else(|| fallback_element(value))?; |
| 696 | Some(CardItem { |
| 697 | id, |
| 698 | visible, |
| 699 | separator: value |
| 700 | .get("separator") |
| 701 | .and_then(Value::as_bool) |
| 702 | .unwrap_or(false), |
| 703 | spacing: parse_spacing(string_field(value, "spacing")), |
| 704 | stretch: string_field(value, "height") |
| 705 | .is_some_and(|height| height.eq_ignore_ascii_case("stretch")), |
| 706 | target_width: parse_target_width(value), |
| 707 | element, |
| 708 | }) |
| 709 | } |
| 710 | |
| 711 | fn parse_target_width(value: &Value) -> Option<TargetWidth> { |
| 712 | string_field(value, "targetWidth").and_then(TargetWidth::parse) |
| 713 | } |
| 714 | |
| 715 | fn parse_element(value: &Value) -> Option<CardElement> { |
| 716 | if !requirements_met(value) { |
| 717 | return None; |
| 718 | } |
| 719 | match string_field(value, "type")? { |
| 720 | "TextBlock" => parse_text_block(value), |
| 721 | "RichTextBlock" => parse_rich_text_block(value), |
| 722 | "Image" => parse_image(value).map(CardElement::Image), |
| 723 | "ImageSet" => parse_image_set(value), |
| 724 | "ColumnSet" => parse_column_set(value), |
| 725 | "Container" => parse_container(value), |
| 726 | "FactSet" => parse_fact_set(value), |
| 727 | "Media" => parse_media(value).map(CardElement::Media), |
| 728 | "Icon" => parse_icon(value).map(CardElement::Icon), |
| 729 | "Table" => parse_table(value), |
| 730 | "CodeBlock" => parse_code_block(value), |
| 731 | "Badge" => parse_badge(value), |
| 732 | "ProgressBar" => parse_progress_bar(value), |
| 733 | "ProgressRing" => parse_progress_ring(value), |
| 734 | "CompoundButton" => parse_compound_button(value), |
| 735 | "Carousel" => parse_carousel(value), |
| 736 | "ActionSet" => parse_action_set(value), |
| 737 | "Rating" => Some(CardElement::Rating(parse_rating(value))), |
| 738 | chart_type if is_chart_type(chart_type) => { |
| 739 | parse_chart(value, chart_type).map(CardElement::Chart) |
| 740 | } |
| 741 | input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => { |
| 742 | parse_input(value, input_type).map(CardElement::Input) |
| 743 | } |
| 744 | _ => None, |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | fn requirements_met(value: &Value) -> bool { |
| 749 | value |
| 750 | .get("requires") |
| 751 | .and_then(Value::as_object) |
| 752 | .is_none_or(|requires| { |
| 753 | requires.iter().all(|(feature, version)| { |
| 754 | feature.eq_ignore_ascii_case(ADAPTIVE_CARDS_FEATURE) |
| 755 | && version_supported(version.as_str().unwrap_or_default()) |
| 756 | }) |
| 757 | }) |
| 758 | } |
| 759 | |
| 760 | fn version_supported(version: &str) -> bool { |
| 761 | let version = version.trim(); |
| 762 | if version == "*" { |
| 763 | return true; |
| 764 | } |
| 765 | let mut parts = version |
| 766 | .split('.') |
| 767 | .map(|part| part.trim().parse::<u32>().unwrap_or(0)); |
| 768 | let required = (parts.next().unwrap_or(0), parts.next().unwrap_or(0)); |
| 769 | required <= SUPPORTED_CARD_VERSION |
| 770 | } |
| 771 | |
| 772 | fn fallback_element(value: &Value) -> Option<CardElement> { |
| 773 | match value.get("fallback") { |
| 774 | Some(Value::String(mode)) if mode.eq_ignore_ascii_case(FALLBACK_DROP) => return None, |
| 775 | Some(fallback @ Value::Object(_)) => { |
| 776 | if let Some(item) = parse_item(fallback) { |
| 777 | return Some(item.element); |
| 778 | } |
| 779 | } |
| 780 | _ => {} |
| 781 | } |
| 782 | fallback_item(value).map(|item| item.element) |
| 783 | } |
| 784 | |
| 785 | fn fallback_item(value: &Value) -> Option<CardItem> { |
| 786 | let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?; |
| 787 | Some(CardItem { |
| 788 | id: None, |
| 789 | visible: true, |
| 790 | separator: false, |
| 791 | spacing: CardSpacing::Default, |
| 792 | stretch: false, |
| 793 | target_width: None, |
| 794 | element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])), |
| 795 | }) |
| 796 | } |
| 797 | |
| 798 | fn plain_text_block(spans: Vec<Span>) -> CardText { |
| 799 | CardText { |
| 800 | spans, |
| 801 | size: TextSize::Default, |
| 802 | bold: false, |
| 803 | color: TextColor::Default, |
| 804 | subtle: false, |
| 805 | wrap: true, |
| 806 | max_lines: None, |
| 807 | alignment: None, |
| 808 | monospace: false, |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | fn parse_text_block(value: &Value) -> Option<CardElement> { |
| 813 | let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?; |
| 814 | let text = format_card_dates(text); |
| 815 | let heading = |
| 816 | string_field(value, "style").is_some_and(|style| style.eq_ignore_ascii_case("heading")); |
| 817 | let size = parse_text_size(string_field(value, "size")); |
| 818 | Some(CardElement::Text(CardText { |
| 819 | spans: card_text_spans(value, &text), |
| 820 | size: match size { |
| 821 | TextSize::Default if heading => TextSize::Large, |
| 822 | other => other, |
| 823 | }, |
| 824 | bold: heading || string_field(value, "weight").is_some_and(is_bold_weight), |
| 825 | color: parse_text_color(string_field(value, "color")), |
| 826 | subtle: bool_field(value, "isSubtle"), |
| 827 | wrap: bool_field(value, "wrap"), |
| 828 | max_lines: value |
| 829 | .get("maxLines") |
| 830 | .and_then(Value::as_u64) |
| 831 | .filter(|lines| *lines > 0) |
| 832 | .map(|lines| lines as usize), |
| 833 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")), |
| 834 | monospace: is_monospace(value), |
| 835 | })) |
| 836 | } |
| 837 | |
| 838 | fn is_monospace(value: &Value) -> bool { |
| 839 | string_field(value, "fontType").is_some_and(|font| font.eq_ignore_ascii_case("monospace")) |
| 840 | } |
| 841 | |
| 842 | fn parse_rich_text_block(value: &Value) -> Option<CardElement> { |
| 843 | let spans: Vec<Span> = value |
| 844 | .get("inlines")? |
| 845 | .as_array()? |
| 846 | .iter() |
| 847 | .flat_map(parse_text_run) |
| 848 | .collect(); |
| 849 | (!spans.is_empty()).then(|| { |
| 850 | CardElement::Text(CardText { |
| 851 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")), |
| 852 | ..plain_text_block(spans) |
| 853 | }) |
| 854 | }) |
| 855 | } |
| 856 | |
| 857 | fn parse_text_run(value: &Value) -> Vec<Span> { |
| 858 | let Some(text) = value |
| 859 | .as_str() |
| 860 | .or_else(|| string_field(value, "text")) |
| 861 | .filter(|text| !text.is_empty()) |
| 862 | else { |
| 863 | return Vec::new(); |
| 864 | }; |
| 865 | let mut spans = split_mentions(&format_card_dates(text)); |
| 866 | if is_monospace(value) { |
| 867 | spans = spans |
| 868 | .into_iter() |
| 869 | .map(|span| match span { |
| 870 | Span::Text(text) => Span::Code(text), |
| 871 | other => other, |
| 872 | }) |
| 873 | .collect(); |
| 874 | } |
| 875 | if string_field(value, "weight").is_some_and(is_bold_weight) { |
| 876 | spans = vec![Span::Bold(spans)]; |
| 877 | } |
| 878 | if bool_field(value, "italic") { |
| 879 | spans = vec![Span::Italic(spans)]; |
| 880 | } |
| 881 | if bool_field(value, "strikethrough") { |
| 882 | spans = vec![Span::Strike(spans)]; |
| 883 | } |
| 884 | if bool_field(value, "underline") { |
| 885 | spans = vec![Span::Underline(spans)]; |
| 886 | } |
| 887 | if let Some(pixels) = run_font_pixels(string_field(value, "size")) { |
| 888 | spans = vec![Span::Sized(FontSize::Pixels(pixels), spans)]; |
| 889 | } |
| 890 | let highlight = bool_field(value, "highlight"); |
| 891 | let color = run_color(string_field(value, "color"), bool_field(value, "isSubtle")) |
| 892 | .or(highlight.then_some(HIGHLIGHT_FOREGROUND)); |
| 893 | if color.is_some() || highlight { |
| 894 | spans = vec![Span::Colored { |
| 895 | color, |
| 896 | background: highlight.then_some(HIGHLIGHT_BACKGROUND), |
| 897 | children: spans, |
| 898 | }]; |
| 899 | } |
| 900 | let url = value |
| 901 | .get("selectAction") |
| 902 | .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION)) |
| 903 | .and_then(|action| string_field(action, "url")) |
| 904 | .filter(|url| is_supported_url(url)); |
| 905 | match url { |
| 906 | Some(url) => vec![Span::Link { |
| 907 | url: url.to_owned(), |
| 908 | children: spans, |
| 909 | }], |
| 910 | None => spans, |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | fn run_font_pixels(size: Option<&str>) -> Option<u16> { |
| 915 | match parse_text_size(size) { |
| 916 | TextSize::Small => Some(12), |
| 917 | TextSize::Default if size.is_none() => None, |
| 918 | TextSize::Default => Some(14), |
| 919 | TextSize::Medium => Some(15), |
| 920 | TextSize::Large => Some(18), |
| 921 | TextSize::ExtraLarge => Some(21), |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | fn run_color(color: Option<&str>, subtle: bool) -> Option<u32> { |
| 926 | match parse_text_color(color) { |
| 927 | TextColor::Accent => Some(ACCENT_RUN_COLOR), |
| 928 | TextColor::Good => Some(GOOD_RUN_COLOR), |
| 929 | TextColor::Warning => Some(WARNING_RUN_COLOR), |
| 930 | TextColor::Attention => Some(ATTENTION_RUN_COLOR), |
| 931 | TextColor::Default | TextColor::Dark | TextColor::Light => { |
| 932 | subtle.then_some(SUBTLE_RUN_COLOR) |
| 933 | } |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | fn parse_image(value: &Value) -> Option<CardImage> { |
| 938 | let url = string_field(value, "url").filter(|url| is_supported_url(url))?; |
| 939 | Some(CardImage { |
| 940 | url: url.to_owned(), |
| 941 | size: parse_image_size(string_field(value, "size")), |
| 942 | width: pixel_field(value, "width"), |
| 943 | height: pixel_field(value, "height"), |
| 944 | person: string_field(value, "style") |
| 945 | .is_some_and(|style| style.eq_ignore_ascii_case("person")), |
| 946 | alt_text: string_field(value, "altText") |
| 947 | .filter(|text| !text.trim().is_empty()) |
| 948 | .map(str::to_owned), |
| 949 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")) |
| 950 | .unwrap_or_default(), |
| 951 | background_color: string_field(value, "backgroundColor").and_then(parse_color_hex), |
| 952 | select_action: parse_select_action(value), |
| 953 | }) |
| 954 | } |
| 955 | |
| 956 | fn parse_image_set(value: &Value) -> Option<CardElement> { |
| 957 | let size = parse_image_size(string_field(value, "imageSize")); |
| 958 | let images: Vec<CardImage> = value |
| 959 | .get("images")? |
| 960 | .as_array()? |
| 961 | .iter() |
| 962 | .filter(|image| is_visible(image)) |
| 963 | .filter_map(parse_image) |
| 964 | .map(|image| match image.size { |
| 965 | ImageSize::Auto => CardImage { size, ..image }, |
| 966 | _ => image, |
| 967 | }) |
| 968 | .collect(); |
| 969 | (!images.is_empty()).then_some(CardElement::ImageSet(images)) |
| 970 | } |
| 971 | |
| 972 | fn parse_column_set(value: &Value) -> Option<CardElement> { |
| 973 | let columns: Vec<CardColumn> = value |
| 974 | .get("columns")? |
| 975 | .as_array()? |
| 976 | .iter() |
| 977 | .filter(|column| is_visible(column)) |
| 978 | .filter_map(|column| { |
| 979 | let items = parse_items(column.get("items")); |
| 980 | (!items.is_empty()).then(|| CardColumn { |
| 981 | width: parse_column_width(column.get("width")), |
| 982 | layout: ContainerLayout::parse(column), |
| 983 | target_width: parse_target_width(column), |
| 984 | items, |
| 985 | select_action: parse_select_action(column), |
| 986 | }) |
| 987 | }) |
| 988 | .collect(); |
| 989 | (!columns.is_empty()).then(|| CardElement::Columns { |
| 990 | columns, |
| 991 | layout: ContainerLayout::parse(value), |
| 992 | }) |
| 993 | } |
| 994 | |
| 995 | fn parse_container(value: &Value) -> Option<CardElement> { |
| 996 | let items = parse_items(value.get("items")); |
| 997 | (!items.is_empty()).then(|| CardElement::Container { |
| 998 | layout: ContainerLayout::parse(value), |
| 999 | items, |
| 1000 | select_action: parse_select_action(value), |
| 1001 | }) |
| 1002 | } |
| 1003 | |
| 1004 | fn card_text_spans(value: &Value, text: &str) -> Vec<Span> { |
| 1005 | if value |
| 1006 | .get(crate::legacy_card::HTML_TEXT) |
| 1007 | .and_then(Value::as_bool) |
| 1008 | == Some(true) |
| 1009 | { |
| 1010 | html_to_spans(text) |
| 1011 | } else { |
| 1012 | html_to_spans(&card_markdown_to_html(text)) |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | fn parse_fact_set(value: &Value) -> Option<CardElement> { |
| 1017 | let facts: Vec<CardFact> = value |
| 1018 | .get("facts")? |
| 1019 | .as_array()? |
| 1020 | .iter() |
| 1021 | .filter_map(|fact| { |
| 1022 | let title = string_field(fact, "title")?; |
| 1023 | let text = string_field(fact, "value").unwrap_or_default(); |
| 1024 | Some(CardFact { |
| 1025 | title: format_card_dates(title), |
| 1026 | value: card_text_spans(fact, &format_card_dates(text)), |
| 1027 | }) |
| 1028 | }) |
| 1029 | .collect(); |
| 1030 | (!facts.is_empty()).then_some(CardElement::Facts(facts)) |
| 1031 | } |
| 1032 | |
| 1033 | fn parse_media(value: &Value) -> Option<CardMedia> { |
| 1034 | let source_url = value |
| 1035 | .get("sources")? |
| 1036 | .as_array()? |
| 1037 | .iter() |
| 1038 | .filter_map(|source| string_field(source, "url")) |
| 1039 | .find(|url| is_supported_url(url))?; |
| 1040 | Some(CardMedia { |
| 1041 | poster_url: string_field(value, "poster") |
| 1042 | .filter(|url| url.starts_with(IMAGE_URL_SCHEME)) |
| 1043 | .map(str::to_owned) |
| 1044 | .or_else(|| crate::youtube::poster_url(source_url)), |
| 1045 | source_url: source_url.to_owned(), |
| 1046 | alt_text: string_field(value, "altText") |
| 1047 | .filter(|text| !text.trim().is_empty()) |
| 1048 | .map(str::to_owned), |
| 1049 | }) |
| 1050 | } |
| 1051 | |
| 1052 | fn parse_icon(value: &Value) -> Option<CardIcon> { |
| 1053 | let name = string_field(value, "name").filter(|name| !name.trim().is_empty())?; |
| 1054 | Some(CardIcon { |
| 1055 | name: name.trim().to_owned(), |
| 1056 | size: parse_icon_size(string_field(value, "size")), |
| 1057 | color: parse_text_color(string_field(value, "color")), |
| 1058 | filled: string_field(value, "style") |
| 1059 | .is_some_and(|style| style.eq_ignore_ascii_case("filled")), |
| 1060 | select_action: parse_select_action(value), |
| 1061 | }) |
| 1062 | } |
| 1063 | |
| 1064 | pub(crate) fn parse_select_action(value: &Value) -> Option<CardAction> { |
| 1065 | let action = parse_action_titled(value.get("selectAction")?, false)?; |
| 1066 | matches!( |
| 1067 | action.kind, |
| 1068 | CardActionKind::OpenUrl(_) |
| 1069 | | CardActionKind::Submit(_) |
| 1070 | | CardActionKind::Execute(_) |
| 1071 | | CardActionKind::ToggleVisibility(_) |
| 1072 | ) |
| 1073 | .then_some(action) |
| 1074 | } |
| 1075 | |
| 1076 | fn parse_refresh(value: &Value) -> Option<CardRefresh> { |
| 1077 | let refresh = value.get("refresh")?; |
| 1078 | let action = parse_action_titled(refresh.get("action")?, false)?; |
| 1079 | let CardActionKind::Execute(execute) = action.kind else { |
| 1080 | return None; |
| 1081 | }; |
| 1082 | Some(CardRefresh { |
| 1083 | action: execute, |
| 1084 | user_ids: refresh |
| 1085 | .get("userIds") |
| 1086 | .and_then(Value::as_array) |
| 1087 | .map(|user_ids| { |
| 1088 | user_ids |
| 1089 | .iter() |
| 1090 | .filter_map(Value::as_str) |
| 1091 | .map(str::to_owned) |
| 1092 | .collect() |
| 1093 | }), |
| 1094 | }) |
| 1095 | } |
| 1096 | |
| 1097 | fn parse_action_set(value: &Value) -> Option<CardElement> { |
| 1098 | let actions = parse_actions(value.get("actions")); |
| 1099 | (!actions.is_empty()).then_some(CardElement::Actions(actions)) |
| 1100 | } |
| 1101 | |
| 1102 | fn parse_actions(value: Option<&Value>) -> Vec<CardAction> { |
| 1103 | value |
| 1104 | .and_then(Value::as_array) |
| 1105 | .into_iter() |
| 1106 | .flatten() |
| 1107 | .filter_map(parse_action) |
| 1108 | .collect() |
| 1109 | } |
| 1110 | |
| 1111 | pub(crate) fn parse_action(value: &Value) -> Option<CardAction> { |
| 1112 | parse_action_titled(value, true) |
| 1113 | } |
| 1114 | |
| 1115 | fn parse_action_titled(value: &Value, title_required: bool) -> Option<CardAction> { |
| 1116 | let id = string_field(value, "id").map(str::to_owned); |
| 1117 | let visible = is_visible(value); |
| 1118 | if !visible && id.is_none() { |
| 1119 | return None; |
| 1120 | } |
| 1121 | let action_type = string_field(value, "type")?; |
| 1122 | if !action_type.starts_with(ACTION_TYPE_PREFIX) { |
| 1123 | return None; |
| 1124 | } |
| 1125 | let title = string_field(value, "title") |
| 1126 | .map(str::trim) |
| 1127 | .filter(|title| !title.is_empty()); |
| 1128 | let title = match title { |
| 1129 | Some(title) => title, |
| 1130 | None if title_required => return None, |
| 1131 | None => "", |
| 1132 | }; |
| 1133 | let data = || value.get("data").cloned().unwrap_or(Value::Null); |
| 1134 | let kind = match action_type { |
| 1135 | OPEN_URL_ACTION => string_field(value, "url") |
| 1136 | .filter(|url| is_supported_url(url)) |
| 1137 | .map_or(CardActionKind::Unsupported, |url| { |
| 1138 | CardActionKind::OpenUrl(url.to_owned()) |
| 1139 | }), |
| 1140 | SUBMIT_ACTION => submit_kind(data()), |
| 1141 | EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| { |
| 1142 | CardActionKind::Execute(ExecuteAction { |
| 1143 | id: id.clone(), |
| 1144 | verb: verb.to_owned(), |
| 1145 | data: data(), |
| 1146 | }) |
| 1147 | }), |
| 1148 | SHOW_CARD_ACTION => value |
| 1149 | .get("card") |
| 1150 | .and_then(AdaptiveCard::from_value) |
| 1151 | .map_or(CardActionKind::Unsupported, |card| { |
| 1152 | CardActionKind::ShowCard(Box::new(card)) |
| 1153 | }), |
| 1154 | TOGGLE_VISIBILITY_ACTION => { |
| 1155 | let targets = parse_toggle_targets(value.get("targetElements")); |
| 1156 | if targets.is_empty() { |
| 1157 | CardActionKind::Unsupported |
| 1158 | } else { |
| 1159 | CardActionKind::ToggleVisibility(targets) |
| 1160 | } |
| 1161 | } |
| 1162 | _ => CardActionKind::Unsupported, |
| 1163 | }; |
| 1164 | Some(CardAction { |
| 1165 | id, |
| 1166 | title: title.to_owned(), |
| 1167 | kind, |
| 1168 | enabled: value |
| 1169 | .get("isEnabled") |
| 1170 | .and_then(Value::as_bool) |
| 1171 | .unwrap_or(true), |
| 1172 | visible, |
| 1173 | collects_inputs: !string_field(value, "associatedInputs") |
| 1174 | .is_some_and(|mode| mode.eq_ignore_ascii_case("none")), |
| 1175 | icon: string_field(value, "iconUrl").and_then(parse_action_icon), |
| 1176 | secondary: string_field(value, "mode") |
| 1177 | .is_some_and(|mode| mode.eq_ignore_ascii_case("secondary")), |
| 1178 | tooltip: string_field(value, "tooltip") |
| 1179 | .map(str::trim) |
| 1180 | .filter(|tooltip| !tooltip.is_empty()) |
| 1181 | .map(str::to_owned), |
| 1182 | }) |
| 1183 | } |
| 1184 | |
| 1185 | fn parse_action_icon(icon_url: &str) -> Option<CardActionIcon> { |
| 1186 | match icon_url.strip_prefix(ICON_URL_PREFIX) { |
| 1187 | Some(name) => Some(name.split(',').next()?.trim()) |
| 1188 | .filter(|name| !name.is_empty()) |
| 1189 | .map(|name| CardActionIcon::Named(name.to_owned())), |
| 1190 | None => icon_url |
| 1191 | .starts_with(IMAGE_URL_SCHEME) |
| 1192 | .then(|| CardActionIcon::Url(icon_url.to_owned())), |
| 1193 | } |
| 1194 | } |
| 1195 | |
| 1196 | fn submit_kind(data: Value) -> CardActionKind { |
| 1197 | let submit = SubmitAction { data }; |
| 1198 | let settings_type = submit |
| 1199 | .teams_settings() |
| 1200 | .and_then(|settings| string_field(settings, "type")); |
| 1201 | let invoke_type = submit |
| 1202 | .invoke_value() |
| 1203 | .and_then(|value| string_field(value, "type")); |
| 1204 | let names_add_app = [settings_type, invoke_type] |
| 1205 | .into_iter() |
| 1206 | .flatten() |
| 1207 | .any(|name| { |
| 1208 | ADD_APP_TYPES |
| 1209 | .iter() |
| 1210 | .any(|known| known.eq_ignore_ascii_case(name)) |
| 1211 | }); |
| 1212 | if names_add_app { |
| 1213 | return CardActionKind::Unavailable(ADD_APP_UNAVAILABLE); |
| 1214 | } |
| 1215 | let open_url = |url: Option<&str>| { |
| 1216 | url.filter(|url| is_supported_url(url)) |
| 1217 | .map_or(CardActionKind::Unsupported, |url| { |
| 1218 | CardActionKind::OpenUrl(url.to_owned()) |
| 1219 | }) |
| 1220 | }; |
| 1221 | if settings_type.is_some_and(|name| name.eq_ignore_ascii_case(SIGN_IN_TYPE)) { |
| 1222 | let url = submit |
| 1223 | .teams_settings() |
| 1224 | .and_then(|settings| string_field(settings, "value")); |
| 1225 | return open_url(url); |
| 1226 | } |
| 1227 | if invoke_type == Some(TAB_INFO_TYPE) { |
| 1228 | let tab_info = submit.invoke_value().and_then(|value| value.get("tabInfo")); |
| 1229 | let url = tab_info |
| 1230 | .and_then(|info| string_field(info, "websiteUrl")) |
| 1231 | .filter(|url| is_supported_url(url)) |
| 1232 | .or_else(|| tab_info.and_then(|info| string_field(info, "contentUrl"))); |
| 1233 | return open_url(url); |
| 1234 | } |
| 1235 | CardActionKind::Submit(submit) |
| 1236 | } |
| 1237 | |
| 1238 | fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> { |
| 1239 | value |
| 1240 | .and_then(Value::as_array) |
| 1241 | .into_iter() |
| 1242 | .flatten() |
| 1243 | .filter_map(|target| match target.as_str() { |
| 1244 | Some(element_id) => Some(ToggleTarget { |
| 1245 | element_id: element_id.to_owned(), |
| 1246 | visible: None, |
| 1247 | }), |
| 1248 | None => Some(ToggleTarget { |
| 1249 | element_id: string_field(target, "elementId")?.to_owned(), |
| 1250 | visible: target.get("isVisible").and_then(Value::as_bool), |
| 1251 | }), |
| 1252 | }) |
| 1253 | .collect() |
| 1254 | } |
| 1255 | |
| 1256 | fn is_bold_weight(weight: &str) -> bool { |
| 1257 | weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold") |
| 1258 | } |
| 1259 | |
| 1260 | pub(crate) fn is_supported_url(url: &str) -> bool { |
| 1261 | SUPPORTED_URL_SCHEMES |
| 1262 | .iter() |
| 1263 | .any(|scheme| url.starts_with(scheme)) |
| 1264 | } |
| 1265 | |
| 1266 | fn is_visible(value: &Value) -> bool { |
| 1267 | value |
| 1268 | .get("isVisible") |
| 1269 | .and_then(Value::as_bool) |
| 1270 | .unwrap_or(true) |
| 1271 | } |
| 1272 | |
| 1273 | pub(crate) fn bool_field(value: &Value, key: &str) -> bool { |
| 1274 | value.get(key).and_then(Value::as_bool).unwrap_or(false) |
| 1275 | } |
| 1276 | |
| 1277 | pub(crate) fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> { |
| 1278 | value.get(key)?.as_str() |
| 1279 | } |
| 1280 | |
| 1281 | pub(crate) fn pixel_field(value: &Value, key: &str) -> Option<f32> { |
| 1282 | let field = value.get(key)?; |
| 1283 | let pixels = match field.as_str() { |
| 1284 | Some(text) => text |
| 1285 | .trim() |
| 1286 | .strip_suffix(PIXEL_SUFFIX)? |
| 1287 | .trim() |
| 1288 | .parse() |
| 1289 | .ok()?, |
| 1290 | None => field.as_f64()? as f32, |
| 1291 | }; |
| 1292 | (pixels > 0.).then_some(pixels) |
| 1293 | } |
| 1294 | |
| 1295 | pub(crate) fn parse_column_width(value: Option<&Value>) -> ColumnWidth { |
| 1296 | let Some(value) = value else { |
| 1297 | return ColumnWidth::Stretch; |
| 1298 | }; |
| 1299 | if let Some(weight) = value.as_f64() { |
| 1300 | return ColumnWidth::Weighted(weight as f32); |
| 1301 | } |
| 1302 | let Some(text) = value.as_str().map(str::trim) else { |
| 1303 | return ColumnWidth::Stretch; |
| 1304 | }; |
| 1305 | if text.eq_ignore_ascii_case("auto") { |
| 1306 | return ColumnWidth::Auto; |
| 1307 | } |
| 1308 | if let Some(pixels) = text |
| 1309 | .strip_suffix(PIXEL_SUFFIX) |
| 1310 | .and_then(|number| number.trim().parse().ok()) |
| 1311 | { |
| 1312 | return ColumnWidth::Pixels(pixels); |
| 1313 | } |
| 1314 | text.parse() |
| 1315 | .map(ColumnWidth::Weighted) |
| 1316 | .unwrap_or(ColumnWidth::Stretch) |
| 1317 | } |
| 1318 | |
| 1319 | fn parse_spacing(value: Option<&str>) -> CardSpacing { |
| 1320 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1321 | Some("none") => CardSpacing::None, |
| 1322 | Some("small") => CardSpacing::Small, |
| 1323 | Some("medium") => CardSpacing::Medium, |
| 1324 | Some("large") => CardSpacing::Large, |
| 1325 | Some("extralarge") => CardSpacing::ExtraLarge, |
| 1326 | Some("padding") => CardSpacing::Padding, |
| 1327 | _ => CardSpacing::Default, |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | fn parse_text_size(value: Option<&str>) -> TextSize { |
| 1332 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1333 | Some("small") => TextSize::Small, |
| 1334 | Some("medium") => TextSize::Medium, |
| 1335 | Some("large") => TextSize::Large, |
| 1336 | Some("extralarge") => TextSize::ExtraLarge, |
| 1337 | _ => TextSize::Default, |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | pub(crate) fn parse_text_color(value: Option<&str>) -> TextColor { |
| 1342 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1343 | Some("dark") => TextColor::Dark, |
| 1344 | Some("light") => TextColor::Light, |
| 1345 | Some("accent") => TextColor::Accent, |
| 1346 | Some("good") => TextColor::Good, |
| 1347 | Some("warning") => TextColor::Warning, |
| 1348 | Some("attention") => TextColor::Attention, |
| 1349 | _ => TextColor::Default, |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | fn parse_image_size(value: Option<&str>) -> ImageSize { |
| 1354 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1355 | Some("stretch") => ImageSize::Stretch, |
| 1356 | Some("small") => ImageSize::Small, |
| 1357 | Some("medium") => ImageSize::Medium, |
| 1358 | Some("large") => ImageSize::Large, |
| 1359 | _ => ImageSize::Auto, |
| 1360 | } |
| 1361 | } |
| 1362 | |
| 1363 | fn parse_icon_size(value: Option<&str>) -> IconSize { |
| 1364 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1365 | Some("xxsmall") => IconSize::ExtraExtraSmall, |
| 1366 | Some("xsmall") => IconSize::ExtraSmall, |
| 1367 | Some("small") => IconSize::Small, |
| 1368 | Some("medium") => IconSize::Medium, |
| 1369 | Some("large") => IconSize::Large, |
| 1370 | Some("xlarge") => IconSize::ExtraLarge, |
| 1371 | Some("xxlarge") => IconSize::ExtraExtraLarge, |
| 1372 | _ => IconSize::Standard, |
| 1373 | } |
| 1374 | } |
| 1375 | |
| 1376 | pub(crate) fn parse_container_style(value: Option<&str>) -> ContainerStyle { |
| 1377 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1378 | Some("emphasis") => ContainerStyle::Emphasis, |
| 1379 | Some("accent") => ContainerStyle::Accent, |
| 1380 | Some("good") => ContainerStyle::Good, |
| 1381 | Some("warning") => ContainerStyle::Warning, |
| 1382 | Some("attention") => ContainerStyle::Attention, |
| 1383 | _ => ContainerStyle::Default, |
| 1384 | } |
| 1385 | } |
| 1386 | |
| 1387 | pub(crate) fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment { |
| 1388 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1389 | Some("center") => VerticalAlignment::Center, |
| 1390 | Some("bottom") => VerticalAlignment::Bottom, |
| 1391 | _ => VerticalAlignment::Top, |
| 1392 | } |
| 1393 | } |