| 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 | let object = root.as_object()?; |
| 506 | let mut items = parse_items(object.get("body")); |
| 507 | let actions = parse_actions(object.get("actions")); |
| 508 | if items.is_empty() |
| 509 | && let Some(item) = fallback_item(root) |
| 510 | { |
| 511 | items.push(item); |
| 512 | } |
| 513 | if items.is_empty() && actions.is_empty() { |
| 514 | return None; |
| 515 | } |
| 516 | let full_width = object |
| 517 | .get("msTeams") |
| 518 | .and_then(|settings| string_field(settings, "width")) |
| 519 | .is_some_and(|width| width.eq_ignore_ascii_case("full")); |
| 520 | Some(AdaptiveCard { |
| 521 | full_width, |
| 522 | items, |
| 523 | actions, |
| 524 | select_action: parse_select_action(root), |
| 525 | refresh: parse_refresh(root), |
| 526 | layout: ContainerLayout::parse(root), |
| 527 | }) |
| 528 | } |
| 529 | |
| 530 | /// Initial visibility of every element and action that has an id, nested cards included. |
| 531 | pub fn element_visibility(&self) -> HashMap<String, bool> { |
| 532 | let mut visibility = HashMap::new(); |
| 533 | collect_visibility(&self.items, &self.actions, &mut visibility); |
| 534 | visibility |
| 535 | } |
| 536 | |
| 537 | pub fn own_inputs(&self) -> Vec<CardInput> { |
| 538 | let mut inputs = Vec::new(); |
| 539 | collect_inputs(&self.items, &mut inputs); |
| 540 | inputs |
| 541 | } |
| 542 | |
| 543 | pub fn all_inputs(&self) -> Vec<CardInput> { |
| 544 | let mut inputs = self.own_inputs(); |
| 545 | for action in self.all_actions() { |
| 546 | if let CardActionKind::ShowCard(card) = &action.kind { |
| 547 | inputs.extend(card.all_inputs()); |
| 548 | } |
| 549 | } |
| 550 | inputs |
| 551 | } |
| 552 | |
| 553 | fn all_actions(&self) -> Vec<&CardAction> { |
| 554 | let mut actions: Vec<&CardAction> = self.actions.iter().collect(); |
| 555 | collect_item_actions(&self.items, &mut actions); |
| 556 | actions |
| 557 | } |
| 558 | |
| 559 | pub fn plain_text(&self) -> Option<String> { |
| 560 | let mut lines = Vec::new(); |
| 561 | collect_lines(&self.items, &mut lines); |
| 562 | (!lines.is_empty()).then(|| lines.join("\n")) |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | fn collect_visibility( |
| 567 | items: &[CardItem], |
| 568 | actions: &[CardAction], |
| 569 | visibility: &mut HashMap<String, bool>, |
| 570 | ) { |
| 571 | for item in items { |
| 572 | if let Some(id) = &item.id { |
| 573 | visibility.insert(id.clone(), item.visible); |
| 574 | } |
| 575 | for nested in item.element.nested_items() { |
| 576 | collect_visibility(nested, &[], visibility); |
| 577 | } |
| 578 | if let CardElement::Actions(actions) = &item.element { |
| 579 | collect_visibility(&[], actions, visibility); |
| 580 | } |
| 581 | } |
| 582 | for action in actions { |
| 583 | if let Some(id) = &action.id { |
| 584 | visibility.insert(id.clone(), action.visible); |
| 585 | } |
| 586 | if let CardActionKind::ShowCard(card) = &action.kind { |
| 587 | collect_visibility(&card.items, &card.actions, visibility); |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) { |
| 593 | for item in items { |
| 594 | if let CardElement::Input(input) = &item.element { |
| 595 | inputs.push(input.clone()); |
| 596 | } |
| 597 | for nested in item.element.nested_items() { |
| 598 | collect_inputs(nested, inputs); |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) { |
| 604 | for item in items { |
| 605 | if let CardElement::Actions(set) = &item.element { |
| 606 | actions.extend(set); |
| 607 | } |
| 608 | for nested in item.element.nested_items() { |
| 609 | collect_item_actions(nested, actions); |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | impl CardElement { |
| 615 | fn nested_items(&self) -> Vec<&[CardItem]> { |
| 616 | match self { |
| 617 | CardElement::Columns { columns, .. } => columns |
| 618 | .iter() |
| 619 | .map(|column| column.items.as_slice()) |
| 620 | .collect(), |
| 621 | CardElement::Container { items, .. } => vec![items.as_slice()], |
| 622 | CardElement::Table(table) => table |
| 623 | .rows |
| 624 | .iter() |
| 625 | .flat_map(|row| &row.cells) |
| 626 | .map(|cell| cell.items.as_slice()) |
| 627 | .collect(), |
| 628 | CardElement::Carousel(carousel) => carousel |
| 629 | .pages |
| 630 | .iter() |
| 631 | .map(|page| page.items.as_slice()) |
| 632 | .collect(), |
| 633 | _ => Vec::new(), |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | pub fn card_content_text(content: &str) -> Option<String> { |
| 639 | AdaptiveCard::parse(content)?.plain_text() |
| 640 | } |
| 641 | |
| 642 | fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) { |
| 643 | for item in items.iter().filter(|item| item.visible) { |
| 644 | match &item.element { |
| 645 | CardElement::Text(text) => push_line(lines, &text.spans), |
| 646 | CardElement::Facts(facts) => { |
| 647 | for fact in facts { |
| 648 | let mut line = format!("{}: ", fact.title); |
| 649 | push_plain(&mut line, &fact.value); |
| 650 | lines.push(line.trim().to_owned()); |
| 651 | } |
| 652 | } |
| 653 | CardElement::CodeBlock(block) => lines.push(block.code.clone()), |
| 654 | CardElement::Badge(badge) if !badge.text.is_empty() => lines.push(badge.text.clone()), |
| 655 | CardElement::CompoundButton(button) => { |
| 656 | lines.push(button.title.clone()); |
| 657 | lines.extend(button.description.clone()); |
| 658 | } |
| 659 | CardElement::ProgressRing(ring) => lines.extend(ring.label.clone()), |
| 660 | _ => {} |
| 661 | } |
| 662 | for nested in item.element.nested_items() { |
| 663 | collect_lines(nested, lines); |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | fn push_line(lines: &mut Vec<String>, spans: &[Span]) { |
| 669 | let mut line = String::new(); |
| 670 | push_plain(&mut line, spans); |
| 671 | let line = line.trim(); |
| 672 | if !line.is_empty() { |
| 673 | lines.push(line.to_owned()); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | pub(crate) fn parse_items(value: Option<&Value>) -> Vec<CardItem> { |
| 678 | value |
| 679 | .and_then(Value::as_array) |
| 680 | .into_iter() |
| 681 | .flatten() |
| 682 | .filter_map(parse_item) |
| 683 | .collect() |
| 684 | } |
| 685 | |
| 686 | fn parse_item(value: &Value) -> Option<CardItem> { |
| 687 | let id = string_field(value, "id").map(str::to_owned); |
| 688 | let visible = is_visible(value); |
| 689 | if !visible && id.is_none() { |
| 690 | return None; |
| 691 | } |
| 692 | let element = parse_element(value).or_else(|| fallback_element(value))?; |
| 693 | Some(CardItem { |
| 694 | id, |
| 695 | visible, |
| 696 | separator: value |
| 697 | .get("separator") |
| 698 | .and_then(Value::as_bool) |
| 699 | .unwrap_or(false), |
| 700 | spacing: parse_spacing(string_field(value, "spacing")), |
| 701 | stretch: string_field(value, "height") |
| 702 | .is_some_and(|height| height.eq_ignore_ascii_case("stretch")), |
| 703 | target_width: parse_target_width(value), |
| 704 | element, |
| 705 | }) |
| 706 | } |
| 707 | |
| 708 | fn parse_target_width(value: &Value) -> Option<TargetWidth> { |
| 709 | string_field(value, "targetWidth").and_then(TargetWidth::parse) |
| 710 | } |
| 711 | |
| 712 | fn parse_element(value: &Value) -> Option<CardElement> { |
| 713 | if !requirements_met(value) { |
| 714 | return None; |
| 715 | } |
| 716 | match string_field(value, "type")? { |
| 717 | "TextBlock" => parse_text_block(value), |
| 718 | "RichTextBlock" => parse_rich_text_block(value), |
| 719 | "Image" => parse_image(value).map(CardElement::Image), |
| 720 | "ImageSet" => parse_image_set(value), |
| 721 | "ColumnSet" => parse_column_set(value), |
| 722 | "Container" => parse_container(value), |
| 723 | "FactSet" => parse_fact_set(value), |
| 724 | "Media" => parse_media(value).map(CardElement::Media), |
| 725 | "Icon" => parse_icon(value).map(CardElement::Icon), |
| 726 | "Table" => parse_table(value), |
| 727 | "CodeBlock" => parse_code_block(value), |
| 728 | "Badge" => parse_badge(value), |
| 729 | "ProgressBar" => parse_progress_bar(value), |
| 730 | "ProgressRing" => parse_progress_ring(value), |
| 731 | "CompoundButton" => parse_compound_button(value), |
| 732 | "Carousel" => parse_carousel(value), |
| 733 | "ActionSet" => parse_action_set(value), |
| 734 | "Rating" => Some(CardElement::Rating(parse_rating(value))), |
| 735 | chart_type if is_chart_type(chart_type) => { |
| 736 | parse_chart(value, chart_type).map(CardElement::Chart) |
| 737 | } |
| 738 | input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => { |
| 739 | parse_input(value, input_type).map(CardElement::Input) |
| 740 | } |
| 741 | _ => None, |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | fn requirements_met(value: &Value) -> bool { |
| 746 | value |
| 747 | .get("requires") |
| 748 | .and_then(Value::as_object) |
| 749 | .is_none_or(|requires| { |
| 750 | requires.iter().all(|(feature, version)| { |
| 751 | feature.eq_ignore_ascii_case(ADAPTIVE_CARDS_FEATURE) |
| 752 | && version_supported(version.as_str().unwrap_or_default()) |
| 753 | }) |
| 754 | }) |
| 755 | } |
| 756 | |
| 757 | fn version_supported(version: &str) -> bool { |
| 758 | let version = version.trim(); |
| 759 | if version == "*" { |
| 760 | return true; |
| 761 | } |
| 762 | let mut parts = version |
| 763 | .split('.') |
| 764 | .map(|part| part.trim().parse::<u32>().unwrap_or(0)); |
| 765 | let required = (parts.next().unwrap_or(0), parts.next().unwrap_or(0)); |
| 766 | required <= SUPPORTED_CARD_VERSION |
| 767 | } |
| 768 | |
| 769 | fn fallback_element(value: &Value) -> Option<CardElement> { |
| 770 | match value.get("fallback") { |
| 771 | Some(Value::String(mode)) if mode.eq_ignore_ascii_case(FALLBACK_DROP) => return None, |
| 772 | Some(fallback @ Value::Object(_)) => { |
| 773 | if let Some(item) = parse_item(fallback) { |
| 774 | return Some(item.element); |
| 775 | } |
| 776 | } |
| 777 | _ => {} |
| 778 | } |
| 779 | fallback_item(value).map(|item| item.element) |
| 780 | } |
| 781 | |
| 782 | fn fallback_item(value: &Value) -> Option<CardItem> { |
| 783 | let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?; |
| 784 | Some(CardItem { |
| 785 | id: None, |
| 786 | visible: true, |
| 787 | separator: false, |
| 788 | spacing: CardSpacing::Default, |
| 789 | stretch: false, |
| 790 | target_width: None, |
| 791 | element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])), |
| 792 | }) |
| 793 | } |
| 794 | |
| 795 | fn plain_text_block(spans: Vec<Span>) -> CardText { |
| 796 | CardText { |
| 797 | spans, |
| 798 | size: TextSize::Default, |
| 799 | bold: false, |
| 800 | color: TextColor::Default, |
| 801 | subtle: false, |
| 802 | wrap: true, |
| 803 | max_lines: None, |
| 804 | alignment: None, |
| 805 | monospace: false, |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | fn parse_text_block(value: &Value) -> Option<CardElement> { |
| 810 | let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?; |
| 811 | let text = format_card_dates(text); |
| 812 | let heading = |
| 813 | string_field(value, "style").is_some_and(|style| style.eq_ignore_ascii_case("heading")); |
| 814 | let size = parse_text_size(string_field(value, "size")); |
| 815 | Some(CardElement::Text(CardText { |
| 816 | spans: html_to_spans(&card_markdown_to_html(&text)), |
| 817 | size: match size { |
| 818 | TextSize::Default if heading => TextSize::Large, |
| 819 | other => other, |
| 820 | }, |
| 821 | bold: heading || string_field(value, "weight").is_some_and(is_bold_weight), |
| 822 | color: parse_text_color(string_field(value, "color")), |
| 823 | subtle: bool_field(value, "isSubtle"), |
| 824 | wrap: bool_field(value, "wrap"), |
| 825 | max_lines: value |
| 826 | .get("maxLines") |
| 827 | .and_then(Value::as_u64) |
| 828 | .filter(|lines| *lines > 0) |
| 829 | .map(|lines| lines as usize), |
| 830 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")), |
| 831 | monospace: is_monospace(value), |
| 832 | })) |
| 833 | } |
| 834 | |
| 835 | fn is_monospace(value: &Value) -> bool { |
| 836 | string_field(value, "fontType").is_some_and(|font| font.eq_ignore_ascii_case("monospace")) |
| 837 | } |
| 838 | |
| 839 | fn parse_rich_text_block(value: &Value) -> Option<CardElement> { |
| 840 | let spans: Vec<Span> = value |
| 841 | .get("inlines")? |
| 842 | .as_array()? |
| 843 | .iter() |
| 844 | .flat_map(parse_text_run) |
| 845 | .collect(); |
| 846 | (!spans.is_empty()).then(|| { |
| 847 | CardElement::Text(CardText { |
| 848 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")), |
| 849 | ..plain_text_block(spans) |
| 850 | }) |
| 851 | }) |
| 852 | } |
| 853 | |
| 854 | fn parse_text_run(value: &Value) -> Vec<Span> { |
| 855 | let Some(text) = value |
| 856 | .as_str() |
| 857 | .or_else(|| string_field(value, "text")) |
| 858 | .filter(|text| !text.is_empty()) |
| 859 | else { |
| 860 | return Vec::new(); |
| 861 | }; |
| 862 | let mut spans = split_mentions(&format_card_dates(text)); |
| 863 | if is_monospace(value) { |
| 864 | spans = spans |
| 865 | .into_iter() |
| 866 | .map(|span| match span { |
| 867 | Span::Text(text) => Span::Code(text), |
| 868 | other => other, |
| 869 | }) |
| 870 | .collect(); |
| 871 | } |
| 872 | if string_field(value, "weight").is_some_and(is_bold_weight) { |
| 873 | spans = vec![Span::Bold(spans)]; |
| 874 | } |
| 875 | if bool_field(value, "italic") { |
| 876 | spans = vec![Span::Italic(spans)]; |
| 877 | } |
| 878 | if bool_field(value, "strikethrough") { |
| 879 | spans = vec![Span::Strike(spans)]; |
| 880 | } |
| 881 | if bool_field(value, "underline") { |
| 882 | spans = vec![Span::Underline(spans)]; |
| 883 | } |
| 884 | if let Some(pixels) = run_font_pixels(string_field(value, "size")) { |
| 885 | spans = vec![Span::Sized(FontSize::Pixels(pixels), spans)]; |
| 886 | } |
| 887 | let highlight = bool_field(value, "highlight"); |
| 888 | let color = run_color(string_field(value, "color"), bool_field(value, "isSubtle")) |
| 889 | .or(highlight.then_some(HIGHLIGHT_FOREGROUND)); |
| 890 | if color.is_some() || highlight { |
| 891 | spans = vec![Span::Colored { |
| 892 | color, |
| 893 | background: highlight.then_some(HIGHLIGHT_BACKGROUND), |
| 894 | children: spans, |
| 895 | }]; |
| 896 | } |
| 897 | let url = value |
| 898 | .get("selectAction") |
| 899 | .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION)) |
| 900 | .and_then(|action| string_field(action, "url")) |
| 901 | .filter(|url| is_supported_url(url)); |
| 902 | match url { |
| 903 | Some(url) => vec![Span::Link { |
| 904 | url: url.to_owned(), |
| 905 | children: spans, |
| 906 | }], |
| 907 | None => spans, |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | fn run_font_pixels(size: Option<&str>) -> Option<u16> { |
| 912 | match parse_text_size(size) { |
| 913 | TextSize::Small => Some(12), |
| 914 | TextSize::Default if size.is_none() => None, |
| 915 | TextSize::Default => Some(14), |
| 916 | TextSize::Medium => Some(15), |
| 917 | TextSize::Large => Some(18), |
| 918 | TextSize::ExtraLarge => Some(21), |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | fn run_color(color: Option<&str>, subtle: bool) -> Option<u32> { |
| 923 | match parse_text_color(color) { |
| 924 | TextColor::Accent => Some(ACCENT_RUN_COLOR), |
| 925 | TextColor::Good => Some(GOOD_RUN_COLOR), |
| 926 | TextColor::Warning => Some(WARNING_RUN_COLOR), |
| 927 | TextColor::Attention => Some(ATTENTION_RUN_COLOR), |
| 928 | TextColor::Default | TextColor::Dark | TextColor::Light => { |
| 929 | subtle.then_some(SUBTLE_RUN_COLOR) |
| 930 | } |
| 931 | } |
| 932 | } |
| 933 | |
| 934 | fn parse_image(value: &Value) -> Option<CardImage> { |
| 935 | let url = string_field(value, "url").filter(|url| is_supported_url(url))?; |
| 936 | Some(CardImage { |
| 937 | url: url.to_owned(), |
| 938 | size: parse_image_size(string_field(value, "size")), |
| 939 | width: pixel_field(value, "width"), |
| 940 | height: pixel_field(value, "height"), |
| 941 | person: string_field(value, "style") |
| 942 | .is_some_and(|style| style.eq_ignore_ascii_case("person")), |
| 943 | alt_text: string_field(value, "altText") |
| 944 | .filter(|text| !text.trim().is_empty()) |
| 945 | .map(str::to_owned), |
| 946 | alignment: parse_horizontal_alignment(string_field(value, "horizontalAlignment")) |
| 947 | .unwrap_or_default(), |
| 948 | background_color: string_field(value, "backgroundColor").and_then(parse_color_hex), |
| 949 | select_action: parse_select_action(value), |
| 950 | }) |
| 951 | } |
| 952 | |
| 953 | fn parse_image_set(value: &Value) -> Option<CardElement> { |
| 954 | let size = parse_image_size(string_field(value, "imageSize")); |
| 955 | let images: Vec<CardImage> = value |
| 956 | .get("images")? |
| 957 | .as_array()? |
| 958 | .iter() |
| 959 | .filter(|image| is_visible(image)) |
| 960 | .filter_map(parse_image) |
| 961 | .map(|image| match image.size { |
| 962 | ImageSize::Auto => CardImage { size, ..image }, |
| 963 | _ => image, |
| 964 | }) |
| 965 | .collect(); |
| 966 | (!images.is_empty()).then_some(CardElement::ImageSet(images)) |
| 967 | } |
| 968 | |
| 969 | fn parse_column_set(value: &Value) -> Option<CardElement> { |
| 970 | let columns: Vec<CardColumn> = value |
| 971 | .get("columns")? |
| 972 | .as_array()? |
| 973 | .iter() |
| 974 | .filter(|column| is_visible(column)) |
| 975 | .filter_map(|column| { |
| 976 | let items = parse_items(column.get("items")); |
| 977 | (!items.is_empty()).then(|| CardColumn { |
| 978 | width: parse_column_width(column.get("width")), |
| 979 | layout: ContainerLayout::parse(column), |
| 980 | target_width: parse_target_width(column), |
| 981 | items, |
| 982 | select_action: parse_select_action(column), |
| 983 | }) |
| 984 | }) |
| 985 | .collect(); |
| 986 | (!columns.is_empty()).then(|| CardElement::Columns { |
| 987 | columns, |
| 988 | layout: ContainerLayout::parse(value), |
| 989 | }) |
| 990 | } |
| 991 | |
| 992 | fn parse_container(value: &Value) -> Option<CardElement> { |
| 993 | let items = parse_items(value.get("items")); |
| 994 | (!items.is_empty()).then(|| CardElement::Container { |
| 995 | layout: ContainerLayout::parse(value), |
| 996 | items, |
| 997 | select_action: parse_select_action(value), |
| 998 | }) |
| 999 | } |
| 1000 | |
| 1001 | fn parse_fact_set(value: &Value) -> Option<CardElement> { |
| 1002 | let facts: Vec<CardFact> = value |
| 1003 | .get("facts")? |
| 1004 | .as_array()? |
| 1005 | .iter() |
| 1006 | .filter_map(|fact| { |
| 1007 | let title = string_field(fact, "title")?; |
| 1008 | let text = string_field(fact, "value").unwrap_or_default(); |
| 1009 | Some(CardFact { |
| 1010 | title: format_card_dates(title), |
| 1011 | value: html_to_spans(&card_markdown_to_html(&format_card_dates(text))), |
| 1012 | }) |
| 1013 | }) |
| 1014 | .collect(); |
| 1015 | (!facts.is_empty()).then_some(CardElement::Facts(facts)) |
| 1016 | } |
| 1017 | |
| 1018 | fn parse_media(value: &Value) -> Option<CardMedia> { |
| 1019 | let source_url = value |
| 1020 | .get("sources")? |
| 1021 | .as_array()? |
| 1022 | .iter() |
| 1023 | .filter_map(|source| string_field(source, "url")) |
| 1024 | .find(|url| is_supported_url(url))?; |
| 1025 | Some(CardMedia { |
| 1026 | poster_url: string_field(value, "poster") |
| 1027 | .filter(|url| url.starts_with(IMAGE_URL_SCHEME)) |
| 1028 | .map(str::to_owned) |
| 1029 | .or_else(|| crate::youtube::poster_url(source_url)), |
| 1030 | source_url: source_url.to_owned(), |
| 1031 | alt_text: string_field(value, "altText") |
| 1032 | .filter(|text| !text.trim().is_empty()) |
| 1033 | .map(str::to_owned), |
| 1034 | }) |
| 1035 | } |
| 1036 | |
| 1037 | fn parse_icon(value: &Value) -> Option<CardIcon> { |
| 1038 | let name = string_field(value, "name").filter(|name| !name.trim().is_empty())?; |
| 1039 | Some(CardIcon { |
| 1040 | name: name.trim().to_owned(), |
| 1041 | size: parse_icon_size(string_field(value, "size")), |
| 1042 | color: parse_text_color(string_field(value, "color")), |
| 1043 | filled: string_field(value, "style") |
| 1044 | .is_some_and(|style| style.eq_ignore_ascii_case("filled")), |
| 1045 | select_action: parse_select_action(value), |
| 1046 | }) |
| 1047 | } |
| 1048 | |
| 1049 | pub(crate) fn parse_select_action(value: &Value) -> Option<CardAction> { |
| 1050 | let action = parse_action_titled(value.get("selectAction")?, false)?; |
| 1051 | matches!( |
| 1052 | action.kind, |
| 1053 | CardActionKind::OpenUrl(_) |
| 1054 | | CardActionKind::Submit(_) |
| 1055 | | CardActionKind::Execute(_) |
| 1056 | | CardActionKind::ToggleVisibility(_) |
| 1057 | ) |
| 1058 | .then_some(action) |
| 1059 | } |
| 1060 | |
| 1061 | fn parse_refresh(value: &Value) -> Option<CardRefresh> { |
| 1062 | let refresh = value.get("refresh")?; |
| 1063 | let action = parse_action_titled(refresh.get("action")?, false)?; |
| 1064 | let CardActionKind::Execute(execute) = action.kind else { |
| 1065 | return None; |
| 1066 | }; |
| 1067 | Some(CardRefresh { |
| 1068 | action: execute, |
| 1069 | user_ids: refresh |
| 1070 | .get("userIds") |
| 1071 | .and_then(Value::as_array) |
| 1072 | .map(|user_ids| { |
| 1073 | user_ids |
| 1074 | .iter() |
| 1075 | .filter_map(Value::as_str) |
| 1076 | .map(str::to_owned) |
| 1077 | .collect() |
| 1078 | }), |
| 1079 | }) |
| 1080 | } |
| 1081 | |
| 1082 | fn parse_action_set(value: &Value) -> Option<CardElement> { |
| 1083 | let actions = parse_actions(value.get("actions")); |
| 1084 | (!actions.is_empty()).then_some(CardElement::Actions(actions)) |
| 1085 | } |
| 1086 | |
| 1087 | fn parse_actions(value: Option<&Value>) -> Vec<CardAction> { |
| 1088 | value |
| 1089 | .and_then(Value::as_array) |
| 1090 | .into_iter() |
| 1091 | .flatten() |
| 1092 | .filter_map(parse_action) |
| 1093 | .collect() |
| 1094 | } |
| 1095 | |
| 1096 | pub(crate) fn parse_action(value: &Value) -> Option<CardAction> { |
| 1097 | parse_action_titled(value, true) |
| 1098 | } |
| 1099 | |
| 1100 | fn parse_action_titled(value: &Value, title_required: bool) -> Option<CardAction> { |
| 1101 | let id = string_field(value, "id").map(str::to_owned); |
| 1102 | let visible = is_visible(value); |
| 1103 | if !visible && id.is_none() { |
| 1104 | return None; |
| 1105 | } |
| 1106 | let action_type = string_field(value, "type")?; |
| 1107 | if !action_type.starts_with(ACTION_TYPE_PREFIX) { |
| 1108 | return None; |
| 1109 | } |
| 1110 | let title = string_field(value, "title") |
| 1111 | .map(str::trim) |
| 1112 | .filter(|title| !title.is_empty()); |
| 1113 | let title = match title { |
| 1114 | Some(title) => title, |
| 1115 | None if title_required => return None, |
| 1116 | None => "", |
| 1117 | }; |
| 1118 | let data = || value.get("data").cloned().unwrap_or(Value::Null); |
| 1119 | let kind = match action_type { |
| 1120 | OPEN_URL_ACTION => string_field(value, "url") |
| 1121 | .filter(|url| is_supported_url(url)) |
| 1122 | .map_or(CardActionKind::Unsupported, |url| { |
| 1123 | CardActionKind::OpenUrl(url.to_owned()) |
| 1124 | }), |
| 1125 | SUBMIT_ACTION => submit_kind(data()), |
| 1126 | EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| { |
| 1127 | CardActionKind::Execute(ExecuteAction { |
| 1128 | id: id.clone(), |
| 1129 | verb: verb.to_owned(), |
| 1130 | data: data(), |
| 1131 | }) |
| 1132 | }), |
| 1133 | SHOW_CARD_ACTION => value |
| 1134 | .get("card") |
| 1135 | .and_then(AdaptiveCard::from_value) |
| 1136 | .map_or(CardActionKind::Unsupported, |card| { |
| 1137 | CardActionKind::ShowCard(Box::new(card)) |
| 1138 | }), |
| 1139 | TOGGLE_VISIBILITY_ACTION => { |
| 1140 | let targets = parse_toggle_targets(value.get("targetElements")); |
| 1141 | if targets.is_empty() { |
| 1142 | CardActionKind::Unsupported |
| 1143 | } else { |
| 1144 | CardActionKind::ToggleVisibility(targets) |
| 1145 | } |
| 1146 | } |
| 1147 | _ => CardActionKind::Unsupported, |
| 1148 | }; |
| 1149 | Some(CardAction { |
| 1150 | id, |
| 1151 | title: title.to_owned(), |
| 1152 | kind, |
| 1153 | enabled: value |
| 1154 | .get("isEnabled") |
| 1155 | .and_then(Value::as_bool) |
| 1156 | .unwrap_or(true), |
| 1157 | visible, |
| 1158 | collects_inputs: !string_field(value, "associatedInputs") |
| 1159 | .is_some_and(|mode| mode.eq_ignore_ascii_case("none")), |
| 1160 | icon: string_field(value, "iconUrl").and_then(parse_action_icon), |
| 1161 | secondary: string_field(value, "mode") |
| 1162 | .is_some_and(|mode| mode.eq_ignore_ascii_case("secondary")), |
| 1163 | tooltip: string_field(value, "tooltip") |
| 1164 | .map(str::trim) |
| 1165 | .filter(|tooltip| !tooltip.is_empty()) |
| 1166 | .map(str::to_owned), |
| 1167 | }) |
| 1168 | } |
| 1169 | |
| 1170 | fn parse_action_icon(icon_url: &str) -> Option<CardActionIcon> { |
| 1171 | match icon_url.strip_prefix(ICON_URL_PREFIX) { |
| 1172 | Some(name) => Some(name.split(',').next()?.trim()) |
| 1173 | .filter(|name| !name.is_empty()) |
| 1174 | .map(|name| CardActionIcon::Named(name.to_owned())), |
| 1175 | None => icon_url |
| 1176 | .starts_with(IMAGE_URL_SCHEME) |
| 1177 | .then(|| CardActionIcon::Url(icon_url.to_owned())), |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | fn submit_kind(data: Value) -> CardActionKind { |
| 1182 | let submit = SubmitAction { data }; |
| 1183 | let settings_type = submit |
| 1184 | .teams_settings() |
| 1185 | .and_then(|settings| string_field(settings, "type")); |
| 1186 | let invoke_type = submit |
| 1187 | .invoke_value() |
| 1188 | .and_then(|value| string_field(value, "type")); |
| 1189 | let names_add_app = [settings_type, invoke_type] |
| 1190 | .into_iter() |
| 1191 | .flatten() |
| 1192 | .any(|name| { |
| 1193 | ADD_APP_TYPES |
| 1194 | .iter() |
| 1195 | .any(|known| known.eq_ignore_ascii_case(name)) |
| 1196 | }); |
| 1197 | if names_add_app { |
| 1198 | return CardActionKind::Unavailable(ADD_APP_UNAVAILABLE); |
| 1199 | } |
| 1200 | let open_url = |url: Option<&str>| { |
| 1201 | url.filter(|url| is_supported_url(url)) |
| 1202 | .map_or(CardActionKind::Unsupported, |url| { |
| 1203 | CardActionKind::OpenUrl(url.to_owned()) |
| 1204 | }) |
| 1205 | }; |
| 1206 | if settings_type.is_some_and(|name| name.eq_ignore_ascii_case(SIGN_IN_TYPE)) { |
| 1207 | let url = submit |
| 1208 | .teams_settings() |
| 1209 | .and_then(|settings| string_field(settings, "value")); |
| 1210 | return open_url(url); |
| 1211 | } |
| 1212 | if invoke_type == Some(TAB_INFO_TYPE) { |
| 1213 | let tab_info = submit.invoke_value().and_then(|value| value.get("tabInfo")); |
| 1214 | let url = tab_info |
| 1215 | .and_then(|info| string_field(info, "websiteUrl")) |
| 1216 | .filter(|url| is_supported_url(url)) |
| 1217 | .or_else(|| tab_info.and_then(|info| string_field(info, "contentUrl"))); |
| 1218 | return open_url(url); |
| 1219 | } |
| 1220 | CardActionKind::Submit(submit) |
| 1221 | } |
| 1222 | |
| 1223 | fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> { |
| 1224 | value |
| 1225 | .and_then(Value::as_array) |
| 1226 | .into_iter() |
| 1227 | .flatten() |
| 1228 | .filter_map(|target| match target.as_str() { |
| 1229 | Some(element_id) => Some(ToggleTarget { |
| 1230 | element_id: element_id.to_owned(), |
| 1231 | visible: None, |
| 1232 | }), |
| 1233 | None => Some(ToggleTarget { |
| 1234 | element_id: string_field(target, "elementId")?.to_owned(), |
| 1235 | visible: target.get("isVisible").and_then(Value::as_bool), |
| 1236 | }), |
| 1237 | }) |
| 1238 | .collect() |
| 1239 | } |
| 1240 | |
| 1241 | fn is_bold_weight(weight: &str) -> bool { |
| 1242 | weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold") |
| 1243 | } |
| 1244 | |
| 1245 | pub(crate) fn is_supported_url(url: &str) -> bool { |
| 1246 | SUPPORTED_URL_SCHEMES |
| 1247 | .iter() |
| 1248 | .any(|scheme| url.starts_with(scheme)) |
| 1249 | } |
| 1250 | |
| 1251 | fn is_visible(value: &Value) -> bool { |
| 1252 | value |
| 1253 | .get("isVisible") |
| 1254 | .and_then(Value::as_bool) |
| 1255 | .unwrap_or(true) |
| 1256 | } |
| 1257 | |
| 1258 | pub(crate) fn bool_field(value: &Value, key: &str) -> bool { |
| 1259 | value.get(key).and_then(Value::as_bool).unwrap_or(false) |
| 1260 | } |
| 1261 | |
| 1262 | pub(crate) fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> { |
| 1263 | value.get(key)?.as_str() |
| 1264 | } |
| 1265 | |
| 1266 | pub(crate) fn pixel_field(value: &Value, key: &str) -> Option<f32> { |
| 1267 | let field = value.get(key)?; |
| 1268 | let pixels = match field.as_str() { |
| 1269 | Some(text) => text |
| 1270 | .trim() |
| 1271 | .strip_suffix(PIXEL_SUFFIX)? |
| 1272 | .trim() |
| 1273 | .parse() |
| 1274 | .ok()?, |
| 1275 | None => field.as_f64()? as f32, |
| 1276 | }; |
| 1277 | (pixels > 0.).then_some(pixels) |
| 1278 | } |
| 1279 | |
| 1280 | pub(crate) fn parse_column_width(value: Option<&Value>) -> ColumnWidth { |
| 1281 | let Some(value) = value else { |
| 1282 | return ColumnWidth::Stretch; |
| 1283 | }; |
| 1284 | if let Some(weight) = value.as_f64() { |
| 1285 | return ColumnWidth::Weighted(weight as f32); |
| 1286 | } |
| 1287 | let Some(text) = value.as_str().map(str::trim) else { |
| 1288 | return ColumnWidth::Stretch; |
| 1289 | }; |
| 1290 | if text.eq_ignore_ascii_case("auto") { |
| 1291 | return ColumnWidth::Auto; |
| 1292 | } |
| 1293 | if let Some(pixels) = text |
| 1294 | .strip_suffix(PIXEL_SUFFIX) |
| 1295 | .and_then(|number| number.trim().parse().ok()) |
| 1296 | { |
| 1297 | return ColumnWidth::Pixels(pixels); |
| 1298 | } |
| 1299 | text.parse() |
| 1300 | .map(ColumnWidth::Weighted) |
| 1301 | .unwrap_or(ColumnWidth::Stretch) |
| 1302 | } |
| 1303 | |
| 1304 | fn parse_spacing(value: Option<&str>) -> CardSpacing { |
| 1305 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1306 | Some("none") => CardSpacing::None, |
| 1307 | Some("small") => CardSpacing::Small, |
| 1308 | Some("medium") => CardSpacing::Medium, |
| 1309 | Some("large") => CardSpacing::Large, |
| 1310 | Some("extralarge") => CardSpacing::ExtraLarge, |
| 1311 | Some("padding") => CardSpacing::Padding, |
| 1312 | _ => CardSpacing::Default, |
| 1313 | } |
| 1314 | } |
| 1315 | |
| 1316 | fn parse_text_size(value: Option<&str>) -> TextSize { |
| 1317 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1318 | Some("small") => TextSize::Small, |
| 1319 | Some("medium") => TextSize::Medium, |
| 1320 | Some("large") => TextSize::Large, |
| 1321 | Some("extralarge") => TextSize::ExtraLarge, |
| 1322 | _ => TextSize::Default, |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | pub(crate) fn parse_text_color(value: Option<&str>) -> TextColor { |
| 1327 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1328 | Some("dark") => TextColor::Dark, |
| 1329 | Some("light") => TextColor::Light, |
| 1330 | Some("accent") => TextColor::Accent, |
| 1331 | Some("good") => TextColor::Good, |
| 1332 | Some("warning") => TextColor::Warning, |
| 1333 | Some("attention") => TextColor::Attention, |
| 1334 | _ => TextColor::Default, |
| 1335 | } |
| 1336 | } |
| 1337 | |
| 1338 | fn parse_image_size(value: Option<&str>) -> ImageSize { |
| 1339 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1340 | Some("stretch") => ImageSize::Stretch, |
| 1341 | Some("small") => ImageSize::Small, |
| 1342 | Some("medium") => ImageSize::Medium, |
| 1343 | Some("large") => ImageSize::Large, |
| 1344 | _ => ImageSize::Auto, |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | fn parse_icon_size(value: Option<&str>) -> IconSize { |
| 1349 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1350 | Some("xxsmall") => IconSize::ExtraExtraSmall, |
| 1351 | Some("xsmall") => IconSize::ExtraSmall, |
| 1352 | Some("small") => IconSize::Small, |
| 1353 | Some("medium") => IconSize::Medium, |
| 1354 | Some("large") => IconSize::Large, |
| 1355 | Some("xlarge") => IconSize::ExtraLarge, |
| 1356 | Some("xxlarge") => IconSize::ExtraExtraLarge, |
| 1357 | _ => IconSize::Standard, |
| 1358 | } |
| 1359 | } |
| 1360 | |
| 1361 | pub(crate) fn parse_container_style(value: Option<&str>) -> ContainerStyle { |
| 1362 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1363 | Some("emphasis") => ContainerStyle::Emphasis, |
| 1364 | Some("accent") => ContainerStyle::Accent, |
| 1365 | Some("good") => ContainerStyle::Good, |
| 1366 | Some("warning") => ContainerStyle::Warning, |
| 1367 | Some("attention") => ContainerStyle::Attention, |
| 1368 | _ => ContainerStyle::Default, |
| 1369 | } |
| 1370 | } |
| 1371 | |
| 1372 | pub(crate) fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment { |
| 1373 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 1374 | Some("center") => VerticalAlignment::Center, |
| 1375 | Some("bottom") => VerticalAlignment::Bottom, |
| 1376 | _ => VerticalAlignment::Top, |
| 1377 | } |
| 1378 | } |