BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / adaptive_card.rs

adaptive_card.rs

adaptive_card.rs 15.6 KiB Download Raw
1use serde_json::Value;
2
3use crate::markdown::markdown_to_html;
4use crate::spans::{Span, html_to_spans};
5use crate::stored::push_plain;
6
7const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
8const IMAGE_URL_SCHEME: &str = "https://";
9const ACTION_TYPE_PREFIX: &str = "Action.";
10const OPEN_URL_ACTION: &str = "Action.OpenUrl";
11const PIXEL_SUFFIX: &str = "px";
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct AdaptiveCard {
15 pub full_width: bool,
16 pub items: Vec<CardItem>,
17 pub actions: Vec<CardAction>,
18}
19
20#[derive(Debug, Clone, PartialEq)]
21pub struct CardItem {
22 pub separator: bool,
23 pub spacing: CardSpacing,
24 pub element: CardElement,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub enum CardElement {
29 Text(CardText),
30 Image(CardImage),
31 ImageSet(Vec<CardImage>),
32 Columns(Vec<CardColumn>),
33 Container {
34 style: ContainerStyle,
35 items: Vec<CardItem>,
36 },
37 Facts(Vec<CardFact>),
38 Actions(Vec<CardAction>),
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum CardSpacing {
43 None,
44 Small,
45 Default,
46 Medium,
47 Large,
48 ExtraLarge,
49 Padding,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum TextSize {
54 Small,
55 Default,
56 Medium,
57 Large,
58 ExtraLarge,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum TextColor {
63 Default,
64 Dark,
65 Light,
66 Accent,
67 Good,
68 Warning,
69 Attention,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum ImageSize {
74 Auto,
75 Stretch,
76 Small,
77 Medium,
78 Large,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ContainerStyle {
83 Default,
84 Emphasis,
85 Accent,
86 Good,
87 Warning,
88 Attention,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum VerticalAlignment {
93 Top,
94 Center,
95 Bottom,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub enum ColumnWidth {
100 Auto,
101 Stretch,
102 Weighted(f32),
103 Pixels(f32),
104}
105
106#[derive(Debug, Clone, PartialEq)]
107pub struct CardText {
108 pub spans: Vec<Span>,
109 pub size: TextSize,
110 pub bold: bool,
111 pub color: TextColor,
112 pub subtle: bool,
113 pub wrap: bool,
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct CardImage {
118 pub url: String,
119 pub size: ImageSize,
120 pub width: Option<f32>,
121 pub height: Option<f32>,
122 pub person: bool,
123}
124
125#[derive(Debug, Clone, PartialEq)]
126pub struct CardColumn {
127 pub width: ColumnWidth,
128 pub vertical_alignment: VerticalAlignment,
129 pub items: Vec<CardItem>,
130}
131
132#[derive(Debug, Clone, PartialEq)]
133pub struct CardFact {
134 pub title: String,
135 pub value: Vec<Span>,
136}
137
138#[derive(Debug, Clone, PartialEq)]
139pub struct CardAction {
140 pub title: String,
141 pub kind: CardActionKind,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum CardActionKind {
146 OpenUrl(String),
147 Unsupported,
148}
149
150impl AdaptiveCard {
151 pub fn parse(content: &str) -> Option<AdaptiveCard> {
152 let root: Value = serde_json::from_str(content).ok()?;
153 let object = root.as_object()?;
154 let mut items = parse_items(object.get("body"));
155 let actions = parse_actions(object.get("actions"));
156 if items.is_empty()
157 && let Some(item) = fallback_item(&root)
158 {
159 items.push(item);
160 }
161 if items.is_empty() && actions.is_empty() {
162 return None;
163 }
164 let full_width = object
165 .get("msTeams")
166 .and_then(|settings| string_field(settings, "width"))
167 .is_some_and(|width| width.eq_ignore_ascii_case("full"));
168 Some(AdaptiveCard {
169 full_width,
170 items,
171 actions,
172 })
173 }
174
175 pub fn plain_text(&self) -> Option<String> {
176 let mut lines = Vec::new();
177 collect_lines(&self.items, &mut lines);
178 (!lines.is_empty()).then(|| lines.join("\n"))
179 }
180}
181
182pub fn card_content_text(content: &str) -> Option<String> {
183 AdaptiveCard::parse(content)?.plain_text()
184}
185
186fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
187 for item in items {
188 match &item.element {
189 CardElement::Text(text) => push_line(lines, &text.spans),
190 CardElement::Columns(columns) => columns
191 .iter()
192 .for_each(|column| collect_lines(&column.items, lines)),
193 CardElement::Container { items, .. } => collect_lines(items, lines),
194 CardElement::Facts(facts) => {
195 for fact in facts {
196 let mut line = format!("{}: ", fact.title);
197 push_plain(&mut line, &fact.value);
198 lines.push(line.trim().to_owned());
199 }
200 }
201 CardElement::Image(_) | CardElement::ImageSet(_) | CardElement::Actions(_) => {}
202 }
203 }
204}
205
206fn push_line(lines: &mut Vec<String>, spans: &[Span]) {
207 let mut line = String::new();
208 push_plain(&mut line, spans);
209 let line = line.trim();
210 if !line.is_empty() {
211 lines.push(line.to_owned());
212 }
213}
214
215fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
216 value
217 .and_then(Value::as_array)
218 .into_iter()
219 .flatten()
220 .filter_map(parse_item)
221 .collect()
222}
223
224fn parse_item(value: &Value) -> Option<CardItem> {
225 if !is_visible(value) {
226 return None;
227 }
228 let element = match string_field(value, "type")? {
229 "TextBlock" => parse_text_block(value),
230 "RichTextBlock" => parse_rich_text_block(value),
231 "Image" => parse_image(value).map(CardElement::Image),
232 "ImageSet" => parse_image_set(value),
233 "ColumnSet" => parse_column_set(value),
234 "Container" => parse_container(value),
235 "FactSet" => parse_fact_set(value),
236 "ActionSet" => parse_action_set(value),
237 _ => None,
238 };
239 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
240 Some(CardItem {
241 separator: value
242 .get("separator")
243 .and_then(Value::as_bool)
244 .unwrap_or(false),
245 spacing: parse_spacing(string_field(value, "spacing")),
246 element,
247 })
248}
249
250fn fallback_item(value: &Value) -> Option<CardItem> {
251 let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;
252 Some(CardItem {
253 separator: false,
254 spacing: CardSpacing::Default,
255 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
256 })
257}
258
259fn plain_text_block(spans: Vec<Span>) -> CardText {
260 CardText {
261 spans,
262 size: TextSize::Default,
263 bold: false,
264 color: TextColor::Default,
265 subtle: false,
266 wrap: true,
267 }
268}
269
270fn parse_text_block(value: &Value) -> Option<CardElement> {
271 let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?;
272 Some(CardElement::Text(CardText {
273 spans: html_to_spans(&markdown_to_html(text)),
274 size: parse_text_size(string_field(value, "size")),
275 bold: string_field(value, "weight").is_some_and(is_bold_weight),
276 color: parse_text_color(string_field(value, "color")),
277 subtle: bool_field(value, "isSubtle"),
278 wrap: bool_field(value, "wrap"),
279 }))
280}
281
282fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
283 let spans: Vec<Span> = value
284 .get("inlines")?
285 .as_array()?
286 .iter()
287 .filter_map(parse_text_run)
288 .collect();
289 (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans)))
290}
291
292fn parse_text_run(value: &Value) -> Option<Span> {
293 let text = value
294 .as_str()
295 .or_else(|| string_field(value, "text"))
296 .filter(|text| !text.is_empty())?;
297 let mut span = Span::Text(text.to_owned());
298 if string_field(value, "weight").is_some_and(is_bold_weight) {
299 span = Span::Bold(vec![span]);
300 }
301 if bool_field(value, "italic") {
302 span = Span::Italic(vec![span]);
303 }
304 if bool_field(value, "strikethrough") {
305 span = Span::Strike(vec![span]);
306 }
307 if bool_field(value, "underline") {
308 span = Span::Underline(vec![span]);
309 }
310 let url = value
311 .get("selectAction")
312 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
313 .and_then(|action| string_field(action, "url"))
314 .filter(|url| is_supported_url(url));
315 Some(match url {
316 Some(url) => Span::Link {
317 url: url.to_owned(),
318 children: vec![span],
319 },
320 None => span,
321 })
322}
323
324fn parse_image(value: &Value) -> Option<CardImage> {
325 let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?;
326 Some(CardImage {
327 url: url.to_owned(),
328 size: parse_image_size(string_field(value, "size")),
329 width: pixel_field(value, "width"),
330 height: pixel_field(value, "height"),
331 person: string_field(value, "style")
332 .is_some_and(|style| style.eq_ignore_ascii_case("person")),
333 })
334}
335
336fn parse_image_set(value: &Value) -> Option<CardElement> {
337 let size = parse_image_size(string_field(value, "imageSize"));
338 let images: Vec<CardImage> = value
339 .get("images")?
340 .as_array()?
341 .iter()
342 .filter(|image| is_visible(image))
343 .filter_map(parse_image)
344 .map(|image| match image.size {
345 ImageSize::Auto => CardImage { size, ..image },
346 _ => image,
347 })
348 .collect();
349 (!images.is_empty()).then_some(CardElement::ImageSet(images))
350}
351
352fn parse_column_set(value: &Value) -> Option<CardElement> {
353 let columns: Vec<CardColumn> = value
354 .get("columns")?
355 .as_array()?
356 .iter()
357 .filter(|column| is_visible(column))
358 .filter_map(|column| {
359 let items = parse_items(column.get("items"));
360 (!items.is_empty()).then(|| CardColumn {
361 width: parse_column_width(column.get("width")),
362 vertical_alignment: parse_vertical_alignment(string_field(
363 column,
364 "verticalContentAlignment",
365 )),
366 items,
367 })
368 })
369 .collect();
370 (!columns.is_empty()).then_some(CardElement::Columns(columns))
371}
372
373fn parse_container(value: &Value) -> Option<CardElement> {
374 let items = parse_items(value.get("items"));
375 (!items.is_empty()).then(|| CardElement::Container {
376 style: parse_container_style(string_field(value, "style")),
377 items,
378 })
379}
380
381fn parse_fact_set(value: &Value) -> Option<CardElement> {
382 let facts: Vec<CardFact> = value
383 .get("facts")?
384 .as_array()?
385 .iter()
386 .filter_map(|fact| {
387 let title = string_field(fact, "title")?;
388 let text = string_field(fact, "value").unwrap_or_default();
389 Some(CardFact {
390 title: title.to_owned(),
391 value: html_to_spans(&markdown_to_html(text)),
392 })
393 })
394 .collect();
395 (!facts.is_empty()).then_some(CardElement::Facts(facts))
396}
397
398fn parse_action_set(value: &Value) -> Option<CardElement> {
399 let actions = parse_actions(value.get("actions"));
400 (!actions.is_empty()).then_some(CardElement::Actions(actions))
401}
402
403fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
404 value
405 .and_then(Value::as_array)
406 .into_iter()
407 .flatten()
408 .filter_map(parse_action)
409 .collect()
410}
411
412fn parse_action(value: &Value) -> Option<CardAction> {
413 if !is_visible(value) {
414 return None;
415 }
416 let action_type = string_field(value, "type")?;
417 if !action_type.starts_with(ACTION_TYPE_PREFIX) {
418 return None;
419 }
420 let title = string_field(value, "title")
421 .map(str::trim)
422 .filter(|title| !title.is_empty())?;
423 let kind = match string_field(value, "url") {
424 Some(url) if action_type == OPEN_URL_ACTION && is_supported_url(url) => {
425 CardActionKind::OpenUrl(url.to_owned())
426 }
427 _ => CardActionKind::Unsupported,
428 };
429 Some(CardAction {
430 title: title.to_owned(),
431 kind,
432 })
433}
434
435fn is_bold_weight(weight: &str) -> bool {
436 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
437}
438
439fn is_supported_url(url: &str) -> bool {
440 SUPPORTED_URL_SCHEMES
441 .iter()
442 .any(|scheme| url.starts_with(scheme))
443}
444
445fn is_visible(value: &Value) -> bool {
446 value
447 .get("isVisible")
448 .and_then(Value::as_bool)
449 .unwrap_or(true)
450}
451
452fn bool_field(value: &Value, key: &str) -> bool {
453 value.get(key).and_then(Value::as_bool).unwrap_or(false)
454}
455
456fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
457 value.get(key)?.as_str()
458}
459
460fn pixel_field(value: &Value, key: &str) -> Option<f32> {
461 let field = value.get(key)?;
462 let pixels = match field.as_str() {
463 Some(text) => text
464 .trim()
465 .strip_suffix(PIXEL_SUFFIX)?
466 .trim()
467 .parse()
468 .ok()?,
469 None => field.as_f64()? as f32,
470 };
471 (pixels > 0.).then_some(pixels)
472}
473
474fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
475 let Some(value) = value else {
476 return ColumnWidth::Stretch;
477 };
478 if let Some(weight) = value.as_f64() {
479 return ColumnWidth::Weighted(weight as f32);
480 }
481 let Some(text) = value.as_str().map(str::trim) else {
482 return ColumnWidth::Stretch;
483 };
484 if text.eq_ignore_ascii_case("auto") {
485 return ColumnWidth::Auto;
486 }
487 if let Some(pixels) = text
488 .strip_suffix(PIXEL_SUFFIX)
489 .and_then(|number| number.trim().parse().ok())
490 {
491 return ColumnWidth::Pixels(pixels);
492 }
493 text.parse()
494 .map(ColumnWidth::Weighted)
495 .unwrap_or(ColumnWidth::Stretch)
496}
497
498fn parse_spacing(value: Option<&str>) -> CardSpacing {
499 match value.map(str::to_ascii_lowercase).as_deref() {
500 Some("none") => CardSpacing::None,
501 Some("small") => CardSpacing::Small,
502 Some("medium") => CardSpacing::Medium,
503 Some("large") => CardSpacing::Large,
504 Some("extralarge") => CardSpacing::ExtraLarge,
505 Some("padding") => CardSpacing::Padding,
506 _ => CardSpacing::Default,
507 }
508}
509
510fn parse_text_size(value: Option<&str>) -> TextSize {
511 match value.map(str::to_ascii_lowercase).as_deref() {
512 Some("small") => TextSize::Small,
513 Some("medium") => TextSize::Medium,
514 Some("large") => TextSize::Large,
515 Some("extralarge") => TextSize::ExtraLarge,
516 _ => TextSize::Default,
517 }
518}
519
520fn parse_text_color(value: Option<&str>) -> TextColor {
521 match value.map(str::to_ascii_lowercase).as_deref() {
522 Some("dark") => TextColor::Dark,
523 Some("light") => TextColor::Light,
524 Some("accent") => TextColor::Accent,
525 Some("good") => TextColor::Good,
526 Some("warning") => TextColor::Warning,
527 Some("attention") => TextColor::Attention,
528 _ => TextColor::Default,
529 }
530}
531
532fn parse_image_size(value: Option<&str>) -> ImageSize {
533 match value.map(str::to_ascii_lowercase).as_deref() {
534 Some("stretch") => ImageSize::Stretch,
535 Some("small") => ImageSize::Small,
536 Some("medium") => ImageSize::Medium,
537 Some("large") => ImageSize::Large,
538 _ => ImageSize::Auto,
539 }
540}
541
542fn parse_container_style(value: Option<&str>) -> ContainerStyle {
543 match value.map(str::to_ascii_lowercase).as_deref() {
544 Some("emphasis") => ContainerStyle::Emphasis,
545 Some("accent") => ContainerStyle::Accent,
546 Some("good") => ContainerStyle::Good,
547 Some("warning") => ContainerStyle::Warning,
548 Some("attention") => ContainerStyle::Attention,
549 _ => ContainerStyle::Default,
550 }
551}
552
553fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
554 match value.map(str::to_ascii_lowercase).as_deref() {
555 Some("center") => VerticalAlignment::Center,
556 Some("bottom") => VerticalAlignment::Bottom,
557 _ => VerticalAlignment::Top,
558 }
559}