BlueGit

ict rusty-teams

feat(cards): Adaptive Cards complete - all elements, inputs, actions, charts, live refresh

| Before | After |
|---|---|
| Unknown elements vanish | Table, CodeBlock, Badge, Icon, Rating, ProgressBar/Ring, CompoundButton, Carousel, Media, 8 chart types |
| Date and time as plain text | Date picker with min/max, 24h time field |
| Validation on send only | Live: maxLength while typing, regex/min/max/required on blur with errorMessage |
| Data.Query choice sets dropped | Typeahead via application/search invoke |
| Jira and link cards never update | Universal Actions refresh: automatic on view (<= 60 members or listed userIds), "Refresh card" in the menu |
| `<at>` shows as text, no italics | Card mentions and `_italic_` |
| TextBlock overflows the card | wrap/maxLines/alignment/heading/monospace, ellipsis like Teams |

- Also: selectAction on card/image/container/column, fallback and requires, targetWidth, backgroundImage, bleed, minHeight, rtl, action overflow menu (mode secondary, more than 6), tooltips, iconUrl, DATE()/TIME().
- msteams submit variants: tab/tabInfoAction opens the tab URL, signin opens the URL, app install shows a disabled button.
- Input.Number still submits strings like before; Input.Rating submits a number.
- Demo: Wiki Cloud chat shows every element, input and chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
526e9e3883c0b33755ded603154b6b5cf2c6d059
Parent
8ef2da69
42 files changed +7806 −347
README.md +1 −1
@@ -43,7 +43,7 @@
43 43 - Send, edit, delete, react, quote-reply, @mentions
44 44 - Forward, copy link, save (Saved panel), pin to the chat banner, mark unread from here
45 45 - Inline images, file cards, link previews
46 - Adaptive Cards: layout, links, images, buttons, inputs, task dialogs
46 - Adaptive Cards like Teams: tables, code blocks, badges, charts, date and time pickers, live refresh, task dialogs
47 47 - GIFs and stickers in messages
48 48 - Select and copy message text
49 49
@@ -43,7 +43,7 @@
43- Send, edit, delete, react, quote-reply, @mentions
43- Send, edit, delete, react, quote-reply, @mentions
44- Forward, copy link, save (Saved panel), pin to the chat banner, mark unread from here
44- Forward, copy link, save (Saved panel), pin to the chat banner, mark unread from here
45- Inline images, file cards, link previews
45- Inline images, file cards, link previews
46- Adaptive Cards: layout, links, images, buttons, inputs, task dialogs
46- Adaptive Cards like Teams: tables, code blocks, badges, charts, date and time pickers, live refresh, task dialogs
47- GIFs and stickers in messages
47- GIFs and stickers in messages
48- Select and copy message text
48- Select and copy message text
49
49
ROADMAP.md +3 −3
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 79 %** (68 done, 2 partial, 17 missing of 87). Partial counts half.
5 **Parity: 80 %** (69 done, 1 partial, 17 missing of 87). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10 10 |---|---|---|---|---|
11 11 | [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
13 | [Reading](#reading) | 89 % | 17 | 0 | 2 |
14 14 | [Writing](#writing) | 100 % | 14 | 0 | 0 |
15 15 | [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16 16 | [Channels](#channels) | 57 % | 4 | 0 | 3 |
@@ -71,7 +71,7 @@ Feature parity with the Microsoft Teams desktop client.
71 71 | Unread jump with New divider | Done | |
72 72 | Read receipts | Done | |
73 73 | Select and copy message text | Done | |
74 | Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host), in the browser on Linux. Date and time are plain text fields, no picker |
74 | Adaptive Cards | Done | Schema 1.6 plus Teams extras: all elements incl. Table, CodeBlock, Badge, Icon, Rating, Carousel, Media and charts; all inputs with date and time pickers, live validation and Data.Query typeahead; all actions incl. overflow menu; Universal Actions auto refresh. URL task dialogs run in a hosted window on Windows, in the browser on Linux. Not yet: message-level carousel layout, chart tooltips |
75 75 | Typing indicator | Done | Shows who types as avatars above the composer (names on hover) and in the list preview; sends your own typing |
76 76 | Link previews | Done | One card per message from the chat service |
77 77 | Loop components | Missing | |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 79 %** (68 done, 2 partial, 17 missing of 87). Partial counts half.
5**Parity: 80 %** (69 done, 1 partial, 17 missing of 87). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
13| [Reading](#reading) | 89 % | 17 | 0 | 2 |
14| [Writing](#writing) | 100 % | 14 | 0 | 0 |
14| [Writing](#writing) | 100 % | 14 | 0 | 0 |
15| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
15| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16| [Channels](#channels) | 57 % | 4 | 0 | 3 |
16| [Channels](#channels) | 57 % | 4 | 0 | 3 |
@@ -71,7 +71,7 @@ Feature parity with the Microsoft Teams desktop client.
71| Unread jump with New divider | Done | |
71| Unread jump with New divider | Done | |
72| Read receipts | Done | |
72| Read receipts | Done | |
73| Select and copy message text | Done | |
73| Select and copy message text | Done | |
74| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host), in the browser on Linux. Date and time are plain text fields, no picker |
74| Adaptive Cards | Done | Schema 1.6 plus Teams extras: all elements incl. Table, CodeBlock, Badge, Icon, Rating, Carousel, Media and charts; all inputs with date and time pickers, live validation and Data.Query typeahead; all actions incl. overflow menu; Universal Actions auto refresh. URL task dialogs run in a hosted window on Windows, in the browser on Linux. Not yet: message-level carousel layout, chart tooltips |
75| Typing indicator | Done | Shows who types as avatars above the composer (names on hover) and in the list preview; sends your own typing |
75| Typing indicator | Done | Shows who types as avatars above the composer (names on hover) and in the list preview; sends your own typing |
76| Link previews | Done | One card per message from the chat service |
76| Link previews | Done | One card per message from the chat service |
77| Loop components | Missing | |
77| Loop components | Missing | |
crates/app/src/card_actions.rs +19 −3
@@ -1,8 +1,8 @@
1 1 use gpui_kit::*;
2 2 use serde_json::Value;
3 3 use teams_core::{
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog,
5 TaskDialogKind, adaptive_cards,
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog, TaskDialogKind,
5 adaptive_cards,
6 6 };
7 7 use tokio::sync::oneshot;
8 8
@@ -227,7 +227,12 @@ impl AppState {
227 227 cx.notify();
228 228 }
229 229
230 fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
230 pub(crate) fn replace_card(
231 &mut self,
232 scope: &CardScope,
233 json: &str,
234 cx: &mut Context<Self>,
235 ) -> bool {
231 236 let Some(card) = AdaptiveCard::parse(json) else {
232 237 return false;
233 238 };
@@ -366,6 +371,17 @@ impl AppState {
366 371 self.announce_cards(scope, cx);
367 372 }
368 373
374 pub fn set_card_slot(
375 &mut self,
376 scope: &CardScope,
377 slot_key: &str,
378 value: usize,
379 cx: &mut Context<Self>,
380 ) {
381 self.cards.set_slot(slot_key, value);
382 self.announce_cards(scope, cx);
383 }
384
369 385 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
370 386 let apps = self.bot_apps.get(conversation_id)?;
371 387 let matched = apps
@@ -1,8 +1,8 @@
1use gpui_kit::*;
1use gpui_kit::*;
2use serde_json::Value;
2use serde_json::Value;
3use teams_core::{
3use teams_core::{
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog,
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog, TaskDialogKind,
5 TaskDialogKind, adaptive_cards,
5 adaptive_cards,
6};
6};
7use tokio::sync::oneshot;
7use tokio::sync::oneshot;
8
8
@@ -227,7 +227,12 @@ impl AppState {
227 cx.notify();
227 cx.notify();
228 }
228 }
229
229
230 fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
230 pub(crate) fn replace_card(
231 &mut self,
232 scope: &CardScope,
233 json: &str,
234 cx: &mut Context<Self>,
235 ) -> bool {
231 let Some(card) = AdaptiveCard::parse(json) else {
236 let Some(card) = AdaptiveCard::parse(json) else {
232 return false;
237 return false;
233 };
238 };
@@ -366,6 +371,17 @@ impl AppState {
366 self.announce_cards(scope, cx);
371 self.announce_cards(scope, cx);
367 }
372 }
368
373
374 pub fn set_card_slot(
375 &mut self,
376 scope: &CardScope,
377 slot_key: &str,
378 value: usize,
379 cx: &mut Context<Self>,
380 ) {
381 self.cards.set_slot(slot_key, value);
382 self.announce_cards(scope, cx);
383 }
384
369 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
385 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
370 let apps = self.bot_apps.get(conversation_id)?;
386 let apps = self.bot_apps.get(conversation_id)?;
371 let matched = apps
387 let matched = apps
crates/app/src/card_inputs.rs +455 −58
@@ -1,21 +1,37 @@
1 use std::time::Duration;
2
1 3 use gpui_kit::component::IndexPath;
4 use gpui_kit::component::calendar::Matcher;
5 use gpui_kit::component::date_picker::{DatePickerEvent, DatePickerState};
2 6 use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
3 use gpui_kit::component::searchable_list::{SearchableListItem, SearchableVec};
7 use gpui_kit::component::searchable_list::{
8 SearchableListDelegate, SearchableListItem, SearchableVec,
9 };
4 10 use gpui_kit::component::select::{SelectEvent, SelectState};
11 use gpui_kit::component::time_field::{TimeFieldEvent, TimeFieldState};
5 12 use gpui_kit::*;
6 13 use regex::Regex;
7 14 use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceStyle,
9 DATE_PLACEHOLDER, TIME_PLACEHOLDER, TextStyle, collect_input_values,
15 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceQuery,
16 ChoiceStyle, InputChoice, TextStyle, collect_input_values, format_date, format_time,
10 17 };
18 use tokio::sync::oneshot;
11 19
12 use crate::app_state::AppState;
20 use crate::app_state::{AppHandle, AppState};
13 21 use crate::card_actions::CardTask;
14 use crate::card_state::{CardScope, Surface};
22 use crate::card_state::{CardScope, Surface, short_reason};
23 use crate::runtime;
15 24
16 25 const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
17 26 const AREA_MIN_ROWS: usize = 3;
18 27 const AREA_MAX_ROWS: usize = 8;
28 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
29 const NOT_CONNECTED: &str = "Not connected";
30 const READ_ONLY: &str = "Read-only mode";
31 const SEARCH_FAILED: &str = "Search failed";
32 const INLINE_ACTION_SUFFIX: &str = "inline";
33
34 pub type SearchAnswer = Result<Vec<InputChoice>, String>;
19 35
20 36 #[derive(Clone)]
21 37 pub struct ChoiceItem {
@@ -35,47 +51,162 @@ impl SearchableListItem for ChoiceItem {
35 51 }
36 52 }
37 53
38 pub type ChoiceSelect = SelectState<SearchableVec<ChoiceItem>>;
54 pub struct RemoteSearch {
55 scope: CardScope,
56 key: String,
57 query: ChoiceQuery,
58 }
59
60 pub struct ChoiceList {
61 items: SearchableVec<ChoiceItem>,
62 remote: Option<RemoteSearch>,
63 search_task: Task<()>,
64 }
65
66 impl ChoiceList {
67 fn new(items: Vec<ChoiceItem>, remote: Option<RemoteSearch>) -> Self {
68 ChoiceList {
69 items: SearchableVec::new(items),
70 remote,
71 search_task: Task::ready(()),
72 }
73 }
74
75 fn found(choices: Vec<InputChoice>, remote: Option<RemoteSearch>) -> Self {
76 ChoiceList::new(choice_item_list(&choices), remote)
77 }
78 }
79
80 impl SearchableListDelegate for ChoiceList {
81 type Item = ChoiceItem;
82
83 fn items_count(&self, section: usize) -> usize {
84 self.items.items_count(section)
85 }
86
87 fn item(&self, ix: IndexPath) -> Option<&ChoiceItem> {
88 self.items.item(ix)
89 }
90
91 fn position<V>(&self, value: &V) -> Option<IndexPath>
92 where
93 ChoiceItem: SearchableListItem<Value = V>,
94 V: PartialEq,
95 {
96 self.items.position(value)
97 }
98
99 fn perform_search(&mut self, query: &str, window: &mut Window, cx: &mut App) -> Task<()> {
100 let Some(remote) = &self.remote else {
101 return self.items.perform_search(query, window, cx);
102 };
103 if query.is_empty() {
104 return Task::ready(());
105 }
106 let (scope, key, choice_query, query_text) = (
107 remote.scope.clone(),
108 remote.key.clone(),
109 remote.query.clone(),
110 query.to_owned(),
111 );
112 self.search_task = window.spawn(cx, async move |cx| {
113 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
114 let app = cx.update(|_, cx| cx.global::<AppHandle>().0.clone()).ok();
115 let Some(app) = app else {
116 return;
117 };
118 let receiver = cx
119 .update(|_, cx| {
120 app.update(cx, |state, _| {
121 state.card_choice_search(&scope, &choice_query, &query_text)
122 })
123 })
124 .ok();
125 let answer = match receiver {
126 Some(receiver) => receiver.await.unwrap_or_else(|_| Err(SEARCH_FAILED.into())),
127 None => return,
128 };
129 cx.update(|window, cx| {
130 app.update(cx, |state, cx| {
131 state.show_choice_results(&scope, &key, &choice_query, answer, window, cx)
132 })
133 })
134 .ok();
135 });
136 Task::ready(())
137 }
138 }
139
140 pub type ChoiceSelect = SelectState<ChoiceList>;
39 141
40 142 #[derive(Clone)]
41 143 pub enum InputField {
42 144 Line(Entity<InputState>),
43 145 Area(Entity<TextareaState>),
44 146 Select(Entity<ChoiceSelect>),
147 Date(Entity<DatePickerState>),
148 Time(Entity<TimeFieldState>),
45 149 }
46 150
47 151 impl InputField {
48 pub fn text(&self, cx: &App) -> String {
152 pub fn text(&self, cx: &App) -> Option<String> {
49 153 match self {
50 InputField::Line(state) => state.read(cx).value().to_string(),
51 InputField::Area(state) => state.read(cx).value().to_string(),
154 InputField::Line(state) => Some(state.read(cx).value().to_string()),
155 InputField::Area(state) => Some(state.read(cx).value().to_string()),
52 156 InputField::Select(state) => {
53 state.read(cx).selected_value().cloned().unwrap_or_default()
157 Some(state.read(cx).selected_value().cloned().unwrap_or_default())
54 158 }
159 InputField::Date(_) | InputField::Time(_) => None,
55 160 }
56 161 }
57 162 }
58 163
59 164 pub struct FieldHandle {
60 165 pub field: InputField,
61 _subscription: Subscription,
166 _subscriptions: Vec<Subscription>,
167 }
168
169 fn choice_item_list(choices: &[InputChoice]) -> Vec<ChoiceItem> {
170 choices
171 .iter()
172 .map(|choice| ChoiceItem {
173 title: choice.title.clone().into(),
174 value: choice.value.clone(),
175 })
176 .collect()
62 177 }
63 178
64 pub fn choice_items(choice: &ChoiceInput) -> SearchableVec<ChoiceItem> {
65 SearchableVec::new(
66 choice
67 .choices
179 pub fn choice_list(choice: &ChoiceInput, scope: &CardScope, key: &str) -> ChoiceList {
180 let remote = choice.query.clone().map(|query| RemoteSearch {
181 scope: scope.clone(),
182 key: key.to_owned(),
183 query,
184 });
185 let mut choices = choice.choices.clone();
186 if remote.is_some() && !choice.value.is_empty() {
187 let known = choices
68 188 .iter()
69 .map(|choice| ChoiceItem {
70 title: choice.title.clone().into(),
189 .any(|candidate| candidate.value == choice.value);
190 if !known {
191 choices.push(InputChoice {
192 title: choice.value.clone(),
71 193 value: choice.value.clone(),
72 })
73 .collect::<Vec<_>>(),
74 )
194 });
195 }
196 }
197 ChoiceList::found(choices, remote)
75 198 }
76 199
77 200 pub fn uses_select(choice: &ChoiceInput) -> bool {
78 !choice.multi && choice.style != ChoiceStyle::Expanded
201 choice.query.is_some() || (!choice.multi && choice.style != ChoiceStyle::Expanded)
202 }
203
204 pub fn length_pattern(max_length: usize) -> Option<Regex> {
205 Regex::new(&format!("^(?s:.{{0,{max_length}}})$")).ok()
206 }
207
208 pub fn inline_action_key(input_key: &str) -> String {
209 format!("{input_key}-{INLINE_ACTION_SUFFIX}")
79 210 }
80 211
81 212 impl AppState {
@@ -86,12 +217,13 @@ impl AppState {
86 217 window: &mut Window,
87 218 cx: &mut Context<Self>,
88 219 ) {
89 for input in card.all_inputs() {
220 let inputs = card.all_inputs();
221 for input in &inputs {
90 222 let key = scope.input_key(&input.id);
91 223 if self.cards.has_input(&key) {
92 224 continue;
93 225 }
94 let handle = Self::create_field(scope, &key, &input, window, cx);
226 let handle = Self::create_field(scope, &key, input, &inputs, window, cx);
95 227 self.cards.seed_input(key, input.initial_value(), handle);
96 228 }
97 229 }
@@ -100,92 +232,274 @@ impl AppState {
100 232 scope: &CardScope,
101 233 key: &str,
102 234 input: &CardInput,
235 inputs: &[CardInput],
103 236 window: &mut Window,
104 237 cx: &mut Context<Self>,
105 238 ) -> Option<FieldHandle> {
106 239 let value = input.initial_value();
107 240 let (scope, key) = (scope.clone(), key.to_owned());
241 let validated = input.clone();
108 242 match &input.kind {
109 243 CardInputKind::Text(text) if text.multiline => {
110 244 let placeholder = text.placeholder.clone().unwrap_or_default();
245 let max_length = text.max_length;
111 246 let state = cx.new(|cx| {
112 247 TextareaState::new(window, cx)
113 248 .auto_grow(AREA_MIN_ROWS, AREA_MAX_ROWS)
114 249 .placeholder(placeholder)
115 250 .default_value(value)
116 251 });
117 let subscription =
118 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
119 if matches!(event, InputEvent::Change) {
120 let text = state.read(cx).value().to_string();
252 let subscription = cx.subscribe_in(&state, window, {
253 let (scope, key) = (scope.clone(), key.clone());
254 move |this, state, event: &InputEvent, window, cx| match event {
255 InputEvent::Change => {
256 let mut text = state.read(cx).value().to_string();
257 if let Some(max_length) = max_length
258 && text.chars().count() > max_length
259 {
260 text = text.chars().take(max_length).collect();
261 state.update(cx, |area, cx| {
262 area.set_value(text.clone(), window, cx)
263 });
264 }
121 265 this.edit_card_input(&scope, &key, text, cx);
122 266 }
123 });
267 InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx),
268 _ => {}
269 }
270 });
124 271 Some(FieldHandle {
125 272 field: InputField::Area(state),
126 _subscription: subscription,
273 _subscriptions: vec![subscription],
127 274 })
128 275 }
129 CardInputKind::Text(_)
130 | CardInputKind::Number(_)
131 | CardInputKind::Date(_)
132 | CardInputKind::Time(_) => {
133 let (placeholder, masked, numeric) = match &input.kind {
276 CardInputKind::Text(_) | CardInputKind::Number(_) => {
277 let (placeholder, masked, pattern, inline_action) = match &input.kind {
134 278 CardInputKind::Text(text) => (
135 279 text.placeholder.clone(),
136 280 text.style == TextStyle::Password,
281 text.max_length.and_then(length_pattern),
282 text.inline_action.clone(),
283 ),
284 CardInputKind::Number(number) => (
285 number.placeholder.clone(),
137 286 false,
287 Regex::new(NUMBER_PATTERN).ok(),
288 None,
138 289 ),
139 CardInputKind::Number(number) => (number.placeholder.clone(), false, true),
140 CardInputKind::Date(_) => (Some(DATE_PLACEHOLDER.to_owned()), false, false),
141 _ => (Some(TIME_PLACEHOLDER.to_owned()), false, false),
290 _ => (None, false, None, None),
142 291 };
143 292 let state = cx.new(|cx| {
144 293 let line = InputState::new(window, cx)
145 294 .placeholder(placeholder.unwrap_or_default())
146 295 .masked(masked)
147 296 .default_value(value);
148 match Regex::new(NUMBER_PATTERN) {
149 Ok(pattern) if numeric => line.pattern(pattern),
150 _ => line,
297 match pattern {
298 Some(pattern) => line.pattern(pattern),
299 None => line,
151 300 }
152 301 });
153 let subscription =
154 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
155 if matches!(event, InputEvent::Change) {
302 let inputs = inputs.to_vec();
303 let subscription = cx.subscribe(&state, {
304 let (scope, key) = (scope.clone(), key.clone());
305 move |this, state, event: &InputEvent, cx| match event {
306 InputEvent::Change => {
156 307 let text = state.read(cx).value().to_string();
157 308 this.edit_card_input(&scope, &key, text, cx);
158 309 }
159 });
310 InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx),
311 InputEvent::PressEnter { .. } => {
312 if let Some(inline) = &inline_action {
313 this.run_inline_action(
314 &scope,
315 inline_action_key(&key),
316 &inline.action,
317 &inputs,
318 cx,
319 );
320 }
321 }
322 InputEvent::Focus => {}
323 }
324 });
160 325 Some(FieldHandle {
161 326 field: InputField::Line(state),
162 _subscription: subscription,
327 _subscriptions: vec![subscription],
163 328 })
164 329 }
165 CardInputKind::Choice(choice) if uses_select(choice) => {
166 let searchable = choice.style == ChoiceStyle::Filtered;
167 let selected = choice
168 .choices
169 .iter()
170 .position(|candidate| candidate.value == value)
171 .map(|row| IndexPath::default().row(row));
330 CardInputKind::Date(moment) => {
331 let (min, max) = (moment.min_date(), moment.max_date());
332 let initial = moment.initial_date();
172 333 let state = cx.new(|cx| {
173 SelectState::new(choice_items(choice), selected, window, cx)
174 .searchable(searchable)
334 let mut picker = DatePickerState::new(window, cx).date_format("%Y-%m-%d");
335 if min.is_some() || max.is_some() {
336 picker = picker.disabled_matcher(Matcher::interval(min, max));
337 }
338 if let Some(date) = initial {
339 picker.set_date(date, window, cx);
340 }
341 picker
342 });
343 let subscription = cx.subscribe(&state, {
344 move |this, _, event: &DatePickerEvent, cx| {
345 let DatePickerEvent::Change(picked) = event;
346 let text = picked.date().start().map(format_date).unwrap_or_default();
347 this.pick_card_input(&scope, &key, text, cx);
348 this.validate_card_input(&scope, &key, &validated, cx);
349 }
175 350 });
351 Some(FieldHandle {
352 field: InputField::Date(state),
353 _subscriptions: vec![subscription],
354 })
355 }
356 CardInputKind::Time(moment) => {
357 let initial = moment.initial_time();
358 let state = cx.new(|cx| {
359 let mut field = TimeFieldState::new(window, cx);
360 if let Some(time) = initial {
361 field.set_time(time, window, cx);
362 }
363 field
364 });
365 let focus_handle = state.focus_handle(cx);
366 let changed = cx.subscribe(&state, {
367 let (scope, key) = (scope.clone(), key.clone());
368 move |this, _, event: &TimeFieldEvent, cx| {
369 let TimeFieldEvent::Change(time) = event;
370 this.pick_card_input(&scope, &key, format_time(*time), cx);
371 }
372 });
373 let blurred = cx.on_blur(&focus_handle, window, move |this, _, cx| {
374 this.validate_card_input(&scope, &key, &validated, cx)
375 });
376 Some(FieldHandle {
377 field: InputField::Time(state),
378 _subscriptions: vec![changed, blurred],
379 })
380 }
381 CardInputKind::Choice(choice) if uses_select(choice) => {
382 let searchable = choice.style == ChoiceStyle::Filtered || choice.query.is_some();
383 let list = choice_list(choice, &scope, &key);
384 let selected = (0..list.items_count(0))
385 .find(|row| {
386 list.item(IndexPath::default().row(*row))
387 .is_some_and(|item| item.value == value)
388 })
389 .map(|row| IndexPath::default().row(row));
390 let state = cx
391 .new(|cx| SelectState::new(list, selected, window, cx).searchable(searchable));
176 392 let subscription = cx.subscribe(
177 393 &state,
178 move |this, _, event: &SelectEvent<SearchableVec<ChoiceItem>>, cx| {
394 move |this, _, event: &SelectEvent<ChoiceList>, cx| {
179 395 let SelectEvent::Confirm(picked) = event;
180 396 this.pick_card_input(&scope, &key, picked.clone().unwrap_or_default(), cx);
181 397 },
182 398 );
183 399 Some(FieldHandle {
184 400 field: InputField::Select(state),
185 _subscription: subscription,
401 _subscriptions: vec![subscription],
186 402 })
187 403 }
188 CardInputKind::Choice(_) | CardInputKind::Toggle(_) => None,
404 CardInputKind::Choice(_) | CardInputKind::Toggle(_) | CardInputKind::Rating(_) => None,
405 }
406 }
407
408 pub fn validate_card_input(
409 &mut self,
410 scope: &CardScope,
411 key: &str,
412 input: &CardInput,
413 cx: &mut Context<Self>,
414 ) {
415 let value = self.cards.input_text(key, cx);
416 match input.validate(&value) {
417 Some(message) => self.cards.set_input_error(key, message),
418 None => self.cards.clear_input_errors(&[key.to_owned()]),
419 }
420 self.announce_cards(scope, cx);
421 }
422
423 pub fn run_inline_action(
424 &mut self,
425 scope: &CardScope,
426 action_key: String,
427 action: &CardAction,
428 inputs: &[CardInput],
429 cx: &mut Context<Self>,
430 ) {
431 match &action.kind {
432 CardActionKind::OpenUrl(url) => cx.open_url(url),
433 _ => self.run_card_action(
434 scope.clone(),
435 action_key,
436 action.clone(),
437 inputs.to_vec(),
438 cx,
439 ),
440 }
441 }
442
443 pub fn card_choice_search(
444 &self,
445 scope: &CardScope,
446 query: &ChoiceQuery,
447 query_text: &str,
448 ) -> oneshot::Receiver<SearchAnswer> {
449 if self.mode.demo {
450 let (dataset, query_text) = (query.dataset.clone(), query_text.to_owned());
451 return runtime::spawn(async move {
452 Ok(crate::demo_input_cards::search(&dataset, &query_text))
453 });
454 }
455 if self.mode.read_only {
456 return runtime::spawn(async { Err(READ_ONLY.to_owned()) });
457 }
458 let Some(engine) = self.engine.clone() else {
459 return runtime::spawn(async { Err(NOT_CONNECTED.to_owned()) });
460 };
461 let (conversation_id, message_id) =
462 (scope.conversation_id.clone(), scope.message_id.clone());
463 let (query, query_text) = (query.clone(), query_text.to_owned());
464 runtime::spawn(async move {
465 engine
466 .card_search(&conversation_id, &message_id, &query, &query_text)
467 .await
468 .map_err(|error| short_reason(&error.to_string()))
469 })
470 }
471
472 pub fn show_choice_results(
473 &mut self,
474 scope: &CardScope,
475 key: &str,
476 query: &ChoiceQuery,
477 answer: SearchAnswer,
478 window: &mut Window,
479 cx: &mut Context<Self>,
480 ) {
481 match answer {
482 Ok(choices) => {
483 if self.cards.input_error(key) == Some(SEARCH_FAILED) {
484 self.cards.clear_input_errors(&[key.to_owned()]);
485 self.announce_cards(scope, cx);
486 }
487 if let Some(InputField::Select(select)) = self.cards.input_field(key).cloned() {
488 let remote = RemoteSearch {
489 scope: scope.clone(),
490 key: key.to_owned(),
491 query: query.clone(),
492 };
493 select.update(cx, |select, cx| {
494 select.set_items(ChoiceList::found(choices, Some(remote)), window, cx);
495 cx.notify();
496 });
497 }
498 }
499 Err(_) => {
500 self.cards.set_input_error(key, SEARCH_FAILED.to_owned());
501 self.announce_cards(scope, cx);
502 }
189 503 }
190 504 }
191 505
@@ -303,6 +617,20 @@ mod tests {
303 617 AdaptiveCard::parse(&card.to_string()).unwrap()
304 618 }
305 619
620 fn typed_card() -> AdaptiveCard {
621 let card = json!({
622 "body": [
623 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
624 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
625 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
626 {"type": "Input.Number", "id": "count", "value": 4},
627 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
628 ],
629 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
630 });
631 AdaptiveCard::parse(&card.to_string()).unwrap()
632 }
633
306 634 fn open(
307 635 cx: &mut TestAppContext,
308 636 surface: Surface,
@@ -311,6 +639,19 @@ mod tests {
311 639 Entity<AppState>,
312 640 CardScope,
313 641 AdaptiveCard,
642 ) {
643 open_card(cx, surface, form_card())
644 }
645
646 fn open_card(
647 cx: &mut TestAppContext,
648 surface: Surface,
649 card: AdaptiveCard,
650 ) -> (
651 &mut VisualTestContext,
652 Entity<AppState>,
653 CardScope,
654 AdaptiveCard,
314 655 ) {
315 656 cx.update(gpui_kit::init);
316 657 let store = Arc::new(Store::open_in_memory().unwrap());
@@ -320,7 +661,6 @@ mod tests {
320 661 surface,
321 662 ..CardScope::message("19:chat@thread.v2", "m1", 0)
322 663 };
323 let card = form_card();
324 664 let (_, window_cx) = cx.add_window_view({
325 665 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
326 666 move |_, _| Harness { app, scope, card }
@@ -430,4 +770,61 @@ mod tests {
430 770 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
431 771 );
432 772 }
773
774 #[gpui_kit::test]
775 fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
776 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
777 let key = scope.input_key("code");
778 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
779 let Some(InputField::Line(line)) = field else {
780 panic!("code is a single line field");
781 };
782 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
783 cx.simulate_input("abcdef");
784 assert_eq!(
785 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
786 "abc"
787 );
788 }
789
790 #[gpui_kit::test]
791 fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
792 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
793 let key = scope.input_key("code");
794 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
795 let Some(InputField::Line(line)) = field else {
796 panic!("code is a single line field");
797 };
798 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
799 cx.simulate_input("AB");
800 let input = card.own_inputs().remove(0);
801 cx.update(|_, cx| {
802 app.update(cx, |state, cx| {
803 state.validate_card_input(&scope, &key, &input, cx)
804 })
805 });
806 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
807 }
808
809 #[gpui_kit::test]
810 fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
811 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
812 let hour_key = scope.input_key("hour");
813 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
814 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
815 cx.update(|_, cx| {
816 app.update(cx, |state, cx| {
817 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
818 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
819 })
820 });
821 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
822 assert_eq!(
823 sent,
824 json!({
825 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
826 "count": "4", "stars": 3.5
827 })
828 );
829 }
433 830 }
@@ -1,21 +1,37 @@
1use std::time::Duration;
2
1use gpui_kit::component::IndexPath;
3use gpui_kit::component::IndexPath;
4use gpui_kit::component::calendar::Matcher;
5use gpui_kit::component::date_picker::{DatePickerEvent, DatePickerState};
2use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
6use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
3use gpui_kit::component::searchable_list::{SearchableListItem, SearchableVec};
7use gpui_kit::component::searchable_list::{
8 SearchableListDelegate, SearchableListItem, SearchableVec,
9};
4use gpui_kit::component::select::{SelectEvent, SelectState};
10use gpui_kit::component::select::{SelectEvent, SelectState};
11use gpui_kit::component::time_field::{TimeFieldEvent, TimeFieldState};
5use gpui_kit::*;
12use gpui_kit::*;
6use regex::Regex;
13use regex::Regex;
7use teams_core::{
14use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceStyle,
15 AdaptiveCard, CardAction, CardActionKind, CardInput, CardInputKind, ChoiceInput, ChoiceQuery,
9 DATE_PLACEHOLDER, TIME_PLACEHOLDER, TextStyle, collect_input_values,
16 ChoiceStyle, InputChoice, TextStyle, collect_input_values, format_date, format_time,
10};
17};
18use tokio::sync::oneshot;
11
19
12use crate::app_state::AppState;
20use crate::app_state::{AppHandle, AppState};
13use crate::card_actions::CardTask;
21use crate::card_actions::CardTask;
14use crate::card_state::{CardScope, Surface};
22use crate::card_state::{CardScope, Surface, short_reason};
23use crate::runtime;
15
24
16const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
25const NUMBER_PATTERN: &str = r"^-?\d*\.?\d*$";
17const AREA_MIN_ROWS: usize = 3;
26const AREA_MIN_ROWS: usize = 3;
18const AREA_MAX_ROWS: usize = 8;
27const AREA_MAX_ROWS: usize = 8;
28const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
29const NOT_CONNECTED: &str = "Not connected";
30const READ_ONLY: &str = "Read-only mode";
31const SEARCH_FAILED: &str = "Search failed";
32const INLINE_ACTION_SUFFIX: &str = "inline";
33
34pub type SearchAnswer = Result<Vec<InputChoice>, String>;
19
35
20#[derive(Clone)]
36#[derive(Clone)]
21pub struct ChoiceItem {
37pub struct ChoiceItem {
@@ -35,47 +51,162 @@ impl SearchableListItem for ChoiceItem {
35 }
51 }
36}
52}
37
53
38pub type ChoiceSelect = SelectState<SearchableVec<ChoiceItem>>;
54pub struct RemoteSearch {
55 scope: CardScope,
56 key: String,
57 query: ChoiceQuery,
58}
59
60pub struct ChoiceList {
61 items: SearchableVec<ChoiceItem>,
62 remote: Option<RemoteSearch>,
63 search_task: Task<()>,
64}
65
66impl ChoiceList {
67 fn new(items: Vec<ChoiceItem>, remote: Option<RemoteSearch>) -> Self {
68 ChoiceList {
69 items: SearchableVec::new(items),
70 remote,
71 search_task: Task::ready(()),
72 }
73 }
74
75 fn found(choices: Vec<InputChoice>, remote: Option<RemoteSearch>) -> Self {
76 ChoiceList::new(choice_item_list(&choices), remote)
77 }
78}
79
80impl SearchableListDelegate for ChoiceList {
81 type Item = ChoiceItem;
82
83 fn items_count(&self, section: usize) -> usize {
84 self.items.items_count(section)
85 }
86
87 fn item(&self, ix: IndexPath) -> Option<&ChoiceItem> {
88 self.items.item(ix)
89 }
90
91 fn position<V>(&self, value: &V) -> Option<IndexPath>
92 where
93 ChoiceItem: SearchableListItem<Value = V>,
94 V: PartialEq,
95 {
96 self.items.position(value)
97 }
98
99 fn perform_search(&mut self, query: &str, window: &mut Window, cx: &mut App) -> Task<()> {
100 let Some(remote) = &self.remote else {
101 return self.items.perform_search(query, window, cx);
102 };
103 if query.is_empty() {
104 return Task::ready(());
105 }
106 let (scope, key, choice_query, query_text) = (
107 remote.scope.clone(),
108 remote.key.clone(),
109 remote.query.clone(),
110 query.to_owned(),
111 );
112 self.search_task = window.spawn(cx, async move |cx| {
113 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
114 let app = cx.update(|_, cx| cx.global::<AppHandle>().0.clone()).ok();
115 let Some(app) = app else {
116 return;
117 };
118 let receiver = cx
119 .update(|_, cx| {
120 app.update(cx, |state, _| {
121 state.card_choice_search(&scope, &choice_query, &query_text)
122 })
123 })
124 .ok();
125 let answer = match receiver {
126 Some(receiver) => receiver.await.unwrap_or_else(|_| Err(SEARCH_FAILED.into())),
127 None => return,
128 };
129 cx.update(|window, cx| {
130 app.update(cx, |state, cx| {
131 state.show_choice_results(&scope, &key, &choice_query, answer, window, cx)
132 })
133 })
134 .ok();
135 });
136 Task::ready(())
137 }
138}
139
140pub type ChoiceSelect = SelectState<ChoiceList>;
39
141
40#[derive(Clone)]
142#[derive(Clone)]
41pub enum InputField {
143pub enum InputField {
42 Line(Entity<InputState>),
144 Line(Entity<InputState>),
43 Area(Entity<TextareaState>),
145 Area(Entity<TextareaState>),
44 Select(Entity<ChoiceSelect>),
146 Select(Entity<ChoiceSelect>),
147 Date(Entity<DatePickerState>),
148 Time(Entity<TimeFieldState>),
45}
149}
46
150
47impl InputField {
151impl InputField {
48 pub fn text(&self, cx: &App) -> String {
152 pub fn text(&self, cx: &App) -> Option<String> {
49 match self {
153 match self {
50 InputField::Line(state) => state.read(cx).value().to_string(),
154 InputField::Line(state) => Some(state.read(cx).value().to_string()),
51 InputField::Area(state) => state.read(cx).value().to_string(),
155 InputField::Area(state) => Some(state.read(cx).value().to_string()),
52 InputField::Select(state) => {
156 InputField::Select(state) => {
53 state.read(cx).selected_value().cloned().unwrap_or_default()
157 Some(state.read(cx).selected_value().cloned().unwrap_or_default())
54 }
158 }
159 InputField::Date(_) | InputField::Time(_) => None,
55 }
160 }
56 }
161 }
57}
162}
58
163
59pub struct FieldHandle {
164pub struct FieldHandle {
60 pub field: InputField,
165 pub field: InputField,
61 _subscription: Subscription,
166 _subscriptions: Vec<Subscription>,
167}
168
169fn choice_item_list(choices: &[InputChoice]) -> Vec<ChoiceItem> {
170 choices
171 .iter()
172 .map(|choice| ChoiceItem {
173 title: choice.title.clone().into(),
174 value: choice.value.clone(),
175 })
176 .collect()
62}
177}
63
178
64pub fn choice_items(choice: &ChoiceInput) -> SearchableVec<ChoiceItem> {
179pub fn choice_list(choice: &ChoiceInput, scope: &CardScope, key: &str) -> ChoiceList {
65 SearchableVec::new(
180 let remote = choice.query.clone().map(|query| RemoteSearch {
66 choice
181 scope: scope.clone(),
67 .choices
182 key: key.to_owned(),
183 query,
184 });
185 let mut choices = choice.choices.clone();
186 if remote.is_some() && !choice.value.is_empty() {
187 let known = choices
68 .iter()
188 .iter()
69 .map(|choice| ChoiceItem {
189 .any(|candidate| candidate.value == choice.value);
70 title: choice.title.clone().into(),
190 if !known {
191 choices.push(InputChoice {
192 title: choice.value.clone(),
71 value: choice.value.clone(),
193 value: choice.value.clone(),
72 })
194 });
73 .collect::<Vec<_>>(),
195 }
74 )
196 }
197 ChoiceList::found(choices, remote)
75}
198}
76
199
77pub fn uses_select(choice: &ChoiceInput) -> bool {
200pub fn uses_select(choice: &ChoiceInput) -> bool {
78 !choice.multi && choice.style != ChoiceStyle::Expanded
201 choice.query.is_some() || (!choice.multi && choice.style != ChoiceStyle::Expanded)
202}
203
204pub fn length_pattern(max_length: usize) -> Option<Regex> {
205 Regex::new(&format!("^(?s:.{{0,{max_length}}})$")).ok()
206}
207
208pub fn inline_action_key(input_key: &str) -> String {
209 format!("{input_key}-{INLINE_ACTION_SUFFIX}")
79}
210}
80
211
81impl AppState {
212impl AppState {
@@ -86,12 +217,13 @@ impl AppState {
86 window: &mut Window,
217 window: &mut Window,
87 cx: &mut Context<Self>,
218 cx: &mut Context<Self>,
88 ) {
219 ) {
89 for input in card.all_inputs() {
220 let inputs = card.all_inputs();
221 for input in &inputs {
90 let key = scope.input_key(&input.id);
222 let key = scope.input_key(&input.id);
91 if self.cards.has_input(&key) {
223 if self.cards.has_input(&key) {
92 continue;
224 continue;
93 }
225 }
94 let handle = Self::create_field(scope, &key, &input, window, cx);
226 let handle = Self::create_field(scope, &key, input, &inputs, window, cx);
95 self.cards.seed_input(key, input.initial_value(), handle);
227 self.cards.seed_input(key, input.initial_value(), handle);
96 }
228 }
97 }
229 }
@@ -100,92 +232,274 @@ impl AppState {
100 scope: &CardScope,
232 scope: &CardScope,
101 key: &str,
233 key: &str,
102 input: &CardInput,
234 input: &CardInput,
235 inputs: &[CardInput],
103 window: &mut Window,
236 window: &mut Window,
104 cx: &mut Context<Self>,
237 cx: &mut Context<Self>,
105 ) -> Option<FieldHandle> {
238 ) -> Option<FieldHandle> {
106 let value = input.initial_value();
239 let value = input.initial_value();
107 let (scope, key) = (scope.clone(), key.to_owned());
240 let (scope, key) = (scope.clone(), key.to_owned());
241 let validated = input.clone();
108 match &input.kind {
242 match &input.kind {
109 CardInputKind::Text(text) if text.multiline => {
243 CardInputKind::Text(text) if text.multiline => {
110 let placeholder = text.placeholder.clone().unwrap_or_default();
244 let placeholder = text.placeholder.clone().unwrap_or_default();
245 let max_length = text.max_length;
111 let state = cx.new(|cx| {
246 let state = cx.new(|cx| {
112 TextareaState::new(window, cx)
247 TextareaState::new(window, cx)
113 .auto_grow(AREA_MIN_ROWS, AREA_MAX_ROWS)
248 .auto_grow(AREA_MIN_ROWS, AREA_MAX_ROWS)
114 .placeholder(placeholder)
249 .placeholder(placeholder)
115 .default_value(value)
250 .default_value(value)
116 });
251 });
117 let subscription =
252 let subscription = cx.subscribe_in(&state, window, {
118 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
253 let (scope, key) = (scope.clone(), key.clone());
119 if matches!(event, InputEvent::Change) {
254 move |this, state, event: &InputEvent, window, cx| match event {
120 let text = state.read(cx).value().to_string();
255 InputEvent::Change => {
256 let mut text = state.read(cx).value().to_string();
257 if let Some(max_length) = max_length
258 && text.chars().count() > max_length
259 {
260 text = text.chars().take(max_length).collect();
261 state.update(cx, |area, cx| {
262 area.set_value(text.clone(), window, cx)
263 });
264 }
121 this.edit_card_input(&scope, &key, text, cx);
265 this.edit_card_input(&scope, &key, text, cx);
122 }
266 }
123 });
267 InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx),
268 _ => {}
269 }
270 });
124 Some(FieldHandle {
271 Some(FieldHandle {
125 field: InputField::Area(state),
272 field: InputField::Area(state),
126 _subscription: subscription,
273 _subscriptions: vec![subscription],
127 })
274 })
128 }
275 }
129 CardInputKind::Text(_)
276 CardInputKind::Text(_) | CardInputKind::Number(_) => {
130 | CardInputKind::Number(_)
277 let (placeholder, masked, pattern, inline_action) = match &input.kind {
131 | CardInputKind::Date(_)
132 | CardInputKind::Time(_) => {
133 let (placeholder, masked, numeric) = match &input.kind {
134 CardInputKind::Text(text) => (
278 CardInputKind::Text(text) => (
135 text.placeholder.clone(),
279 text.placeholder.clone(),
136 text.style == TextStyle::Password,
280 text.style == TextStyle::Password,
281 text.max_length.and_then(length_pattern),
282 text.inline_action.clone(),
283 ),
284 CardInputKind::Number(number) => (
285 number.placeholder.clone(),
137 false,
286 false,
287 Regex::new(NUMBER_PATTERN).ok(),
288 None,
138 ),
289 ),
139 CardInputKind::Number(number) => (number.placeholder.clone(), false, true),
290 _ => (None, false, None, None),
140 CardInputKind::Date(_) => (Some(DATE_PLACEHOLDER.to_owned()), false, false),
141 _ => (Some(TIME_PLACEHOLDER.to_owned()), false, false),
142 };
291 };
143 let state = cx.new(|cx| {
292 let state = cx.new(|cx| {
144 let line = InputState::new(window, cx)
293 let line = InputState::new(window, cx)
145 .placeholder(placeholder.unwrap_or_default())
294 .placeholder(placeholder.unwrap_or_default())
146 .masked(masked)
295 .masked(masked)
147 .default_value(value);
296 .default_value(value);
148 match Regex::new(NUMBER_PATTERN) {
297 match pattern {
149 Ok(pattern) if numeric => line.pattern(pattern),
298 Some(pattern) => line.pattern(pattern),
150 _ => line,
299 None => line,
151 }
300 }
152 });
301 });
153 let subscription =
302 let inputs = inputs.to_vec();
154 cx.subscribe(&state, move |this, state, event: &InputEvent, cx| {
303 let subscription = cx.subscribe(&state, {
155 if matches!(event, InputEvent::Change) {
304 let (scope, key) = (scope.clone(), key.clone());
305 move |this, state, event: &InputEvent, cx| match event {
306 InputEvent::Change => {
156 let text = state.read(cx).value().to_string();
307 let text = state.read(cx).value().to_string();
157 this.edit_card_input(&scope, &key, text, cx);
308 this.edit_card_input(&scope, &key, text, cx);
158 }
309 }
159 });
310 InputEvent::Blur => this.validate_card_input(&scope, &key, &validated, cx),
311 InputEvent::PressEnter { .. } => {
312 if let Some(inline) = &inline_action {
313 this.run_inline_action(
314 &scope,
315 inline_action_key(&key),
316 &inline.action,
317 &inputs,
318 cx,
319 );
320 }
321 }
322 InputEvent::Focus => {}
323 }
324 });
160 Some(FieldHandle {
325 Some(FieldHandle {
161 field: InputField::Line(state),
326 field: InputField::Line(state),
162 _subscription: subscription,
327 _subscriptions: vec![subscription],
163 })
328 })
164 }
329 }
165 CardInputKind::Choice(choice) if uses_select(choice) => {
330 CardInputKind::Date(moment) => {
166 let searchable = choice.style == ChoiceStyle::Filtered;
331 let (min, max) = (moment.min_date(), moment.max_date());
167 let selected = choice
332 let initial = moment.initial_date();
168 .choices
169 .iter()
170 .position(|candidate| candidate.value == value)
171 .map(|row| IndexPath::default().row(row));
172 let state = cx.new(|cx| {
333 let state = cx.new(|cx| {
173 SelectState::new(choice_items(choice), selected, window, cx)
334 let mut picker = DatePickerState::new(window, cx).date_format("%Y-%m-%d");
174 .searchable(searchable)
335 if min.is_some() || max.is_some() {
336 picker = picker.disabled_matcher(Matcher::interval(min, max));
337 }
338 if let Some(date) = initial {
339 picker.set_date(date, window, cx);
340 }
341 picker
342 });
343 let subscription = cx.subscribe(&state, {
344 move |this, _, event: &DatePickerEvent, cx| {
345 let DatePickerEvent::Change(picked) = event;
346 let text = picked.date().start().map(format_date).unwrap_or_default();
347 this.pick_card_input(&scope, &key, text, cx);
348 this.validate_card_input(&scope, &key, &validated, cx);
349 }
175 });
350 });
351 Some(FieldHandle {
352 field: InputField::Date(state),
353 _subscriptions: vec![subscription],
354 })
355 }
356 CardInputKind::Time(moment) => {
357 let initial = moment.initial_time();
358 let state = cx.new(|cx| {
359 let mut field = TimeFieldState::new(window, cx);
360 if let Some(time) = initial {
361 field.set_time(time, window, cx);
362 }
363 field
364 });
365 let focus_handle = state.focus_handle(cx);
366 let changed = cx.subscribe(&state, {
367 let (scope, key) = (scope.clone(), key.clone());
368 move |this, _, event: &TimeFieldEvent, cx| {
369 let TimeFieldEvent::Change(time) = event;
370 this.pick_card_input(&scope, &key, format_time(*time), cx);
371 }
372 });
373 let blurred = cx.on_blur(&focus_handle, window, move |this, _, cx| {
374 this.validate_card_input(&scope, &key, &validated, cx)
375 });
376 Some(FieldHandle {
377 field: InputField::Time(state),
378 _subscriptions: vec![changed, blurred],
379 })
380 }
381 CardInputKind::Choice(choice) if uses_select(choice) => {
382 let searchable = choice.style == ChoiceStyle::Filtered || choice.query.is_some();
383 let list = choice_list(choice, &scope, &key);
384 let selected = (0..list.items_count(0))
385 .find(|row| {
386 list.item(IndexPath::default().row(*row))
387 .is_some_and(|item| item.value == value)
388 })
389 .map(|row| IndexPath::default().row(row));
390 let state = cx
391 .new(|cx| SelectState::new(list, selected, window, cx).searchable(searchable));
176 let subscription = cx.subscribe(
392 let subscription = cx.subscribe(
177 &state,
393 &state,
178 move |this, _, event: &SelectEvent<SearchableVec<ChoiceItem>>, cx| {
394 move |this, _, event: &SelectEvent<ChoiceList>, cx| {
179 let SelectEvent::Confirm(picked) = event;
395 let SelectEvent::Confirm(picked) = event;
180 this.pick_card_input(&scope, &key, picked.clone().unwrap_or_default(), cx);
396 this.pick_card_input(&scope, &key, picked.clone().unwrap_or_default(), cx);
181 },
397 },
182 );
398 );
183 Some(FieldHandle {
399 Some(FieldHandle {
184 field: InputField::Select(state),
400 field: InputField::Select(state),
185 _subscription: subscription,
401 _subscriptions: vec![subscription],
186 })
402 })
187 }
403 }
188 CardInputKind::Choice(_) | CardInputKind::Toggle(_) => None,
404 CardInputKind::Choice(_) | CardInputKind::Toggle(_) | CardInputKind::Rating(_) => None,
405 }
406 }
407
408 pub fn validate_card_input(
409 &mut self,
410 scope: &CardScope,
411 key: &str,
412 input: &CardInput,
413 cx: &mut Context<Self>,
414 ) {
415 let value = self.cards.input_text(key, cx);
416 match input.validate(&value) {
417 Some(message) => self.cards.set_input_error(key, message),
418 None => self.cards.clear_input_errors(&[key.to_owned()]),
419 }
420 self.announce_cards(scope, cx);
421 }
422
423 pub fn run_inline_action(
424 &mut self,
425 scope: &CardScope,
426 action_key: String,
427 action: &CardAction,
428 inputs: &[CardInput],
429 cx: &mut Context<Self>,
430 ) {
431 match &action.kind {
432 CardActionKind::OpenUrl(url) => cx.open_url(url),
433 _ => self.run_card_action(
434 scope.clone(),
435 action_key,
436 action.clone(),
437 inputs.to_vec(),
438 cx,
439 ),
440 }
441 }
442
443 pub fn card_choice_search(
444 &self,
445 scope: &CardScope,
446 query: &ChoiceQuery,
447 query_text: &str,
448 ) -> oneshot::Receiver<SearchAnswer> {
449 if self.mode.demo {
450 let (dataset, query_text) = (query.dataset.clone(), query_text.to_owned());
451 return runtime::spawn(async move {
452 Ok(crate::demo_input_cards::search(&dataset, &query_text))
453 });
454 }
455 if self.mode.read_only {
456 return runtime::spawn(async { Err(READ_ONLY.to_owned()) });
457 }
458 let Some(engine) = self.engine.clone() else {
459 return runtime::spawn(async { Err(NOT_CONNECTED.to_owned()) });
460 };
461 let (conversation_id, message_id) =
462 (scope.conversation_id.clone(), scope.message_id.clone());
463 let (query, query_text) = (query.clone(), query_text.to_owned());
464 runtime::spawn(async move {
465 engine
466 .card_search(&conversation_id, &message_id, &query, &query_text)
467 .await
468 .map_err(|error| short_reason(&error.to_string()))
469 })
470 }
471
472 pub fn show_choice_results(
473 &mut self,
474 scope: &CardScope,
475 key: &str,
476 query: &ChoiceQuery,
477 answer: SearchAnswer,
478 window: &mut Window,
479 cx: &mut Context<Self>,
480 ) {
481 match answer {
482 Ok(choices) => {
483 if self.cards.input_error(key) == Some(SEARCH_FAILED) {
484 self.cards.clear_input_errors(&[key.to_owned()]);
485 self.announce_cards(scope, cx);
486 }
487 if let Some(InputField::Select(select)) = self.cards.input_field(key).cloned() {
488 let remote = RemoteSearch {
489 scope: scope.clone(),
490 key: key.to_owned(),
491 query: query.clone(),
492 };
493 select.update(cx, |select, cx| {
494 select.set_items(ChoiceList::found(choices, Some(remote)), window, cx);
495 cx.notify();
496 });
497 }
498 }
499 Err(_) => {
500 self.cards.set_input_error(key, SEARCH_FAILED.to_owned());
501 self.announce_cards(scope, cx);
502 }
189 }
503 }
190 }
504 }
191
505
@@ -303,6 +617,20 @@ mod tests {
303 AdaptiveCard::parse(&card.to_string()).unwrap()
617 AdaptiveCard::parse(&card.to_string()).unwrap()
304 }
618 }
305
619
620 fn typed_card() -> AdaptiveCard {
621 let card = json!({
622 "body": [
623 {"type": "Input.Text", "id": "code", "maxLength": 3, "regex": "^[a-z]+$", "errorMessage": "Letters only"},
624 {"type": "Input.Date", "id": "day", "value": "2026-11-02", "min": "2026-10-01", "max": "2026-12-31"},
625 {"type": "Input.Time", "id": "hour", "value": "09:30", "min": "10:00", "errorMessage": "Too early"},
626 {"type": "Input.Number", "id": "count", "value": 4},
627 {"type": "Input.Rating", "id": "stars", "value": 2, "allowHalf": true}
628 ],
629 "actions": [{"type": "Action.Submit", "title": "Save", "data": {"action": "save"}}]
630 });
631 AdaptiveCard::parse(&card.to_string()).unwrap()
632 }
633
306 fn open(
634 fn open(
307 cx: &mut TestAppContext,
635 cx: &mut TestAppContext,
308 surface: Surface,
636 surface: Surface,
@@ -311,6 +639,19 @@ mod tests {
311 Entity<AppState>,
639 Entity<AppState>,
312 CardScope,
640 CardScope,
313 AdaptiveCard,
641 AdaptiveCard,
642 ) {
643 open_card(cx, surface, form_card())
644 }
645
646 fn open_card(
647 cx: &mut TestAppContext,
648 surface: Surface,
649 card: AdaptiveCard,
650 ) -> (
651 &mut VisualTestContext,
652 Entity<AppState>,
653 CardScope,
654 AdaptiveCard,
314 ) {
655 ) {
315 cx.update(gpui_kit::init);
656 cx.update(gpui_kit::init);
316 let store = Arc::new(Store::open_in_memory().unwrap());
657 let store = Arc::new(Store::open_in_memory().unwrap());
@@ -320,7 +661,6 @@ mod tests {
320 surface,
661 surface,
321 ..CardScope::message("19:chat@thread.v2", "m1", 0)
662 ..CardScope::message("19:chat@thread.v2", "m1", 0)
322 };
663 };
323 let card = form_card();
324 let (_, window_cx) = cx.add_window_view({
664 let (_, window_cx) = cx.add_window_view({
325 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
665 let (app, scope, card) = (app.clone(), scope.clone(), card.clone());
326 move |_, _| Harness { app, scope, card }
666 move |_, _| Harness { app, scope, card }
@@ -430,4 +770,61 @@ mod tests {
430 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
770 object(&[("action", "save"), ("name", "Ada"), ("agree", "false")])
431 );
771 );
432 }
772 }
773
774 #[gpui_kit::test]
775 fn typing_past_the_max_length_is_ignored(cx: &mut TestAppContext) {
776 let (cx, app, scope, _) = open_card(cx, Surface::Message, typed_card());
777 let key = scope.input_key("code");
778 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
779 let Some(InputField::Line(line)) = field else {
780 panic!("code is a single line field");
781 };
782 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
783 cx.simulate_input("abcdef");
784 assert_eq!(
785 cx.update(|_, cx| app.read(cx).cards.input_text(&key, cx)),
786 "abc"
787 );
788 }
789
790 #[gpui_kit::test]
791 fn blur_validation_shows_the_error_message(cx: &mut TestAppContext) {
792 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
793 let key = scope.input_key("code");
794 let field = cx.update(|_, cx| app.read(cx).cards.input_field(&key).cloned());
795 let Some(InputField::Line(line)) = field else {
796 panic!("code is a single line field");
797 };
798 cx.update(|window, cx| line.update(cx, |state, cx| state.focus(window, cx)));
799 cx.simulate_input("AB");
800 let input = card.own_inputs().remove(0);
801 cx.update(|_, cx| {
802 app.update(cx, |state, cx| {
803 state.validate_card_input(&scope, &key, &input, cx)
804 })
805 });
806 assert_eq!(error_of(cx, &app, &key).as_deref(), Some("Letters only"));
807 }
808
809 #[gpui_kit::test]
810 fn date_time_and_rating_values_are_collected_with_their_types(cx: &mut TestAppContext) {
811 let (cx, app, scope, card) = open_card(cx, Surface::Message, typed_card());
812 let hour_key = scope.input_key("hour");
813 assert!(task_for(cx, &app, &scope, &card, 0).is_none());
814 assert_eq!(error_of(cx, &app, &hour_key).as_deref(), Some("Too early"));
815 cx.update(|_, cx| {
816 app.update(cx, |state, cx| {
817 state.pick_card_input(&scope, &hour_key, "10:15".into(), cx);
818 state.pick_card_input(&scope, &scope.input_key("stars"), "3.5".into(), cx);
819 })
820 });
821 let sent = sent_value(task_for(cx, &app, &scope, &card, 0));
822 assert_eq!(
823 sent,
824 json!({
825 "action": "save", "code": "", "day": "2026-11-02", "hour": "10:15",
826 "count": "4", "stars": 3.5
827 })
828 );
829 }
433}
830}
crates/app/src/card_refresh.rs added +122 −0
@@ -0,0 +1,122 @@
1 use gpui_kit::*;
2 use teams_core::{AdaptiveCard, CardActionOutcome, ExecuteAction, ExecuteTrigger};
3 use tokio::sync::oneshot;
4
5 use crate::app_state::AppState;
6 use crate::card_actions::CardAnswer;
7 use crate::card_state::{CardScope, short_reason};
8 use crate::runtime;
9
10 impl AppState {
11 pub fn request_card_refreshes(
12 &mut self,
13 conversation_id: &str,
14 message_id: &str,
15 cards: &[AdaptiveCard],
16 cx: &mut Context<Self>,
17 ) {
18 if self.mode.read_only {
19 return;
20 }
21 let Some((card_index, refresh)) = cards
22 .iter()
23 .enumerate()
24 .find_map(|(index, card)| card.refresh.as_ref().map(|refresh| (index, refresh)))
25 else {
26 return;
27 };
28 let member_count = self
29 .sidebar
30 .chats
31 .iter()
32 .find(|chat| chat.id == conversation_id)
33 .map(|chat| chat.members.len());
34 let my_user_id = self.directory.me.as_ref().map(|me| me.user_id.as_str());
35 if !refresh.runs_automatically(member_count, my_user_id) {
36 return;
37 }
38 let scope = CardScope::message(conversation_id, message_id, card_index);
39 self.start_card_refresh(scope, refresh.action.clone(), ExecuteTrigger::Automatic, cx);
40 }
41
42 pub fn refresh_card_manually(
43 &mut self,
44 scope: CardScope,
45 action: ExecuteAction,
46 cx: &mut Context<Self>,
47 ) {
48 self.start_card_refresh(scope, action, ExecuteTrigger::Manual, cx);
49 }
50
51 fn start_card_refresh(
52 &mut self,
53 scope: CardScope,
54 action: ExecuteAction,
55 trigger: ExecuteTrigger,
56 cx: &mut Context<Self>,
57 ) {
58 let manual = trigger == ExecuteTrigger::Manual;
59 if !self
60 .cards
61 .begin_refresh(&scope.conversation_id, &scope.message_id, manual)
62 {
63 return;
64 }
65 let Some(receiver) = self.refresh_answer(&scope, action, trigger) else {
66 self.cards
67 .cancel_refresh(&scope.conversation_id, &scope.message_id);
68 return;
69 };
70 cx.spawn(async move |this, cx| {
71 let answer = receiver
72 .await
73 .unwrap_or_else(|_| Err("cancelled".to_owned()));
74 this.update(cx, |state, cx| {
75 state.finish_card_refresh(&scope, answer, cx)
76 })
77 .ok();
78 })
79 .detach();
80 }
81
82 fn refresh_answer(
83 &self,
84 scope: &CardScope,
85 action: ExecuteAction,
86 trigger: ExecuteTrigger,
87 ) -> Option<oneshot::Receiver<CardAnswer>> {
88 if self.mode.demo {
89 return Some(runtime::spawn(crate::demo::refresh_answer()));
90 }
91 let engine = self.engine.clone()?;
92 let (conversation_id, message_id) =
93 (scope.conversation_id.clone(), scope.message_id.clone());
94 Some(runtime::spawn(async move {
95 let outcome = engine
96 .card_refresh(&conversation_id, &message_id, &action, trigger)
97 .await
98 .map_err(|error| short_reason(&error.to_string()))?;
99 Ok((outcome, None))
100 }))
101 }
102
103 fn finish_card_refresh(
104 &mut self,
105 scope: &CardScope,
106 answer: CardAnswer,
107 cx: &mut Context<Self>,
108 ) {
109 let was_full = self.cards.finish_refresh();
110 let replaced = match answer {
111 Ok((CardActionOutcome::ReplaceCard(json), _)) => self.replace_card(scope, &json, cx),
112 Ok((CardActionOutcome::Failed(reason), _)) | Err(reason) => {
113 eprintln!("card refresh failed: {reason}");
114 false
115 }
116 Ok(_) => false,
117 };
118 if was_full && !replaced {
119 self.announce_cards(scope, cx);
120 }
121 }
122 }
@@ -0,0 +1,122 @@
1use gpui_kit::*;
2use teams_core::{AdaptiveCard, CardActionOutcome, ExecuteAction, ExecuteTrigger};
3use tokio::sync::oneshot;
4
5use crate::app_state::AppState;
6use crate::card_actions::CardAnswer;
7use crate::card_state::{CardScope, short_reason};
8use crate::runtime;
9
10impl AppState {
11 pub fn request_card_refreshes(
12 &mut self,
13 conversation_id: &str,
14 message_id: &str,
15 cards: &[AdaptiveCard],
16 cx: &mut Context<Self>,
17 ) {
18 if self.mode.read_only {
19 return;
20 }
21 let Some((card_index, refresh)) = cards
22 .iter()
23 .enumerate()
24 .find_map(|(index, card)| card.refresh.as_ref().map(|refresh| (index, refresh)))
25 else {
26 return;
27 };
28 let member_count = self
29 .sidebar
30 .chats
31 .iter()
32 .find(|chat| chat.id == conversation_id)
33 .map(|chat| chat.members.len());
34 let my_user_id = self.directory.me.as_ref().map(|me| me.user_id.as_str());
35 if !refresh.runs_automatically(member_count, my_user_id) {
36 return;
37 }
38 let scope = CardScope::message(conversation_id, message_id, card_index);
39 self.start_card_refresh(scope, refresh.action.clone(), ExecuteTrigger::Automatic, cx);
40 }
41
42 pub fn refresh_card_manually(
43 &mut self,
44 scope: CardScope,
45 action: ExecuteAction,
46 cx: &mut Context<Self>,
47 ) {
48 self.start_card_refresh(scope, action, ExecuteTrigger::Manual, cx);
49 }
50
51 fn start_card_refresh(
52 &mut self,
53 scope: CardScope,
54 action: ExecuteAction,
55 trigger: ExecuteTrigger,
56 cx: &mut Context<Self>,
57 ) {
58 let manual = trigger == ExecuteTrigger::Manual;
59 if !self
60 .cards
61 .begin_refresh(&scope.conversation_id, &scope.message_id, manual)
62 {
63 return;
64 }
65 let Some(receiver) = self.refresh_answer(&scope, action, trigger) else {
66 self.cards
67 .cancel_refresh(&scope.conversation_id, &scope.message_id);
68 return;
69 };
70 cx.spawn(async move |this, cx| {
71 let answer = receiver
72 .await
73 .unwrap_or_else(|_| Err("cancelled".to_owned()));
74 this.update(cx, |state, cx| {
75 state.finish_card_refresh(&scope, answer, cx)
76 })
77 .ok();
78 })
79 .detach();
80 }
81
82 fn refresh_answer(
83 &self,
84 scope: &CardScope,
85 action: ExecuteAction,
86 trigger: ExecuteTrigger,
87 ) -> Option<oneshot::Receiver<CardAnswer>> {
88 if self.mode.demo {
89 return Some(runtime::spawn(crate::demo::refresh_answer()));
90 }
91 let engine = self.engine.clone()?;
92 let (conversation_id, message_id) =
93 (scope.conversation_id.clone(), scope.message_id.clone());
94 Some(runtime::spawn(async move {
95 let outcome = engine
96 .card_refresh(&conversation_id, &message_id, &action, trigger)
97 .await
98 .map_err(|error| short_reason(&error.to_string()))?;
99 Ok((outcome, None))
100 }))
101 }
102
103 fn finish_card_refresh(
104 &mut self,
105 scope: &CardScope,
106 answer: CardAnswer,
107 cx: &mut Context<Self>,
108 ) {
109 let was_full = self.cards.finish_refresh();
110 let replaced = match answer {
111 Ok((CardActionOutcome::ReplaceCard(json), _)) => self.replace_card(scope, &json, cx),
112 Ok((CardActionOutcome::Failed(reason), _)) | Err(reason) => {
113 eprintln!("card refresh failed: {reason}");
114 false
115 }
116 Ok(_) => false,
117 };
118 if was_full && !replaced {
119 self.announce_cards(scope, cx);
120 }
121 }
122}
crates/app/src/card_state.rs +92 −8
@@ -1,4 +1,4 @@
1 use std::collections::HashMap;
1 use std::collections::{HashMap, HashSet};
2 2 use std::time::Duration;
3 3
4 4 use teams_core::AdaptiveCard;
@@ -10,6 +10,7 @@ use crate::card_inputs::{FieldHandle, InputField};
10 10 const DIALOG_KEY: &str = "task-dialog";
11 11 pub const DONE_HOLD: Duration = Duration::from_millis(1600);
12 12 pub const MAX_REASON_CHARS: usize = 160;
13 const MAX_REFRESHES_IN_FLIGHT: usize = 3;
13 14
14 15 #[derive(Debug, Clone, PartialEq, Eq)]
15 16 pub enum ActionPhase {
@@ -84,11 +85,14 @@ pub struct CardState {
84 85 phases: HashMap<String, ActionPhase>,
85 86 visibility: HashMap<String, bool>,
86 87 open_cards: HashMap<String, usize>,
88 slots: HashMap<String, usize>,
87 89 notes: HashMap<String, String>,
88 90 overrides: HashMap<(String, String), CardOverride>,
89 91 input_values: HashMap<String, String>,
90 92 input_errors: HashMap<String, String>,
91 93 input_fields: HashMap<String, FieldHandle>,
94 refreshed: HashSet<(String, String)>,
95 refreshes_in_flight: usize,
92 96 }
93 97
94 98 impl CardState {
@@ -114,10 +118,14 @@ impl CardState {
114 118 self.phases.retain(|key, _| !key.starts_with(card_key));
115 119 self.visibility.retain(|key, _| !key.starts_with(card_key));
116 120 self.open_cards.retain(|key, _| !key.starts_with(card_key));
121 self.slots.retain(|key, _| !key.starts_with(card_key));
117 122 self.notes.remove(card_key);
118 self.input_values.retain(|key, _| !key.starts_with(card_key));
119 self.input_errors.retain(|key, _| !key.starts_with(card_key));
120 self.input_fields.retain(|key, _| !key.starts_with(card_key));
123 self.input_values
124 .retain(|key, _| !key.starts_with(card_key));
125 self.input_errors
126 .retain(|key, _| !key.starts_with(card_key));
127 self.input_fields
128 .retain(|key, _| !key.starts_with(card_key));
121 129 }
122 130
123 131 pub fn has_input(&self, input_key: &str) -> bool {
@@ -132,14 +140,15 @@ impl CardState {
132 140 }
133 141
134 142 pub fn input_value(&self, input_key: &str) -> &str {
135 self.input_values
136 .get(input_key)
137 .map_or("", String::as_str)
143 self.input_values.get(input_key).map_or("", String::as_str)
138 144 }
139 145
140 146 pub fn input_text(&self, input_key: &str, cx: &App) -> String {
141 147 match self.input_fields.get(input_key) {
142 Some(handle) => handle.field.text(cx),
148 Some(handle) => handle
149 .field
150 .text(cx)
151 .unwrap_or_else(|| self.input_value(input_key).to_owned()),
143 152 None => self.input_value(input_key).to_owned(),
144 153 }
145 154 }
@@ -188,6 +197,14 @@ impl CardState {
188 197 }
189 198 }
190 199
200 pub fn slot(&self, slot_key: &str, default: usize) -> usize {
201 self.slots.get(slot_key).copied().unwrap_or(default)
202 }
203
204 pub fn set_slot(&mut self, slot_key: &str, value: usize) {
205 self.slots.insert(slot_key.to_owned(), value);
206 }
207
191 208 pub fn note(&self, card_key: &str) -> Option<&str> {
192 209 self.notes.get(card_key).map(String::as_str)
193 210 }
@@ -212,6 +229,32 @@ impl CardState {
212 229 );
213 230 }
214 231
232 pub fn begin_refresh(&mut self, conversation_id: &str, message_id: &str, manual: bool) -> bool {
233 let key = (conversation_id.to_owned(), message_id.to_owned());
234 if !manual
235 && (self.refreshed.contains(&key)
236 || self.refreshes_in_flight >= MAX_REFRESHES_IN_FLIGHT)
237 {
238 return false;
239 }
240 self.refreshed.insert(key);
241 self.refreshes_in_flight += 1;
242 true
243 }
244
245 pub fn cancel_refresh(&mut self, conversation_id: &str, message_id: &str) {
246 self.refreshed
247 .remove(&(conversation_id.to_owned(), message_id.to_owned()));
248 self.refreshes_in_flight = self.refreshes_in_flight.saturating_sub(1);
249 }
250
251 /// True when the throttle was full, so a deferred refresh may start now.
252 pub fn finish_refresh(&mut self) -> bool {
253 let was_full = self.refreshes_in_flight >= MAX_REFRESHES_IN_FLIGHT;
254 self.refreshes_in_flight = self.refreshes_in_flight.saturating_sub(1);
255 was_full
256 }
257
215 258 pub fn overrides_for(&self, conversation_id: &str) -> HashMap<String, CardOverride> {
216 259 self.overrides
217 260 .iter()
@@ -267,6 +310,16 @@ mod tests {
267 310 assert_eq!(state.open_card("set"), None);
268 311 }
269 312
313 #[test]
314 fn slots_default_until_set_and_clear_with_their_card() {
315 let mut state = CardState::default();
316 assert_eq!(state.slot("m-card-0-3", 2), 2);
317 state.set_slot("m-card-0-3", 5);
318 assert_eq!(state.slot("m-card-0-3", 2), 5);
319 state.clear_card("m-card-0");
320 assert_eq!(state.slot("m-card-0-3", 2), 2);
321 }
322
270 323 #[test]
271 324 fn overrides_are_scoped_to_their_conversation() {
272 325 let mut state = CardState::default();
@@ -279,6 +332,37 @@ mod tests {
279 332 assert!(state.overrides_for("c2").is_empty());
280 333 }
281 334
335 #[test]
336 fn a_message_refreshes_once_unless_asked_manually() {
337 let mut state = CardState::default();
338 assert!(state.begin_refresh("c", "m", false));
339 assert!(!state.begin_refresh("c", "m", false));
340 assert!(state.begin_refresh("c", "m", true));
341 assert!(state.begin_refresh("c", "other", false));
342 }
343
344 #[test]
345 fn at_most_three_automatic_refreshes_run_at_once() {
346 let mut state = CardState::default();
347 for message_id in ["a", "b", "c"] {
348 assert!(state.begin_refresh("c", message_id, false));
349 }
350 assert!(!state.begin_refresh("c", "d", false));
351 assert!(state.begin_refresh("c", "d", true));
352 assert!(state.finish_refresh());
353 assert!(state.finish_refresh());
354 assert!(!state.finish_refresh());
355 assert!(state.begin_refresh("c", "e", false));
356 }
357
358 #[test]
359 fn a_cancelled_refresh_may_start_again() {
360 let mut state = CardState::default();
361 assert!(state.begin_refresh("c", "m", false));
362 state.cancel_refresh("c", "m");
363 assert!(state.begin_refresh("c", "m", false));
364 }
365
282 366 #[test]
283 367 fn reasons_are_shortened() {
284 368 assert_eq!(
@@ -1,4 +1,4 @@
1use std::collections::HashMap;
1use std::collections::{HashMap, HashSet};
2use std::time::Duration;
2use std::time::Duration;
3
3
4use teams_core::AdaptiveCard;
4use teams_core::AdaptiveCard;
@@ -10,6 +10,7 @@ use crate::card_inputs::{FieldHandle, InputField};
10const DIALOG_KEY: &str = "task-dialog";
10const DIALOG_KEY: &str = "task-dialog";
11pub const DONE_HOLD: Duration = Duration::from_millis(1600);
11pub const DONE_HOLD: Duration = Duration::from_millis(1600);
12pub const MAX_REASON_CHARS: usize = 160;
12pub const MAX_REASON_CHARS: usize = 160;
13const MAX_REFRESHES_IN_FLIGHT: usize = 3;
13
14
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ActionPhase {
16pub enum ActionPhase {
@@ -84,11 +85,14 @@ pub struct CardState {
84 phases: HashMap<String, ActionPhase>,
85 phases: HashMap<String, ActionPhase>,
85 visibility: HashMap<String, bool>,
86 visibility: HashMap<String, bool>,
86 open_cards: HashMap<String, usize>,
87 open_cards: HashMap<String, usize>,
88 slots: HashMap<String, usize>,
87 notes: HashMap<String, String>,
89 notes: HashMap<String, String>,
88 overrides: HashMap<(String, String), CardOverride>,
90 overrides: HashMap<(String, String), CardOverride>,
89 input_values: HashMap<String, String>,
91 input_values: HashMap<String, String>,
90 input_errors: HashMap<String, String>,
92 input_errors: HashMap<String, String>,
91 input_fields: HashMap<String, FieldHandle>,
93 input_fields: HashMap<String, FieldHandle>,
94 refreshed: HashSet<(String, String)>,
95 refreshes_in_flight: usize,
92}
96}
93
97
94impl CardState {
98impl CardState {
@@ -114,10 +118,14 @@ impl CardState {
114 self.phases.retain(|key, _| !key.starts_with(card_key));
118 self.phases.retain(|key, _| !key.starts_with(card_key));
115 self.visibility.retain(|key, _| !key.starts_with(card_key));
119 self.visibility.retain(|key, _| !key.starts_with(card_key));
116 self.open_cards.retain(|key, _| !key.starts_with(card_key));
120 self.open_cards.retain(|key, _| !key.starts_with(card_key));
121 self.slots.retain(|key, _| !key.starts_with(card_key));
117 self.notes.remove(card_key);
122 self.notes.remove(card_key);
118 self.input_values.retain(|key, _| !key.starts_with(card_key));
123 self.input_values
119 self.input_errors.retain(|key, _| !key.starts_with(card_key));
124 .retain(|key, _| !key.starts_with(card_key));
120 self.input_fields.retain(|key, _| !key.starts_with(card_key));
125 self.input_errors
126 .retain(|key, _| !key.starts_with(card_key));
127 self.input_fields
128 .retain(|key, _| !key.starts_with(card_key));
121 }
129 }
122
130
123 pub fn has_input(&self, input_key: &str) -> bool {
131 pub fn has_input(&self, input_key: &str) -> bool {
@@ -132,14 +140,15 @@ impl CardState {
132 }
140 }
133
141
134 pub fn input_value(&self, input_key: &str) -> &str {
142 pub fn input_value(&self, input_key: &str) -> &str {
135 self.input_values
143 self.input_values.get(input_key).map_or("", String::as_str)
136 .get(input_key)
137 .map_or("", String::as_str)
138 }
144 }
139
145
140 pub fn input_text(&self, input_key: &str, cx: &App) -> String {
146 pub fn input_text(&self, input_key: &str, cx: &App) -> String {
141 match self.input_fields.get(input_key) {
147 match self.input_fields.get(input_key) {
142 Some(handle) => handle.field.text(cx),
148 Some(handle) => handle
149 .field
150 .text(cx)
151 .unwrap_or_else(|| self.input_value(input_key).to_owned()),
143 None => self.input_value(input_key).to_owned(),
152 None => self.input_value(input_key).to_owned(),
144 }
153 }
145 }
154 }
@@ -188,6 +197,14 @@ impl CardState {
188 }
197 }
189 }
198 }
190
199
200 pub fn slot(&self, slot_key: &str, default: usize) -> usize {
201 self.slots.get(slot_key).copied().unwrap_or(default)
202 }
203
204 pub fn set_slot(&mut self, slot_key: &str, value: usize) {
205 self.slots.insert(slot_key.to_owned(), value);
206 }
207
191 pub fn note(&self, card_key: &str) -> Option<&str> {
208 pub fn note(&self, card_key: &str) -> Option<&str> {
192 self.notes.get(card_key).map(String::as_str)
209 self.notes.get(card_key).map(String::as_str)
193 }
210 }
@@ -212,6 +229,32 @@ impl CardState {
212 );
229 );
213 }
230 }
214
231
232 pub fn begin_refresh(&mut self, conversation_id: &str, message_id: &str, manual: bool) -> bool {
233 let key = (conversation_id.to_owned(), message_id.to_owned());
234 if !manual
235 && (self.refreshed.contains(&key)
236 || self.refreshes_in_flight >= MAX_REFRESHES_IN_FLIGHT)
237 {
238 return false;
239 }
240 self.refreshed.insert(key);
241 self.refreshes_in_flight += 1;
242 true
243 }
244
245 pub fn cancel_refresh(&mut self, conversation_id: &str, message_id: &str) {
246 self.refreshed
247 .remove(&(conversation_id.to_owned(), message_id.to_owned()));
248 self.refreshes_in_flight = self.refreshes_in_flight.saturating_sub(1);
249 }
250
251 /// True when the throttle was full, so a deferred refresh may start now.
252 pub fn finish_refresh(&mut self) -> bool {
253 let was_full = self.refreshes_in_flight >= MAX_REFRESHES_IN_FLIGHT;
254 self.refreshes_in_flight = self.refreshes_in_flight.saturating_sub(1);
255 was_full
256 }
257
215 pub fn overrides_for(&self, conversation_id: &str) -> HashMap<String, CardOverride> {
258 pub fn overrides_for(&self, conversation_id: &str) -> HashMap<String, CardOverride> {
216 self.overrides
259 self.overrides
217 .iter()
260 .iter()
@@ -267,6 +310,16 @@ mod tests {
267 assert_eq!(state.open_card("set"), None);
310 assert_eq!(state.open_card("set"), None);
268 }
311 }
269
312
313 #[test]
314 fn slots_default_until_set_and_clear_with_their_card() {
315 let mut state = CardState::default();
316 assert_eq!(state.slot("m-card-0-3", 2), 2);
317 state.set_slot("m-card-0-3", 5);
318 assert_eq!(state.slot("m-card-0-3", 2), 5);
319 state.clear_card("m-card-0");
320 assert_eq!(state.slot("m-card-0-3", 2), 2);
321 }
322
270 #[test]
323 #[test]
271 fn overrides_are_scoped_to_their_conversation() {
324 fn overrides_are_scoped_to_their_conversation() {
272 let mut state = CardState::default();
325 let mut state = CardState::default();
@@ -279,6 +332,37 @@ mod tests {
279 assert!(state.overrides_for("c2").is_empty());
332 assert!(state.overrides_for("c2").is_empty());
280 }
333 }
281
334
335 #[test]
336 fn a_message_refreshes_once_unless_asked_manually() {
337 let mut state = CardState::default();
338 assert!(state.begin_refresh("c", "m", false));
339 assert!(!state.begin_refresh("c", "m", false));
340 assert!(state.begin_refresh("c", "m", true));
341 assert!(state.begin_refresh("c", "other", false));
342 }
343
344 #[test]
345 fn at_most_three_automatic_refreshes_run_at_once() {
346 let mut state = CardState::default();
347 for message_id in ["a", "b", "c"] {
348 assert!(state.begin_refresh("c", message_id, false));
349 }
350 assert!(!state.begin_refresh("c", "d", false));
351 assert!(state.begin_refresh("c", "d", true));
352 assert!(state.finish_refresh());
353 assert!(state.finish_refresh());
354 assert!(!state.finish_refresh());
355 assert!(state.begin_refresh("c", "e", false));
356 }
357
358 #[test]
359 fn a_cancelled_refresh_may_start_again() {
360 let mut state = CardState::default();
361 assert!(state.begin_refresh("c", "m", false));
362 state.cancel_refresh("c", "m");
363 assert!(state.begin_refresh("c", "m", false));
364 }
365
282 #[test]
366 #[test]
283 fn reasons_are_shortened() {
367 fn reasons_are_shortened() {
284 assert_eq!(
368 assert_eq!(
crates/app/src/demo.rs +26 −2
@@ -839,10 +839,26 @@ fn bot_messages() -> Vec<MessageRecord> {
839 839 ]}
840 840 ]
841 841 });
842 vec![
842 let mut messages = vec![
843 843 bot_card_message("b1", at(0, 13, 45), &card),
844 844 bot_card_message("b2", at(0, 13, 52), &input_card()),
845 ]
845 bot_card_message("b3", at(0, 13, 58), &crate::demo_input_cards::all_inputs_card()),
846 ];
847 messages.extend(
848 crate::demo_cards::behaviour_cards()
849 .iter()
850 .zip(0u32..)
851 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
852 );
853 messages.extend(
854 crate::demo_chart_cards::cards()
855 .iter()
856 .zip(0..)
857 .map(|(chart_card, minute)| {
858 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
859 }),
860 );
861 messages
846 862 }
847 863
848 864 fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
@@ -949,6 +965,14 @@ pub async fn card_answer(task: CardTask) -> CardAnswer {
949 965 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
950 966 }
951 967
968 pub async fn refresh_answer() -> CardAnswer {
969 tokio::time::sleep(CARD_ANSWER_DELAY).await;
970 Ok((
971 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
972 Some((bot_app(), BOT_ID.to_owned())),
973 ))
974 }
975
952 976 fn settings_card() -> serde_json::Value {
953 977 serde_json::json!({
954 978 "type": "AdaptiveCard",
@@ -839,10 +839,26 @@ fn bot_messages() -> Vec<MessageRecord> {
839 ]}
839 ]}
840 ]
840 ]
841 });
841 });
842 vec![
842 let mut messages = vec![
843 bot_card_message("b1", at(0, 13, 45), &card),
843 bot_card_message("b1", at(0, 13, 45), &card),
844 bot_card_message("b2", at(0, 13, 52), &input_card()),
844 bot_card_message("b2", at(0, 13, 52), &input_card()),
845 ]
845 bot_card_message("b3", at(0, 13, 58), &crate::demo_input_cards::all_inputs_card()),
846 ];
847 messages.extend(
848 crate::demo_cards::behaviour_cards()
849 .iter()
850 .zip(0u32..)
851 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
852 );
853 messages.extend(
854 crate::demo_chart_cards::cards()
855 .iter()
856 .zip(0..)
857 .map(|(chart_card, minute)| {
858 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
859 }),
860 );
861 messages
846}
862}
847
863
848fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
864fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
@@ -949,6 +965,14 @@ pub async fn card_answer(task: CardTask) -> CardAnswer {
949 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
965 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
950}
966}
951
967
968pub async fn refresh_answer() -> CardAnswer {
969 tokio::time::sleep(CARD_ANSWER_DELAY).await;
970 Ok((
971 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
972 Some((bot_app(), BOT_ID.to_owned())),
973 ))
974}
975
952fn settings_card() -> serde_json::Value {
976fn settings_card() -> serde_json::Value {
953 serde_json::json!({
977 serde_json::json!({
954 "type": "AdaptiveCard",
978 "type": "AdaptiveCard",
crates/app/src/demo_cards.rs added +387 −0
@@ -0,0 +1,387 @@
1 use chrono::Local;
2 use serde_json::{Value, json};
3
4 const CARD_POSTER_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=360";
5 const CARD_ICON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=32";
6 const VIDEO_URL: &str = "https://example.com/videos/release-tour.mp4";
7
8 pub fn behaviour_cards() -> Vec<Value> {
9 vec![
10 refresh_card("Build status: waiting for the automatic refresh..."),
11 actions_card(),
12 text_card(),
13 select_action_card(),
14 media_and_icon_card(),
15 text_layout_card(),
16 text_runs_card(),
17 layout_card(),
18 fallback_card(),
19 target_width_card(),
20 table_card(),
21 code_block_card(),
22 badge_card(),
23 progress_card(),
24 compound_button_card(),
25 carousel_card(),
26 action_overflow_card(),
27 dates_card(),
28 ]
29 }
30
31 pub fn refreshed_card() -> Value {
32 refresh_card(&format!(
33 "Build #482 passed (refreshed at {})",
34 Local::now().format("%H:%M:%S")
35 ))
36 }
37
38 fn refresh_card(status: &str) -> Value {
39 json!({
40 "type": "AdaptiveCard",
41 "refresh": {"action": {"type": "Action.Execute", "verb": "refreshStatus", "data": {"build": 482}}},
42 "body": [
43 {"type": "TextBlock", "weight": "bolder", "text": "Refreshing card"},
44 {"type": "TextBlock", "wrap": true, "text": status},
45 {"type": "TextBlock", "wrap": true, "isSubtle": true, "size": "small", "text": "Updates itself once when it is first shown. Use the message menu to refresh again."}
46 ]
47 })
48 }
49
50 fn actions_card() -> Value {
51 json!({
52 "type": "AdaptiveCard",
53 "body": [
54 {"type": "TextBlock", "weight": "bolder", "text": "Submit variants"}
55 ],
56 "actions": [
57 {"type": "Action.Submit", "title": "Open tab", "iconUrl": "icon:Open", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {
58 "contentUrl": "https://example.com/tabs/content", "websiteUrl": "https://example.com/tabs/site", "name": "Release tab", "entityId": "release"
59 }}}}},
60 {"type": "Action.Submit", "title": "Sign in", "iconUrl": "icon:LockClosed", "data": {"msteams": {"type": "signin", "value": "https://example.com/signin"}}},
61 {"type": "Action.Submit", "title": "Custom invoke", "data": {"msteams": {"type": "invoke", "value": {"type": "demo/custom", "payload": 1}}}},
62 {"type": "Action.Submit", "title": "Add app", "data": {"msteams": {"type": "invoke", "value": {"type": "appInstallToConversation"}}}}
63 ]
64 })
65 }
66
67 fn text_card() -> Value {
68 json!({
69 "type": "AdaptiveCard",
70 "msteams": {"entities": [
71 {"type": "mention", "text": "<at>Mara Lindqvist</at>", "mentioned": {"id": "29:mara", "name": "Mara Lindqvist"}}
72 ]},
73 "body": [
74 {"type": "TextBlock", "weight": "bolder", "text": "Mentions and italics"},
75 {"type": "TextBlock", "wrap": true, "text": "Hi <at>Mara Lindqvist</at>, this is _italic_, this is *also italic*, and **bold**. Names like snake_case_name and https://example.com/a_b_c stay as they are."},
76 {"type": "FactSet", "facts": [{"title": "Reviewer", "value": "<at>Dana Demo</at>"}, {"title": "Note", "value": "_soft_ launch"}]},
77 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "cc "}, {"type": "TextRun", "text": "<at>Priya Nair</at>", "weight": "bolder"}]}
78 ]
79 })
80 }
81
82 fn select_action_card() -> Value {
83 json!({
84 "type": "AdaptiveCard",
85 "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/card"},
86 "body": [
87 {"type": "TextBlock", "weight": "bolder", "text": "Clickable areas"},
88 {"type": "TextBlock", "wrap": true, "isSubtle": true, "size": "small", "text": "The card, the container, the column and the image each open a page or toggle the note."},
89 {"type": "Container", "style": "emphasis", "selectAction": {"type": "Action.ToggleVisibility", "targetElements": ["container-note"]}, "items": [
90 {"type": "TextBlock", "wrap": true, "text": "Container: click to toggle the note"},
91 {"type": "TextBlock", "id": "container-note", "isVisible": false, "isSubtle": true, "text": "Container note"}
92 ]},
93 {"type": "ColumnSet", "columns": [
94 {"type": "Column", "width": "auto", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/image"}, "items": [
95 {"type": "Image", "url": CARD_ICON_URL, "size": "small", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/image"}}
96 ]},
97 {"type": "Column", "width": "stretch", "selectAction": {"type": "Action.Submit", "data": {"action": "watch"}}, "items": [
98 {"type": "TextBlock", "wrap": true, "text": "Column: click to submit"}
99 ]}
100 ]}
101 ]
102 })
103 }
104
105 fn media_and_icon_card() -> Value {
106 json!({
107 "type": "AdaptiveCard",
108 "body": [
109 {"type": "TextBlock", "weight": "bolder", "text": "Media and icons"},
110 {"type": "Media", "poster": CARD_POSTER_URL, "altText": "Release tour video", "sources": [{"mimeType": "video/mp4", "url": VIDEO_URL}]},
111 {"type": "ColumnSet", "columns": [
112 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Calendar", "size": "Large", "color": "accent"}]},
113 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Mail", "size": "Medium"}]},
114 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Warning", "size": "Standard", "color": "warning", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/warning"}}]},
115 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Alert", "size": "Small", "color": "good"}]},
116 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "NoSuchFluentName", "size": "Large"}]}
117 ]}
118 ],
119 "actions": [
120 {"type": "Action.OpenUrl", "title": "Send", "url": "https://example.com/send", "iconUrl": "icon:Send"},
121 {"type": "Action.OpenUrl", "title": "Logo", "url": "https://example.com/logo", "iconUrl": CARD_ICON_URL}
122 ]
123 })
124 }
125
126 fn text_layout_card() -> Value {
127 json!({
128 "type": "AdaptiveCard",
129 "body": [
130 {"type": "TextBlock", "style": "heading", "text": "Text layout"},
131 {"type": "TextBlock", "text": "wrap is false by default, so this long line is cut off with an ellipsis at the card edge instead of overflowing"},
132 {"type": "TextBlock", "wrap": true, "maxLines": 2, "text": "maxLines 2 with wrap: this text is long enough to need more than two lines, so the third line is cut off with an ellipsis. More words follow to fill the space and prove the clamp."},
133 {"type": "TextBlock", "horizontalAlignment": "center", "text": "Centered"},
134 {"type": "TextBlock", "horizontalAlignment": "right", "text": "Right aligned"},
135 {"type": "TextBlock", "fontType": "monospace", "text": "monospace: let answer = 42;"},
136 {"type": "TextBlock", "color": "dark", "text": "Dark colour stays readable"},
137 {"type": "TextBlock", "color": "light", "text": "Light colour stays readable"}
138 ]
139 })
140 }
141
142 fn text_runs_card() -> Value {
143 json!({
144 "type": "AdaptiveCard",
145 "body": [
146 {"type": "TextBlock", "weight": "bolder", "text": "Text runs"},
147 {"type": "RichTextBlock", "inlines": [
148 {"type": "TextRun", "text": "highlighted ", "highlight": true},
149 {"type": "TextRun", "text": "good ", "color": "good", "weight": "bolder"},
150 {"type": "TextRun", "text": "attention ", "color": "attention"},
151 {"type": "TextRun", "text": "subtle ", "isSubtle": true},
152 {"type": "TextRun", "text": "large ", "size": "large"},
153 {"type": "TextRun", "text": "small ", "size": "small"},
154 {"type": "TextRun", "text": "mono", "fontType": "monospace"}
155 ]},
156 {"type": "RichTextBlock", "horizontalAlignment": "center", "inlines": [{"type": "TextRun", "text": "centered rich text"}]}
157 ]
158 })
159 }
160
161 fn layout_card() -> Value {
162 json!({
163 "type": "AdaptiveCard",
164 "minHeight": "260px",
165 "verticalContentAlignment": "center",
166 "backgroundImage": {"url": CARD_POSTER_URL, "fillMode": "cover"},
167 "body": [
168 {"type": "Container", "style": "good", "bleed": true, "items": [
169 {"type": "TextBlock", "weight": "bolder", "text": "Bleed container touches the card edges"}
170 ]},
171 {"type": "TextBlock", "weight": "bolder", "text": "Card with background image, minHeight and centered content"},
172 {"type": "Container", "style": "emphasis", "minHeight": "70px", "verticalContentAlignment": "center", "items": [
173 {"type": "TextBlock", "text": "minHeight 70 with centered text"}
174 ]},
175 {"type": "Container", "style": "accent", "rtl": true, "items": [
176 {"type": "TextBlock", "text": "rtl container aligns text right"}
177 ]},
178 {"type": "Container", "style": "warning", "minHeight": "90px", "items": [
179 {"type": "TextBlock", "text": "Top"},
180 {"type": "Container", "height": "stretch", "style": "emphasis", "items": [{"type": "TextBlock", "text": "height: stretch fills the free space"}]},
181 {"type": "TextBlock", "weight": "bolder", "text": "Bottom"}
182 ]},
183 {"type": "ColumnSet", "rtl": true, "style": "emphasis", "columns": [
184 {"type": "Column", "width": "stretch", "style": "attention", "items": [{"type": "TextBlock", "text": "First column"}]},
185 {"type": "Column", "width": "stretch", "style": "good", "items": [{"type": "TextBlock", "text": "Second column"}]}
186 ]},
187 {"type": "Image", "url": CARD_ICON_URL, "altText": "Hover for alt text", "size": "small", "horizontalAlignment": "center", "backgroundColor": "#FFB0B0B0"}
188 ]
189 })
190 }
191
192 fn fallback_card() -> Value {
193 json!({
194 "type": "AdaptiveCard",
195 "fallbackText": "This card needs a newer client",
196 "body": [
197 {"type": "TextBlock", "weight": "bolder", "text": "Fallback"},
198 {"type": "Hologram", "fallback": {"type": "TextBlock", "wrap": true, "text": "Unknown element replaced by its fallback"}},
199 {"type": "Hologram", "fallback": "drop"},
200 {"type": "Hologram"},
201 {"type": "TextBlock", "text": "never shown", "requires": {"adaptiveCards": "1.9"}, "fallback": {"type": "TextBlock", "wrap": true, "text": "Needs 1.9, fell back to this"}},
202 {"type": "TextBlock", "wrap": true, "text": "Requires 1.x is met", "requires": {"adaptiveCards": "1.x"}},
203 {"type": "TextBlock", "wrap": true, "text": "Hidden: unknown feature", "requires": {"fancyFeature": "1.0"}, "fallback": "drop"}
204 ]
205 })
206 }
207
208 fn target_width_card() -> Value {
209 json!({
210 "type": "AdaptiveCard",
211 "body": [
212 {"type": "TextBlock", "weight": "bolder", "text": "Target width (this card is standard)"},
213 {"type": "TextBlock", "targetWidth": "standard", "text": "Visible: standard"},
214 {"type": "TextBlock", "targetWidth": "atLeast:standard", "text": "Visible: atLeast:standard"},
215 {"type": "TextBlock", "targetWidth": "atMost:standard", "text": "Visible: atMost:standard"},
216 {"type": "TextBlock", "targetWidth": "wide", "text": "Hidden: wide"},
217 {"type": "TextBlock", "targetWidth": "veryNarrow", "text": "Hidden: veryNarrow"},
218 {"type": "TextBlock", "targetWidth": "atMost:narrow", "text": "Hidden: atMost:narrow"}
219 ]
220 })
221 }
222
223 fn table_card() -> Value {
224 json!({
225 "type": "AdaptiveCard",
226 "body": [
227 {"type": "TextBlock", "weight": "bolder", "text": "Table"},
228 {"type": "Table", "gridStyle": "accent", "horizontalCellContentAlignment": "center", "verticalCellContentAlignment": "center",
229 "columns": [{"width": 2, "horizontalCellContentAlignment": "left"}, {"width": 1}, {"width": "70px", "horizontalCellContentAlignment": "right"}],
230 "rows": [
231 {"type": "TableRow", "cells": [
232 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Service"}]},
233 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "State"}]},
234 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Ms"}]}
235 ]},
236 {"type": "TableRow", "cells": [
237 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "API gateway"}]},
238 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "color": "good", "text": "Healthy"}]},
239 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "42"}]}
240 ]},
241 {"type": "TableRow", "style": "attention", "cells": [
242 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Search"}]},
243 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "color": "attention", "text": "Degraded"}]},
244 {"type": "TableCell", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/search"}, "items": [{"type": "TextBlock", "wrap": true, "text": "1830"}]}
245 ]}
246 ]},
247 {"type": "Table", "firstRowAsHeader": false, "showGridLines": false, "rows": [
248 {"type": "TableRow", "cells": [
249 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "No header"}]},
250 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "No grid lines"}]}
251 ]}
252 ]}
253 ]
254 })
255 }
256
257 fn code_block_card() -> Value {
258 let snippet: String = (1..=14)
259 .map(|line| format!(" let value_{line} = compute({line});\n"))
260 .collect();
261 json!({
262 "type": "AdaptiveCard",
263 "body": [
264 {"type": "TextBlock", "weight": "bolder", "text": "Code blocks"},
265 {"type": "CodeBlock", "language": "Rust", "startLineNumber": 8, "codeSnippet": format!("fn main() {{\n{snippet}}}")},
266 {"type": "CodeBlock", "language": "Json", "codeSnippet": "{\"short\": true}"}
267 ]
268 })
269 }
270
271 fn badge_card() -> Value {
272 let styles = [
273 "default",
274 "accent",
275 "good",
276 "attention",
277 "warning",
278 "subtle",
279 "informative",
280 ];
281 let filled: Vec<Value> = styles
282 .iter()
283 .map(|style| json!({"type": "Badge", "text": style, "style": style, "icon": "Checkmark"}))
284 .collect();
285 let tinted: Vec<Value> = styles
286 .iter()
287 .map(|style| json!({"type": "Badge", "text": style, "style": style, "appearance": "tint"}))
288 .collect();
289 json!({
290 "type": "AdaptiveCard",
291 "body": [
292 {"type": "TextBlock", "weight": "bolder", "text": "Badges"},
293 {"type": "Container", "items": filled},
294 {"type": "Container", "spacing": "small", "items": tinted},
295 {"type": "ColumnSet", "spacing": "small", "columns": [
296 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Square", "shape": "square", "style": "accent"}]},
297 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Rounded", "shape": "rounded", "style": "accent"}]},
298 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Large", "size": "large", "style": "good", "icon": "Star", "iconPosition": "After", "tooltip": "Large badge with trailing icon"}]},
299 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "XL", "size": "extraLarge", "style": "warning"}]}
300 ]}
301 ]
302 })
303 }
304
305 fn progress_card() -> Value {
306 json!({
307 "type": "AdaptiveCard",
308 "body": [
309 {"type": "TextBlock", "weight": "bolder", "text": "Progress"},
310 {"type": "ProgressBar", "value": 65},
311 {"type": "ProgressBar", "value": 30, "color": "good", "spacing": "small"},
312 {"type": "ProgressBar", "color": "attention", "spacing": "small"},
313 {"type": "ProgressRing", "label": "Loading data...", "spacing": "medium"},
314 {"type": "ProgressRing", "label": "Above", "labelPosition": "above", "size": "large", "spacing": "medium"},
315 {"type": "ProgressRing", "size": "tiny", "spacing": "medium"}
316 ]
317 })
318 }
319
320 fn compound_button_card() -> Value {
321 json!({
322 "type": "AdaptiveCard",
323 "body": [
324 {"type": "TextBlock", "weight": "bolder", "text": "Compound buttons"},
325 {"type": "CompoundButton", "icon": "Calendar", "title": "Schedule a meeting", "description": "Find a time that works for everyone", "badge": "New", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/schedule"}},
326 {"type": "CompoundButton", "icon": "Document", "title": "Open the release notes", "description": "Opens in your browser", "spacing": "small", "selectAction": {"type": "Action.Submit", "data": {"action": "notes"}}}
327 ]
328 })
329 }
330
331 fn carousel_card() -> Value {
332 json!({
333 "type": "AdaptiveCard",
334 "body": [
335 {"type": "TextBlock", "weight": "bolder", "text": "Carousel"},
336 {"type": "Carousel", "timer": 4000, "pages": [
337 {"type": "CarouselPage", "style": "emphasis", "minHeight": "80px", "verticalContentAlignment": "center", "items": [
338 {"type": "TextBlock", "weight": "bolder", "text": "Page one"},
339 {"type": "TextBlock", "wrap": true, "text": "Use the arrows or the dots."}
340 ]},
341 {"type": "CarouselPage", "style": "good", "minHeight": "80px", "items": [
342 {"type": "TextBlock", "weight": "bolder", "text": "Page two"},
343 {"type": "Image", "url": CARD_ICON_URL, "size": "small"}
344 ]},
345 {"type": "CarouselPage", "style": "accent", "minHeight": "80px", "items": [
346 {"type": "TextBlock", "weight": "bolder", "text": "Page three"}
347 ]}
348 ]}
349 ]
350 })
351 }
352
353 fn action_overflow_card() -> Value {
354 let url = "https://example.com/action";
355 json!({
356 "type": "AdaptiveCard",
357 "body": [
358 {"type": "TextBlock", "weight": "bolder", "text": "Action modes, tooltips and overflow"},
359 {"type": "ActionSet", "actions": [
360 {"type": "Action.OpenUrl", "title": "Primary", "url": url, "tooltip": "Tooltip on hover"},
361 {"type": "Action.OpenUrl", "title": "Positive", "url": url, "style": "positive"},
362 {"type": "Action.OpenUrl", "title": "Destructive", "url": url, "style": "destructive"},
363 {"type": "Action.OpenUrl", "title": "Disabled", "url": url, "isEnabled": false, "tooltip": "Not available right now"},
364 {"type": "Action.OpenUrl", "title": "Secondary A", "url": url, "mode": "secondary"},
365 {"type": "Action.OpenUrl", "title": "Secondary B", "url": url, "mode": "secondary"}
366 ]}
367 ],
368 "actions": (1..=8)
369 .map(|number| json!({"type": "Action.OpenUrl", "title": format!("Action {number}"), "url": url}))
370 .collect::<Vec<_>>()
371 })
372 }
373
374 fn dates_card() -> Value {
375 json!({
376 "type": "AdaptiveCard",
377 "body": [
378 {"type": "TextBlock", "weight": "bolder", "text": "Dates and times"},
379 {"type": "TextBlock", "wrap": true, "text": "Short {{DATE(2026-10-09T14:05:00Z, SHORT)}}"},
380 {"type": "TextBlock", "wrap": true, "text": "Long {{DATE(2026-10-09T14:05:00Z, LONG)}}"},
381 {"type": "TextBlock", "wrap": true, "text": "Compact {{DATE(2026-10-09T14:05:00Z, COMPACT)}} at {{TIME(2026-10-09T14:05:00Z)}}"},
382 {"type": "TextBlock", "wrap": true, "text": "Malformed stays literal: {{DATE(tomorrow, SHORT)}}"},
383 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "Run: {{TIME(2026-10-09T09:30:00+02:00)}}"}]},
384 {"type": "FactSet", "facts": [{"title": "Due", "value": "{{DATE(2026-10-12T08:00:00Z, SHORT)}}"}]}
385 ]
386 })
387 }
@@ -0,0 +1,387 @@
1use chrono::Local;
2use serde_json::{Value, json};
3
4const CARD_POSTER_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=360";
5const CARD_ICON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=32";
6const VIDEO_URL: &str = "https://example.com/videos/release-tour.mp4";
7
8pub fn behaviour_cards() -> Vec<Value> {
9 vec![
10 refresh_card("Build status: waiting for the automatic refresh..."),
11 actions_card(),
12 text_card(),
13 select_action_card(),
14 media_and_icon_card(),
15 text_layout_card(),
16 text_runs_card(),
17 layout_card(),
18 fallback_card(),
19 target_width_card(),
20 table_card(),
21 code_block_card(),
22 badge_card(),
23 progress_card(),
24 compound_button_card(),
25 carousel_card(),
26 action_overflow_card(),
27 dates_card(),
28 ]
29}
30
31pub fn refreshed_card() -> Value {
32 refresh_card(&format!(
33 "Build #482 passed (refreshed at {})",
34 Local::now().format("%H:%M:%S")
35 ))
36}
37
38fn refresh_card(status: &str) -> Value {
39 json!({
40 "type": "AdaptiveCard",
41 "refresh": {"action": {"type": "Action.Execute", "verb": "refreshStatus", "data": {"build": 482}}},
42 "body": [
43 {"type": "TextBlock", "weight": "bolder", "text": "Refreshing card"},
44 {"type": "TextBlock", "wrap": true, "text": status},
45 {"type": "TextBlock", "wrap": true, "isSubtle": true, "size": "small", "text": "Updates itself once when it is first shown. Use the message menu to refresh again."}
46 ]
47 })
48}
49
50fn actions_card() -> Value {
51 json!({
52 "type": "AdaptiveCard",
53 "body": [
54 {"type": "TextBlock", "weight": "bolder", "text": "Submit variants"}
55 ],
56 "actions": [
57 {"type": "Action.Submit", "title": "Open tab", "iconUrl": "icon:Open", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {
58 "contentUrl": "https://example.com/tabs/content", "websiteUrl": "https://example.com/tabs/site", "name": "Release tab", "entityId": "release"
59 }}}}},
60 {"type": "Action.Submit", "title": "Sign in", "iconUrl": "icon:LockClosed", "data": {"msteams": {"type": "signin", "value": "https://example.com/signin"}}},
61 {"type": "Action.Submit", "title": "Custom invoke", "data": {"msteams": {"type": "invoke", "value": {"type": "demo/custom", "payload": 1}}}},
62 {"type": "Action.Submit", "title": "Add app", "data": {"msteams": {"type": "invoke", "value": {"type": "appInstallToConversation"}}}}
63 ]
64 })
65}
66
67fn text_card() -> Value {
68 json!({
69 "type": "AdaptiveCard",
70 "msteams": {"entities": [
71 {"type": "mention", "text": "<at>Mara Lindqvist</at>", "mentioned": {"id": "29:mara", "name": "Mara Lindqvist"}}
72 ]},
73 "body": [
74 {"type": "TextBlock", "weight": "bolder", "text": "Mentions and italics"},
75 {"type": "TextBlock", "wrap": true, "text": "Hi <at>Mara Lindqvist</at>, this is _italic_, this is *also italic*, and **bold**. Names like snake_case_name and https://example.com/a_b_c stay as they are."},
76 {"type": "FactSet", "facts": [{"title": "Reviewer", "value": "<at>Dana Demo</at>"}, {"title": "Note", "value": "_soft_ launch"}]},
77 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "cc "}, {"type": "TextRun", "text": "<at>Priya Nair</at>", "weight": "bolder"}]}
78 ]
79 })
80}
81
82fn select_action_card() -> Value {
83 json!({
84 "type": "AdaptiveCard",
85 "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/card"},
86 "body": [
87 {"type": "TextBlock", "weight": "bolder", "text": "Clickable areas"},
88 {"type": "TextBlock", "wrap": true, "isSubtle": true, "size": "small", "text": "The card, the container, the column and the image each open a page or toggle the note."},
89 {"type": "Container", "style": "emphasis", "selectAction": {"type": "Action.ToggleVisibility", "targetElements": ["container-note"]}, "items": [
90 {"type": "TextBlock", "wrap": true, "text": "Container: click to toggle the note"},
91 {"type": "TextBlock", "id": "container-note", "isVisible": false, "isSubtle": true, "text": "Container note"}
92 ]},
93 {"type": "ColumnSet", "columns": [
94 {"type": "Column", "width": "auto", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/image"}, "items": [
95 {"type": "Image", "url": CARD_ICON_URL, "size": "small", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/image"}}
96 ]},
97 {"type": "Column", "width": "stretch", "selectAction": {"type": "Action.Submit", "data": {"action": "watch"}}, "items": [
98 {"type": "TextBlock", "wrap": true, "text": "Column: click to submit"}
99 ]}
100 ]}
101 ]
102 })
103}
104
105fn media_and_icon_card() -> Value {
106 json!({
107 "type": "AdaptiveCard",
108 "body": [
109 {"type": "TextBlock", "weight": "bolder", "text": "Media and icons"},
110 {"type": "Media", "poster": CARD_POSTER_URL, "altText": "Release tour video", "sources": [{"mimeType": "video/mp4", "url": VIDEO_URL}]},
111 {"type": "ColumnSet", "columns": [
112 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Calendar", "size": "Large", "color": "accent"}]},
113 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Mail", "size": "Medium"}]},
114 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Warning", "size": "Standard", "color": "warning", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/warning"}}]},
115 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "Alert", "size": "Small", "color": "good"}]},
116 {"type": "Column", "width": "auto", "items": [{"type": "Icon", "name": "NoSuchFluentName", "size": "Large"}]}
117 ]}
118 ],
119 "actions": [
120 {"type": "Action.OpenUrl", "title": "Send", "url": "https://example.com/send", "iconUrl": "icon:Send"},
121 {"type": "Action.OpenUrl", "title": "Logo", "url": "https://example.com/logo", "iconUrl": CARD_ICON_URL}
122 ]
123 })
124}
125
126fn text_layout_card() -> Value {
127 json!({
128 "type": "AdaptiveCard",
129 "body": [
130 {"type": "TextBlock", "style": "heading", "text": "Text layout"},
131 {"type": "TextBlock", "text": "wrap is false by default, so this long line is cut off with an ellipsis at the card edge instead of overflowing"},
132 {"type": "TextBlock", "wrap": true, "maxLines": 2, "text": "maxLines 2 with wrap: this text is long enough to need more than two lines, so the third line is cut off with an ellipsis. More words follow to fill the space and prove the clamp."},
133 {"type": "TextBlock", "horizontalAlignment": "center", "text": "Centered"},
134 {"type": "TextBlock", "horizontalAlignment": "right", "text": "Right aligned"},
135 {"type": "TextBlock", "fontType": "monospace", "text": "monospace: let answer = 42;"},
136 {"type": "TextBlock", "color": "dark", "text": "Dark colour stays readable"},
137 {"type": "TextBlock", "color": "light", "text": "Light colour stays readable"}
138 ]
139 })
140}
141
142fn text_runs_card() -> Value {
143 json!({
144 "type": "AdaptiveCard",
145 "body": [
146 {"type": "TextBlock", "weight": "bolder", "text": "Text runs"},
147 {"type": "RichTextBlock", "inlines": [
148 {"type": "TextRun", "text": "highlighted ", "highlight": true},
149 {"type": "TextRun", "text": "good ", "color": "good", "weight": "bolder"},
150 {"type": "TextRun", "text": "attention ", "color": "attention"},
151 {"type": "TextRun", "text": "subtle ", "isSubtle": true},
152 {"type": "TextRun", "text": "large ", "size": "large"},
153 {"type": "TextRun", "text": "small ", "size": "small"},
154 {"type": "TextRun", "text": "mono", "fontType": "monospace"}
155 ]},
156 {"type": "RichTextBlock", "horizontalAlignment": "center", "inlines": [{"type": "TextRun", "text": "centered rich text"}]}
157 ]
158 })
159}
160
161fn layout_card() -> Value {
162 json!({
163 "type": "AdaptiveCard",
164 "minHeight": "260px",
165 "verticalContentAlignment": "center",
166 "backgroundImage": {"url": CARD_POSTER_URL, "fillMode": "cover"},
167 "body": [
168 {"type": "Container", "style": "good", "bleed": true, "items": [
169 {"type": "TextBlock", "weight": "bolder", "text": "Bleed container touches the card edges"}
170 ]},
171 {"type": "TextBlock", "weight": "bolder", "text": "Card with background image, minHeight and centered content"},
172 {"type": "Container", "style": "emphasis", "minHeight": "70px", "verticalContentAlignment": "center", "items": [
173 {"type": "TextBlock", "text": "minHeight 70 with centered text"}
174 ]},
175 {"type": "Container", "style": "accent", "rtl": true, "items": [
176 {"type": "TextBlock", "text": "rtl container aligns text right"}
177 ]},
178 {"type": "Container", "style": "warning", "minHeight": "90px", "items": [
179 {"type": "TextBlock", "text": "Top"},
180 {"type": "Container", "height": "stretch", "style": "emphasis", "items": [{"type": "TextBlock", "text": "height: stretch fills the free space"}]},
181 {"type": "TextBlock", "weight": "bolder", "text": "Bottom"}
182 ]},
183 {"type": "ColumnSet", "rtl": true, "style": "emphasis", "columns": [
184 {"type": "Column", "width": "stretch", "style": "attention", "items": [{"type": "TextBlock", "text": "First column"}]},
185 {"type": "Column", "width": "stretch", "style": "good", "items": [{"type": "TextBlock", "text": "Second column"}]}
186 ]},
187 {"type": "Image", "url": CARD_ICON_URL, "altText": "Hover for alt text", "size": "small", "horizontalAlignment": "center", "backgroundColor": "#FFB0B0B0"}
188 ]
189 })
190}
191
192fn fallback_card() -> Value {
193 json!({
194 "type": "AdaptiveCard",
195 "fallbackText": "This card needs a newer client",
196 "body": [
197 {"type": "TextBlock", "weight": "bolder", "text": "Fallback"},
198 {"type": "Hologram", "fallback": {"type": "TextBlock", "wrap": true, "text": "Unknown element replaced by its fallback"}},
199 {"type": "Hologram", "fallback": "drop"},
200 {"type": "Hologram"},
201 {"type": "TextBlock", "text": "never shown", "requires": {"adaptiveCards": "1.9"}, "fallback": {"type": "TextBlock", "wrap": true, "text": "Needs 1.9, fell back to this"}},
202 {"type": "TextBlock", "wrap": true, "text": "Requires 1.x is met", "requires": {"adaptiveCards": "1.x"}},
203 {"type": "TextBlock", "wrap": true, "text": "Hidden: unknown feature", "requires": {"fancyFeature": "1.0"}, "fallback": "drop"}
204 ]
205 })
206}
207
208fn target_width_card() -> Value {
209 json!({
210 "type": "AdaptiveCard",
211 "body": [
212 {"type": "TextBlock", "weight": "bolder", "text": "Target width (this card is standard)"},
213 {"type": "TextBlock", "targetWidth": "standard", "text": "Visible: standard"},
214 {"type": "TextBlock", "targetWidth": "atLeast:standard", "text": "Visible: atLeast:standard"},
215 {"type": "TextBlock", "targetWidth": "atMost:standard", "text": "Visible: atMost:standard"},
216 {"type": "TextBlock", "targetWidth": "wide", "text": "Hidden: wide"},
217 {"type": "TextBlock", "targetWidth": "veryNarrow", "text": "Hidden: veryNarrow"},
218 {"type": "TextBlock", "targetWidth": "atMost:narrow", "text": "Hidden: atMost:narrow"}
219 ]
220 })
221}
222
223fn table_card() -> Value {
224 json!({
225 "type": "AdaptiveCard",
226 "body": [
227 {"type": "TextBlock", "weight": "bolder", "text": "Table"},
228 {"type": "Table", "gridStyle": "accent", "horizontalCellContentAlignment": "center", "verticalCellContentAlignment": "center",
229 "columns": [{"width": 2, "horizontalCellContentAlignment": "left"}, {"width": 1}, {"width": "70px", "horizontalCellContentAlignment": "right"}],
230 "rows": [
231 {"type": "TableRow", "cells": [
232 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Service"}]},
233 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "State"}]},
234 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Ms"}]}
235 ]},
236 {"type": "TableRow", "cells": [
237 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "API gateway"}]},
238 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "color": "good", "text": "Healthy"}]},
239 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "42"}]}
240 ]},
241 {"type": "TableRow", "style": "attention", "cells": [
242 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "Search"}]},
243 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "color": "attention", "text": "Degraded"}]},
244 {"type": "TableCell", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/search"}, "items": [{"type": "TextBlock", "wrap": true, "text": "1830"}]}
245 ]}
246 ]},
247 {"type": "Table", "firstRowAsHeader": false, "showGridLines": false, "rows": [
248 {"type": "TableRow", "cells": [
249 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "No header"}]},
250 {"type": "TableCell", "items": [{"type": "TextBlock", "wrap": true, "text": "No grid lines"}]}
251 ]}
252 ]}
253 ]
254 })
255}
256
257fn code_block_card() -> Value {
258 let snippet: String = (1..=14)
259 .map(|line| format!(" let value_{line} = compute({line});\n"))
260 .collect();
261 json!({
262 "type": "AdaptiveCard",
263 "body": [
264 {"type": "TextBlock", "weight": "bolder", "text": "Code blocks"},
265 {"type": "CodeBlock", "language": "Rust", "startLineNumber": 8, "codeSnippet": format!("fn main() {{\n{snippet}}}")},
266 {"type": "CodeBlock", "language": "Json", "codeSnippet": "{\"short\": true}"}
267 ]
268 })
269}
270
271fn badge_card() -> Value {
272 let styles = [
273 "default",
274 "accent",
275 "good",
276 "attention",
277 "warning",
278 "subtle",
279 "informative",
280 ];
281 let filled: Vec<Value> = styles
282 .iter()
283 .map(|style| json!({"type": "Badge", "text": style, "style": style, "icon": "Checkmark"}))
284 .collect();
285 let tinted: Vec<Value> = styles
286 .iter()
287 .map(|style| json!({"type": "Badge", "text": style, "style": style, "appearance": "tint"}))
288 .collect();
289 json!({
290 "type": "AdaptiveCard",
291 "body": [
292 {"type": "TextBlock", "weight": "bolder", "text": "Badges"},
293 {"type": "Container", "items": filled},
294 {"type": "Container", "spacing": "small", "items": tinted},
295 {"type": "ColumnSet", "spacing": "small", "columns": [
296 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Square", "shape": "square", "style": "accent"}]},
297 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Rounded", "shape": "rounded", "style": "accent"}]},
298 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "Large", "size": "large", "style": "good", "icon": "Star", "iconPosition": "After", "tooltip": "Large badge with trailing icon"}]},
299 {"type": "Column", "width": "auto", "items": [{"type": "Badge", "text": "XL", "size": "extraLarge", "style": "warning"}]}
300 ]}
301 ]
302 })
303}
304
305fn progress_card() -> Value {
306 json!({
307 "type": "AdaptiveCard",
308 "body": [
309 {"type": "TextBlock", "weight": "bolder", "text": "Progress"},
310 {"type": "ProgressBar", "value": 65},
311 {"type": "ProgressBar", "value": 30, "color": "good", "spacing": "small"},
312 {"type": "ProgressBar", "color": "attention", "spacing": "small"},
313 {"type": "ProgressRing", "label": "Loading data...", "spacing": "medium"},
314 {"type": "ProgressRing", "label": "Above", "labelPosition": "above", "size": "large", "spacing": "medium"},
315 {"type": "ProgressRing", "size": "tiny", "spacing": "medium"}
316 ]
317 })
318}
319
320fn compound_button_card() -> Value {
321 json!({
322 "type": "AdaptiveCard",
323 "body": [
324 {"type": "TextBlock", "weight": "bolder", "text": "Compound buttons"},
325 {"type": "CompoundButton", "icon": "Calendar", "title": "Schedule a meeting", "description": "Find a time that works for everyone", "badge": "New", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/schedule"}},
326 {"type": "CompoundButton", "icon": "Document", "title": "Open the release notes", "description": "Opens in your browser", "spacing": "small", "selectAction": {"type": "Action.Submit", "data": {"action": "notes"}}}
327 ]
328 })
329}
330
331fn carousel_card() -> Value {
332 json!({
333 "type": "AdaptiveCard",
334 "body": [
335 {"type": "TextBlock", "weight": "bolder", "text": "Carousel"},
336 {"type": "Carousel", "timer": 4000, "pages": [
337 {"type": "CarouselPage", "style": "emphasis", "minHeight": "80px", "verticalContentAlignment": "center", "items": [
338 {"type": "TextBlock", "weight": "bolder", "text": "Page one"},
339 {"type": "TextBlock", "wrap": true, "text": "Use the arrows or the dots."}
340 ]},
341 {"type": "CarouselPage", "style": "good", "minHeight": "80px", "items": [
342 {"type": "TextBlock", "weight": "bolder", "text": "Page two"},
343 {"type": "Image", "url": CARD_ICON_URL, "size": "small"}
344 ]},
345 {"type": "CarouselPage", "style": "accent", "minHeight": "80px", "items": [
346 {"type": "TextBlock", "weight": "bolder", "text": "Page three"}
347 ]}
348 ]}
349 ]
350 })
351}
352
353fn action_overflow_card() -> Value {
354 let url = "https://example.com/action";
355 json!({
356 "type": "AdaptiveCard",
357 "body": [
358 {"type": "TextBlock", "weight": "bolder", "text": "Action modes, tooltips and overflow"},
359 {"type": "ActionSet", "actions": [
360 {"type": "Action.OpenUrl", "title": "Primary", "url": url, "tooltip": "Tooltip on hover"},
361 {"type": "Action.OpenUrl", "title": "Positive", "url": url, "style": "positive"},
362 {"type": "Action.OpenUrl", "title": "Destructive", "url": url, "style": "destructive"},
363 {"type": "Action.OpenUrl", "title": "Disabled", "url": url, "isEnabled": false, "tooltip": "Not available right now"},
364 {"type": "Action.OpenUrl", "title": "Secondary A", "url": url, "mode": "secondary"},
365 {"type": "Action.OpenUrl", "title": "Secondary B", "url": url, "mode": "secondary"}
366 ]}
367 ],
368 "actions": (1..=8)
369 .map(|number| json!({"type": "Action.OpenUrl", "title": format!("Action {number}"), "url": url}))
370 .collect::<Vec<_>>()
371 })
372}
373
374fn dates_card() -> Value {
375 json!({
376 "type": "AdaptiveCard",
377 "body": [
378 {"type": "TextBlock", "weight": "bolder", "text": "Dates and times"},
379 {"type": "TextBlock", "wrap": true, "text": "Short {{DATE(2026-10-09T14:05:00Z, SHORT)}}"},
380 {"type": "TextBlock", "wrap": true, "text": "Long {{DATE(2026-10-09T14:05:00Z, LONG)}}"},
381 {"type": "TextBlock", "wrap": true, "text": "Compact {{DATE(2026-10-09T14:05:00Z, COMPACT)}} at {{TIME(2026-10-09T14:05:00Z)}}"},
382 {"type": "TextBlock", "wrap": true, "text": "Malformed stays literal: {{DATE(tomorrow, SHORT)}}"},
383 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "Run: {{TIME(2026-10-09T09:30:00+02:00)}}"}]},
384 {"type": "FactSet", "facts": [{"title": "Due", "value": "{{DATE(2026-10-12T08:00:00Z, SHORT)}}"}]}
385 ]
386 })
387}
crates/app/src/demo_chart_cards.rs added +141 −0
@@ -0,0 +1,141 @@
1 use serde_json::{Value, json};
2
3 const FRUIT: [(&str, u32); 8] = [
4 ("Pear", 59),
5 ("Banana", 292),
6 ("Apple", 143),
7 ("Peach", 98),
8 ("Kiwi", 179),
9 ("Grapefruit", 50),
10 ("Orange", 212),
11 ("Cantaloupe", 68),
12 ];
13
14 const PRODUCTS: [(&str, [u32; 8]); 4] = [
15 ("Outlook", [24, 27, 18, 30, 20, 35, 40, 45]),
16 ("Teams", [9, 100, 22, 40, 30, 45, 50, 55]),
17 ("Office", [10, 20, 30, 40, 50, 60, 70, 80]),
18 ("Windows", [10, 20, 30, 40, 50, 60, 70, 80]),
19 ];
20
21 const TREND: [(&str, [u32; 6]); 5] = [
22 ("Outlook", [99, 6, 63, 64, 63, 78]),
23 ("Teams", [12, 82, 12, 33, 1, 80]),
24 ("Office", [66, 93, 65, 13, 90, 48]),
25 ("Windows", [9, 19, 0, 61, 21, 72]),
26 ("Exchange", [35, 11, 91, 97, 97, 45]),
27 ];
28
29 pub fn cards() -> Vec<Value> {
30 vec![
31 card(vec![slice_chart("Chart.Donut", "Fruit sales")]),
32 card(vec![slice_chart("Chart.Pie", "Fruit sales")]),
33 card(vec![
34 text("Basic"),
35 json!({"type": "Chart.Gauge", "value": 50, "subLabel": "Risk score", "segments": [
36 {"legend": "Low risk", "size": 33, "color": "good"},
37 {"legend": "Medium risk", "size": 34, "color": "warning"},
38 {"legend": "High risk", "size": 33, "color": "attention"}
39 ]}),
40 text("Single value"),
41 json!({"type": "Chart.Gauge", "value": 35, "valueFormat": "fraction", "segments": [
42 {"legend": "Used", "size": 35},
43 {"legend": "Unused", "size": 65, "color": "neutral"}
44 ]}),
45 ]),
46 card(vec![json!({
47 "type": "Chart.Line", "title": "Daily usage", "xAxisTitle": "Days", "yAxisTitle": "Sales",
48 "colorSet": "categorical", "data": series_data(&TREND)
49 })]),
50 card(vec![json!({
51 "type": "Chart.VerticalBar", "title": "Fruit sales", "xAxisTitle": "Fruit", "yAxisTitle": "Crates",
52 "showBarValues": true, "colorSet": "categorical", "data": xy_data(&FRUIT)
53 })]),
54 card(vec![
55 json!({
56 "type": "Chart.VerticalBar.Grouped", "title": "Grouped", "xAxisTitle": "Days", "yAxisTitle": "Sales",
57 "colorSet": "diverging", "data": series_data(&PRODUCTS)
58 }),
59 json!({
60 "type": "Chart.VerticalBar.Grouped", "title": "Stacked", "stacked": true, "xAxisTitle": "Days",
61 "yAxisTitle": "Sales", "data": series_data(&PRODUCTS)
62 }),
63 ]),
64 card(vec![
65 text("AbsoluteWithAxis"),
66 json!({
67 "type": "Chart.HorizontalBar", "title": "Fruit sales", "xAxisTitle": "Fruit", "yAxisTitle": "Crates",
68 "colorSet": "diverging", "data": xy_data(&FRUIT[..6])
69 }),
70 text("AbsoluteNoAxis"),
71 json!({
72 "type": "Chart.HorizontalBar", "title": "Fruit sales", "displayMode": "AbsoluteNoAxis",
73 "data": xy_data(&FRUIT[..6])
74 }),
75 text("PartToWhole"),
76 json!({"type": "Chart.HorizontalBar", "title": "Learning goal", "displayMode": "PartToWhole",
77 "color": "categoricalPurple", "data": [
78 {"x": "Yes, I have defined my day of learning goal", "y": 15},
79 {"x": "No, I haven't yet had time to do it", "y": 24},
80 {"x": "I am not interested in learning", "y": 2}
81 ]}),
82 ]),
83 card(vec![json!({
84 "type": "Chart.HorizontalBar.Stacked", "title": "Sample", "showBarValues": true, "data": [
85 stacked_row("Outlook", [24, 27, 18]),
86 stacked_row("Teams", [9, 100, 22]),
87 stacked_row("Office", [40, 12, 60])
88 ]
89 })]),
90 ]
91 }
92
93 fn card(body: Vec<Value>) -> Value {
94 json!({"type": "AdaptiveCard", "version": "1.5", "body": body})
95 }
96
97 fn text(label: &str) -> Value {
98 json!({"type": "TextBlock", "text": label, "size": "medium", "weight": "bolder", "separator": true, "spacing": "large"})
99 }
100
101 fn slice_chart(chart_type: &str, title: &str) -> Value {
102 let data: Vec<Value> = FRUIT
103 .iter()
104 .map(|(legend, value)| json!({"legend": legend, "value": value}))
105 .collect();
106 json!({"type": chart_type, "title": title, "colorSet": "categorical", "data": data})
107 }
108
109 fn xy_data(points: &[(&str, u32)]) -> Vec<Value> {
110 points
111 .iter()
112 .map(|(label, value)| json!({"x": label, "y": value}))
113 .collect()
114 }
115
116 fn series_data<const COUNT: usize>(series: &[(&str, [u32; COUNT])]) -> Vec<Value> {
117 series
118 .iter()
119 .map(|(legend, values)| {
120 let points: Vec<Value> = values
121 .iter()
122 .enumerate()
123 .map(|(index, value)| json!({"x": format!("2023-05-{:02}", index + 1), "y": value}))
124 .collect();
125 json!({"legend": legend, "values": points})
126 })
127 .collect()
128 }
129
130 fn stacked_row(title: &str, values: [u32; 3]) -> Value {
131 let colors = ["good", "warning", "attention"];
132 let points: Vec<Value> = values
133 .iter()
134 .zip(colors)
135 .enumerate()
136 .map(|(index, (value, color))| {
137 json!({"legend": format!("2023-05-{:02}", index + 1), "value": value, "color": color})
138 })
139 .collect();
140 json!({"title": title, "data": points})
141 }
@@ -0,0 +1,141 @@
1use serde_json::{Value, json};
2
3const FRUIT: [(&str, u32); 8] = [
4 ("Pear", 59),
5 ("Banana", 292),
6 ("Apple", 143),
7 ("Peach", 98),
8 ("Kiwi", 179),
9 ("Grapefruit", 50),
10 ("Orange", 212),
11 ("Cantaloupe", 68),
12];
13
14const PRODUCTS: [(&str, [u32; 8]); 4] = [
15 ("Outlook", [24, 27, 18, 30, 20, 35, 40, 45]),
16 ("Teams", [9, 100, 22, 40, 30, 45, 50, 55]),
17 ("Office", [10, 20, 30, 40, 50, 60, 70, 80]),
18 ("Windows", [10, 20, 30, 40, 50, 60, 70, 80]),
19];
20
21const TREND: [(&str, [u32; 6]); 5] = [
22 ("Outlook", [99, 6, 63, 64, 63, 78]),
23 ("Teams", [12, 82, 12, 33, 1, 80]),
24 ("Office", [66, 93, 65, 13, 90, 48]),
25 ("Windows", [9, 19, 0, 61, 21, 72]),
26 ("Exchange", [35, 11, 91, 97, 97, 45]),
27];
28
29pub fn cards() -> Vec<Value> {
30 vec![
31 card(vec![slice_chart("Chart.Donut", "Fruit sales")]),
32 card(vec![slice_chart("Chart.Pie", "Fruit sales")]),
33 card(vec![
34 text("Basic"),
35 json!({"type": "Chart.Gauge", "value": 50, "subLabel": "Risk score", "segments": [
36 {"legend": "Low risk", "size": 33, "color": "good"},
37 {"legend": "Medium risk", "size": 34, "color": "warning"},
38 {"legend": "High risk", "size": 33, "color": "attention"}
39 ]}),
40 text("Single value"),
41 json!({"type": "Chart.Gauge", "value": 35, "valueFormat": "fraction", "segments": [
42 {"legend": "Used", "size": 35},
43 {"legend": "Unused", "size": 65, "color": "neutral"}
44 ]}),
45 ]),
46 card(vec![json!({
47 "type": "Chart.Line", "title": "Daily usage", "xAxisTitle": "Days", "yAxisTitle": "Sales",
48 "colorSet": "categorical", "data": series_data(&TREND)
49 })]),
50 card(vec![json!({
51 "type": "Chart.VerticalBar", "title": "Fruit sales", "xAxisTitle": "Fruit", "yAxisTitle": "Crates",
52 "showBarValues": true, "colorSet": "categorical", "data": xy_data(&FRUIT)
53 })]),
54 card(vec![
55 json!({
56 "type": "Chart.VerticalBar.Grouped", "title": "Grouped", "xAxisTitle": "Days", "yAxisTitle": "Sales",
57 "colorSet": "diverging", "data": series_data(&PRODUCTS)
58 }),
59 json!({
60 "type": "Chart.VerticalBar.Grouped", "title": "Stacked", "stacked": true, "xAxisTitle": "Days",
61 "yAxisTitle": "Sales", "data": series_data(&PRODUCTS)
62 }),
63 ]),
64 card(vec![
65 text("AbsoluteWithAxis"),
66 json!({
67 "type": "Chart.HorizontalBar", "title": "Fruit sales", "xAxisTitle": "Fruit", "yAxisTitle": "Crates",
68 "colorSet": "diverging", "data": xy_data(&FRUIT[..6])
69 }),
70 text("AbsoluteNoAxis"),
71 json!({
72 "type": "Chart.HorizontalBar", "title": "Fruit sales", "displayMode": "AbsoluteNoAxis",
73 "data": xy_data(&FRUIT[..6])
74 }),
75 text("PartToWhole"),
76 json!({"type": "Chart.HorizontalBar", "title": "Learning goal", "displayMode": "PartToWhole",
77 "color": "categoricalPurple", "data": [
78 {"x": "Yes, I have defined my day of learning goal", "y": 15},
79 {"x": "No, I haven't yet had time to do it", "y": 24},
80 {"x": "I am not interested in learning", "y": 2}
81 ]}),
82 ]),
83 card(vec![json!({
84 "type": "Chart.HorizontalBar.Stacked", "title": "Sample", "showBarValues": true, "data": [
85 stacked_row("Outlook", [24, 27, 18]),
86 stacked_row("Teams", [9, 100, 22]),
87 stacked_row("Office", [40, 12, 60])
88 ]
89 })]),
90 ]
91}
92
93fn card(body: Vec<Value>) -> Value {
94 json!({"type": "AdaptiveCard", "version": "1.5", "body": body})
95}
96
97fn text(label: &str) -> Value {
98 json!({"type": "TextBlock", "text": label, "size": "medium", "weight": "bolder", "separator": true, "spacing": "large"})
99}
100
101fn slice_chart(chart_type: &str, title: &str) -> Value {
102 let data: Vec<Value> = FRUIT
103 .iter()
104 .map(|(legend, value)| json!({"legend": legend, "value": value}))
105 .collect();
106 json!({"type": chart_type, "title": title, "colorSet": "categorical", "data": data})
107}
108
109fn xy_data(points: &[(&str, u32)]) -> Vec<Value> {
110 points
111 .iter()
112 .map(|(label, value)| json!({"x": label, "y": value}))
113 .collect()
114}
115
116fn series_data<const COUNT: usize>(series: &[(&str, [u32; COUNT])]) -> Vec<Value> {
117 series
118 .iter()
119 .map(|(legend, values)| {
120 let points: Vec<Value> = values
121 .iter()
122 .enumerate()
123 .map(|(index, value)| json!({"x": format!("2023-05-{:02}", index + 1), "y": value}))
124 .collect();
125 json!({"legend": legend, "values": points})
126 })
127 .collect()
128}
129
130fn stacked_row(title: &str, values: [u32; 3]) -> Value {
131 let colors = ["good", "warning", "attention"];
132 let points: Vec<Value> = values
133 .iter()
134 .zip(colors)
135 .enumerate()
136 .map(|(index, (value, color))| {
137 json!({"legend": format!("2023-05-{:02}", index + 1), "value": value, "color": color})
138 })
139 .collect();
140 json!({"title": title, "data": points})
141}
crates/app/src/demo_input_cards.rs added +70 −0
@@ -0,0 +1,70 @@
1 use serde_json::{Value, json};
2 use teams_core::InputChoice;
3
4 const DATASET_SERVICES: &str = "demo.services";
5
6 const SERVICES: [(&str, &str); 10] = [
7 ("Billing API", "billing-api"),
8 ("Build Farm", "build-farm"),
9 ("Chat Gateway", "chat-gateway"),
10 ("Identity Provider", "identity"),
11 ("Notification Hub", "notification-hub"),
12 ("Search Index", "search-index"),
13 ("Storage Broker", "storage-broker"),
14 ("Task Scheduler", "task-scheduler"),
15 ("Telemetry Collector", "telemetry"),
16 ("Wiki Renderer", "wiki-renderer"),
17 ];
18
19 pub fn search(dataset: &str, query_text: &str) -> Vec<InputChoice> {
20 if dataset != DATASET_SERVICES {
21 return Vec::new();
22 }
23 let needle = query_text.to_lowercase();
24 SERVICES
25 .iter()
26 .filter(|(title, _)| title.to_lowercase().contains(&needle))
27 .map(|(title, value)| InputChoice {
28 title: (*title).to_owned(),
29 value: (*value).to_owned(),
30 })
31 .collect()
32 }
33
34 pub fn all_inputs_card() -> Value {
35 json!({
36 "type": "AdaptiveCard",
37 "body": [
38 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Maintenance window"},
39 {"type": "Input.Date", "id": "window_day", "label": "Day", "isRequired": true, "errorMessage": "Pick a day in the planning range", "min": "2026-10-01", "max": "2026-12-31", "value": "2026-11-02"},
40 {"type": "Input.Time", "id": "window_start", "label": "Start (24h)", "isRequired": true, "errorMessage": "Start between 06:00 and 20:00", "min": "06:00", "max": "20:00", "value": "09:30"},
41 {"type": "Input.Text", "id": "ticket", "label": "Ticket", "placeholder": "ABC-1234", "maxLength": 8, "regex": "^[A-Z]{3}-\\d{1,4}$", "isRequired": true, "errorMessage": "Use the form ABC-1234",
42 "inlineAction": {"type": "Action.Submit", "title": "Look up", "data": {"action": "lookup"}}},
43 {"type": "Input.Number", "id": "servers", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "isRequired": true, "errorMessage": "Between 1 and 20 servers", "value": 4},
44 {"type": "Input.ChoiceSet", "id": "service", "label": "Service", "placeholder": "Type to search services", "isRequired": true, "errorMessage": "Pick a service",
45 "choices.data": {"type": "Data.Query", "dataset": DATASET_SERVICES, "count": 5}},
46 {"type": "Input.Rating", "id": "risk", "label": "Risk", "max": 5, "value": 2.5, "allowHalf": true, "color": "marigold", "size": "large", "isRequired": true, "errorMessage": "Rate the risk"},
47 {"type": "Input.Toggle", "id": "notify", "title": "Notify everyone who uses the service and wait for the confirmation before the window starts", "wrap": true, "value": "true"},
48 {"type": "Rating", "value": 4.5, "count": 128, "max": 5},
49 {"type": "Rating", "value": 3.7, "count": 1204, "style": "compact"}
50 ],
51 "actions": [
52 {"type": "Action.Submit", "title": "Schedule", "data": {"action": "schedule"}}
53 ]
54 })
55 }
56
57 #[cfg(test)]
58 mod tests {
59 use super::*;
60
61 #[test]
62 fn search_filters_the_local_list_case_insensitively() {
63 let values: Vec<String> = search(DATASET_SERVICES, "CH")
64 .into_iter()
65 .map(|choice| choice.value)
66 .collect();
67 assert_eq!(values, ["chat-gateway", "search-index", "task-scheduler"]);
68 assert!(search("other", "ch").is_empty());
69 }
70 }
@@ -0,0 +1,70 @@
1use serde_json::{Value, json};
2use teams_core::InputChoice;
3
4const DATASET_SERVICES: &str = "demo.services";
5
6const SERVICES: [(&str, &str); 10] = [
7 ("Billing API", "billing-api"),
8 ("Build Farm", "build-farm"),
9 ("Chat Gateway", "chat-gateway"),
10 ("Identity Provider", "identity"),
11 ("Notification Hub", "notification-hub"),
12 ("Search Index", "search-index"),
13 ("Storage Broker", "storage-broker"),
14 ("Task Scheduler", "task-scheduler"),
15 ("Telemetry Collector", "telemetry"),
16 ("Wiki Renderer", "wiki-renderer"),
17];
18
19pub fn search(dataset: &str, query_text: &str) -> Vec<InputChoice> {
20 if dataset != DATASET_SERVICES {
21 return Vec::new();
22 }
23 let needle = query_text.to_lowercase();
24 SERVICES
25 .iter()
26 .filter(|(title, _)| title.to_lowercase().contains(&needle))
27 .map(|(title, value)| InputChoice {
28 title: (*title).to_owned(),
29 value: (*value).to_owned(),
30 })
31 .collect()
32}
33
34pub fn all_inputs_card() -> Value {
35 json!({
36 "type": "AdaptiveCard",
37 "body": [
38 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Maintenance window"},
39 {"type": "Input.Date", "id": "window_day", "label": "Day", "isRequired": true, "errorMessage": "Pick a day in the planning range", "min": "2026-10-01", "max": "2026-12-31", "value": "2026-11-02"},
40 {"type": "Input.Time", "id": "window_start", "label": "Start (24h)", "isRequired": true, "errorMessage": "Start between 06:00 and 20:00", "min": "06:00", "max": "20:00", "value": "09:30"},
41 {"type": "Input.Text", "id": "ticket", "label": "Ticket", "placeholder": "ABC-1234", "maxLength": 8, "regex": "^[A-Z]{3}-\\d{1,4}$", "isRequired": true, "errorMessage": "Use the form ABC-1234",
42 "inlineAction": {"type": "Action.Submit", "title": "Look up", "data": {"action": "lookup"}}},
43 {"type": "Input.Number", "id": "servers", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "isRequired": true, "errorMessage": "Between 1 and 20 servers", "value": 4},
44 {"type": "Input.ChoiceSet", "id": "service", "label": "Service", "placeholder": "Type to search services", "isRequired": true, "errorMessage": "Pick a service",
45 "choices.data": {"type": "Data.Query", "dataset": DATASET_SERVICES, "count": 5}},
46 {"type": "Input.Rating", "id": "risk", "label": "Risk", "max": 5, "value": 2.5, "allowHalf": true, "color": "marigold", "size": "large", "isRequired": true, "errorMessage": "Rate the risk"},
47 {"type": "Input.Toggle", "id": "notify", "title": "Notify everyone who uses the service and wait for the confirmation before the window starts", "wrap": true, "value": "true"},
48 {"type": "Rating", "value": 4.5, "count": 128, "max": 5},
49 {"type": "Rating", "value": 3.7, "count": 1204, "style": "compact"}
50 ],
51 "actions": [
52 {"type": "Action.Submit", "title": "Schedule", "data": {"action": "schedule"}}
53 ]
54 })
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn search_filters_the_local_list_case_insensitively() {
63 let values: Vec<String> = search(DATASET_SERVICES, "CH")
64 .into_iter()
65 .map(|choice| choice.value)
66 .collect();
67 assert_eq!(values, ["chat-gateway", "search-index", "task-scheduler"]);
68 assert!(search("other", "ch").is_empty());
69 }
70}
crates/app/src/main.rs +4 −0
@@ -12,10 +12,14 @@ mod card_actions;
12 12 mod card_inputs;
13 13 mod chat_actions;
14 14 mod crash_log;
15 mod card_refresh;
15 16 mod card_state;
16 17 mod data;
17 18 mod demo;
19 mod demo_cards;
20 mod demo_chart_cards;
18 21 mod demo_gifs;
22 mod demo_input_cards;
19 23 mod downloads;
20 24 mod emoji;
21 25 mod format;
@@ -12,10 +12,14 @@ mod card_actions;
12mod card_inputs;
12mod card_inputs;
13mod chat_actions;
13mod chat_actions;
14mod crash_log;
14mod crash_log;
15mod card_refresh;
15mod card_state;
16mod card_state;
16mod data;
17mod data;
17mod demo;
18mod demo;
19mod demo_cards;
20mod demo_chart_cards;
18mod demo_gifs;
21mod demo_gifs;
22mod demo_input_cards;
19mod downloads;
23mod downloads;
20mod emoji;
24mod emoji;
21mod format;
25mod format;
crates/app/src/views/adaptive_card.rs +528 −116
@@ -1,16 +1,26 @@
1 1 use std::collections::HashMap;
2 2 use std::rc::Rc;
3 3
4 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4 use gpui_kit::component::{ActiveTheme as _, h_flex, tooltip::Tooltip, v_flex};
5 5 use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 7 use teams_core::{
8 8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
10 VerticalAlignment,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerLayout, ContainerStyle,
10 HorizontalAlignment, ImageSize, TextColor, TextSize, VerticalAlignment, WidthClass,
11 split_overflow,
11 12 };
12 13
13 use super::card_input::input_view;
14 use super::card_carousel::carousel_view;
15 use super::card_chart::chart_view;
16 use super::card_code_block::code_block_view;
17 use super::card_icon::{action_icon_view, icon_view};
18 use super::card_input::{input_view, rating_display_view};
19 use super::card_media::media_view;
20 use super::card_table::table_view;
21 use super::card_widgets::{
22 badge_view, compound_button_view, leading, progress_bar_view, progress_ring_view,
23 };
14 24 use super::widgets::symbol;
15 25 use crate::app_state::{AppHandle, AppState};
16 26 use crate::card_state::{ActionPhase, CardScope, CardState};
@@ -44,15 +54,22 @@ const IMAGE_SET_GAP: f32 = 6.;
44 54 const SMALL_IMAGE: f32 = 40.;
45 55 const MEDIUM_IMAGE: f32 = 80.;
46 56 const LARGE_IMAGE: f32 = 160.;
47 const EXTERNAL_IMAGE_SCHEME: &str = "https://";
57 const EXTERNAL_IMAGE_SCHEMES: [&str; 2] = ["https://", "http://"];
58 const ACTION_OVERFLOW_LABEL: &str = "...";
59 const ACTION_OVERFLOW_TOOLTIP: &str = "More actions";
60 const OVERFLOW_PANEL_PADDING: f32 = 4.;
61 const SELECT_TINT: f32 = 0.07;
62
63 pub(super) type ClickHandler = Rc<dyn Fn(&mut App)>;
48 64
49 struct CardContext<'a> {
50 cx: &'a App,
51 scope: &'a CardScope,
52 state: &'a CardState,
65 pub(super) struct CardContext<'a> {
66 pub(super) cx: &'a App,
67 pub(super) scope: &'a CardScope,
68 pub(super) state: &'a CardState,
53 69 root_key: String,
54 70 initial_visibility: Rc<HashMap<String, bool>>,
55 71 inputs: Vec<CardInput>,
72 width_class: WidthClass,
56 73 }
57 74
58 75 impl<'a> CardContext<'a> {
@@ -64,6 +81,7 @@ impl<'a> CardContext<'a> {
64 81 root_key: scope.card_key(),
65 82 initial_visibility: Rc::new(card.element_visibility()),
66 83 inputs: card.own_inputs(),
84 width_class: WidthClass::from_pixels(card_width(card)),
67 85 }
68 86 }
69 87
@@ -77,10 +95,11 @@ impl<'a> CardContext<'a> {
77 95 root_key: self.root_key.clone(),
78 96 initial_visibility: self.initial_visibility.clone(),
79 97 inputs,
98 width_class: self.width_class,
80 99 }
81 100 }
82 101
83 fn visible(&self, id: Option<&String>, initial: bool) -> bool {
102 pub(super) fn visible(&self, id: Option<&String>, initial: bool) -> bool {
84 103 match id {
85 104 Some(id) => self
86 105 .state
@@ -125,21 +144,38 @@ pub fn ensure_cards_inputs(
125 144 });
126 145 }
127 146
147 pub fn request_card_refreshes(
148 app: &Entity<AppState>,
149 cards: &[AdaptiveCard],
150 conversation_id: &str,
151 message_id: &str,
152 cx: &mut App,
153 ) {
154 if cards.iter().all(|card| card.refresh.is_none()) {
155 return;
156 }
157 app.update(cx, |state, cx| {
158 state.request_card_refreshes(conversation_id, message_id, cards, cx)
159 });
160 }
161
128 162 pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
129 163 let context = CardContext::new(card, scope, cx);
130 164 let id = scope.card_key();
131 let width = if card.full_width {
132 CARD_FULL_WIDTH
133 } else {
134 CARD_WIDTH
135 };
136 165 let note = context.state.note(&id).map(str::to_owned);
166 let select_handler = card
167 .select_action
168 .as_ref()
169 .filter(|action| action.is_clickable())
170 .and_then(|action| click_handler(action, &format!("{id}-select"), None, &context));
137 171 let visible_actions = card
138 172 .actions
139 173 .iter()
140 174 .any(|action| context.visible(action.id.as_ref(), action.visible));
141 175 v_flex()
142 .w(px(width))
176 .id(ElementId::Name(format!("{id}-root").into()))
177 .relative()
178 .w(px(card_width(card)))
143 179 .max_w(relative(1.))
144 180 .p(px(CARD_PADDING))
145 181 .rounded(px(CARD_RADIUS))
@@ -147,7 +183,18 @@ pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement
147 183 .border(px(CARD_BORDER_WIDTH))
148 184 .border_color(theme::border())
149 185 .text_color(theme::text_strong())
150 .child(items_view(&card.items, &id, &context))
186 .when_some(select_handler, |root, handler| {
187 root.cursor_pointer()
188 .hover(|root| root.bg(theme::row_hover()))
189 .on_click(move |_, _, cx| {
190 cx.stop_propagation();
191 handler(cx)
192 })
193 })
194 .when_some(card.layout.background_image.clone(), |root, url| {
195 root.child(background_layer(&url, CARD_RADIUS))
196 })
197 .child(aligned_body(&card.items, &id, &context, &card.layout, true))
151 198 .when(visible_actions, |card_element| {
152 199 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
153 200 actions_view(&card.actions, &format!("{id}-actions"), &context),
@@ -165,20 +212,81 @@ pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement
165 212 .into_any_element()
166 213 }
167 214
168 fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
169 let mut shown = 0;
215 fn card_width(card: &AdaptiveCard) -> f32 {
216 if card.full_width {
217 CARD_FULL_WIDTH
218 } else {
219 CARD_WIDTH
220 }
221 }
222
223 fn background_layer(url: &str, radius: f32) -> AnyElement {
224 div()
225 .absolute()
226 .inset_0()
227 .rounded(px(radius))
228 .overflow_hidden()
229 .child(
230 img(url.to_owned())
231 .size_full()
232 .object_fit(ObjectFit::Cover)
233 .with_loading(|| div().into_any_element())
234 .with_fallback(|| div().into_any_element()),
235 )
236 .into_any_element()
237 }
238
239 fn aligned_body(
240 items: &[CardItem],
241 id: &str,
242 context: &CardContext,
243 layout: &ContainerLayout,
244 top_level: bool,
245 ) -> Div {
246 items_view(items, id, context, top_level)
247 .when_some(layout.min_height, |body, height| body.min_h(px(height)))
248 .map(|body| match layout.vertical_alignment {
249 VerticalAlignment::Top => body.justify_start(),
250 VerticalAlignment::Center => body.justify_center(),
251 VerticalAlignment::Bottom => body.justify_end(),
252 })
253 .when(layout.rtl, |body| body.text_right())
254 }
255
256 pub(super) fn items_view(
257 items: &[CardItem],
258 id: &str,
259 context: &CardContext,
260 top_level: bool,
261 ) -> Div {
262 let shown: Vec<(usize, &CardItem)> = items
263 .iter()
264 .enumerate()
265 .filter(|(_, item)| {
266 context.visible(item.id.as_ref(), item.visible)
267 && item
268 .target_width
269 .is_none_or(|target| target.matches(context.width_class))
270 })
271 .collect();
170 272 let mut column = v_flex().w_full();
171 for (index, item) in items.iter().enumerate() {
172 if !context.visible(item.id.as_ref(), item.visible) {
173 continue;
174 }
273 for (position, (index, item)) in shown.iter().enumerate() {
175 274 let item_id = format!("{id}-{index}");
176 let first = shown == 0;
177 shown += 1;
275 let first = position == 0;
276 let bleed = top_level
277 .then(|| bleed_edges(item, first, position + 1 == shown.len()))
278 .flatten();
178 279 column = column.child(
179 280 div()
180 .w_full()
181 .when(!first, |wrapper| {
281 .map(|wrapper| match bleed {
282 Some(edges) => wrapper
283 .mx(px(-CARD_PADDING))
284 .when(edges.top, |wrapper| wrapper.mt(px(-CARD_PADDING)))
285 .when(edges.bottom, |wrapper| wrapper.mb(px(-CARD_PADDING))),
286 None => wrapper.w_full(),
287 })
288 .when(item.stretch, |wrapper| wrapper.flex_grow(1.))
289 .when(!first && bleed.is_none_or(|edges| !edges.top), |wrapper| {
182 290 wrapper.mt(px(spacing_pixels(item.spacing)))
183 291 })
184 292 .when(!first && item.separator, |wrapper| {
@@ -187,12 +295,28 @@ fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
187 295 .border_t_1()
188 296 .border_color(theme::border())
189 297 })
190 .child(element_view(&item.element, &item_id, context)),
298 .child(element_view(&item.element, &item_id, context, bleed)),
191 299 );
192 300 }
193 301 column
194 302 }
195 303
304 #[derive(Clone, Copy)]
305 pub(super) struct BleedEdges {
306 top: bool,
307 bottom: bool,
308 }
309
310 fn bleed_edges(item: &CardItem, first: bool, last: bool) -> Option<BleedEdges> {
311 match &item.element {
312 CardElement::Container { layout, .. } if layout.bleed => Some(BleedEdges {
313 top: first,
314 bottom: last,
315 }),
316 _ => None,
317 }
318 }
319
196 320 fn spacing_pixels(spacing: CardSpacing) -> f32 {
197 321 match spacing {
198 322 CardSpacing::None => 0.,
@@ -204,39 +328,107 @@ fn spacing_pixels(spacing: CardSpacing) -> f32 {
204 328 }
205 329 }
206 330
207 fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyElement {
331 fn element_view(
332 element: &CardElement,
333 id: &str,
334 context: &CardContext,
335 bleed: Option<BleedEdges>,
336 ) -> AnyElement {
208 337 match element {
209 338 CardElement::Text(text) => text_view(text, id, context.cx),
210 CardElement::Image(image) => image_view(image, id),
211 CardElement::ImageSet(images) => h_flex()
212 .flex_wrap()
213 .gap(px(IMAGE_SET_GAP))
214 .children(
215 images
216 .iter()
217 .enumerate()
218 .map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
219 )
220 .into_any_element(),
221 CardElement::Columns(columns) => columns_view(columns, id, context),
222 CardElement::Container { style, items } => {
223 let tint = container_tint(*style);
224 items_view(items, id, context)
225 .when_some(tint, |container, tint| {
226 container
227 .p(px(CONTAINER_PADDING))
228 .rounded(px(CONTAINER_RADIUS))
229 .bg(tint)
230 })
339 CardElement::Image(image) => aligned_image(image, id, context),
340 CardElement::ImageSet(images) => {
341 h_flex()
342 .flex_wrap()
343 .gap(px(IMAGE_SET_GAP))
344 .children(images.iter().enumerate().map(|(index, image)| {
345 selectable_image(image, &format!("{id}-{index}"), context)
346 }))
231 347 .into_any_element()
232 348 }
349 CardElement::Columns { columns, layout } => columns_view(columns, layout, id, context),
350 CardElement::Container {
351 layout,
352 items,
353 select_action,
354 } => selectable(
355 container_view(items, id, context, layout, bleed).into_any_element(),
356 select_action.as_ref(),
357 id,
358 false,
359 context,
360 ),
233 361 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
362 CardElement::Media(media) => media_view(media, id),
363 CardElement::Icon(icon) => selectable(
364 icon_view(icon),
365 icon.select_action.as_ref(),
366 id,
367 true,
368 context,
369 ),
370 CardElement::Table(table) => table_view(table, id, context),
371 CardElement::CodeBlock(block) => code_block_view(block, id, context),
372 CardElement::Badge(badge) => leading(badge_view(badge, id)),
373 CardElement::ProgressBar(bar) => progress_bar_view(bar, id),
374 CardElement::ProgressRing(ring) => leading(progress_ring_view(ring, id)),
375 CardElement::CompoundButton(button) => compound_button_view(button, id, context),
376 CardElement::Carousel(carousel) => carousel_view(carousel, id, context),
234 377 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
235 CardElement::Input(input) => input_view(input, context.scope, context.state),
378 CardElement::Input(input) => {
379 input_view(input, context.scope, context.state, &context.inputs)
380 }
381 CardElement::Rating(display) => rating_display_view(display),
382 CardElement::Chart(chart) => chart_view(chart),
236 383 }
237 384 }
238 385
239 fn container_tint(style: ContainerStyle) -> Option<Hsla> {
386 pub(super) fn container_view(
387 items: &[CardItem],
388 id: &str,
389 context: &CardContext,
390 layout: &ContainerLayout,
391 bleed: Option<BleedEdges>,
392 ) -> Div {
393 let tint = container_tint(layout.style);
394 let padded = tint.is_some() || layout.background_image.is_some();
395 let inset = |edge: bool| {
396 if edge {
397 CARD_PADDING
398 } else if padded {
399 CONTAINER_PADDING
400 } else {
401 0.
402 }
403 };
404 v_flex()
405 .w_full()
406 .relative()
407 .map(|container| match bleed {
408 Some(edges) => container
409 .px(px(CARD_PADDING))
410 .pt(px(inset(edges.top)))
411 .pb(px(inset(edges.bottom)))
412 .when(edges.top, |container| {
413 container.rounded_t(px(CARD_RADIUS - CARD_BORDER_WIDTH))
414 })
415 .when(edges.bottom, |container| {
416 container.rounded_b(px(CARD_RADIUS - CARD_BORDER_WIDTH))
417 }),
418 None => container.when(padded, |container| {
419 container
420 .p(px(CONTAINER_PADDING))
421 .rounded(px(CONTAINER_RADIUS))
422 }),
423 })
424 .when_some(tint, |container, tint| container.bg(tint))
425 .when_some(layout.background_image.clone(), |container, url| {
426 container.child(background_layer(&url, CONTAINER_RADIUS))
427 })
428 .child(aligned_body(items, id, context, layout, false))
429 }
430
431 pub(super) fn container_tint(style: ContainerStyle) -> Option<Hsla> {
240 432 match style {
241 433 ContainerStyle::Default => None,
242 434 ContainerStyle::Emphasis => Some(theme::surface_raised()),
@@ -258,14 +450,16 @@ fn text_size(size: TextSize) -> f32 {
258 450 }
259 451
260 452 fn text_color(text: &CardText) -> Hsla {
261 match text.color {
453 card_color(text.color, text.subtle)
454 }
455
456 pub(super) fn card_color(color: TextColor, subtle: bool) -> Hsla {
457 match color {
262 458 TextColor::Accent => theme::accent_text(),
263 459 TextColor::Good => theme::green(),
264 460 TextColor::Warning => theme::amber(),
265 461 TextColor::Attention => theme::red_soft(),
266 TextColor::Default | TextColor::Dark | TextColor::Light if text.subtle => {
267 theme::text_muted()
268 }
462 TextColor::Default | TextColor::Dark | TextColor::Light if subtle => theme::text_muted(),
269 463 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
270 464 }
271 465 }
@@ -273,13 +467,30 @@ fn text_color(text: &CardText) -> Hsla {
273 467 fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
274 468 div()
275 469 .w_full()
470 .min_w(px(0.))
276 471 .text_size(px(text_size(text.size)))
277 472 .line_height(relative(TEXT_LINE_HEIGHT))
278 473 .text_color(text_color(text))
279 474 .when(text.bold, |element| {
280 475 element.font_weight(FontWeight::SEMIBOLD)
281 476 })
282 .when(!text.wrap, |element| element.whitespace_nowrap())
477 .when(text.monospace, |element| {
478 element.font_family(cx.theme().mono_font_family.clone())
479 })
480 .map(|element| match text.alignment {
481 Some(HorizontalAlignment::Left) => element.text_left(),
482 Some(HorizontalAlignment::Center) => element.text_center(),
483 Some(HorizontalAlignment::Right) => element.text_right(),
484 None => element,
485 })
486 .map(|element| match (text.wrap, text.max_lines) {
487 (false, _) => element
488 .whitespace_nowrap()
489 .overflow_hidden()
490 .text_ellipsis(),
491 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
492 (true, None) => element,
493 })
283 494 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
284 495 .into_any_element()
285 496 }
@@ -313,28 +524,70 @@ fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
313 524 .into_any_element()
314 525 }
315 526
316 fn columns_view(columns: &[CardColumn], id: &str, context: &CardContext) -> AnyElement {
527 fn columns_view(
528 columns: &[CardColumn],
529 layout: &ContainerLayout,
530 id: &str,
531 context: &CardContext,
532 ) -> AnyElement {
533 let tint = container_tint(layout.style);
317 534 div()
318 535 .flex()
319 .flex_row()
536 .map(|row| {
537 if layout.rtl {
538 row.flex_row_reverse()
539 } else {
540 row.flex_row()
541 }
542 })
320 543 .items_stretch()
321 544 .w_full()
322 545 .gap(px(COLUMN_GAP))
323 .children(columns.iter().enumerate().map(|(index, column)| {
324 let content = items_view(&column.items, &format!("{id}-{index}"), context);
325 let aligned = v_flex()
326 .h_full()
327 .map(|aligned| match column.vertical_alignment {
328 VerticalAlignment::Top => aligned.justify_start(),
329 VerticalAlignment::Center => aligned.justify_center(),
330 VerticalAlignment::Bottom => aligned.justify_end(),
331 });
332 sized_column(aligned, column.width).child(content)
333 }))
546 .when_some(layout.min_height, |row, height| row.min_h(px(height)))
547 .when_some(tint, |row, tint| {
548 row.p(px(CONTAINER_PADDING))
549 .rounded(px(CONTAINER_RADIUS))
550 .bg(tint)
551 })
552 .children(
553 columns
554 .iter()
555 .enumerate()
556 .filter(|(_, column)| {
557 column
558 .target_width
559 .is_none_or(|target| target.matches(context.width_class))
560 })
561 .map(|(index, column)| {
562 let content = container_view(
563 &column.items,
564 &format!("{id}-{index}"),
565 context,
566 &column.layout,
567 None,
568 );
569 let content = selectable(
570 content.into_any_element(),
571 column.select_action.as_ref(),
572 &format!("{id}-{index}"),
573 false,
574 context,
575 );
576 let aligned =
577 v_flex()
578 .h_full()
579 .map(|aligned| match column.layout.vertical_alignment {
580 VerticalAlignment::Top => aligned.justify_start(),
581 VerticalAlignment::Center => aligned.justify_center(),
582 VerticalAlignment::Bottom => aligned.justify_end(),
583 });
584 sized_column(aligned, column.width).child(content)
585 }),
586 )
334 587 .into_any_element()
335 588 }
336 589
337 fn sized_column(column: Div, width: ColumnWidth) -> Div {
590 pub(super) fn sized_column(column: Div, width: ColumnWidth) -> Div {
338 591 match width {
339 592 ColumnWidth::Auto => column.flex_none(),
340 593 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
@@ -346,6 +599,70 @@ fn sized_column(column: Div, width: ColumnWidth) -> Div {
346 599 }
347 600 }
348 601
602 fn aligned_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
603 h_flex()
604 .w_full()
605 .map(|row| match image.alignment {
606 HorizontalAlignment::Left => row.justify_start(),
607 HorizontalAlignment::Center => row.justify_center(),
608 HorizontalAlignment::Right => row.justify_end(),
609 })
610 .child(selectable_image(image, id, context))
611 .into_any_element()
612 }
613
614 fn selectable_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
615 selectable(
616 image_view(image, id),
617 image.select_action.as_ref(),
618 id,
619 true,
620 context,
621 )
622 }
623
624 pub(super) fn selectable(
625 content: AnyElement,
626 select_action: Option<&CardAction>,
627 id: &str,
628 fit: bool,
629 context: &CardContext,
630 ) -> AnyElement {
631 let select_key = format!("{id}-select");
632 let Some(handler) = select_action
633 .filter(|action| action.is_clickable())
634 .and_then(|action| click_handler(action, &select_key, None, context))
635 else {
636 return content;
637 };
638 let group = SharedString::from(select_key.clone());
639 div()
640 .id(ElementId::Name(select_key.into()))
641 .group(group.clone())
642 .relative()
643 .cursor_pointer()
644 .map(|wrapper| {
645 if fit {
646 wrapper.self_start().flex_none()
647 } else {
648 wrapper.w_full()
649 }
650 })
651 .on_click(move |_, _, cx| {
652 cx.stop_propagation();
653 handler(cx)
654 })
655 .child(content)
656 .child(
657 div()
658 .absolute()
659 .inset_0()
660 .rounded(px(CONTAINER_RADIUS))
661 .group_hover(group, |tint| tint.bg(white().opacity(SELECT_TINT))),
662 )
663 .into_any_element()
664 }
665
349 666 fn image_view(image: &CardImage, id: &str) -> AnyElement {
350 667 let width = match (image.width, image.height, named_image_width(image.size)) {
351 668 (Some(width), _, _) => width,
@@ -368,10 +685,18 @@ fn image_view(image: &CardImage, id: &str) -> AnyElement {
368 685 .flex_none()
369 686 .overflow_hidden()
370 687 .rounded(radius);
371 if !image.url.starts_with(EXTERNAL_IMAGE_SCHEME) {
688 if !EXTERNAL_IMAGE_SCHEMES
689 .iter()
690 .any(|scheme| image.url.starts_with(scheme))
691 {
372 692 return frame.bg(theme::surface_raised()).into_any_element();
373 693 }
694 let alt_text = image.alt_text.clone();
374 695 frame
696 .when_some(image.background_color, |frame, color| frame.bg(rgba(color)))
697 .when_some(alt_text, |frame, alt_text| {
698 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
699 })
375 700 .child(
376 701 img(image.url.clone())
377 702 .size_full()
@@ -410,18 +735,46 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
410 735 CardActionKind::ShowCard(card) => Some(card),
411 736 _ => None,
412 737 });
738 let split = split_overflow(actions, |action| {
739 context.visible(action.id.as_ref(), action.visible)
740 });
741 let overflow_key = format!("{id}-overflow");
742 let overflow_open = !split.overflow.is_empty() && context.state.slot(&overflow_key, 0) == 1;
413 743 v_flex()
414 744 .w_full()
415 745 .gap(px(ACTION_GAP))
416 746 .child(
417 h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
418 actions
419 .iter()
420 .enumerate()
421 .filter(|(_, action)| context.visible(action.id.as_ref(), action.visible))
422 .map(|(index, action)| action_button(action, index, id, context)),
423 ),
747 h_flex()
748 .w_full()
749 .flex_wrap()
750 .gap(px(ACTION_GAP))
751 .children(
752 split
753 .primary
754 .iter()
755 .map(|&index| action_button(&actions[index], index, id, context)),
756 )
757 .when(!split.overflow.is_empty(), |row| {
758 row.child(overflow_button(&overflow_key, overflow_open, context))
759 }),
424 760 )
761 .when(overflow_open, |column| {
762 column.child(
763 v_flex()
764 .self_start()
765 .items_start()
766 .gap(px(OVERFLOW_PANEL_PADDING))
767 .p(px(OVERFLOW_PANEL_PADDING))
768 .rounded(px(CONTAINER_RADIUS))
769 .bg(theme::surface_raised())
770 .children(
771 split
772 .overflow
773 .iter()
774 .map(|&index| action_button(&actions[index], index, id, context)),
775 ),
776 )
777 })
425 778 .when_some(open_card, |column, card| {
426 779 let nested_id = format!("{id}-show");
427 780 let nested_context = context.nested(card);
@@ -432,7 +785,7 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
432 785 .gap(px(ACTION_GAP))
433 786 .rounded(px(CONTAINER_RADIUS))
434 787 .bg(theme::surface_raised())
435 .child(items_view(&card.items, &nested_id, &nested_context))
788 .child(items_view(&card.items, &nested_id, &nested_context, false))
436 789 .when(!card.actions.is_empty(), |nested| {
437 790 nested.child(actions_view(
438 791 &card.actions,
@@ -444,6 +797,44 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
444 797 })
445 798 }
446 799
800 fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Stateful<Div> {
801 let handler = slot_handler(context, overflow_key, usize::from(!open));
802 action_frame(overflow_key, theme::border_strong())
803 .text_color(theme::accent_text())
804 .cursor_pointer()
805 .hover(|button| button.bg(theme::row_hover()))
806 .when(open, |button| button.bg(theme::row_hover()))
807 .tooltip(|window, cx| Tooltip::new(ACTION_OVERFLOW_TOOLTIP).build(window, cx))
808 .child(ACTION_OVERFLOW_LABEL)
809 .on_click(move |_, _, cx| {
810 cx.stop_propagation();
811 handler(cx)
812 })
813 }
814
815 fn action_frame(button_id: &str, border: Hsla) -> Stateful<Div> {
816 div()
817 .id(ElementId::Name(button_id.to_owned().into()))
818 .px(px(12.))
819 .py(px(6.))
820 .rounded(px(ACTION_RADIUS))
821 .border_1()
822 .border_color(border)
823 .text_size(px(ACTION_TEXT_SIZE))
824 .font_weight(FontWeight::SEMIBOLD)
825 }
826
827 pub(super) fn slot_handler(context: &CardContext, slot_key: &str, value: usize) -> ClickHandler {
828 let scope = context.scope.clone();
829 let slot_key = slot_key.to_owned();
830 Rc::new(move |cx| {
831 let (scope, slot_key) = (scope.clone(), slot_key.clone());
832 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
833 state.set_card_slot(&scope, &slot_key, value, cx)
834 });
835 })
836 }
837
447 838 fn action_button(
448 839 action: &CardAction,
449 840 index: usize,
@@ -457,25 +848,22 @@ fn action_button(
457 848 &phase,
458 849 context.state.open_card(actions_id) == Some(index),
459 850 );
460 let button = div()
461 .id(ElementId::Name(button_id.clone().into()))
462 .px(px(12.))
463 .py(px(6.))
464 .rounded(px(ACTION_RADIUS))
465 .border_1()
466 .border_color(match phase {
467 Some(ActionPhase::Failed(_)) => theme::red(),
468 _ => theme::border_strong(),
469 })
470 .text_size(px(ACTION_TEXT_SIZE))
471 .font_weight(FontWeight::SEMIBOLD)
472 .child(label);
851 let border = match phase {
852 Some(ActionPhase::Failed(_)) => theme::red(),
853 _ => theme::border_strong(),
854 };
855 let button = action_frame(&button_id, border).child(label);
473 856 if !action.is_clickable() {
857 let hint = match action.kind {
858 CardActionKind::Unavailable(reason) if action.enabled => Some(reason.to_owned()),
859 _ if action.enabled => Some(ACTION_DISABLED_TOOLTIP.to_owned()),
860 _ => action.tooltip.clone(),
861 };
474 862 return button
475 863 .text_color(theme::text_muted())
476 864 .opacity(ACTION_DISABLED_OPACITY)
477 .when(action.enabled, |button| {
478 button.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
865 .when_some(hint, |button, hint| {
866 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
479 867 })
480 868 .on_click(|_, _, cx| cx.stop_propagation());
481 869 }
@@ -485,46 +873,59 @@ fn action_button(
485 873 .opacity(ACTION_BUSY_OPACITY)
486 874 .on_click(|_, _, cx| cx.stop_propagation());
487 875 }
876 let hint = failure_reason(&phase).or_else(|| action.tooltip.clone());
488 877 let enabled = enabled
489 878 .cursor_pointer()
490 879 .hover(|button| button.bg(theme::row_hover()))
491 .when_some(failure_reason(&phase), |button, reason| {
492 button.tooltip(move |window, cx| Tooltip::new(reason.clone()).build(window, cx))
880 .when_some(hint, |button, hint| {
881 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
493 882 });
883 match click_handler(action, &button_id, Some((actions_id, index)), context) {
884 Some(handler) => enabled.on_click(move |_, _, cx| {
885 cx.stop_propagation();
886 handler(cx)
887 }),
888 None => enabled,
889 }
890 }
891
892 fn click_handler(
893 action: &CardAction,
894 action_key: &str,
895 show_card: Option<(&str, usize)>,
896 context: &CardContext,
897 ) -> Option<ClickHandler> {
494 898 let scope = context.scope.clone();
495 899 match &action.kind {
496 900 CardActionKind::OpenUrl(url) => {
497 901 let url = url.clone();
498 enabled.on_click(move |_, _, cx| {
499 cx.stop_propagation();
500 cx.open_url(&url);
501 })
902 Some(Rc::new(move |cx| cx.open_url(&url)))
502 903 }
503 904 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
504 905 let action = action.clone();
906 let action_key = action_key.to_owned();
505 907 let inputs = context.inputs.clone();
506 enabled.on_click(move |_, _, cx| {
507 cx.stop_propagation();
508 let (scope, action, button_id, inputs) = (
908 Some(Rc::new(move |cx| {
909 let (scope, action, action_key, inputs) = (
509 910 scope.clone(),
510 911 action.clone(),
511 button_id.clone(),
912 action_key.clone(),
512 913 inputs.clone(),
513 914 );
514 915 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
515 state.run_card_action(scope, button_id, action, inputs, cx)
916 state.run_card_action(scope, action_key, action, inputs, cx)
516 917 });
517 })
918 }))
518 919 }
519 920 CardActionKind::ShowCard(_) => {
921 let (actions_id, index) = show_card?;
520 922 let actions_id = actions_id.to_owned();
521 enabled.on_click(move |_, _, cx| {
522 cx.stop_propagation();
923 Some(Rc::new(move |cx| {
523 924 let (scope, actions_id) = (scope.clone(), actions_id.clone());
524 925 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
525 926 state.toggle_show_card(&scope, &actions_id, index, cx)
526 927 });
527 })
928 }))
528 929 }
529 930 CardActionKind::ToggleVisibility(targets) => {
530 931 let elements: Vec<(String, bool, Option<bool>)> = targets
@@ -539,16 +940,15 @@ fn action_button(
539 940 })
540 941 .collect();
541 942 let root_key = context.root_key.clone();
542 enabled.on_click(move |_, _, cx| {
543 cx.stop_propagation();
943 Some(Rc::new(move |cx| {
544 944 let (scope, root_key, elements) =
545 945 (scope.clone(), root_key.clone(), elements.clone());
546 946 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
547 947 state.toggle_card_elements(&scope, &root_key, elements, cx)
548 948 });
549 })
949 }))
550 950 }
551 CardActionKind::Unsupported => enabled,
951 CardActionKind::Unavailable(_) | CardActionKind::Unsupported => None,
552 952 }
553 953 }
554 954
@@ -568,7 +968,19 @@ fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) ->
568 968 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
569 969 .child(action.title.clone())
570 970 .into_any_element(),
571 _ if open => format!("{} ^", action.title).into_any_element(),
572 _ => action.title.clone().into_any_element(),
971 _ if open => titled(action, format!("{} ^", action.title)),
972 _ => titled(action, action.title.clone()),
973 }
974 }
975
976 fn titled(action: &CardAction, text: String) -> AnyElement {
977 match action.icon.as_ref().map(action_icon_view) {
978 Some(icon) => h_flex()
979 .gap(px(ACTION_ICON_GAP))
980 .items_center()
981 .child(icon)
982 .child(text)
983 .into_any_element(),
984 None => text.into_any_element(),
573 985 }
574 986 }
@@ -1,16 +1,26 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::component::{ActiveTheme as _, h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7use teams_core::{
7use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerLayout, ContainerStyle,
10 VerticalAlignment,
10 HorizontalAlignment, ImageSize, TextColor, TextSize, VerticalAlignment, WidthClass,
11 split_overflow,
11};
12};
12
13
13use super::card_input::input_view;
14use super::card_carousel::carousel_view;
15use super::card_chart::chart_view;
16use super::card_code_block::code_block_view;
17use super::card_icon::{action_icon_view, icon_view};
18use super::card_input::{input_view, rating_display_view};
19use super::card_media::media_view;
20use super::card_table::table_view;
21use super::card_widgets::{
22 badge_view, compound_button_view, leading, progress_bar_view, progress_ring_view,
23};
14use super::widgets::symbol;
24use super::widgets::symbol;
15use crate::app_state::{AppHandle, AppState};
25use crate::app_state::{AppHandle, AppState};
16use crate::card_state::{ActionPhase, CardScope, CardState};
26use crate::card_state::{ActionPhase, CardScope, CardState};
@@ -44,15 +54,22 @@ const IMAGE_SET_GAP: f32 = 6.;
44const SMALL_IMAGE: f32 = 40.;
54const SMALL_IMAGE: f32 = 40.;
45const MEDIUM_IMAGE: f32 = 80.;
55const MEDIUM_IMAGE: f32 = 80.;
46const LARGE_IMAGE: f32 = 160.;
56const LARGE_IMAGE: f32 = 160.;
47const EXTERNAL_IMAGE_SCHEME: &str = "https://";
57const EXTERNAL_IMAGE_SCHEMES: [&str; 2] = ["https://", "http://"];
58const ACTION_OVERFLOW_LABEL: &str = "...";
59const ACTION_OVERFLOW_TOOLTIP: &str = "More actions";
60const OVERFLOW_PANEL_PADDING: f32 = 4.;
61const SELECT_TINT: f32 = 0.07;
62
63pub(super) type ClickHandler = Rc<dyn Fn(&mut App)>;
48
64
49struct CardContext<'a> {
65pub(super) struct CardContext<'a> {
50 cx: &'a App,
66 pub(super) cx: &'a App,
51 scope: &'a CardScope,
67 pub(super) scope: &'a CardScope,
52 state: &'a CardState,
68 pub(super) state: &'a CardState,
53 root_key: String,
69 root_key: String,
54 initial_visibility: Rc<HashMap<String, bool>>,
70 initial_visibility: Rc<HashMap<String, bool>>,
55 inputs: Vec<CardInput>,
71 inputs: Vec<CardInput>,
72 width_class: WidthClass,
56}
73}
57
74
58impl<'a> CardContext<'a> {
75impl<'a> CardContext<'a> {
@@ -64,6 +81,7 @@ impl<'a> CardContext<'a> {
64 root_key: scope.card_key(),
81 root_key: scope.card_key(),
65 initial_visibility: Rc::new(card.element_visibility()),
82 initial_visibility: Rc::new(card.element_visibility()),
66 inputs: card.own_inputs(),
83 inputs: card.own_inputs(),
84 width_class: WidthClass::from_pixels(card_width(card)),
67 }
85 }
68 }
86 }
69
87
@@ -77,10 +95,11 @@ impl<'a> CardContext<'a> {
77 root_key: self.root_key.clone(),
95 root_key: self.root_key.clone(),
78 initial_visibility: self.initial_visibility.clone(),
96 initial_visibility: self.initial_visibility.clone(),
79 inputs,
97 inputs,
98 width_class: self.width_class,
80 }
99 }
81 }
100 }
82
101
83 fn visible(&self, id: Option<&String>, initial: bool) -> bool {
102 pub(super) fn visible(&self, id: Option<&String>, initial: bool) -> bool {
84 match id {
103 match id {
85 Some(id) => self
104 Some(id) => self
86 .state
105 .state
@@ -125,21 +144,38 @@ pub fn ensure_cards_inputs(
125 });
144 });
126}
145}
127
146
147pub fn request_card_refreshes(
148 app: &Entity<AppState>,
149 cards: &[AdaptiveCard],
150 conversation_id: &str,
151 message_id: &str,
152 cx: &mut App,
153) {
154 if cards.iter().all(|card| card.refresh.is_none()) {
155 return;
156 }
157 app.update(cx, |state, cx| {
158 state.request_card_refreshes(conversation_id, message_id, cards, cx)
159 });
160}
161
128pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
162pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
129 let context = CardContext::new(card, scope, cx);
163 let context = CardContext::new(card, scope, cx);
130 let id = scope.card_key();
164 let id = scope.card_key();
131 let width = if card.full_width {
132 CARD_FULL_WIDTH
133 } else {
134 CARD_WIDTH
135 };
136 let note = context.state.note(&id).map(str::to_owned);
165 let note = context.state.note(&id).map(str::to_owned);
166 let select_handler = card
167 .select_action
168 .as_ref()
169 .filter(|action| action.is_clickable())
170 .and_then(|action| click_handler(action, &format!("{id}-select"), None, &context));
137 let visible_actions = card
171 let visible_actions = card
138 .actions
172 .actions
139 .iter()
173 .iter()
140 .any(|action| context.visible(action.id.as_ref(), action.visible));
174 .any(|action| context.visible(action.id.as_ref(), action.visible));
141 v_flex()
175 v_flex()
142 .w(px(width))
176 .id(ElementId::Name(format!("{id}-root").into()))
177 .relative()
178 .w(px(card_width(card)))
143 .max_w(relative(1.))
179 .max_w(relative(1.))
144 .p(px(CARD_PADDING))
180 .p(px(CARD_PADDING))
145 .rounded(px(CARD_RADIUS))
181 .rounded(px(CARD_RADIUS))
@@ -147,7 +183,18 @@ pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement
147 .border(px(CARD_BORDER_WIDTH))
183 .border(px(CARD_BORDER_WIDTH))
148 .border_color(theme::border())
184 .border_color(theme::border())
149 .text_color(theme::text_strong())
185 .text_color(theme::text_strong())
150 .child(items_view(&card.items, &id, &context))
186 .when_some(select_handler, |root, handler| {
187 root.cursor_pointer()
188 .hover(|root| root.bg(theme::row_hover()))
189 .on_click(move |_, _, cx| {
190 cx.stop_propagation();
191 handler(cx)
192 })
193 })
194 .when_some(card.layout.background_image.clone(), |root, url| {
195 root.child(background_layer(&url, CARD_RADIUS))
196 })
197 .child(aligned_body(&card.items, &id, &context, &card.layout, true))
151 .when(visible_actions, |card_element| {
198 .when(visible_actions, |card_element| {
152 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
199 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
153 actions_view(&card.actions, &format!("{id}-actions"), &context),
200 actions_view(&card.actions, &format!("{id}-actions"), &context),
@@ -165,20 +212,81 @@ pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement
165 .into_any_element()
212 .into_any_element()
166}
213}
167
214
168fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
215fn card_width(card: &AdaptiveCard) -> f32 {
169 let mut shown = 0;
216 if card.full_width {
217 CARD_FULL_WIDTH
218 } else {
219 CARD_WIDTH
220 }
221}
222
223fn background_layer(url: &str, radius: f32) -> AnyElement {
224 div()
225 .absolute()
226 .inset_0()
227 .rounded(px(radius))
228 .overflow_hidden()
229 .child(
230 img(url.to_owned())
231 .size_full()
232 .object_fit(ObjectFit::Cover)
233 .with_loading(|| div().into_any_element())
234 .with_fallback(|| div().into_any_element()),
235 )
236 .into_any_element()
237}
238
239fn aligned_body(
240 items: &[CardItem],
241 id: &str,
242 context: &CardContext,
243 layout: &ContainerLayout,
244 top_level: bool,
245) -> Div {
246 items_view(items, id, context, top_level)
247 .when_some(layout.min_height, |body, height| body.min_h(px(height)))
248 .map(|body| match layout.vertical_alignment {
249 VerticalAlignment::Top => body.justify_start(),
250 VerticalAlignment::Center => body.justify_center(),
251 VerticalAlignment::Bottom => body.justify_end(),
252 })
253 .when(layout.rtl, |body| body.text_right())
254}
255
256pub(super) fn items_view(
257 items: &[CardItem],
258 id: &str,
259 context: &CardContext,
260 top_level: bool,
261) -> Div {
262 let shown: Vec<(usize, &CardItem)> = items
263 .iter()
264 .enumerate()
265 .filter(|(_, item)| {
266 context.visible(item.id.as_ref(), item.visible)
267 && item
268 .target_width
269 .is_none_or(|target| target.matches(context.width_class))
270 })
271 .collect();
170 let mut column = v_flex().w_full();
272 let mut column = v_flex().w_full();
171 for (index, item) in items.iter().enumerate() {
273 for (position, (index, item)) in shown.iter().enumerate() {
172 if !context.visible(item.id.as_ref(), item.visible) {
173 continue;
174 }
175 let item_id = format!("{id}-{index}");
274 let item_id = format!("{id}-{index}");
176 let first = shown == 0;
275 let first = position == 0;
177 shown += 1;
276 let bleed = top_level
277 .then(|| bleed_edges(item, first, position + 1 == shown.len()))
278 .flatten();
178 column = column.child(
279 column = column.child(
179 div()
280 div()
180 .w_full()
281 .map(|wrapper| match bleed {
181 .when(!first, |wrapper| {
282 Some(edges) => wrapper
283 .mx(px(-CARD_PADDING))
284 .when(edges.top, |wrapper| wrapper.mt(px(-CARD_PADDING)))
285 .when(edges.bottom, |wrapper| wrapper.mb(px(-CARD_PADDING))),
286 None => wrapper.w_full(),
287 })
288 .when(item.stretch, |wrapper| wrapper.flex_grow(1.))
289 .when(!first && bleed.is_none_or(|edges| !edges.top), |wrapper| {
182 wrapper.mt(px(spacing_pixels(item.spacing)))
290 wrapper.mt(px(spacing_pixels(item.spacing)))
183 })
291 })
184 .when(!first && item.separator, |wrapper| {
292 .when(!first && item.separator, |wrapper| {
@@ -187,12 +295,28 @@ fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
187 .border_t_1()
295 .border_t_1()
188 .border_color(theme::border())
296 .border_color(theme::border())
189 })
297 })
190 .child(element_view(&item.element, &item_id, context)),
298 .child(element_view(&item.element, &item_id, context, bleed)),
191 );
299 );
192 }
300 }
193 column
301 column
194}
302}
195
303
304#[derive(Clone, Copy)]
305pub(super) struct BleedEdges {
306 top: bool,
307 bottom: bool,
308}
309
310fn bleed_edges(item: &CardItem, first: bool, last: bool) -> Option<BleedEdges> {
311 match &item.element {
312 CardElement::Container { layout, .. } if layout.bleed => Some(BleedEdges {
313 top: first,
314 bottom: last,
315 }),
316 _ => None,
317 }
318}
319
196fn spacing_pixels(spacing: CardSpacing) -> f32 {
320fn spacing_pixels(spacing: CardSpacing) -> f32 {
197 match spacing {
321 match spacing {
198 CardSpacing::None => 0.,
322 CardSpacing::None => 0.,
@@ -204,39 +328,107 @@ fn spacing_pixels(spacing: CardSpacing) -> f32 {
204 }
328 }
205}
329}
206
330
207fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyElement {
331fn element_view(
332 element: &CardElement,
333 id: &str,
334 context: &CardContext,
335 bleed: Option<BleedEdges>,
336) -> AnyElement {
208 match element {
337 match element {
209 CardElement::Text(text) => text_view(text, id, context.cx),
338 CardElement::Text(text) => text_view(text, id, context.cx),
210 CardElement::Image(image) => image_view(image, id),
339 CardElement::Image(image) => aligned_image(image, id, context),
211 CardElement::ImageSet(images) => h_flex()
340 CardElement::ImageSet(images) => {
212 .flex_wrap()
341 h_flex()
213 .gap(px(IMAGE_SET_GAP))
342 .flex_wrap()
214 .children(
343 .gap(px(IMAGE_SET_GAP))
215 images
344 .children(images.iter().enumerate().map(|(index, image)| {
216 .iter()
345 selectable_image(image, &format!("{id}-{index}"), context)
217 .enumerate()
346 }))
218 .map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
219 )
220 .into_any_element(),
221 CardElement::Columns(columns) => columns_view(columns, id, context),
222 CardElement::Container { style, items } => {
223 let tint = container_tint(*style);
224 items_view(items, id, context)
225 .when_some(tint, |container, tint| {
226 container
227 .p(px(CONTAINER_PADDING))
228 .rounded(px(CONTAINER_RADIUS))
229 .bg(tint)
230 })
231 .into_any_element()
347 .into_any_element()
232 }
348 }
349 CardElement::Columns { columns, layout } => columns_view(columns, layout, id, context),
350 CardElement::Container {
351 layout,
352 items,
353 select_action,
354 } => selectable(
355 container_view(items, id, context, layout, bleed).into_any_element(),
356 select_action.as_ref(),
357 id,
358 false,
359 context,
360 ),
233 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
361 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
362 CardElement::Media(media) => media_view(media, id),
363 CardElement::Icon(icon) => selectable(
364 icon_view(icon),
365 icon.select_action.as_ref(),
366 id,
367 true,
368 context,
369 ),
370 CardElement::Table(table) => table_view(table, id, context),
371 CardElement::CodeBlock(block) => code_block_view(block, id, context),
372 CardElement::Badge(badge) => leading(badge_view(badge, id)),
373 CardElement::ProgressBar(bar) => progress_bar_view(bar, id),
374 CardElement::ProgressRing(ring) => leading(progress_ring_view(ring, id)),
375 CardElement::CompoundButton(button) => compound_button_view(button, id, context),
376 CardElement::Carousel(carousel) => carousel_view(carousel, id, context),
234 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
377 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
235 CardElement::Input(input) => input_view(input, context.scope, context.state),
378 CardElement::Input(input) => {
379 input_view(input, context.scope, context.state, &context.inputs)
380 }
381 CardElement::Rating(display) => rating_display_view(display),
382 CardElement::Chart(chart) => chart_view(chart),
236 }
383 }
237}
384}
238
385
239fn container_tint(style: ContainerStyle) -> Option<Hsla> {
386pub(super) fn container_view(
387 items: &[CardItem],
388 id: &str,
389 context: &CardContext,
390 layout: &ContainerLayout,
391 bleed: Option<BleedEdges>,
392) -> Div {
393 let tint = container_tint(layout.style);
394 let padded = tint.is_some() || layout.background_image.is_some();
395 let inset = |edge: bool| {
396 if edge {
397 CARD_PADDING
398 } else if padded {
399 CONTAINER_PADDING
400 } else {
401 0.
402 }
403 };
404 v_flex()
405 .w_full()
406 .relative()
407 .map(|container| match bleed {
408 Some(edges) => container
409 .px(px(CARD_PADDING))
410 .pt(px(inset(edges.top)))
411 .pb(px(inset(edges.bottom)))
412 .when(edges.top, |container| {
413 container.rounded_t(px(CARD_RADIUS - CARD_BORDER_WIDTH))
414 })
415 .when(edges.bottom, |container| {
416 container.rounded_b(px(CARD_RADIUS - CARD_BORDER_WIDTH))
417 }),
418 None => container.when(padded, |container| {
419 container
420 .p(px(CONTAINER_PADDING))
421 .rounded(px(CONTAINER_RADIUS))
422 }),
423 })
424 .when_some(tint, |container, tint| container.bg(tint))
425 .when_some(layout.background_image.clone(), |container, url| {
426 container.child(background_layer(&url, CONTAINER_RADIUS))
427 })
428 .child(aligned_body(items, id, context, layout, false))
429}
430
431pub(super) fn container_tint(style: ContainerStyle) -> Option<Hsla> {
240 match style {
432 match style {
241 ContainerStyle::Default => None,
433 ContainerStyle::Default => None,
242 ContainerStyle::Emphasis => Some(theme::surface_raised()),
434 ContainerStyle::Emphasis => Some(theme::surface_raised()),
@@ -258,14 +450,16 @@ fn text_size(size: TextSize) -> f32 {
258}
450}
259
451
260fn text_color(text: &CardText) -> Hsla {
452fn text_color(text: &CardText) -> Hsla {
261 match text.color {
453 card_color(text.color, text.subtle)
454}
455
456pub(super) fn card_color(color: TextColor, subtle: bool) -> Hsla {
457 match color {
262 TextColor::Accent => theme::accent_text(),
458 TextColor::Accent => theme::accent_text(),
263 TextColor::Good => theme::green(),
459 TextColor::Good => theme::green(),
264 TextColor::Warning => theme::amber(),
460 TextColor::Warning => theme::amber(),
265 TextColor::Attention => theme::red_soft(),
461 TextColor::Attention => theme::red_soft(),
266 TextColor::Default | TextColor::Dark | TextColor::Light if text.subtle => {
462 TextColor::Default | TextColor::Dark | TextColor::Light if subtle => theme::text_muted(),
267 theme::text_muted()
268 }
269 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
463 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
270 }
464 }
271}
465}
@@ -273,13 +467,30 @@ fn text_color(text: &CardText) -> Hsla {
273fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
467fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
274 div()
468 div()
275 .w_full()
469 .w_full()
470 .min_w(px(0.))
276 .text_size(px(text_size(text.size)))
471 .text_size(px(text_size(text.size)))
277 .line_height(relative(TEXT_LINE_HEIGHT))
472 .line_height(relative(TEXT_LINE_HEIGHT))
278 .text_color(text_color(text))
473 .text_color(text_color(text))
279 .when(text.bold, |element| {
474 .when(text.bold, |element| {
280 element.font_weight(FontWeight::SEMIBOLD)
475 element.font_weight(FontWeight::SEMIBOLD)
281 })
476 })
282 .when(!text.wrap, |element| element.whitespace_nowrap())
477 .when(text.monospace, |element| {
478 element.font_family(cx.theme().mono_font_family.clone())
479 })
480 .map(|element| match text.alignment {
481 Some(HorizontalAlignment::Left) => element.text_left(),
482 Some(HorizontalAlignment::Center) => element.text_center(),
483 Some(HorizontalAlignment::Right) => element.text_right(),
484 None => element,
485 })
486 .map(|element| match (text.wrap, text.max_lines) {
487 (false, _) => element
488 .whitespace_nowrap()
489 .overflow_hidden()
490 .text_ellipsis(),
491 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
492 (true, None) => element,
493 })
283 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
494 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
284 .into_any_element()
495 .into_any_element()
285}
496}
@@ -313,28 +524,70 @@ fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
313 .into_any_element()
524 .into_any_element()
314}
525}
315
526
316fn columns_view(columns: &[CardColumn], id: &str, context: &CardContext) -> AnyElement {
527fn columns_view(
528 columns: &[CardColumn],
529 layout: &ContainerLayout,
530 id: &str,
531 context: &CardContext,
532) -> AnyElement {
533 let tint = container_tint(layout.style);
317 div()
534 div()
318 .flex()
535 .flex()
319 .flex_row()
536 .map(|row| {
537 if layout.rtl {
538 row.flex_row_reverse()
539 } else {
540 row.flex_row()
541 }
542 })
320 .items_stretch()
543 .items_stretch()
321 .w_full()
544 .w_full()
322 .gap(px(COLUMN_GAP))
545 .gap(px(COLUMN_GAP))
323 .children(columns.iter().enumerate().map(|(index, column)| {
546 .when_some(layout.min_height, |row, height| row.min_h(px(height)))
324 let content = items_view(&column.items, &format!("{id}-{index}"), context);
547 .when_some(tint, |row, tint| {
325 let aligned = v_flex()
548 row.p(px(CONTAINER_PADDING))
326 .h_full()
549 .rounded(px(CONTAINER_RADIUS))
327 .map(|aligned| match column.vertical_alignment {
550 .bg(tint)
328 VerticalAlignment::Top => aligned.justify_start(),
551 })
329 VerticalAlignment::Center => aligned.justify_center(),
552 .children(
330 VerticalAlignment::Bottom => aligned.justify_end(),
553 columns
331 });
554 .iter()
332 sized_column(aligned, column.width).child(content)
555 .enumerate()
333 }))
556 .filter(|(_, column)| {
557 column
558 .target_width
559 .is_none_or(|target| target.matches(context.width_class))
560 })
561 .map(|(index, column)| {
562 let content = container_view(
563 &column.items,
564 &format!("{id}-{index}"),
565 context,
566 &column.layout,
567 None,
568 );
569 let content = selectable(
570 content.into_any_element(),
571 column.select_action.as_ref(),
572 &format!("{id}-{index}"),
573 false,
574 context,
575 );
576 let aligned =
577 v_flex()
578 .h_full()
579 .map(|aligned| match column.layout.vertical_alignment {
580 VerticalAlignment::Top => aligned.justify_start(),
581 VerticalAlignment::Center => aligned.justify_center(),
582 VerticalAlignment::Bottom => aligned.justify_end(),
583 });
584 sized_column(aligned, column.width).child(content)
585 }),
586 )
334 .into_any_element()
587 .into_any_element()
335}
588}
336
589
337fn sized_column(column: Div, width: ColumnWidth) -> Div {
590pub(super) fn sized_column(column: Div, width: ColumnWidth) -> Div {
338 match width {
591 match width {
339 ColumnWidth::Auto => column.flex_none(),
592 ColumnWidth::Auto => column.flex_none(),
340 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
593 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
@@ -346,6 +599,70 @@ fn sized_column(column: Div, width: ColumnWidth) -> Div {
346 }
599 }
347}
600}
348
601
602fn aligned_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
603 h_flex()
604 .w_full()
605 .map(|row| match image.alignment {
606 HorizontalAlignment::Left => row.justify_start(),
607 HorizontalAlignment::Center => row.justify_center(),
608 HorizontalAlignment::Right => row.justify_end(),
609 })
610 .child(selectable_image(image, id, context))
611 .into_any_element()
612}
613
614fn selectable_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
615 selectable(
616 image_view(image, id),
617 image.select_action.as_ref(),
618 id,
619 true,
620 context,
621 )
622}
623
624pub(super) fn selectable(
625 content: AnyElement,
626 select_action: Option<&CardAction>,
627 id: &str,
628 fit: bool,
629 context: &CardContext,
630) -> AnyElement {
631 let select_key = format!("{id}-select");
632 let Some(handler) = select_action
633 .filter(|action| action.is_clickable())
634 .and_then(|action| click_handler(action, &select_key, None, context))
635 else {
636 return content;
637 };
638 let group = SharedString::from(select_key.clone());
639 div()
640 .id(ElementId::Name(select_key.into()))
641 .group(group.clone())
642 .relative()
643 .cursor_pointer()
644 .map(|wrapper| {
645 if fit {
646 wrapper.self_start().flex_none()
647 } else {
648 wrapper.w_full()
649 }
650 })
651 .on_click(move |_, _, cx| {
652 cx.stop_propagation();
653 handler(cx)
654 })
655 .child(content)
656 .child(
657 div()
658 .absolute()
659 .inset_0()
660 .rounded(px(CONTAINER_RADIUS))
661 .group_hover(group, |tint| tint.bg(white().opacity(SELECT_TINT))),
662 )
663 .into_any_element()
664}
665
349fn image_view(image: &CardImage, id: &str) -> AnyElement {
666fn image_view(image: &CardImage, id: &str) -> AnyElement {
350 let width = match (image.width, image.height, named_image_width(image.size)) {
667 let width = match (image.width, image.height, named_image_width(image.size)) {
351 (Some(width), _, _) => width,
668 (Some(width), _, _) => width,
@@ -368,10 +685,18 @@ fn image_view(image: &CardImage, id: &str) -> AnyElement {
368 .flex_none()
685 .flex_none()
369 .overflow_hidden()
686 .overflow_hidden()
370 .rounded(radius);
687 .rounded(radius);
371 if !image.url.starts_with(EXTERNAL_IMAGE_SCHEME) {
688 if !EXTERNAL_IMAGE_SCHEMES
689 .iter()
690 .any(|scheme| image.url.starts_with(scheme))
691 {
372 return frame.bg(theme::surface_raised()).into_any_element();
692 return frame.bg(theme::surface_raised()).into_any_element();
373 }
693 }
694 let alt_text = image.alt_text.clone();
374 frame
695 frame
696 .when_some(image.background_color, |frame, color| frame.bg(rgba(color)))
697 .when_some(alt_text, |frame, alt_text| {
698 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
699 })
375 .child(
700 .child(
376 img(image.url.clone())
701 img(image.url.clone())
377 .size_full()
702 .size_full()
@@ -410,18 +735,46 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
410 CardActionKind::ShowCard(card) => Some(card),
735 CardActionKind::ShowCard(card) => Some(card),
411 _ => None,
736 _ => None,
412 });
737 });
738 let split = split_overflow(actions, |action| {
739 context.visible(action.id.as_ref(), action.visible)
740 });
741 let overflow_key = format!("{id}-overflow");
742 let overflow_open = !split.overflow.is_empty() && context.state.slot(&overflow_key, 0) == 1;
413 v_flex()
743 v_flex()
414 .w_full()
744 .w_full()
415 .gap(px(ACTION_GAP))
745 .gap(px(ACTION_GAP))
416 .child(
746 .child(
417 h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
747 h_flex()
418 actions
748 .w_full()
419 .iter()
749 .flex_wrap()
420 .enumerate()
750 .gap(px(ACTION_GAP))
421 .filter(|(_, action)| context.visible(action.id.as_ref(), action.visible))
751 .children(
422 .map(|(index, action)| action_button(action, index, id, context)),
752 split
423 ),
753 .primary
754 .iter()
755 .map(|&index| action_button(&actions[index], index, id, context)),
756 )
757 .when(!split.overflow.is_empty(), |row| {
758 row.child(overflow_button(&overflow_key, overflow_open, context))
759 }),
424 )
760 )
761 .when(overflow_open, |column| {
762 column.child(
763 v_flex()
764 .self_start()
765 .items_start()
766 .gap(px(OVERFLOW_PANEL_PADDING))
767 .p(px(OVERFLOW_PANEL_PADDING))
768 .rounded(px(CONTAINER_RADIUS))
769 .bg(theme::surface_raised())
770 .children(
771 split
772 .overflow
773 .iter()
774 .map(|&index| action_button(&actions[index], index, id, context)),
775 ),
776 )
777 })
425 .when_some(open_card, |column, card| {
778 .when_some(open_card, |column, card| {
426 let nested_id = format!("{id}-show");
779 let nested_id = format!("{id}-show");
427 let nested_context = context.nested(card);
780 let nested_context = context.nested(card);
@@ -432,7 +785,7 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
432 .gap(px(ACTION_GAP))
785 .gap(px(ACTION_GAP))
433 .rounded(px(CONTAINER_RADIUS))
786 .rounded(px(CONTAINER_RADIUS))
434 .bg(theme::surface_raised())
787 .bg(theme::surface_raised())
435 .child(items_view(&card.items, &nested_id, &nested_context))
788 .child(items_view(&card.items, &nested_id, &nested_context, false))
436 .when(!card.actions.is_empty(), |nested| {
789 .when(!card.actions.is_empty(), |nested| {
437 nested.child(actions_view(
790 nested.child(actions_view(
438 &card.actions,
791 &card.actions,
@@ -444,6 +797,44 @@ fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div
444 })
797 })
445}
798}
446
799
800fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Stateful<Div> {
801 let handler = slot_handler(context, overflow_key, usize::from(!open));
802 action_frame(overflow_key, theme::border_strong())
803 .text_color(theme::accent_text())
804 .cursor_pointer()
805 .hover(|button| button.bg(theme::row_hover()))
806 .when(open, |button| button.bg(theme::row_hover()))
807 .tooltip(|window, cx| Tooltip::new(ACTION_OVERFLOW_TOOLTIP).build(window, cx))
808 .child(ACTION_OVERFLOW_LABEL)
809 .on_click(move |_, _, cx| {
810 cx.stop_propagation();
811 handler(cx)
812 })
813}
814
815fn action_frame(button_id: &str, border: Hsla) -> Stateful<Div> {
816 div()
817 .id(ElementId::Name(button_id.to_owned().into()))
818 .px(px(12.))
819 .py(px(6.))
820 .rounded(px(ACTION_RADIUS))
821 .border_1()
822 .border_color(border)
823 .text_size(px(ACTION_TEXT_SIZE))
824 .font_weight(FontWeight::SEMIBOLD)
825}
826
827pub(super) fn slot_handler(context: &CardContext, slot_key: &str, value: usize) -> ClickHandler {
828 let scope = context.scope.clone();
829 let slot_key = slot_key.to_owned();
830 Rc::new(move |cx| {
831 let (scope, slot_key) = (scope.clone(), slot_key.clone());
832 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
833 state.set_card_slot(&scope, &slot_key, value, cx)
834 });
835 })
836}
837
447fn action_button(
838fn action_button(
448 action: &CardAction,
839 action: &CardAction,
449 index: usize,
840 index: usize,
@@ -457,25 +848,22 @@ fn action_button(
457 &phase,
848 &phase,
458 context.state.open_card(actions_id) == Some(index),
849 context.state.open_card(actions_id) == Some(index),
459 );
850 );
460 let button = div()
851 let border = match phase {
461 .id(ElementId::Name(button_id.clone().into()))
852 Some(ActionPhase::Failed(_)) => theme::red(),
462 .px(px(12.))
853 _ => theme::border_strong(),
463 .py(px(6.))
854 };
464 .rounded(px(ACTION_RADIUS))
855 let button = action_frame(&button_id, border).child(label);
465 .border_1()
466 .border_color(match phase {
467 Some(ActionPhase::Failed(_)) => theme::red(),
468 _ => theme::border_strong(),
469 })
470 .text_size(px(ACTION_TEXT_SIZE))
471 .font_weight(FontWeight::SEMIBOLD)
472 .child(label);
473 if !action.is_clickable() {
856 if !action.is_clickable() {
857 let hint = match action.kind {
858 CardActionKind::Unavailable(reason) if action.enabled => Some(reason.to_owned()),
859 _ if action.enabled => Some(ACTION_DISABLED_TOOLTIP.to_owned()),
860 _ => action.tooltip.clone(),
861 };
474 return button
862 return button
475 .text_color(theme::text_muted())
863 .text_color(theme::text_muted())
476 .opacity(ACTION_DISABLED_OPACITY)
864 .opacity(ACTION_DISABLED_OPACITY)
477 .when(action.enabled, |button| {
865 .when_some(hint, |button, hint| {
478 button.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
866 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
479 })
867 })
480 .on_click(|_, _, cx| cx.stop_propagation());
868 .on_click(|_, _, cx| cx.stop_propagation());
481 }
869 }
@@ -485,46 +873,59 @@ fn action_button(
485 .opacity(ACTION_BUSY_OPACITY)
873 .opacity(ACTION_BUSY_OPACITY)
486 .on_click(|_, _, cx| cx.stop_propagation());
874 .on_click(|_, _, cx| cx.stop_propagation());
487 }
875 }
876 let hint = failure_reason(&phase).or_else(|| action.tooltip.clone());
488 let enabled = enabled
877 let enabled = enabled
489 .cursor_pointer()
878 .cursor_pointer()
490 .hover(|button| button.bg(theme::row_hover()))
879 .hover(|button| button.bg(theme::row_hover()))
491 .when_some(failure_reason(&phase), |button, reason| {
880 .when_some(hint, |button, hint| {
492 button.tooltip(move |window, cx| Tooltip::new(reason.clone()).build(window, cx))
881 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
493 });
882 });
883 match click_handler(action, &button_id, Some((actions_id, index)), context) {
884 Some(handler) => enabled.on_click(move |_, _, cx| {
885 cx.stop_propagation();
886 handler(cx)
887 }),
888 None => enabled,
889 }
890}
891
892fn click_handler(
893 action: &CardAction,
894 action_key: &str,
895 show_card: Option<(&str, usize)>,
896 context: &CardContext,
897) -> Option<ClickHandler> {
494 let scope = context.scope.clone();
898 let scope = context.scope.clone();
495 match &action.kind {
899 match &action.kind {
496 CardActionKind::OpenUrl(url) => {
900 CardActionKind::OpenUrl(url) => {
497 let url = url.clone();
901 let url = url.clone();
498 enabled.on_click(move |_, _, cx| {
902 Some(Rc::new(move |cx| cx.open_url(&url)))
499 cx.stop_propagation();
500 cx.open_url(&url);
501 })
502 }
903 }
503 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
904 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
504 let action = action.clone();
905 let action = action.clone();
906 let action_key = action_key.to_owned();
505 let inputs = context.inputs.clone();
907 let inputs = context.inputs.clone();
506 enabled.on_click(move |_, _, cx| {
908 Some(Rc::new(move |cx| {
507 cx.stop_propagation();
909 let (scope, action, action_key, inputs) = (
508 let (scope, action, button_id, inputs) = (
509 scope.clone(),
910 scope.clone(),
510 action.clone(),
911 action.clone(),
511 button_id.clone(),
912 action_key.clone(),
512 inputs.clone(),
913 inputs.clone(),
513 );
914 );
514 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
915 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
515 state.run_card_action(scope, button_id, action, inputs, cx)
916 state.run_card_action(scope, action_key, action, inputs, cx)
516 });
917 });
517 })
918 }))
518 }
919 }
519 CardActionKind::ShowCard(_) => {
920 CardActionKind::ShowCard(_) => {
921 let (actions_id, index) = show_card?;
520 let actions_id = actions_id.to_owned();
922 let actions_id = actions_id.to_owned();
521 enabled.on_click(move |_, _, cx| {
923 Some(Rc::new(move |cx| {
522 cx.stop_propagation();
523 let (scope, actions_id) = (scope.clone(), actions_id.clone());
924 let (scope, actions_id) = (scope.clone(), actions_id.clone());
524 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
925 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
525 state.toggle_show_card(&scope, &actions_id, index, cx)
926 state.toggle_show_card(&scope, &actions_id, index, cx)
526 });
927 });
527 })
928 }))
528 }
929 }
529 CardActionKind::ToggleVisibility(targets) => {
930 CardActionKind::ToggleVisibility(targets) => {
530 let elements: Vec<(String, bool, Option<bool>)> = targets
931 let elements: Vec<(String, bool, Option<bool>)> = targets
@@ -539,16 +940,15 @@ fn action_button(
539 })
940 })
540 .collect();
941 .collect();
541 let root_key = context.root_key.clone();
942 let root_key = context.root_key.clone();
542 enabled.on_click(move |_, _, cx| {
943 Some(Rc::new(move |cx| {
543 cx.stop_propagation();
544 let (scope, root_key, elements) =
944 let (scope, root_key, elements) =
545 (scope.clone(), root_key.clone(), elements.clone());
945 (scope.clone(), root_key.clone(), elements.clone());
546 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
946 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
547 state.toggle_card_elements(&scope, &root_key, elements, cx)
947 state.toggle_card_elements(&scope, &root_key, elements, cx)
548 });
948 });
549 })
949 }))
550 }
950 }
551 CardActionKind::Unsupported => enabled,
951 CardActionKind::Unavailable(_) | CardActionKind::Unsupported => None,
552 }
952 }
553}
953}
554
954
@@ -568,7 +968,19 @@ fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) ->
568 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
968 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
569 .child(action.title.clone())
969 .child(action.title.clone())
570 .into_any_element(),
970 .into_any_element(),
571 _ if open => format!("{} ^", action.title).into_any_element(),
971 _ if open => titled(action, format!("{} ^", action.title)),
572 _ => action.title.clone().into_any_element(),
972 _ => titled(action, action.title.clone()),
973 }
974}
975
976fn titled(action: &CardAction, text: String) -> AnyElement {
977 match action.icon.as_ref().map(action_icon_view) {
978 Some(icon) => h_flex()
979 .gap(px(ACTION_ICON_GAP))
980 .items_center()
981 .child(icon)
982 .child(text)
983 .into_any_element(),
984 None => text.into_any_element(),
573 }
985 }
574}
986}
crates/app/src/views/card_chart.rs added +1042 −0
@@ -0,0 +1,1042 @@
1 use std::collections::HashSet;
2 use std::f32::consts::{FRAC_PI_2, PI, TAU};
3
4 use gpui_kit::component::{h_flex, v_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::*;
7 use teams_core::{
8 BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint, ChartSeries,
9 GaugeValueFormat, format_chart_value, label_stride, nice_scale, series_categories,
10 series_maximum, series_value, slice_angles, unit_fraction,
11 };
12
13 use crate::theme;
14
15 const CHART_HEIGHT: f32 = 200.;
16 const GAUGE_HEIGHT: f32 = 136.;
17 const GAUGE_MAX_RADIUS: f32 = 100.;
18 const GAUGE_RING_RATIO: f32 = 0.72;
19 const GAUGE_VALUE_SIZE: f32 = 22.;
20 const GAUGE_MARKER_RADIUS: f32 = 6.;
21 const DONUT_HOLE_RATIO: f32 = 0.58;
22 const SLICE_GAP: f32 = 2.;
23 const SLICE_LABEL_MIN_SWEEP: f32 = 0.32;
24 const ARC_STEP: f32 = 0.05;
25 const TITLE_SIZE: f32 = 13.5;
26 const LABEL_SIZE: f32 = 11.;
27 const LABEL_LINE_HEIGHT: f32 = 14.;
28 const LEGEND_SIZE: f32 = 12.;
29 const LEGEND_DOT: f32 = 8.;
30 const LEGEND_GAP: f32 = 12.;
31 const SECTION_GAP: f32 = 8.;
32 const AXIS_TICK_TARGET: usize = 4;
33 const AXIS_LABEL_GAP: f32 = 6.;
34 const AXIS_TITLE_HEIGHT: f32 = 16.;
35 const CATEGORY_LABEL_HEIGHT: f32 = 20.;
36 const FRAME_PADDING: f32 = 8.;
37 const VALUE_GUTTER: f32 = 40.;
38 const LABEL_COLUMN_MAX_RATIO: f32 = 0.4;
39 const BAR_SLOT_RATIO: f32 = 0.64;
40 const BAR_MAX_WIDTH: f32 = 56.;
41 const BAR_RADIUS: f32 = 2.;
42 const GROUP_GAP: f32 = 2.;
43 const HORIZONTAL_ROW_HEIGHT: f32 = 30.;
44 const HORIZONTAL_BAR_HEIGHT: f32 = 18.;
45 const WHOLE_ROW_HEIGHT: f32 = 46.;
46 const WHOLE_BAR_HEIGHT: f32 = 10.;
47 const SEGMENT_LABEL_MIN_WIDTH: f32 = 26.;
48 const LINE_WIDTH: f32 = 2.;
49 const MARKER_RADIUS: f32 = 3.5;
50 const GRID_WIDTH: f32 = 1.;
51 const ELLIPSIS: &str = "\u{2026}";
52 const LIGHT_FILL_LUMINANCE: f32 = 0.62;
53 const DARK_LABEL: u32 = 0x161617;
54
55 #[derive(Clone, Copy)]
56 struct Rect {
57 left: f32,
58 top: f32,
59 right: f32,
60 bottom: f32,
61 }
62
63 impl Rect {
64 fn from_bounds(bounds: Bounds<Pixels>) -> Rect {
65 Rect {
66 left: f32::from(bounds.origin.x),
67 top: f32::from(bounds.origin.y),
68 right: f32::from(bounds.origin.x + bounds.size.width),
69 bottom: f32::from(bounds.origin.y + bounds.size.height),
70 }
71 }
72
73 fn width(&self) -> f32 {
74 self.right - self.left
75 }
76
77 fn height(&self) -> f32 {
78 self.bottom - self.top
79 }
80
81 fn center_x(&self) -> f32 {
82 (self.left + self.right) / 2.
83 }
84
85 fn center_y(&self) -> f32 {
86 (self.top + self.bottom) / 2.
87 }
88
89 fn bounds(&self) -> Bounds<Pixels> {
90 Bounds::new(
91 point(px(self.left), px(self.top)),
92 size(px(self.width().max(0.)), px(self.height().max(0.))),
93 )
94 }
95 }
96
97 #[derive(Clone, Copy)]
98 enum LabelAlign {
99 Left,
100 Center,
101 Right,
102 }
103
104 struct Pen<'a> {
105 window: &'a mut Window,
106 cx: &'a mut App,
107 }
108
109 impl Pen<'_> {
110 fn shape(&self, text: &str, size_pixels: f32, color: Hsla, weight: FontWeight) -> ShapedLine {
111 let mut font = self.window.text_style().font();
112 font.weight = weight;
113 let run = TextRun {
114 len: text.len(),
115 font,
116 color,
117 background_color: None,
118 underline: None,
119 strikethrough: None,
120 };
121 self.window
122 .text_system()
123 .shape_line(text.to_owned().into(), px(size_pixels), &[run], None)
124 }
125
126 fn text_width(&self, text: &str) -> f32 {
127 f32::from(
128 self.shape(text, LABEL_SIZE, theme::text_muted(), FontWeight::NORMAL)
129 .width,
130 )
131 }
132
133 fn text(&mut self, text: &str, x: f32, y: f32, align: LabelAlign, color: Hsla) {
134 self.sized_text(text, (x, y), align, color, LABEL_SIZE, FontWeight::NORMAL);
135 }
136
137 fn sized_text(
138 &mut self,
139 text: &str,
140 (x, y): (f32, f32),
141 align: LabelAlign,
142 color: Hsla,
143 size_pixels: f32,
144 weight: FontWeight,
145 ) {
146 if text.is_empty() {
147 return;
148 }
149 let line = self.shape(text, size_pixels, color, weight);
150 let width = f32::from(line.width);
151 let left = match align {
152 LabelAlign::Left => x,
153 LabelAlign::Center => x - width / 2.,
154 LabelAlign::Right => x - width,
155 };
156 let _ = line.paint(
157 point(px(left), px(y)),
158 px(size_pixels * 1.25),
159 TextAlign::Left,
160 None,
161 self.window,
162 self.cx,
163 );
164 }
165
166 fn fitted(&self, text: &str, max_width: f32) -> String {
167 if self.text_width(text) <= max_width {
168 return text.to_owned();
169 }
170 let characters: Vec<char> = text.chars().collect();
171 (1..characters.len())
172 .rev()
173 .map(|length| {
174 format!(
175 "{}{ELLIPSIS}",
176 characters[..length].iter().collect::<String>()
177 )
178 })
179 .find(|candidate| self.text_width(candidate) <= max_width)
180 .unwrap_or_else(|| ELLIPSIS.to_owned())
181 }
182
183 fn rect(&mut self, rect: Rect, color: Hsla, radius: f32) {
184 if rect.width() <= 0. || rect.height() <= 0. {
185 return;
186 }
187 self.window.paint_quad(quad(
188 rect.bounds(),
189 px(radius),
190 color,
191 px(0.),
192 transparent_black(),
193 BorderStyle::default(),
194 ));
195 }
196
197 fn circle(&mut self, x: f32, y: f32, radius: f32, color: Hsla) {
198 self.rect(
199 Rect {
200 left: x - radius,
201 top: y - radius,
202 right: x + radius,
203 bottom: y + radius,
204 },
205 color,
206 radius,
207 );
208 }
209
210 fn horizontal_line(&mut self, left: f32, right: f32, y: f32, color: Hsla) {
211 self.rect(
212 Rect {
213 left,
214 top: y - GRID_WIDTH / 2.,
215 right,
216 bottom: y + GRID_WIDTH / 2.,
217 },
218 color,
219 0.,
220 );
221 }
222
223 fn vertical_line(&mut self, x: f32, top: f32, bottom: f32, color: Hsla) {
224 self.rect(
225 Rect {
226 left: x - GRID_WIDTH / 2.,
227 top,
228 right: x + GRID_WIDTH / 2.,
229 bottom,
230 },
231 color,
232 0.,
233 );
234 }
235
236 fn polyline(&mut self, points: &[(f32, f32)], color: Hsla) {
237 let Some(((first_x, first_y), rest)) = points.split_first() else {
238 return;
239 };
240 let mut builder = PathBuilder::stroke(px(LINE_WIDTH));
241 builder.move_to(point(px(*first_x), px(*first_y)));
242 for (x, y) in rest {
243 builder.line_to(point(px(*x), px(*y)));
244 }
245 if let Ok(path) = builder.build() {
246 self.window.paint_path(path, color);
247 }
248 }
249
250 fn sector(&mut self, center: (f32, f32), radii: (f32, f32), angles: (f32, f32), color: Hsla) {
251 let (inner, outer) = radii;
252 let (start, end) = angles;
253 let steps = ((end - start).abs() / ARC_STEP).ceil().max(1.) as usize;
254 let arc_point = |radius: f32, step: usize| {
255 let angle = start + (end - start) * step as f32 / steps as f32;
256 point(
257 px(center.0 + radius * angle.cos()),
258 px(center.1 + radius * angle.sin()),
259 )
260 };
261 let mut builder = PathBuilder::fill();
262 builder.move_to(arc_point(outer, 0));
263 for step in 1..=steps {
264 builder.line_to(arc_point(outer, step));
265 }
266 if inner > 0. {
267 for step in (0..=steps).rev() {
268 builder.line_to(arc_point(inner, step));
269 }
270 } else {
271 builder.line_to(point(px(center.0), px(center.1)));
272 }
273 builder.close();
274 if let Ok(path) = builder.build() {
275 self.window.paint_path(path, color);
276 }
277 }
278 }
279
280 pub fn chart_view(chart: &CardChart) -> AnyElement {
281 let legend_entries = if chart.show_legend {
282 chart.legend_entries()
283 } else {
284 Vec::new()
285 };
286 let height = chart_height(chart);
287 let drawing_chart = chart.clone();
288 let drawing = canvas(
289 |_, _, _| (),
290 move |bounds, (), window, cx| {
291 paint_chart(&drawing_chart, bounds, &mut Pen { window, cx });
292 },
293 )
294 .h(px(height));
295 let side_legend = matches!(chart.kind, ChartKind::Donut(_) | ChartKind::Pie(_));
296 let body = if side_legend {
297 h_flex()
298 .w_full()
299 .items_center()
300 .gap(px(LEGEND_GAP))
301 .child(drawing.flex_1().min_w(px(0.)))
302 .child(legend_view(&legend_entries, true))
303 .into_any_element()
304 } else {
305 v_flex()
306 .w_full()
307 .gap(px(SECTION_GAP))
308 .child(drawing.w_full())
309 .child(legend_view(&legend_entries, false))
310 .into_any_element()
311 };
312 v_flex()
313 .w_full()
314 .gap(px(SECTION_GAP))
315 .when_some(chart.title.clone(), |column, title| {
316 column.child(
317 div()
318 .text_size(px(TITLE_SIZE))
319 .font_weight(FontWeight::SEMIBOLD)
320 .text_color(theme::text_strong())
321 .child(title),
322 )
323 })
324 .child(body)
325 .into_any_element()
326 }
327
328 fn legend_view(entries: &[(String, ChartColor)], vertical: bool) -> Div {
329 let container = if vertical {
330 v_flex().flex_none().gap(px(6.))
331 } else {
332 h_flex().flex_wrap().gap_x(px(LEGEND_GAP)).gap_y(px(4.))
333 };
334 container.children(entries.iter().map(|(label, color)| {
335 h_flex()
336 .gap(px(6.))
337 .items_center()
338 .text_size(px(LEGEND_SIZE))
339 .text_color(theme::text_muted())
340 .child(
341 div()
342 .flex_none()
343 .size(px(LEGEND_DOT))
344 .rounded(px(LEGEND_DOT / 2.))
345 .bg(palette(*color)),
346 )
347 .child(label.clone())
348 }))
349 }
350
351 fn chart_height(chart: &CardChart) -> f32 {
352 let title_rows = |has_axis_title: bool| {
353 if has_axis_title {
354 AXIS_TITLE_HEIGHT
355 } else {
356 0.
357 }
358 };
359 match &chart.kind {
360 ChartKind::Gauge(_) => GAUGE_HEIGHT,
361 ChartKind::HorizontalBar { bars, mode } => match mode {
362 BarDisplayMode::AbsoluteWithAxis => {
363 bars.len() as f32 * HORIZONTAL_ROW_HEIGHT
364 + CATEGORY_LABEL_HEIGHT
365 + title_rows(chart.y_axis_title.is_some())
366 + title_rows(chart.x_axis_title.is_some())
367 + FRAME_PADDING
368 }
369 BarDisplayMode::AbsoluteNoAxis => {
370 bars.len() as f32 * HORIZONTAL_ROW_HEIGHT
371 + title_rows(chart.x_axis_title.is_some())
372 + FRAME_PADDING
373 }
374 BarDisplayMode::PartToWhole => bars.len() as f32 * WHOLE_ROW_HEIGHT,
375 },
376 ChartKind::StackedHorizontalBar(rows) => {
377 rows.len() as f32 * HORIZONTAL_ROW_HEIGHT
378 + CATEGORY_LABEL_HEIGHT
379 + title_rows(chart.y_axis_title.is_some())
380 + title_rows(chart.x_axis_title.is_some())
381 + FRAME_PADDING
382 }
383 _ => CHART_HEIGHT,
384 }
385 }
386
387 fn paint_chart(chart: &CardChart, bounds: Bounds<Pixels>, pen: &mut Pen) {
388 let area = Rect::from_bounds(bounds);
389 match &chart.kind {
390 ChartKind::Donut(slices) => paint_slices(pen, slices, area, DONUT_HOLE_RATIO),
391 ChartKind::Pie(slices) => paint_slices(pen, slices, area, 0.),
392 ChartKind::Gauge(gauge) => paint_gauge(pen, gauge, area),
393 ChartKind::Line(series) => paint_lines(pen, chart, series, area),
394 ChartKind::VerticalBar(bars) => paint_vertical_bars(pen, chart, bars, area),
395 ChartKind::GroupedBar { series, stacked } => {
396 paint_grouped_bars(pen, chart, series, *stacked, area)
397 }
398 ChartKind::HorizontalBar { bars, mode } => match mode {
399 BarDisplayMode::PartToWhole => paint_part_to_whole(pen, bars, area),
400 _ => paint_horizontal_bars(pen, chart, bars, *mode, area),
401 },
402 ChartKind::StackedHorizontalBar(rows) => paint_stacked_rows(pen, chart, rows, area),
403 }
404 }
405
406 fn paint_slices(pen: &mut Pen, slices: &[ChartPoint], area: Rect, hole_ratio: f32) {
407 let radius = area.width().min(area.height()) / 2. - FRAME_PADDING / 2.;
408 if radius <= 0. {
409 return;
410 }
411 let center = (area.center_x(), area.center_y());
412 let inner = radius * hole_ratio;
413 let values: Vec<f64> = slices.iter().map(|slice| slice.value).collect();
414 let visible = values.iter().filter(|value| **value > 0.).count();
415 let gap = if visible > 1 { SLICE_GAP / radius } else { 0. };
416 for (slice, (start, end)) in slices.iter().zip(slice_angles(&values)) {
417 let sweep = end - start;
418 if sweep <= 0. {
419 continue;
420 }
421 let fill = palette(slice.color);
422 let trim = gap.min(sweep / 4.);
423 pen.sector(
424 center,
425 (inner, radius),
426 (start + trim / 2., end - trim / 2.),
427 fill,
428 );
429 if sweep >= SLICE_LABEL_MIN_SWEEP {
430 let middle = (start + end) / 2.;
431 let label_radius = (inner + radius) / 2.;
432 pen.sized_text(
433 &format_chart_value(slice.value),
434 (
435 center.0 + label_radius * middle.cos(),
436 center.1 + label_radius * middle.sin() - LABEL_LINE_HEIGHT / 2.,
437 ),
438 LabelAlign::Center,
439 label_color_on(fill),
440 LABEL_SIZE,
441 FontWeight::SEMIBOLD,
442 );
443 }
444 }
445 }
446
447 fn paint_gauge(pen: &mut Pen, gauge: &ChartGauge, area: Rect) {
448 let radius = (area.width() / 2. - FRAME_PADDING * 1.5).min(GAUGE_MAX_RADIUS);
449 if radius <= 0. {
450 return;
451 }
452 let center = (area.center_x(), area.top + FRAME_PADDING / 2. + radius);
453 let inner = radius * GAUGE_RING_RATIO;
454 let segment_total: f64 = gauge.segments.iter().map(|segment| segment.size).sum();
455 let fraction = unit_fraction(gauge.value, gauge.minimum, gauge.maximum);
456 if segment_total > 0. {
457 let sizes: Vec<f64> = gauge.segments.iter().map(|segment| segment.size).collect();
458 let gap = SLICE_GAP / radius;
459 for (segment, (start, end)) in gauge.segments.iter().zip(slice_angles(&sizes)) {
460 let (start, end) = (half_arc_angle(start), half_arc_angle(end));
461 let trim = gap.min((end - start) / 4.);
462 pen.sector(
463 center,
464 (inner, radius),
465 (start + trim / 2., end - trim / 2.),
466 palette(segment.color),
467 );
468 }
469 } else {
470 pen.sector(
471 center,
472 (inner, radius),
473 (PI, TAU),
474 palette(ChartColor::Neutral),
475 );
476 pen.sector(
477 center,
478 (inner, radius),
479 (PI, PI + PI * fraction),
480 palette(ChartColor::CategoricalBlue),
481 );
482 }
483 let marker_angle = PI + PI * fraction;
484 let marker_radius = (inner + radius) / 2.;
485 let marker = (
486 center.0 + marker_radius * marker_angle.cos(),
487 center.1 + marker_radius * marker_angle.sin(),
488 );
489 pen.circle(
490 marker.0,
491 marker.1,
492 GAUGE_MARKER_RADIUS,
493 theme::text_strong(),
494 );
495 pen.circle(
496 marker.0,
497 marker.1,
498 GAUGE_MARKER_RADIUS - 2.,
499 theme::surface(),
500 );
501 let value_text = match gauge.format {
502 GaugeValueFormat::Percentage => {
503 format!("{}%", format_chart_value((fraction * 100.).round() as f64))
504 }
505 GaugeValueFormat::Fraction => format!(
506 "{}/{}",
507 format_chart_value(gauge.value),
508 format_chart_value(gauge.maximum)
509 ),
510 };
511 pen.sized_text(
512 &value_text,
513 (center.0, center.1 - GAUGE_VALUE_SIZE * 1.1),
514 LabelAlign::Center,
515 theme::text_strong(),
516 GAUGE_VALUE_SIZE,
517 FontWeight::SEMIBOLD,
518 );
519 if let Some(sub_label) = &gauge.sub_label {
520 pen.text(
521 sub_label,
522 center.0,
523 center.1 + 4.,
524 LabelAlign::Center,
525 theme::text_muted(),
526 );
527 }
528 if gauge.show_min_max {
529 let end_offset = marker_radius;
530 let y = center.1 + 4.;
531 pen.text(
532 &format_chart_value(gauge.minimum),
533 center.0 - end_offset,
534 y,
535 LabelAlign::Center,
536 theme::text_muted(),
537 );
538 pen.text(
539 &format_chart_value(gauge.maximum),
540 center.0 + end_offset,
541 y,
542 LabelAlign::Center,
543 theme::text_muted(),
544 );
545 }
546 }
547
548 struct VerticalFrame {
549 plot: Rect,
550 slot_width: f32,
551 maximum: f64,
552 }
553
554 impl VerticalFrame {
555 fn slot_center(&self, index: usize) -> f32 {
556 self.plot.left + self.slot_width * (index as f32 + 0.5)
557 }
558
559 fn y(&self, value: f64) -> f32 {
560 self.plot.bottom - self.plot.height() * unit_fraction(value, 0., self.maximum)
561 }
562 }
563
564 fn vertical_frame(
565 pen: &mut Pen,
566 chart: &CardChart,
567 area: Rect,
568 categories: &[String],
569 maximum_value: f64,
570 ) -> VerticalFrame {
571 let scale = nice_scale(maximum_value, AXIS_TICK_TARGET);
572 let ticks = scale.ticks();
573 let tick_labels: Vec<String> = ticks.iter().map(|tick| format_chart_value(*tick)).collect();
574 let label_width = tick_labels
575 .iter()
576 .map(|label| pen.text_width(label))
577 .fold(0., f32::max);
578 let top_padding = if chart.y_axis_title.is_some() {
579 AXIS_TITLE_HEIGHT + FRAME_PADDING
580 } else {
581 FRAME_PADDING
582 };
583 let bottom_padding = CATEGORY_LABEL_HEIGHT
584 + if chart.x_axis_title.is_some() {
585 AXIS_TITLE_HEIGHT
586 } else {
587 0.
588 };
589 let plot = Rect {
590 left: area.left + label_width + AXIS_LABEL_GAP + FRAME_PADDING / 2.,
591 top: area.top + top_padding,
592 right: area.right - FRAME_PADDING,
593 bottom: area.bottom - bottom_padding,
594 };
595 let frame = VerticalFrame {
596 plot,
597 slot_width: plot.width() / categories.len().max(1) as f32,
598 maximum: scale.maximum,
599 };
600 if let Some(title) = &chart.y_axis_title {
601 pen.text(
602 title,
603 area.left,
604 area.top,
605 LabelAlign::Left,
606 theme::text_muted(),
607 );
608 }
609 for (tick, label) in ticks.iter().zip(&tick_labels) {
610 let y = frame.y(*tick);
611 let line_color = if *tick == 0. {
612 theme::border_strong()
613 } else {
614 theme::border()
615 };
616 pen.horizontal_line(plot.left, plot.right, y, line_color);
617 pen.text(
618 label,
619 plot.left - AXIS_LABEL_GAP,
620 y - LABEL_LINE_HEIGHT / 2.,
621 LabelAlign::Right,
622 theme::text_muted(),
623 );
624 }
625 let widest_category = categories
626 .iter()
627 .map(|category| pen.text_width(category))
628 .fold(0., f32::max);
629 let stride = label_stride(
630 categories.len(),
631 frame.slot_width,
632 widest_category + AXIS_LABEL_GAP,
633 );
634 let fitted: Vec<String> = categories
635 .iter()
636 .map(|category| pen.fitted(category, frame.slot_width - AXIS_LABEL_GAP))
637 .collect();
638 let fitted_are_unique = fitted.iter().collect::<HashSet<_>>().len() == categories.len();
639 let (labels, stride) = if stride > 1 && fitted_are_unique {
640 (fitted.as_slice(), 1)
641 } else {
642 (categories, stride)
643 };
644 for (index, label) in labels.iter().enumerate().step_by(stride) {
645 pen.text(
646 label,
647 frame.slot_center(index),
648 plot.bottom + 4.,
649 LabelAlign::Center,
650 theme::text_muted(),
651 );
652 }
653 if let Some(title) = &chart.x_axis_title {
654 pen.text(
655 title,
656 plot.center_x(),
657 area.bottom - AXIS_TITLE_HEIGHT + 2.,
658 LabelAlign::Center,
659 theme::text_muted(),
660 );
661 }
662 frame
663 }
664
665 fn paint_bar_value(pen: &mut Pen, value: f64, x: f32, top: f32) {
666 pen.text(
667 &format_chart_value(value),
668 x,
669 top - LABEL_LINE_HEIGHT - 1.,
670 LabelAlign::Center,
671 theme::text_strong(),
672 );
673 }
674
675 fn paint_vertical_bars(pen: &mut Pen, chart: &CardChart, bars: &[ChartPoint], area: Rect) {
676 let categories: Vec<String> = bars.iter().map(|bar| bar.label.clone()).collect();
677 let maximum = bars.iter().map(|bar| bar.value).fold(0., f64::max);
678 let frame = vertical_frame(pen, chart, area, &categories, maximum);
679 let bar_width = (frame.slot_width * BAR_SLOT_RATIO).min(BAR_MAX_WIDTH);
680 for (index, bar) in bars.iter().enumerate() {
681 let center = frame.slot_center(index);
682 let top = frame.y(bar.value);
683 pen.rect(
684 Rect {
685 left: center - bar_width / 2.,
686 top,
687 right: center + bar_width / 2.,
688 bottom: frame.plot.bottom,
689 },
690 palette(bar.color),
691 BAR_RADIUS,
692 );
693 if chart.show_values {
694 paint_bar_value(pen, bar.value, center, top);
695 }
696 }
697 }
698
699 fn paint_grouped_bars(
700 pen: &mut Pen,
701 chart: &CardChart,
702 series: &[ChartSeries],
703 stacked: bool,
704 area: Rect,
705 ) {
706 let categories = series_categories(series);
707 let frame = vertical_frame(
708 pen,
709 chart,
710 area,
711 &categories,
712 series_maximum(series, stacked),
713 );
714 let group_width =
715 (frame.slot_width * BAR_SLOT_RATIO).min(BAR_MAX_WIDTH * series.len().max(1) as f32);
716 let bar_width = if stacked {
717 group_width.min(BAR_MAX_WIDTH)
718 } else {
719 group_width / series.len().max(1) as f32
720 };
721 for (index, category) in categories.iter().enumerate() {
722 let center = frame.slot_center(index);
723 let mut stack_total = 0.;
724 for (series_index, entry) in series.iter().enumerate() {
725 let value = series_value(entry, category).max(0.);
726 let (left, bottom_value, top_value) = if stacked {
727 let base = stack_total;
728 stack_total += value;
729 (center - bar_width / 2., base, stack_total)
730 } else {
731 let left = center - group_width / 2. + bar_width * series_index as f32;
732 (left, 0., value)
733 };
734 let gap = if stacked { 0. } else { GROUP_GAP / 2. };
735 pen.rect(
736 Rect {
737 left: left + gap,
738 top: frame.y(top_value),
739 right: left + bar_width - gap,
740 bottom: frame.y(bottom_value),
741 },
742 palette(entry.color),
743 if stacked { 0. } else { BAR_RADIUS },
744 );
745 if chart.show_values && !stacked {
746 paint_bar_value(pen, value, left + bar_width / 2., frame.y(value));
747 }
748 }
749 }
750 }
751
752 fn paint_lines(pen: &mut Pen, chart: &CardChart, series: &[ChartSeries], area: Rect) {
753 let categories = series_categories(series);
754 let frame = vertical_frame(pen, chart, area, &categories, series_maximum(series, false));
755 for entry in series {
756 let color = palette(entry.color);
757 let points: Vec<(f32, f32)> = categories
758 .iter()
759 .enumerate()
760 .filter(|(_, category)| entry.points.iter().any(|point| point.label == **category))
761 .map(|(index, category)| {
762 (
763 frame.slot_center(index),
764 frame.y(series_value(entry, category)),
765 )
766 })
767 .collect();
768 pen.polyline(&points, color);
769 for (x, y) in &points {
770 pen.circle(*x, *y, MARKER_RADIUS + 1.5, theme::surface());
771 pen.circle(*x, *y, MARKER_RADIUS, color);
772 }
773 }
774 }
775
776 struct HorizontalFrame {
777 plot: Rect,
778 row_height: f32,
779 maximum: f64,
780 }
781
782 impl HorizontalFrame {
783 fn row_center(&self, index: usize) -> f32 {
784 self.plot.top + self.row_height * (index as f32 + 0.5)
785 }
786
787 fn x(&self, value: f64) -> f32 {
788 self.plot.left + self.plot.width() * unit_fraction(value, 0., self.maximum)
789 }
790 }
791
792 fn horizontal_frame(
793 pen: &mut Pen,
794 chart: &CardChart,
795 area: Rect,
796 labels: &[String],
797 maximum_value: f64,
798 with_axis: bool,
799 ) -> HorizontalFrame {
800 let scale = nice_scale(maximum_value, AXIS_TICK_TARGET);
801 let widest_label = labels
802 .iter()
803 .map(|label| pen.text_width(label))
804 .fold(0., f32::max);
805 let label_width = widest_label.min(area.width() * LABEL_COLUMN_MAX_RATIO);
806 let top_padding = if chart.x_axis_title.is_some() {
807 AXIS_TITLE_HEIGHT
808 } else {
809 FRAME_PADDING / 2.
810 };
811 let bottom_padding = if with_axis {
812 CATEGORY_LABEL_HEIGHT
813 + if chart.y_axis_title.is_some() {
814 AXIS_TITLE_HEIGHT
815 } else {
816 0.
817 }
818 } else {
819 FRAME_PADDING / 2.
820 };
821 let plot = Rect {
822 left: area.left + label_width + AXIS_LABEL_GAP * 2.,
823 top: area.top + top_padding,
824 right: area.right - VALUE_GUTTER,
825 bottom: area.bottom - bottom_padding,
826 };
827 let frame = HorizontalFrame {
828 plot,
829 row_height: plot.height() / labels.len().max(1) as f32,
830 maximum: scale.maximum,
831 };
832 if let Some(title) = &chart.x_axis_title {
833 pen.text(
834 title,
835 area.left,
836 area.top,
837 LabelAlign::Left,
838 theme::text_muted(),
839 );
840 }
841 if with_axis {
842 for tick in scale.ticks() {
843 let x = frame.x(tick);
844 let line_color = if tick == 0. {
845 theme::border_strong()
846 } else {
847 theme::border()
848 };
849 pen.vertical_line(x, plot.top, plot.bottom, line_color);
850 pen.text(
851 &format_chart_value(tick),
852 x,
853 plot.bottom + 4.,
854 LabelAlign::Center,
855 theme::text_muted(),
856 );
857 }
858 if let Some(title) = &chart.y_axis_title {
859 pen.text(
860 title,
861 plot.center_x(),
862 area.bottom - AXIS_TITLE_HEIGHT + 2.,
863 LabelAlign::Center,
864 theme::text_muted(),
865 );
866 }
867 }
868 for (index, label) in labels.iter().enumerate() {
869 let fitted = pen.fitted(label, label_width);
870 pen.text(
871 &fitted,
872 plot.left - AXIS_LABEL_GAP,
873 frame.row_center(index) - LABEL_LINE_HEIGHT / 2.,
874 LabelAlign::Right,
875 theme::text_soft(),
876 );
877 }
878 frame
879 }
880
881 fn paint_horizontal_bars(
882 pen: &mut Pen,
883 chart: &CardChart,
884 bars: &[ChartPoint],
885 mode: BarDisplayMode,
886 area: Rect,
887 ) {
888 let labels: Vec<String> = bars.iter().map(|bar| bar.label.clone()).collect();
889 let maximum = bars.iter().map(|bar| bar.value).fold(0., f64::max);
890 let with_axis = mode == BarDisplayMode::AbsoluteWithAxis;
891 let frame = horizontal_frame(pen, chart, area, &labels, maximum, with_axis);
892 let bar_height = HORIZONTAL_BAR_HEIGHT.min(frame.row_height * 0.7);
893 for (index, bar) in bars.iter().enumerate() {
894 let center = frame.row_center(index);
895 let right = frame.x(bar.value);
896 pen.rect(
897 Rect {
898 left: frame.plot.left,
899 top: center - bar_height / 2.,
900 right,
901 bottom: center + bar_height / 2.,
902 },
903 palette(bar.color),
904 BAR_RADIUS,
905 );
906 if chart.show_values || !with_axis {
907 pen.text(
908 &format_chart_value(bar.value),
909 right + 6.,
910 center - LABEL_LINE_HEIGHT / 2.,
911 LabelAlign::Left,
912 theme::text_strong(),
913 );
914 }
915 }
916 }
917
918 fn paint_part_to_whole(pen: &mut Pen, bars: &[ChartPoint], area: Rect) {
919 let total: f64 = bars.iter().map(|bar| bar.value.max(0.)).sum();
920 for (index, bar) in bars.iter().enumerate() {
921 let top = area.top + WHOLE_ROW_HEIGHT * index as f32;
922 let value_text = format_chart_value(bar.value);
923 let value_width = pen.text_width(&value_text);
924 let label = pen.fitted(&bar.label, area.width() - value_width - LEGEND_GAP);
925 pen.text(&label, area.left, top, LabelAlign::Left, theme::text_soft());
926 pen.text(
927 &value_text,
928 area.right,
929 top,
930 LabelAlign::Right,
931 theme::text_strong(),
932 );
933 let track = Rect {
934 left: area.left,
935 top: top + LABEL_LINE_HEIGHT + 6.,
936 right: area.right,
937 bottom: top + LABEL_LINE_HEIGHT + 6. + WHOLE_BAR_HEIGHT,
938 };
939 pen.rect(track, theme::surface_raised(), WHOLE_BAR_HEIGHT / 2.);
940 let share = unit_fraction(bar.value, 0., total);
941 pen.rect(
942 Rect {
943 right: track.left + track.width() * share,
944 ..track
945 },
946 palette(bar.color),
947 WHOLE_BAR_HEIGHT / 2.,
948 );
949 }
950 }
951
952 fn paint_stacked_rows(pen: &mut Pen, chart: &CardChart, rows: &[ChartSeries], area: Rect) {
953 let labels: Vec<String> = rows.iter().map(|row| row.legend.clone()).collect();
954 let maximum = rows
955 .iter()
956 .map(|row| {
957 row.points
958 .iter()
959 .map(|point| point.value.max(0.))
960 .sum::<f64>()
961 })
962 .fold(0., f64::max);
963 let frame = horizontal_frame(pen, chart, area, &labels, maximum, true);
964 let bar_height = HORIZONTAL_BAR_HEIGHT.min(frame.row_height * 0.7);
965 for (index, row) in rows.iter().enumerate() {
966 let center = frame.row_center(index);
967 let mut consumed = 0.;
968 for point in &row.points {
969 let start = frame.x(consumed);
970 consumed += point.value.max(0.);
971 let end = frame.x(consumed);
972 let fill = palette(point.color);
973 pen.rect(
974 Rect {
975 left: start,
976 top: center - bar_height / 2.,
977 right: (end - 1.).max(start),
978 bottom: center + bar_height / 2.,
979 },
980 fill,
981 0.,
982 );
983 if chart.show_values && end - start >= SEGMENT_LABEL_MIN_WIDTH {
984 pen.text(
985 &format_chart_value(point.value),
986 (start + end) / 2.,
987 center - LABEL_LINE_HEIGHT / 2.,
988 LabelAlign::Center,
989 label_color_on(fill),
990 );
991 }
992 }
993 }
994 }
995
996 fn half_arc_angle(full_circle_angle: f32) -> f32 {
997 PI + (full_circle_angle + FRAC_PI_2) / 2.
998 }
999
1000 fn label_color_on(fill: Hsla) -> Hsla {
1001 if fill.l > LIGHT_FILL_LUMINANCE {
1002 theme::color(DARK_LABEL)
1003 } else {
1004 theme::white()
1005 }
1006 }
1007
1008 fn palette(color: ChartColor) -> Hsla {
1009 theme::color(match color {
1010 ChartColor::Good => 0x3fb56f,
1011 ChartColor::Warning => 0xf2b33d,
1012 ChartColor::Attention => 0xe5484d,
1013 ChartColor::Neutral => 0x4a4a50,
1014 ChartColor::CategoricalRed => 0xe5484d,
1015 ChartColor::CategoricalPurple => 0x9b6bdc,
1016 ChartColor::CategoricalLavender => 0xb4a7f5,
1017 ChartColor::CategoricalBlue => 0x4f8cff,
1018 ChartColor::CategoricalLightBlue => 0x7cc4f7,
1019 ChartColor::CategoricalTeal => 0x2fb8a6,
1020 ChartColor::CategoricalGreen => 0x4cb86a,
1021 ChartColor::CategoricalLime => 0xa5d24a,
1022 ChartColor::CategoricalMarigold => 0xf0a830,
1023 ChartColor::Sequential1 => 0xc7dbff,
1024 ChartColor::Sequential2 => 0xa3c4fb,
1025 ChartColor::Sequential3 => 0x7eabf6,
1026 ChartColor::Sequential4 => 0x5b92ee,
1027 ChartColor::Sequential5 => 0x3f79e0,
1028 ChartColor::Sequential6 => 0x2e61c8,
1029 ChartColor::Sequential7 => 0x2a4fa3,
1030 ChartColor::Sequential8 => 0x253f80,
1031 ChartColor::DivergingBlue => 0x3b6fd6,
1032 ChartColor::DivergingLightBlue => 0x7fb2f0,
1033 ChartColor::DivergingCyan => 0x4cc3d9,
1034 ChartColor::DivergingTeal => 0x2fa89a,
1035 ChartColor::DivergingYellow => 0xe8d44d,
1036 ChartColor::DivergingPeach => 0xf2a679,
1037 ChartColor::DivergingLightRed => 0xea7a72,
1038 ChartColor::DivergingRed => 0xd64545,
1039 ChartColor::DivergingMaroon => 0x962b3a,
1040 ChartColor::DivergingGray => 0x8a8a92,
1041 })
1042 }
@@ -0,0 +1,1042 @@
1use std::collections::HashSet;
2use std::f32::consts::{FRAC_PI_2, PI, TAU};
3
4use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::{
8 BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint, ChartSeries,
9 GaugeValueFormat, format_chart_value, label_stride, nice_scale, series_categories,
10 series_maximum, series_value, slice_angles, unit_fraction,
11};
12
13use crate::theme;
14
15const CHART_HEIGHT: f32 = 200.;
16const GAUGE_HEIGHT: f32 = 136.;
17const GAUGE_MAX_RADIUS: f32 = 100.;
18const GAUGE_RING_RATIO: f32 = 0.72;
19const GAUGE_VALUE_SIZE: f32 = 22.;
20const GAUGE_MARKER_RADIUS: f32 = 6.;
21const DONUT_HOLE_RATIO: f32 = 0.58;
22const SLICE_GAP: f32 = 2.;
23const SLICE_LABEL_MIN_SWEEP: f32 = 0.32;
24const ARC_STEP: f32 = 0.05;
25const TITLE_SIZE: f32 = 13.5;
26const LABEL_SIZE: f32 = 11.;
27const LABEL_LINE_HEIGHT: f32 = 14.;
28const LEGEND_SIZE: f32 = 12.;
29const LEGEND_DOT: f32 = 8.;
30const LEGEND_GAP: f32 = 12.;
31const SECTION_GAP: f32 = 8.;
32const AXIS_TICK_TARGET: usize = 4;
33const AXIS_LABEL_GAP: f32 = 6.;
34const AXIS_TITLE_HEIGHT: f32 = 16.;
35const CATEGORY_LABEL_HEIGHT: f32 = 20.;
36const FRAME_PADDING: f32 = 8.;
37const VALUE_GUTTER: f32 = 40.;
38const LABEL_COLUMN_MAX_RATIO: f32 = 0.4;
39const BAR_SLOT_RATIO: f32 = 0.64;
40const BAR_MAX_WIDTH: f32 = 56.;
41const BAR_RADIUS: f32 = 2.;
42const GROUP_GAP: f32 = 2.;
43const HORIZONTAL_ROW_HEIGHT: f32 = 30.;
44const HORIZONTAL_BAR_HEIGHT: f32 = 18.;
45const WHOLE_ROW_HEIGHT: f32 = 46.;
46const WHOLE_BAR_HEIGHT: f32 = 10.;
47const SEGMENT_LABEL_MIN_WIDTH: f32 = 26.;
48const LINE_WIDTH: f32 = 2.;
49const MARKER_RADIUS: f32 = 3.5;
50const GRID_WIDTH: f32 = 1.;
51const ELLIPSIS: &str = "\u{2026}";
52const LIGHT_FILL_LUMINANCE: f32 = 0.62;
53const DARK_LABEL: u32 = 0x161617;
54
55#[derive(Clone, Copy)]
56struct Rect {
57 left: f32,
58 top: f32,
59 right: f32,
60 bottom: f32,
61}
62
63impl Rect {
64 fn from_bounds(bounds: Bounds<Pixels>) -> Rect {
65 Rect {
66 left: f32::from(bounds.origin.x),
67 top: f32::from(bounds.origin.y),
68 right: f32::from(bounds.origin.x + bounds.size.width),
69 bottom: f32::from(bounds.origin.y + bounds.size.height),
70 }
71 }
72
73 fn width(&self) -> f32 {
74 self.right - self.left
75 }
76
77 fn height(&self) -> f32 {
78 self.bottom - self.top
79 }
80
81 fn center_x(&self) -> f32 {
82 (self.left + self.right) / 2.
83 }
84
85 fn center_y(&self) -> f32 {
86 (self.top + self.bottom) / 2.
87 }
88
89 fn bounds(&self) -> Bounds<Pixels> {
90 Bounds::new(
91 point(px(self.left), px(self.top)),
92 size(px(self.width().max(0.)), px(self.height().max(0.))),
93 )
94 }
95}
96
97#[derive(Clone, Copy)]
98enum LabelAlign {
99 Left,
100 Center,
101 Right,
102}
103
104struct Pen<'a> {
105 window: &'a mut Window,
106 cx: &'a mut App,
107}
108
109impl Pen<'_> {
110 fn shape(&self, text: &str, size_pixels: f32, color: Hsla, weight: FontWeight) -> ShapedLine {
111 let mut font = self.window.text_style().font();
112 font.weight = weight;
113 let run = TextRun {
114 len: text.len(),
115 font,
116 color,
117 background_color: None,
118 underline: None,
119 strikethrough: None,
120 };
121 self.window
122 .text_system()
123 .shape_line(text.to_owned().into(), px(size_pixels), &[run], None)
124 }
125
126 fn text_width(&self, text: &str) -> f32 {
127 f32::from(
128 self.shape(text, LABEL_SIZE, theme::text_muted(), FontWeight::NORMAL)
129 .width,
130 )
131 }
132
133 fn text(&mut self, text: &str, x: f32, y: f32, align: LabelAlign, color: Hsla) {
134 self.sized_text(text, (x, y), align, color, LABEL_SIZE, FontWeight::NORMAL);
135 }
136
137 fn sized_text(
138 &mut self,
139 text: &str,
140 (x, y): (f32, f32),
141 align: LabelAlign,
142 color: Hsla,
143 size_pixels: f32,
144 weight: FontWeight,
145 ) {
146 if text.is_empty() {
147 return;
148 }
149 let line = self.shape(text, size_pixels, color, weight);
150 let width = f32::from(line.width);
151 let left = match align {
152 LabelAlign::Left => x,
153 LabelAlign::Center => x - width / 2.,
154 LabelAlign::Right => x - width,
155 };
156 let _ = line.paint(
157 point(px(left), px(y)),
158 px(size_pixels * 1.25),
159 TextAlign::Left,
160 None,
161 self.window,
162 self.cx,
163 );
164 }
165
166 fn fitted(&self, text: &str, max_width: f32) -> String {
167 if self.text_width(text) <= max_width {
168 return text.to_owned();
169 }
170 let characters: Vec<char> = text.chars().collect();
171 (1..characters.len())
172 .rev()
173 .map(|length| {
174 format!(
175 "{}{ELLIPSIS}",
176 characters[..length].iter().collect::<String>()
177 )
178 })
179 .find(|candidate| self.text_width(candidate) <= max_width)
180 .unwrap_or_else(|| ELLIPSIS.to_owned())
181 }
182
183 fn rect(&mut self, rect: Rect, color: Hsla, radius: f32) {
184 if rect.width() <= 0. || rect.height() <= 0. {
185 return;
186 }
187 self.window.paint_quad(quad(
188 rect.bounds(),
189 px(radius),
190 color,
191 px(0.),
192 transparent_black(),
193 BorderStyle::default(),
194 ));
195 }
196
197 fn circle(&mut self, x: f32, y: f32, radius: f32, color: Hsla) {
198 self.rect(
199 Rect {
200 left: x - radius,
201 top: y - radius,
202 right: x + radius,
203 bottom: y + radius,
204 },
205 color,
206 radius,
207 );
208 }
209
210 fn horizontal_line(&mut self, left: f32, right: f32, y: f32, color: Hsla) {
211 self.rect(
212 Rect {
213 left,
214 top: y - GRID_WIDTH / 2.,
215 right,
216 bottom: y + GRID_WIDTH / 2.,
217 },
218 color,
219 0.,
220 );
221 }
222
223 fn vertical_line(&mut self, x: f32, top: f32, bottom: f32, color: Hsla) {
224 self.rect(
225 Rect {
226 left: x - GRID_WIDTH / 2.,
227 top,
228 right: x + GRID_WIDTH / 2.,
229 bottom,
230 },
231 color,
232 0.,
233 );
234 }
235
236 fn polyline(&mut self, points: &[(f32, f32)], color: Hsla) {
237 let Some(((first_x, first_y), rest)) = points.split_first() else {
238 return;
239 };
240 let mut builder = PathBuilder::stroke(px(LINE_WIDTH));
241 builder.move_to(point(px(*first_x), px(*first_y)));
242 for (x, y) in rest {
243 builder.line_to(point(px(*x), px(*y)));
244 }
245 if let Ok(path) = builder.build() {
246 self.window.paint_path(path, color);
247 }
248 }
249
250 fn sector(&mut self, center: (f32, f32), radii: (f32, f32), angles: (f32, f32), color: Hsla) {
251 let (inner, outer) = radii;
252 let (start, end) = angles;
253 let steps = ((end - start).abs() / ARC_STEP).ceil().max(1.) as usize;
254 let arc_point = |radius: f32, step: usize| {
255 let angle = start + (end - start) * step as f32 / steps as f32;
256 point(
257 px(center.0 + radius * angle.cos()),
258 px(center.1 + radius * angle.sin()),
259 )
260 };
261 let mut builder = PathBuilder::fill();
262 builder.move_to(arc_point(outer, 0));
263 for step in 1..=steps {
264 builder.line_to(arc_point(outer, step));
265 }
266 if inner > 0. {
267 for step in (0..=steps).rev() {
268 builder.line_to(arc_point(inner, step));
269 }
270 } else {
271 builder.line_to(point(px(center.0), px(center.1)));
272 }
273 builder.close();
274 if let Ok(path) = builder.build() {
275 self.window.paint_path(path, color);
276 }
277 }
278}
279
280pub fn chart_view(chart: &CardChart) -> AnyElement {
281 let legend_entries = if chart.show_legend {
282 chart.legend_entries()
283 } else {
284 Vec::new()
285 };
286 let height = chart_height(chart);
287 let drawing_chart = chart.clone();
288 let drawing = canvas(
289 |_, _, _| (),
290 move |bounds, (), window, cx| {
291 paint_chart(&drawing_chart, bounds, &mut Pen { window, cx });
292 },
293 )
294 .h(px(height));
295 let side_legend = matches!(chart.kind, ChartKind::Donut(_) | ChartKind::Pie(_));
296 let body = if side_legend {
297 h_flex()
298 .w_full()
299 .items_center()
300 .gap(px(LEGEND_GAP))
301 .child(drawing.flex_1().min_w(px(0.)))
302 .child(legend_view(&legend_entries, true))
303 .into_any_element()
304 } else {
305 v_flex()
306 .w_full()
307 .gap(px(SECTION_GAP))
308 .child(drawing.w_full())
309 .child(legend_view(&legend_entries, false))
310 .into_any_element()
311 };
312 v_flex()
313 .w_full()
314 .gap(px(SECTION_GAP))
315 .when_some(chart.title.clone(), |column, title| {
316 column.child(
317 div()
318 .text_size(px(TITLE_SIZE))
319 .font_weight(FontWeight::SEMIBOLD)
320 .text_color(theme::text_strong())
321 .child(title),
322 )
323 })
324 .child(body)
325 .into_any_element()
326}
327
328fn legend_view(entries: &[(String, ChartColor)], vertical: bool) -> Div {
329 let container = if vertical {
330 v_flex().flex_none().gap(px(6.))
331 } else {
332 h_flex().flex_wrap().gap_x(px(LEGEND_GAP)).gap_y(px(4.))
333 };
334 container.children(entries.iter().map(|(label, color)| {
335 h_flex()
336 .gap(px(6.))
337 .items_center()
338 .text_size(px(LEGEND_SIZE))
339 .text_color(theme::text_muted())
340 .child(
341 div()
342 .flex_none()
343 .size(px(LEGEND_DOT))
344 .rounded(px(LEGEND_DOT / 2.))
345 .bg(palette(*color)),
346 )
347 .child(label.clone())
348 }))
349}
350
351fn chart_height(chart: &CardChart) -> f32 {
352 let title_rows = |has_axis_title: bool| {
353 if has_axis_title {
354 AXIS_TITLE_HEIGHT
355 } else {
356 0.
357 }
358 };
359 match &chart.kind {
360 ChartKind::Gauge(_) => GAUGE_HEIGHT,
361 ChartKind::HorizontalBar { bars, mode } => match mode {
362 BarDisplayMode::AbsoluteWithAxis => {
363 bars.len() as f32 * HORIZONTAL_ROW_HEIGHT
364 + CATEGORY_LABEL_HEIGHT
365 + title_rows(chart.y_axis_title.is_some())
366 + title_rows(chart.x_axis_title.is_some())
367 + FRAME_PADDING
368 }
369 BarDisplayMode::AbsoluteNoAxis => {
370 bars.len() as f32 * HORIZONTAL_ROW_HEIGHT
371 + title_rows(chart.x_axis_title.is_some())
372 + FRAME_PADDING
373 }
374 BarDisplayMode::PartToWhole => bars.len() as f32 * WHOLE_ROW_HEIGHT,
375 },
376 ChartKind::StackedHorizontalBar(rows) => {
377 rows.len() as f32 * HORIZONTAL_ROW_HEIGHT
378 + CATEGORY_LABEL_HEIGHT
379 + title_rows(chart.y_axis_title.is_some())
380 + title_rows(chart.x_axis_title.is_some())
381 + FRAME_PADDING
382 }
383 _ => CHART_HEIGHT,
384 }
385}
386
387fn paint_chart(chart: &CardChart, bounds: Bounds<Pixels>, pen: &mut Pen) {
388 let area = Rect::from_bounds(bounds);
389 match &chart.kind {
390 ChartKind::Donut(slices) => paint_slices(pen, slices, area, DONUT_HOLE_RATIO),
391 ChartKind::Pie(slices) => paint_slices(pen, slices, area, 0.),
392 ChartKind::Gauge(gauge) => paint_gauge(pen, gauge, area),
393 ChartKind::Line(series) => paint_lines(pen, chart, series, area),
394 ChartKind::VerticalBar(bars) => paint_vertical_bars(pen, chart, bars, area),
395 ChartKind::GroupedBar { series, stacked } => {
396 paint_grouped_bars(pen, chart, series, *stacked, area)
397 }
398 ChartKind::HorizontalBar { bars, mode } => match mode {
399 BarDisplayMode::PartToWhole => paint_part_to_whole(pen, bars, area),
400 _ => paint_horizontal_bars(pen, chart, bars, *mode, area),
401 },
402 ChartKind::StackedHorizontalBar(rows) => paint_stacked_rows(pen, chart, rows, area),
403 }
404}
405
406fn paint_slices(pen: &mut Pen, slices: &[ChartPoint], area: Rect, hole_ratio: f32) {
407 let radius = area.width().min(area.height()) / 2. - FRAME_PADDING / 2.;
408 if radius <= 0. {
409 return;
410 }
411 let center = (area.center_x(), area.center_y());
412 let inner = radius * hole_ratio;
413 let values: Vec<f64> = slices.iter().map(|slice| slice.value).collect();
414 let visible = values.iter().filter(|value| **value > 0.).count();
415 let gap = if visible > 1 { SLICE_GAP / radius } else { 0. };
416 for (slice, (start, end)) in slices.iter().zip(slice_angles(&values)) {
417 let sweep = end - start;
418 if sweep <= 0. {
419 continue;
420 }
421 let fill = palette(slice.color);
422 let trim = gap.min(sweep / 4.);
423 pen.sector(
424 center,
425 (inner, radius),
426 (start + trim / 2., end - trim / 2.),
427 fill,
428 );
429 if sweep >= SLICE_LABEL_MIN_SWEEP {
430 let middle = (start + end) / 2.;
431 let label_radius = (inner + radius) / 2.;
432 pen.sized_text(
433 &format_chart_value(slice.value),
434 (
435 center.0 + label_radius * middle.cos(),
436 center.1 + label_radius * middle.sin() - LABEL_LINE_HEIGHT / 2.,
437 ),
438 LabelAlign::Center,
439 label_color_on(fill),
440 LABEL_SIZE,
441 FontWeight::SEMIBOLD,
442 );
443 }
444 }
445}
446
447fn paint_gauge(pen: &mut Pen, gauge: &ChartGauge, area: Rect) {
448 let radius = (area.width() / 2. - FRAME_PADDING * 1.5).min(GAUGE_MAX_RADIUS);
449 if radius <= 0. {
450 return;
451 }
452 let center = (area.center_x(), area.top + FRAME_PADDING / 2. + radius);
453 let inner = radius * GAUGE_RING_RATIO;
454 let segment_total: f64 = gauge.segments.iter().map(|segment| segment.size).sum();
455 let fraction = unit_fraction(gauge.value, gauge.minimum, gauge.maximum);
456 if segment_total > 0. {
457 let sizes: Vec<f64> = gauge.segments.iter().map(|segment| segment.size).collect();
458 let gap = SLICE_GAP / radius;
459 for (segment, (start, end)) in gauge.segments.iter().zip(slice_angles(&sizes)) {
460 let (start, end) = (half_arc_angle(start), half_arc_angle(end));
461 let trim = gap.min((end - start) / 4.);
462 pen.sector(
463 center,
464 (inner, radius),
465 (start + trim / 2., end - trim / 2.),
466 palette(segment.color),
467 );
468 }
469 } else {
470 pen.sector(
471 center,
472 (inner, radius),
473 (PI, TAU),
474 palette(ChartColor::Neutral),
475 );
476 pen.sector(
477 center,
478 (inner, radius),
479 (PI, PI + PI * fraction),
480 palette(ChartColor::CategoricalBlue),
481 );
482 }
483 let marker_angle = PI + PI * fraction;
484 let marker_radius = (inner + radius) / 2.;
485 let marker = (
486 center.0 + marker_radius * marker_angle.cos(),
487 center.1 + marker_radius * marker_angle.sin(),
488 );
489 pen.circle(
490 marker.0,
491 marker.1,
492 GAUGE_MARKER_RADIUS,
493 theme::text_strong(),
494 );
495 pen.circle(
496 marker.0,
497 marker.1,
498 GAUGE_MARKER_RADIUS - 2.,
499 theme::surface(),
500 );
501 let value_text = match gauge.format {
502 GaugeValueFormat::Percentage => {
503 format!("{}%", format_chart_value((fraction * 100.).round() as f64))
504 }
505 GaugeValueFormat::Fraction => format!(
506 "{}/{}",
507 format_chart_value(gauge.value),
508 format_chart_value(gauge.maximum)
509 ),
510 };
511 pen.sized_text(
512 &value_text,
513 (center.0, center.1 - GAUGE_VALUE_SIZE * 1.1),
514 LabelAlign::Center,
515 theme::text_strong(),
516 GAUGE_VALUE_SIZE,
517 FontWeight::SEMIBOLD,
518 );
519 if let Some(sub_label) = &gauge.sub_label {
520 pen.text(
521 sub_label,
522 center.0,
523 center.1 + 4.,
524 LabelAlign::Center,
525 theme::text_muted(),
526 );
527 }
528 if gauge.show_min_max {
529 let end_offset = marker_radius;
530 let y = center.1 + 4.;
531 pen.text(
532 &format_chart_value(gauge.minimum),
533 center.0 - end_offset,
534 y,
535 LabelAlign::Center,
536 theme::text_muted(),
537 );
538 pen.text(
539 &format_chart_value(gauge.maximum),
540 center.0 + end_offset,
541 y,
542 LabelAlign::Center,
543 theme::text_muted(),
544 );
545 }
546}
547
548struct VerticalFrame {
549 plot: Rect,
550 slot_width: f32,
551 maximum: f64,
552}
553
554impl VerticalFrame {
555 fn slot_center(&self, index: usize) -> f32 {
556 self.plot.left + self.slot_width * (index as f32 + 0.5)
557 }
558
559 fn y(&self, value: f64) -> f32 {
560 self.plot.bottom - self.plot.height() * unit_fraction(value, 0., self.maximum)
561 }
562}
563
564fn vertical_frame(
565 pen: &mut Pen,
566 chart: &CardChart,
567 area: Rect,
568 categories: &[String],
569 maximum_value: f64,
570) -> VerticalFrame {
571 let scale = nice_scale(maximum_value, AXIS_TICK_TARGET);
572 let ticks = scale.ticks();
573 let tick_labels: Vec<String> = ticks.iter().map(|tick| format_chart_value(*tick)).collect();
574 let label_width = tick_labels
575 .iter()
576 .map(|label| pen.text_width(label))
577 .fold(0., f32::max);
578 let top_padding = if chart.y_axis_title.is_some() {
579 AXIS_TITLE_HEIGHT + FRAME_PADDING
580 } else {
581 FRAME_PADDING
582 };
583 let bottom_padding = CATEGORY_LABEL_HEIGHT
584 + if chart.x_axis_title.is_some() {
585 AXIS_TITLE_HEIGHT
586 } else {
587 0.
588 };
589 let plot = Rect {
590 left: area.left + label_width + AXIS_LABEL_GAP + FRAME_PADDING / 2.,
591 top: area.top + top_padding,
592 right: area.right - FRAME_PADDING,
593 bottom: area.bottom - bottom_padding,
594 };
595 let frame = VerticalFrame {
596 plot,
597 slot_width: plot.width() / categories.len().max(1) as f32,
598 maximum: scale.maximum,
599 };
600 if let Some(title) = &chart.y_axis_title {
601 pen.text(
602 title,
603 area.left,
604 area.top,
605 LabelAlign::Left,
606 theme::text_muted(),
607 );
608 }
609 for (tick, label) in ticks.iter().zip(&tick_labels) {
610 let y = frame.y(*tick);
611 let line_color = if *tick == 0. {
612 theme::border_strong()
613 } else {
614 theme::border()
615 };
616 pen.horizontal_line(plot.left, plot.right, y, line_color);
617 pen.text(
618 label,
619 plot.left - AXIS_LABEL_GAP,
620 y - LABEL_LINE_HEIGHT / 2.,
621 LabelAlign::Right,
622 theme::text_muted(),
623 );
624 }
625 let widest_category = categories
626 .iter()
627 .map(|category| pen.text_width(category))
628 .fold(0., f32::max);
629 let stride = label_stride(
630 categories.len(),
631 frame.slot_width,
632 widest_category + AXIS_LABEL_GAP,
633 );
634 let fitted: Vec<String> = categories
635 .iter()
636 .map(|category| pen.fitted(category, frame.slot_width - AXIS_LABEL_GAP))
637 .collect();
638 let fitted_are_unique = fitted.iter().collect::<HashSet<_>>().len() == categories.len();
639 let (labels, stride) = if stride > 1 && fitted_are_unique {
640 (fitted.as_slice(), 1)
641 } else {
642 (categories, stride)
643 };
644 for (index, label) in labels.iter().enumerate().step_by(stride) {
645 pen.text(
646 label,
647 frame.slot_center(index),
648 plot.bottom + 4.,
649 LabelAlign::Center,
650 theme::text_muted(),
651 );
652 }
653 if let Some(title) = &chart.x_axis_title {
654 pen.text(
655 title,
656 plot.center_x(),
657 area.bottom - AXIS_TITLE_HEIGHT + 2.,
658 LabelAlign::Center,
659 theme::text_muted(),
660 );
661 }
662 frame
663}
664
665fn paint_bar_value(pen: &mut Pen, value: f64, x: f32, top: f32) {
666 pen.text(
667 &format_chart_value(value),
668 x,
669 top - LABEL_LINE_HEIGHT - 1.,
670 LabelAlign::Center,
671 theme::text_strong(),
672 );
673}
674
675fn paint_vertical_bars(pen: &mut Pen, chart: &CardChart, bars: &[ChartPoint], area: Rect) {
676 let categories: Vec<String> = bars.iter().map(|bar| bar.label.clone()).collect();
677 let maximum = bars.iter().map(|bar| bar.value).fold(0., f64::max);
678 let frame = vertical_frame(pen, chart, area, &categories, maximum);
679 let bar_width = (frame.slot_width * BAR_SLOT_RATIO).min(BAR_MAX_WIDTH);
680 for (index, bar) in bars.iter().enumerate() {
681 let center = frame.slot_center(index);
682 let top = frame.y(bar.value);
683 pen.rect(
684 Rect {
685 left: center - bar_width / 2.,
686 top,
687 right: center + bar_width / 2.,
688 bottom: frame.plot.bottom,
689 },
690 palette(bar.color),
691 BAR_RADIUS,
692 );
693 if chart.show_values {
694 paint_bar_value(pen, bar.value, center, top);
695 }
696 }
697}
698
699fn paint_grouped_bars(
700 pen: &mut Pen,
701 chart: &CardChart,
702 series: &[ChartSeries],
703 stacked: bool,
704 area: Rect,
705) {
706 let categories = series_categories(series);
707 let frame = vertical_frame(
708 pen,
709 chart,
710 area,
711 &categories,
712 series_maximum(series, stacked),
713 );
714 let group_width =
715 (frame.slot_width * BAR_SLOT_RATIO).min(BAR_MAX_WIDTH * series.len().max(1) as f32);
716 let bar_width = if stacked {
717 group_width.min(BAR_MAX_WIDTH)
718 } else {
719 group_width / series.len().max(1) as f32
720 };
721 for (index, category) in categories.iter().enumerate() {
722 let center = frame.slot_center(index);
723 let mut stack_total = 0.;
724 for (series_index, entry) in series.iter().enumerate() {
725 let value = series_value(entry, category).max(0.);
726 let (left, bottom_value, top_value) = if stacked {
727 let base = stack_total;
728 stack_total += value;
729 (center - bar_width / 2., base, stack_total)
730 } else {
731 let left = center - group_width / 2. + bar_width * series_index as f32;
732 (left, 0., value)
733 };
734 let gap = if stacked { 0. } else { GROUP_GAP / 2. };
735 pen.rect(
736 Rect {
737 left: left + gap,
738 top: frame.y(top_value),
739 right: left + bar_width - gap,
740 bottom: frame.y(bottom_value),
741 },
742 palette(entry.color),
743 if stacked { 0. } else { BAR_RADIUS },
744 );
745 if chart.show_values && !stacked {
746 paint_bar_value(pen, value, left + bar_width / 2., frame.y(value));
747 }
748 }
749 }
750}
751
752fn paint_lines(pen: &mut Pen, chart: &CardChart, series: &[ChartSeries], area: Rect) {
753 let categories = series_categories(series);
754 let frame = vertical_frame(pen, chart, area, &categories, series_maximum(series, false));
755 for entry in series {
756 let color = palette(entry.color);
757 let points: Vec<(f32, f32)> = categories
758 .iter()
759 .enumerate()
760 .filter(|(_, category)| entry.points.iter().any(|point| point.label == **category))
761 .map(|(index, category)| {
762 (
763 frame.slot_center(index),
764 frame.y(series_value(entry, category)),
765 )
766 })
767 .collect();
768 pen.polyline(&points, color);
769 for (x, y) in &points {
770 pen.circle(*x, *y, MARKER_RADIUS + 1.5, theme::surface());
771 pen.circle(*x, *y, MARKER_RADIUS, color);
772 }
773 }
774}
775
776struct HorizontalFrame {
777 plot: Rect,
778 row_height: f32,
779 maximum: f64,
780}
781
782impl HorizontalFrame {
783 fn row_center(&self, index: usize) -> f32 {
784 self.plot.top + self.row_height * (index as f32 + 0.5)
785 }
786
787 fn x(&self, value: f64) -> f32 {
788 self.plot.left + self.plot.width() * unit_fraction(value, 0., self.maximum)
789 }
790}
791
792fn horizontal_frame(
793 pen: &mut Pen,
794 chart: &CardChart,
795 area: Rect,
796 labels: &[String],
797 maximum_value: f64,
798 with_axis: bool,
799) -> HorizontalFrame {
800 let scale = nice_scale(maximum_value, AXIS_TICK_TARGET);
801 let widest_label = labels
802 .iter()
803 .map(|label| pen.text_width(label))
804 .fold(0., f32::max);
805 let label_width = widest_label.min(area.width() * LABEL_COLUMN_MAX_RATIO);
806 let top_padding = if chart.x_axis_title.is_some() {
807 AXIS_TITLE_HEIGHT
808 } else {
809 FRAME_PADDING / 2.
810 };
811 let bottom_padding = if with_axis {
812 CATEGORY_LABEL_HEIGHT
813 + if chart.y_axis_title.is_some() {
814 AXIS_TITLE_HEIGHT
815 } else {
816 0.
817 }
818 } else {
819 FRAME_PADDING / 2.
820 };
821 let plot = Rect {
822 left: area.left + label_width + AXIS_LABEL_GAP * 2.,
823 top: area.top + top_padding,
824 right: area.right - VALUE_GUTTER,
825 bottom: area.bottom - bottom_padding,
826 };
827 let frame = HorizontalFrame {
828 plot,
829 row_height: plot.height() / labels.len().max(1) as f32,
830 maximum: scale.maximum,
831 };
832 if let Some(title) = &chart.x_axis_title {
833 pen.text(
834 title,
835 area.left,
836 area.top,
837 LabelAlign::Left,
838 theme::text_muted(),
839 );
840 }
841 if with_axis {
842 for tick in scale.ticks() {
843 let x = frame.x(tick);
844 let line_color = if tick == 0. {
845 theme::border_strong()
846 } else {
847 theme::border()
848 };
849 pen.vertical_line(x, plot.top, plot.bottom, line_color);
850 pen.text(
851 &format_chart_value(tick),
852 x,
853 plot.bottom + 4.,
854 LabelAlign::Center,
855 theme::text_muted(),
856 );
857 }
858 if let Some(title) = &chart.y_axis_title {
859 pen.text(
860 title,
861 plot.center_x(),
862 area.bottom - AXIS_TITLE_HEIGHT + 2.,
863 LabelAlign::Center,
864 theme::text_muted(),
865 );
866 }
867 }
868 for (index, label) in labels.iter().enumerate() {
869 let fitted = pen.fitted(label, label_width);
870 pen.text(
871 &fitted,
872 plot.left - AXIS_LABEL_GAP,
873 frame.row_center(index) - LABEL_LINE_HEIGHT / 2.,
874 LabelAlign::Right,
875 theme::text_soft(),
876 );
877 }
878 frame
879}
880
881fn paint_horizontal_bars(
882 pen: &mut Pen,
883 chart: &CardChart,
884 bars: &[ChartPoint],
885 mode: BarDisplayMode,
886 area: Rect,
887) {
888 let labels: Vec<String> = bars.iter().map(|bar| bar.label.clone()).collect();
889 let maximum = bars.iter().map(|bar| bar.value).fold(0., f64::max);
890 let with_axis = mode == BarDisplayMode::AbsoluteWithAxis;
891 let frame = horizontal_frame(pen, chart, area, &labels, maximum, with_axis);
892 let bar_height = HORIZONTAL_BAR_HEIGHT.min(frame.row_height * 0.7);
893 for (index, bar) in bars.iter().enumerate() {
894 let center = frame.row_center(index);
895 let right = frame.x(bar.value);
896 pen.rect(
897 Rect {
898 left: frame.plot.left,
899 top: center - bar_height / 2.,
900 right,
901 bottom: center + bar_height / 2.,
902 },
903 palette(bar.color),
904 BAR_RADIUS,
905 );
906 if chart.show_values || !with_axis {
907 pen.text(
908 &format_chart_value(bar.value),
909 right + 6.,
910 center - LABEL_LINE_HEIGHT / 2.,
911 LabelAlign::Left,
912 theme::text_strong(),
913 );
914 }
915 }
916}
917
918fn paint_part_to_whole(pen: &mut Pen, bars: &[ChartPoint], area: Rect) {
919 let total: f64 = bars.iter().map(|bar| bar.value.max(0.)).sum();
920 for (index, bar) in bars.iter().enumerate() {
921 let top = area.top + WHOLE_ROW_HEIGHT * index as f32;
922 let value_text = format_chart_value(bar.value);
923 let value_width = pen.text_width(&value_text);
924 let label = pen.fitted(&bar.label, area.width() - value_width - LEGEND_GAP);
925 pen.text(&label, area.left, top, LabelAlign::Left, theme::text_soft());
926 pen.text(
927 &value_text,
928 area.right,
929 top,
930 LabelAlign::Right,
931 theme::text_strong(),
932 );
933 let track = Rect {
934 left: area.left,
935 top: top + LABEL_LINE_HEIGHT + 6.,
936 right: area.right,
937 bottom: top + LABEL_LINE_HEIGHT + 6. + WHOLE_BAR_HEIGHT,
938 };
939 pen.rect(track, theme::surface_raised(), WHOLE_BAR_HEIGHT / 2.);
940 let share = unit_fraction(bar.value, 0., total);
941 pen.rect(
942 Rect {
943 right: track.left + track.width() * share,
944 ..track
945 },
946 palette(bar.color),
947 WHOLE_BAR_HEIGHT / 2.,
948 );
949 }
950}
951
952fn paint_stacked_rows(pen: &mut Pen, chart: &CardChart, rows: &[ChartSeries], area: Rect) {
953 let labels: Vec<String> = rows.iter().map(|row| row.legend.clone()).collect();
954 let maximum = rows
955 .iter()
956 .map(|row| {
957 row.points
958 .iter()
959 .map(|point| point.value.max(0.))
960 .sum::<f64>()
961 })
962 .fold(0., f64::max);
963 let frame = horizontal_frame(pen, chart, area, &labels, maximum, true);
964 let bar_height = HORIZONTAL_BAR_HEIGHT.min(frame.row_height * 0.7);
965 for (index, row) in rows.iter().enumerate() {
966 let center = frame.row_center(index);
967 let mut consumed = 0.;
968 for point in &row.points {
969 let start = frame.x(consumed);
970 consumed += point.value.max(0.);
971 let end = frame.x(consumed);
972 let fill = palette(point.color);
973 pen.rect(
974 Rect {
975 left: start,
976 top: center - bar_height / 2.,
977 right: (end - 1.).max(start),
978 bottom: center + bar_height / 2.,
979 },
980 fill,
981 0.,
982 );
983 if chart.show_values && end - start >= SEGMENT_LABEL_MIN_WIDTH {
984 pen.text(
985 &format_chart_value(point.value),
986 (start + end) / 2.,
987 center - LABEL_LINE_HEIGHT / 2.,
988 LabelAlign::Center,
989 label_color_on(fill),
990 );
991 }
992 }
993 }
994}
995
996fn half_arc_angle(full_circle_angle: f32) -> f32 {
997 PI + (full_circle_angle + FRAC_PI_2) / 2.
998}
999
1000fn label_color_on(fill: Hsla) -> Hsla {
1001 if fill.l > LIGHT_FILL_LUMINANCE {
1002 theme::color(DARK_LABEL)
1003 } else {
1004 theme::white()
1005 }
1006}
1007
1008fn palette(color: ChartColor) -> Hsla {
1009 theme::color(match color {
1010 ChartColor::Good => 0x3fb56f,
1011 ChartColor::Warning => 0xf2b33d,
1012 ChartColor::Attention => 0xe5484d,
1013 ChartColor::Neutral => 0x4a4a50,
1014 ChartColor::CategoricalRed => 0xe5484d,
1015 ChartColor::CategoricalPurple => 0x9b6bdc,
1016 ChartColor::CategoricalLavender => 0xb4a7f5,
1017 ChartColor::CategoricalBlue => 0x4f8cff,
1018 ChartColor::CategoricalLightBlue => 0x7cc4f7,
1019 ChartColor::CategoricalTeal => 0x2fb8a6,
1020 ChartColor::CategoricalGreen => 0x4cb86a,
1021 ChartColor::CategoricalLime => 0xa5d24a,
1022 ChartColor::CategoricalMarigold => 0xf0a830,
1023 ChartColor::Sequential1 => 0xc7dbff,
1024 ChartColor::Sequential2 => 0xa3c4fb,
1025 ChartColor::Sequential3 => 0x7eabf6,
1026 ChartColor::Sequential4 => 0x5b92ee,
1027 ChartColor::Sequential5 => 0x3f79e0,
1028 ChartColor::Sequential6 => 0x2e61c8,
1029 ChartColor::Sequential7 => 0x2a4fa3,
1030 ChartColor::Sequential8 => 0x253f80,
1031 ChartColor::DivergingBlue => 0x3b6fd6,
1032 ChartColor::DivergingLightBlue => 0x7fb2f0,
1033 ChartColor::DivergingCyan => 0x4cc3d9,
1034 ChartColor::DivergingTeal => 0x2fa89a,
1035 ChartColor::DivergingYellow => 0xe8d44d,
1036 ChartColor::DivergingPeach => 0xf2a679,
1037 ChartColor::DivergingLightRed => 0xea7a72,
1038 ChartColor::DivergingRed => 0xd64545,
1039 ChartColor::DivergingMaroon => 0x962b3a,
1040 ChartColor::DivergingGray => 0x8a8a92,
1041 })
1042}
crates/app/src/views/card_code_block.rs added +140 −0
@@ -0,0 +1,140 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::tooltip::Tooltip;
3 use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
4 use gpui_kit::prelude::FluentBuilder as _;
5 use gpui_kit::*;
6 use teams_core::CardCodeBlock;
7
8 use super::adaptive_card::{CardContext, slot_handler};
9 use super::widgets::icon;
10 use crate::theme;
11
12 const COLLAPSED_LINES: usize = 10;
13 const CODE_TEXT_SIZE: f32 = 12.5;
14 const CODE_LINE_HEIGHT: f32 = 1.45;
15 const CODE_RADIUS: f32 = 6.;
16 const CODE_PADDING: f32 = 8.;
17 const HEADER_PADDING_X: f32 = 10.;
18 const HEADER_PADDING_Y: f32 = 4.;
19 const GUTTER_DIGIT_WIDTH: f32 = 8.;
20 const GUTTER_GAP: f32 = 12.;
21 const COPY_ICON_SIZE: f32 = 14.;
22 const TAB_REPLACEMENT: &str = " ";
23 const COPY_TOOLTIP: &str = "Copy code";
24
25 pub(super) fn code_block_view(
26 block: &CardCodeBlock,
27 id: &str,
28 context: &CardContext,
29 ) -> AnyElement {
30 let lines: Vec<String> = block
31 .code
32 .lines()
33 .map(|line| line.replace('\t', TAB_REPLACEMENT))
34 .collect();
35 let expanded_key = format!("{id}-expanded");
36 let expanded = context.state.slot(&expanded_key, 0) == 1;
37 let hidden = lines.len().saturating_sub(COLLAPSED_LINES);
38 let shown = if expanded {
39 lines.len()
40 } else {
41 lines.len().min(COLLAPSED_LINES)
42 };
43 let last_number = block.start_line + lines.len().saturating_sub(1);
44 let gutter_width = last_number.to_string().len() as f32 * GUTTER_DIGIT_WIDTH;
45 let code = block.code.clone();
46 let toggle = slot_handler(context, &expanded_key, usize::from(!expanded));
47 v_flex()
48 .w_full()
49 .overflow_hidden()
50 .rounded(px(CODE_RADIUS))
51 .bg(theme::code_surface())
52 .border_1()
53 .border_color(theme::code_header_border())
54 .child(
55 h_flex()
56 .w_full()
57 .justify_between()
58 .items_center()
59 .px(px(HEADER_PADDING_X))
60 .py(px(HEADER_PADDING_Y))
61 .border_b_1()
62 .border_color(theme::code_header_border())
63 .text_size(px(11.5))
64 .text_color(theme::text_muted())
65 .child(block.language.clone().unwrap_or_default())
66 .child(
67 div()
68 .id(ElementId::Name(format!("{id}-copy").into()))
69 .cursor_pointer()
70 .p(px(2.))
71 .rounded(px(4.))
72 .hover(|button| button.bg(theme::row_hover()))
73 .tooltip(|window, cx| Tooltip::new(COPY_TOOLTIP).build(window, cx))
74 .on_click(move |_, _, cx| {
75 cx.stop_propagation();
76 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
77 })
78 .child(icon(IconName::Copy, COPY_ICON_SIZE, theme::text_muted())),
79 ),
80 )
81 .child(
82 v_flex()
83 .w_full()
84 .p(px(CODE_PADDING))
85 .font_family(context.cx.theme().mono_font_family.clone())
86 .text_size(px(CODE_TEXT_SIZE))
87 .line_height(relative(CODE_LINE_HEIGHT))
88 .children(lines.iter().take(shown).enumerate().map(|(offset, line)| {
89 h_flex()
90 .w_full()
91 .gap(px(GUTTER_GAP))
92 .child(
93 div()
94 .w(px(gutter_width))
95 .flex_none()
96 .text_right()
97 .text_color(theme::text_faint())
98 .child((block.start_line + offset).to_string()),
99 )
100 .child(
101 div()
102 .flex_1()
103 .min_w(px(0.))
104 .overflow_hidden()
105 .whitespace_nowrap()
106 .text_color(theme::text_strong())
107 .child(if line.is_empty() {
108 " ".to_owned()
109 } else {
110 line.clone()
111 }),
112 )
113 })),
114 )
115 .when(hidden > 0, |frame| {
116 frame.child(
117 div()
118 .id(ElementId::Name(format!("{id}-expand").into()))
119 .w_full()
120 .px(px(HEADER_PADDING_X))
121 .py(px(HEADER_PADDING_Y))
122 .border_t_1()
123 .border_color(theme::code_header_border())
124 .text_size(px(12.))
125 .text_color(theme::accent_text())
126 .cursor_pointer()
127 .hover(|footer| footer.bg(theme::row_hover()))
128 .on_click(move |_, _, cx| {
129 cx.stop_propagation();
130 toggle(cx)
131 })
132 .child(if expanded {
133 "Collapse".to_owned()
134 } else {
135 format!("Expand ({hidden} more lines)")
136 }),
137 )
138 })
139 .into_any_element()
140 }
@@ -0,0 +1,140 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::tooltip::Tooltip;
3use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use teams_core::CardCodeBlock;
7
8use super::adaptive_card::{CardContext, slot_handler};
9use super::widgets::icon;
10use crate::theme;
11
12const COLLAPSED_LINES: usize = 10;
13const CODE_TEXT_SIZE: f32 = 12.5;
14const CODE_LINE_HEIGHT: f32 = 1.45;
15const CODE_RADIUS: f32 = 6.;
16const CODE_PADDING: f32 = 8.;
17const HEADER_PADDING_X: f32 = 10.;
18const HEADER_PADDING_Y: f32 = 4.;
19const GUTTER_DIGIT_WIDTH: f32 = 8.;
20const GUTTER_GAP: f32 = 12.;
21const COPY_ICON_SIZE: f32 = 14.;
22const TAB_REPLACEMENT: &str = " ";
23const COPY_TOOLTIP: &str = "Copy code";
24
25pub(super) fn code_block_view(
26 block: &CardCodeBlock,
27 id: &str,
28 context: &CardContext,
29) -> AnyElement {
30 let lines: Vec<String> = block
31 .code
32 .lines()
33 .map(|line| line.replace('\t', TAB_REPLACEMENT))
34 .collect();
35 let expanded_key = format!("{id}-expanded");
36 let expanded = context.state.slot(&expanded_key, 0) == 1;
37 let hidden = lines.len().saturating_sub(COLLAPSED_LINES);
38 let shown = if expanded {
39 lines.len()
40 } else {
41 lines.len().min(COLLAPSED_LINES)
42 };
43 let last_number = block.start_line + lines.len().saturating_sub(1);
44 let gutter_width = last_number.to_string().len() as f32 * GUTTER_DIGIT_WIDTH;
45 let code = block.code.clone();
46 let toggle = slot_handler(context, &expanded_key, usize::from(!expanded));
47 v_flex()
48 .w_full()
49 .overflow_hidden()
50 .rounded(px(CODE_RADIUS))
51 .bg(theme::code_surface())
52 .border_1()
53 .border_color(theme::code_header_border())
54 .child(
55 h_flex()
56 .w_full()
57 .justify_between()
58 .items_center()
59 .px(px(HEADER_PADDING_X))
60 .py(px(HEADER_PADDING_Y))
61 .border_b_1()
62 .border_color(theme::code_header_border())
63 .text_size(px(11.5))
64 .text_color(theme::text_muted())
65 .child(block.language.clone().unwrap_or_default())
66 .child(
67 div()
68 .id(ElementId::Name(format!("{id}-copy").into()))
69 .cursor_pointer()
70 .p(px(2.))
71 .rounded(px(4.))
72 .hover(|button| button.bg(theme::row_hover()))
73 .tooltip(|window, cx| Tooltip::new(COPY_TOOLTIP).build(window, cx))
74 .on_click(move |_, _, cx| {
75 cx.stop_propagation();
76 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
77 })
78 .child(icon(IconName::Copy, COPY_ICON_SIZE, theme::text_muted())),
79 ),
80 )
81 .child(
82 v_flex()
83 .w_full()
84 .p(px(CODE_PADDING))
85 .font_family(context.cx.theme().mono_font_family.clone())
86 .text_size(px(CODE_TEXT_SIZE))
87 .line_height(relative(CODE_LINE_HEIGHT))
88 .children(lines.iter().take(shown).enumerate().map(|(offset, line)| {
89 h_flex()
90 .w_full()
91 .gap(px(GUTTER_GAP))
92 .child(
93 div()
94 .w(px(gutter_width))
95 .flex_none()
96 .text_right()
97 .text_color(theme::text_faint())
98 .child((block.start_line + offset).to_string()),
99 )
100 .child(
101 div()
102 .flex_1()
103 .min_w(px(0.))
104 .overflow_hidden()
105 .whitespace_nowrap()
106 .text_color(theme::text_strong())
107 .child(if line.is_empty() {
108 " ".to_owned()
109 } else {
110 line.clone()
111 }),
112 )
113 })),
114 )
115 .when(hidden > 0, |frame| {
116 frame.child(
117 div()
118 .id(ElementId::Name(format!("{id}-expand").into()))
119 .w_full()
120 .px(px(HEADER_PADDING_X))
121 .py(px(HEADER_PADDING_Y))
122 .border_t_1()
123 .border_color(theme::code_header_border())
124 .text_size(px(12.))
125 .text_color(theme::accent_text())
126 .cursor_pointer()
127 .hover(|footer| footer.bg(theme::row_hover()))
128 .on_click(move |_, _, cx| {
129 cx.stop_propagation();
130 toggle(cx)
131 })
132 .child(if expanded {
133 "Collapse".to_owned()
134 } else {
135 format!("Expand ({hidden} more lines)")
136 }),
137 )
138 })
139 .into_any_element()
140}
crates/app/src/views/card_icon.rs added +212 −0
@@ -0,0 +1,212 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::*;
3 use teams_core::{CardActionIcon, CardIcon, IconSize};
4
5 use super::adaptive_card::card_color;
6 use super::widgets::icon;
7 use crate::theme;
8
9 const ACTION_ICON_SIZE: f32 = 16.;
10 const UNKNOWN_GLYPH_RATIO: f32 = 0.45;
11 const UNKNOWN_GLYPH_RADIUS: f32 = 2.;
12 const GLYPH_RATIO: f32 = 0.85;
13 const STYLE_SUFFIXES: [&str; 2] = ["regular", "filled"];
14
15 const FLUENT_ICONS: &[(&str, IconName)] = &[
16 ("add", IconName::Plus),
17 ("alert", IconName::Bell),
18 ("arrowdown", IconName::ArrowDown),
19 ("arrowup", IconName::ArrowUp),
20 ("arrowleft", IconName::ArrowLeft),
21 ("arrowright", IconName::ArrowRight),
22 ("arrowdownload", IconName::Download),
23 ("arrowupload", IconName::Upload),
24 ("arrowsync", IconName::RefreshCw),
25 ("arrowclockwise", IconName::RotateCw),
26 ("arrowrepeatall", IconName::RefreshCw),
27 ("attach", IconName::Paperclip),
28 ("bookmark", IconName::Bookmark),
29 ("briefcase", IconName::Briefcase),
30 ("building", IconName::Building),
31 ("calendar", IconName::Calendar),
32 ("calendarltr", IconName::Calendar),
33 ("calendardate", IconName::Calendar),
34 ("calendarclock", IconName::CalendarClock),
35 ("camera", IconName::Camera),
36 ("chat", IconName::MessageSquare),
37 ("comment", IconName::MessageSquare),
38 ("commentmultiple", IconName::MessageSquare),
39 ("chartmultiple", IconName::ChartBar),
40 ("checkmark", IconName::Check),
41 ("checkmarkcircle", IconName::CircleCheck),
42 ("chevrondown", IconName::ChevronDown),
43 ("chevronup", IconName::ChevronUp),
44 ("chevronleft", IconName::ChevronLeft),
45 ("chevronright", IconName::ChevronRight),
46 ("clipboard", IconName::Clipboard),
47 ("clock", IconName::Clock),
48 ("cloud", IconName::Cloud),
49 ("code", IconName::Code),
50 ("copy", IconName::Copy),
51 ("database", IconName::Database),
52 ("delete", IconName::Trash),
53 ("dismiss", IconName::X),
54 ("dismisscircle", IconName::CircleX),
55 ("document", IconName::File),
56 ("documenttext", IconName::FileText),
57 ("edit", IconName::Pencil),
58 ("errorcircle", IconName::CircleAlert),
59 ("eye", IconName::Eye),
60 ("eyeoff", IconName::EyeOff),
61 ("flag", IconName::Flag),
62 ("flash", IconName::Zap),
63 ("folder", IconName::Folder),
64 ("gift", IconName::Gift),
65 ("globe", IconName::Globe),
66 ("heart", IconName::Heart),
67 ("home", IconName::House),
68 ("image", IconName::Image),
69 ("info", IconName::Info),
70 ("key", IconName::Key),
71 ("link", IconName::Link),
72 ("list", IconName::List),
73 ("location", IconName::MapPin),
74 ("lock", IconName::Lock),
75 ("lockclosed", IconName::Lock),
76 ("mail", IconName::Mail),
77 ("megaphone", IconName::Megaphone),
78 ("mic", IconName::Mic),
79 ("money", IconName::DollarSign),
80 ("open", IconName::ExternalLink),
81 ("people", IconName::Users),
82 ("peoplecommunity", IconName::Users),
83 ("person", IconName::User),
84 ("personadd", IconName::UserPlus),
85 ("personcircle", IconName::CircleUser),
86 ("phone", IconName::Phone),
87 ("pin", IconName::Pin),
88 ("play", IconName::Play),
89 ("question", IconName::CircleQuestionMark),
90 ("questioncircle", IconName::CircleQuestionMark),
91 ("rocket", IconName::Rocket),
92 ("search", IconName::Search),
93 ("send", IconName::Send),
94 ("settings", IconName::Settings),
95 ("share", IconName::Share),
96 ("shield", IconName::Shield),
97 ("shieldcheckmark", IconName::ShieldCheck),
98 ("star", IconName::Star),
99 ("table", IconName::Table),
100 ("tag", IconName::Tag),
101 ("target", IconName::Target),
102 ("thumbdislike", IconName::ThumbsDown),
103 ("thumblike", IconName::ThumbsUp),
104 ("timer", IconName::Timer),
105 ("trophy", IconName::Trophy),
106 ("video", IconName::Video),
107 ("warning", IconName::TriangleAlert),
108 ("wrench", IconName::Wrench),
109 ("task", IconName::ClipboardCheck),
110 ];
111
112 pub fn fluent_icon(name: &str) -> Option<IconName> {
113 let mut key = name.trim().to_ascii_lowercase();
114 for suffix in STYLE_SUFFIXES {
115 if let Some(stripped) = key.strip_suffix(suffix) {
116 key = stripped.to_owned();
117 }
118 }
119 let key = key.trim_end_matches(|character: char| character.is_ascii_digit());
120 FLUENT_ICONS
121 .iter()
122 .find(|(known, _)| *known == key)
123 .map(|(_, glyph)| *glyph)
124 }
125
126 pub fn icon_pixels(size: IconSize) -> f32 {
127 match size {
128 IconSize::ExtraExtraSmall => 12.,
129 IconSize::ExtraSmall => 16.,
130 IconSize::Small => 20.,
131 IconSize::Standard => 24.,
132 IconSize::Medium => 32.,
133 IconSize::Large => 48.,
134 IconSize::ExtraLarge => 64.,
135 IconSize::ExtraExtraLarge => 72.,
136 }
137 }
138
139 pub fn icon_view(card_icon: &CardIcon) -> AnyElement {
140 glyph_view(
141 &card_icon.name,
142 icon_pixels(card_icon.size),
143 card_color(card_icon.color, false),
144 )
145 }
146
147 pub fn action_icon_view(action_icon: &CardActionIcon) -> AnyElement {
148 match action_icon {
149 CardActionIcon::Named(name) => glyph_view(name, ACTION_ICON_SIZE, theme::accent_text()),
150 CardActionIcon::Url(url) => img(url.clone())
151 .size(px(ACTION_ICON_SIZE))
152 .flex_none()
153 .object_fit(ObjectFit::Contain)
154 .with_loading(|| div().into_any_element())
155 .with_fallback(|| div().into_any_element())
156 .into_any_element(),
157 }
158 }
159
160 pub(super) fn glyph_view(name: &str, size: f32, color: Hsla) -> AnyElement {
161 let frame = div()
162 .size(px(size))
163 .flex_none()
164 .flex()
165 .items_center()
166 .justify_center();
167 match fluent_icon(name) {
168 Some(glyph) => frame
169 .child(icon(glyph, size * GLYPH_RATIO, color))
170 .into_any_element(),
171 None => frame
172 .child(
173 div()
174 .size(px(size * UNKNOWN_GLYPH_RATIO))
175 .rounded(px(UNKNOWN_GLYPH_RADIUS))
176 .bg(theme::text_muted()),
177 )
178 .into_any_element(),
179 }
180 }
181
182 #[cfg(test)]
183 mod tests {
184 use gpui_kit::assets::IconName;
185 use teams_core::IconSize;
186
187 use super::{fluent_icon, icon_pixels};
188
189 #[test]
190 fn fluent_names_map_ignoring_case_style_and_size_suffixes() {
191 assert_eq!(fluent_icon("Calendar"), Some(IconName::Calendar));
192 assert_eq!(fluent_icon("MailRegular"), Some(IconName::Mail));
193 assert_eq!(fluent_icon("Alert24"), Some(IconName::Bell));
194 assert_eq!(fluent_icon("NoSuchIcon"), None);
195 }
196
197 #[test]
198 fn sizes_grow_with_the_scale() {
199 let sizes = [
200 IconSize::ExtraExtraSmall,
201 IconSize::ExtraSmall,
202 IconSize::Small,
203 IconSize::Standard,
204 IconSize::Medium,
205 IconSize::Large,
206 IconSize::ExtraLarge,
207 IconSize::ExtraExtraLarge,
208 ];
209 let pixels: Vec<f32> = sizes.into_iter().map(icon_pixels).collect();
210 assert!(pixels.windows(2).all(|pair| pair[0] < pair[1]));
211 }
212 }
@@ -0,0 +1,212 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::*;
3use teams_core::{CardActionIcon, CardIcon, IconSize};
4
5use super::adaptive_card::card_color;
6use super::widgets::icon;
7use crate::theme;
8
9const ACTION_ICON_SIZE: f32 = 16.;
10const UNKNOWN_GLYPH_RATIO: f32 = 0.45;
11const UNKNOWN_GLYPH_RADIUS: f32 = 2.;
12const GLYPH_RATIO: f32 = 0.85;
13const STYLE_SUFFIXES: [&str; 2] = ["regular", "filled"];
14
15const FLUENT_ICONS: &[(&str, IconName)] = &[
16 ("add", IconName::Plus),
17 ("alert", IconName::Bell),
18 ("arrowdown", IconName::ArrowDown),
19 ("arrowup", IconName::ArrowUp),
20 ("arrowleft", IconName::ArrowLeft),
21 ("arrowright", IconName::ArrowRight),
22 ("arrowdownload", IconName::Download),
23 ("arrowupload", IconName::Upload),
24 ("arrowsync", IconName::RefreshCw),
25 ("arrowclockwise", IconName::RotateCw),
26 ("arrowrepeatall", IconName::RefreshCw),
27 ("attach", IconName::Paperclip),
28 ("bookmark", IconName::Bookmark),
29 ("briefcase", IconName::Briefcase),
30 ("building", IconName::Building),
31 ("calendar", IconName::Calendar),
32 ("calendarltr", IconName::Calendar),
33 ("calendardate", IconName::Calendar),
34 ("calendarclock", IconName::CalendarClock),
35 ("camera", IconName::Camera),
36 ("chat", IconName::MessageSquare),
37 ("comment", IconName::MessageSquare),
38 ("commentmultiple", IconName::MessageSquare),
39 ("chartmultiple", IconName::ChartBar),
40 ("checkmark", IconName::Check),
41 ("checkmarkcircle", IconName::CircleCheck),
42 ("chevrondown", IconName::ChevronDown),
43 ("chevronup", IconName::ChevronUp),
44 ("chevronleft", IconName::ChevronLeft),
45 ("chevronright", IconName::ChevronRight),
46 ("clipboard", IconName::Clipboard),
47 ("clock", IconName::Clock),
48 ("cloud", IconName::Cloud),
49 ("code", IconName::Code),
50 ("copy", IconName::Copy),
51 ("database", IconName::Database),
52 ("delete", IconName::Trash),
53 ("dismiss", IconName::X),
54 ("dismisscircle", IconName::CircleX),
55 ("document", IconName::File),
56 ("documenttext", IconName::FileText),
57 ("edit", IconName::Pencil),
58 ("errorcircle", IconName::CircleAlert),
59 ("eye", IconName::Eye),
60 ("eyeoff", IconName::EyeOff),
61 ("flag", IconName::Flag),
62 ("flash", IconName::Zap),
63 ("folder", IconName::Folder),
64 ("gift", IconName::Gift),
65 ("globe", IconName::Globe),
66 ("heart", IconName::Heart),
67 ("home", IconName::House),
68 ("image", IconName::Image),
69 ("info", IconName::Info),
70 ("key", IconName::Key),
71 ("link", IconName::Link),
72 ("list", IconName::List),
73 ("location", IconName::MapPin),
74 ("lock", IconName::Lock),
75 ("lockclosed", IconName::Lock),
76 ("mail", IconName::Mail),
77 ("megaphone", IconName::Megaphone),
78 ("mic", IconName::Mic),
79 ("money", IconName::DollarSign),
80 ("open", IconName::ExternalLink),
81 ("people", IconName::Users),
82 ("peoplecommunity", IconName::Users),
83 ("person", IconName::User),
84 ("personadd", IconName::UserPlus),
85 ("personcircle", IconName::CircleUser),
86 ("phone", IconName::Phone),
87 ("pin", IconName::Pin),
88 ("play", IconName::Play),
89 ("question", IconName::CircleQuestionMark),
90 ("questioncircle", IconName::CircleQuestionMark),
91 ("rocket", IconName::Rocket),
92 ("search", IconName::Search),
93 ("send", IconName::Send),
94 ("settings", IconName::Settings),
95 ("share", IconName::Share),
96 ("shield", IconName::Shield),
97 ("shieldcheckmark", IconName::ShieldCheck),
98 ("star", IconName::Star),
99 ("table", IconName::Table),
100 ("tag", IconName::Tag),
101 ("target", IconName::Target),
102 ("thumbdislike", IconName::ThumbsDown),
103 ("thumblike", IconName::ThumbsUp),
104 ("timer", IconName::Timer),
105 ("trophy", IconName::Trophy),
106 ("video", IconName::Video),
107 ("warning", IconName::TriangleAlert),
108 ("wrench", IconName::Wrench),
109 ("task", IconName::ClipboardCheck),
110];
111
112pub fn fluent_icon(name: &str) -> Option<IconName> {
113 let mut key = name.trim().to_ascii_lowercase();
114 for suffix in STYLE_SUFFIXES {
115 if let Some(stripped) = key.strip_suffix(suffix) {
116 key = stripped.to_owned();
117 }
118 }
119 let key = key.trim_end_matches(|character: char| character.is_ascii_digit());
120 FLUENT_ICONS
121 .iter()
122 .find(|(known, _)| *known == key)
123 .map(|(_, glyph)| *glyph)
124}
125
126pub fn icon_pixels(size: IconSize) -> f32 {
127 match size {
128 IconSize::ExtraExtraSmall => 12.,
129 IconSize::ExtraSmall => 16.,
130 IconSize::Small => 20.,
131 IconSize::Standard => 24.,
132 IconSize::Medium => 32.,
133 IconSize::Large => 48.,
134 IconSize::ExtraLarge => 64.,
135 IconSize::ExtraExtraLarge => 72.,
136 }
137}
138
139pub fn icon_view(card_icon: &CardIcon) -> AnyElement {
140 glyph_view(
141 &card_icon.name,
142 icon_pixels(card_icon.size),
143 card_color(card_icon.color, false),
144 )
145}
146
147pub fn action_icon_view(action_icon: &CardActionIcon) -> AnyElement {
148 match action_icon {
149 CardActionIcon::Named(name) => glyph_view(name, ACTION_ICON_SIZE, theme::accent_text()),
150 CardActionIcon::Url(url) => img(url.clone())
151 .size(px(ACTION_ICON_SIZE))
152 .flex_none()
153 .object_fit(ObjectFit::Contain)
154 .with_loading(|| div().into_any_element())
155 .with_fallback(|| div().into_any_element())
156 .into_any_element(),
157 }
158}
159
160pub(super) fn glyph_view(name: &str, size: f32, color: Hsla) -> AnyElement {
161 let frame = div()
162 .size(px(size))
163 .flex_none()
164 .flex()
165 .items_center()
166 .justify_center();
167 match fluent_icon(name) {
168 Some(glyph) => frame
169 .child(icon(glyph, size * GLYPH_RATIO, color))
170 .into_any_element(),
171 None => frame
172 .child(
173 div()
174 .size(px(size * UNKNOWN_GLYPH_RATIO))
175 .rounded(px(UNKNOWN_GLYPH_RADIUS))
176 .bg(theme::text_muted()),
177 )
178 .into_any_element(),
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use gpui_kit::assets::IconName;
185 use teams_core::IconSize;
186
187 use super::{fluent_icon, icon_pixels};
188
189 #[test]
190 fn fluent_names_map_ignoring_case_style_and_size_suffixes() {
191 assert_eq!(fluent_icon("Calendar"), Some(IconName::Calendar));
192 assert_eq!(fluent_icon("MailRegular"), Some(IconName::Mail));
193 assert_eq!(fluent_icon("Alert24"), Some(IconName::Bell));
194 assert_eq!(fluent_icon("NoSuchIcon"), None);
195 }
196
197 #[test]
198 fn sizes_grow_with_the_scale() {
199 let sizes = [
200 IconSize::ExtraExtraSmall,
201 IconSize::ExtraSmall,
202 IconSize::Small,
203 IconSize::Standard,
204 IconSize::Medium,
205 IconSize::Large,
206 IconSize::ExtraLarge,
207 IconSize::ExtraExtraLarge,
208 ];
209 let pixels: Vec<f32> = sizes.into_iter().map(icon_pixels).collect();
210 assert!(pixels.windows(2).all(|pair| pair[0] < pair[1]));
211 }
212}
crates/app/src/views/card_input.rs +228 −8
@@ -1,15 +1,22 @@
1 use gpui_kit::assets::IconName;
1 2 use gpui_kit::component::checkbox::Checkbox;
3 use gpui_kit::component::date_picker::DatePicker;
2 4 use gpui_kit::component::input::{Input, Textarea};
3 5 use gpui_kit::component::radio::{Radio, RadioGroup};
4 6 use gpui_kit::component::select::Select;
5 use gpui_kit::component::v_flex;
7 use gpui_kit::component::time_field::TimeField;
8 use gpui_kit::component::{h_flex, v_flex};
6 9 use gpui_kit::prelude::FluentBuilder as _;
7 10 use gpui_kit::*;
8 use teams_core::{CardInput, CardInputKind, ChoiceInput, ToggleInput};
11 use teams_core::{
12 CardActionKind, CardInput, CardInputKind, ChoiceInput, DATE_PLACEHOLDER, InlineAction,
13 RatingColor, RatingDisplay, RatingInput, RatingSize, RatingStyle, ToggleInput,
14 };
9 15
16 use super::widgets::{icon, symbol};
10 17 use crate::app_state::AppHandle;
11 use crate::card_inputs::{InputField, uses_select};
12 use crate::card_state::{CardScope, CardState};
18 use crate::card_inputs::{InputField, inline_action_key, uses_select};
19 use crate::card_state::{ActionPhase, CardScope, CardState};
13 20 use crate::theme;
14 21
15 22 const INPUT_GAP: f32 = 4.;
@@ -17,8 +24,22 @@ const LABEL_SIZE: f32 = 12.5;
17 24 const ERROR_SIZE: f32 = 12.;
18 25 const FIELD_RADIUS: f32 = 6.;
19 26 const CHOICE_GAP: f32 = 6.;
27 const STAR_GAP: f32 = 2.;
28 const STAR_MEDIUM: f32 = 20.;
29 const STAR_LARGE: f32 = 28.;
30 const RATING_TEXT_SIZE: f32 = 13.;
31 const RATING_TEXT_GAP: f32 = 6.;
32 const HALF: f64 = 0.5;
33 const INLINE_ICON_SIZE: f32 = 16.;
34 const INLINE_BUTTON_PADDING: f32 = 4.;
35 const INLINE_BUSY_OPACITY: f32 = 0.5;
20 36
21 pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> AnyElement {
37 pub fn input_view(
38 input: &CardInput,
39 scope: &CardScope,
40 state: &CardState,
41 inputs: &[CardInput],
42 ) -> AnyElement {
22 43 let key = scope.input_key(&input.id);
23 44 let error = state.input_error(&key).map(str::to_owned);
24 45 let label = input
@@ -53,7 +74,7 @@ pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> An
53 74 } else {
54 75 transparent_black()
55 76 })
56 .child(control_view(input, &key, scope, state)),
77 .child(control_view(input, &key, scope, state, inputs)),
57 78 )
58 79 .when_some(error, |column, error| {
59 80 column.child(
@@ -66,16 +87,40 @@ pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> An
66 87 .into_any_element()
67 88 }
68 89
69 fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardState) -> AnyElement {
90 fn control_view(
91 input: &CardInput,
92 key: &str,
93 scope: &CardScope,
94 state: &CardState,
95 inputs: &[CardInput],
96 ) -> AnyElement {
70 97 let current = state.input_value(key).to_owned();
71 98 match &input.kind {
72 99 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
100 CardInputKind::Rating(rating) => rating_input_view(rating, key, &current, scope),
73 101 CardInputKind::Choice(choice) if !uses_select(choice) => {
74 102 choices_view(choice, key, &current, scope)
75 103 }
76 104 _ => match state.input_field(key) {
77 Some(InputField::Line(field)) => Input::new(field).into_any_element(),
105 Some(InputField::Line(field)) => {
106 let inline = match &input.kind {
107 CardInputKind::Text(text) => text.inline_action.as_ref(),
108 _ => None,
109 };
110 Input::new(field)
111 .when_some(inline, |line, inline| {
112 line.suffix(inline_action_view(inline, key, scope, state, inputs))
113 })
114 .into_any_element()
115 }
78 116 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
117 Some(InputField::Date(field)) => DatePicker::new(field)
118 .placeholder(DATE_PLACEHOLDER)
119 .cleanable(!input.required)
120 .into_any_element(),
121 Some(InputField::Time(field)) => TimeField::new(field)
122 .invalid(state.input_error(key).is_some())
123 .into_any_element(),
79 124 Some(InputField::Select(field)) => {
80 125 let placeholder = match &input.kind {
81 126 CardInputKind::Choice(choice) => choice.placeholder.clone(),
@@ -93,12 +138,187 @@ fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardSta
93 138 }
94 139 }
95 140
141 fn inline_action_view(
142 inline: &InlineAction,
143 key: &str,
144 scope: &CardScope,
145 state: &CardState,
146 inputs: &[CardInput],
147 ) -> AnyElement {
148 let action_key = inline_action_key(key);
149 let phase = state.phase(&action_key).cloned();
150 let glyph = match (&phase, &inline.icon_url) {
151 (Some(ActionPhase::Done), _) => {
152 symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()
153 }
154 (_, Some(url)) if url.starts_with("https://") => img(url.clone())
155 .size(px(INLINE_ICON_SIZE))
156 .into_any_element(),
157 _ => {
158 let name = match inline.action.kind {
159 CardActionKind::OpenUrl(_) => IconName::ExternalLink,
160 _ => IconName::SendHorizontal,
161 };
162 icon(name, INLINE_ICON_SIZE, theme::accent_text()).into_any_element()
163 }
164 };
165 let (scope, action, inputs) = (scope.clone(), inline.action.clone(), inputs.to_vec());
166 div()
167 .id(ElementId::Name(action_key.clone().into()))
168 .p(px(INLINE_BUTTON_PADDING))
169 .rounded(px(FIELD_RADIUS))
170 .cursor_pointer()
171 .hover(|button| button.bg(theme::row_hover()))
172 .when(phase == Some(ActionPhase::Busy), |button| {
173 button.opacity(INLINE_BUSY_OPACITY)
174 })
175 .child(glyph)
176 .on_click(move |_, _, cx| {
177 cx.stop_propagation();
178 let (scope, action, action_key, inputs) = (
179 scope.clone(),
180 action.clone(),
181 action_key.clone(),
182 inputs.clone(),
183 );
184 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
185 state.run_inline_action(&scope, action_key, &action, &inputs, cx)
186 });
187 })
188 .into_any_element()
189 }
190
191 fn star_pixels(size: RatingSize) -> f32 {
192 match size {
193 RatingSize::Medium => STAR_MEDIUM,
194 RatingSize::Large => STAR_LARGE,
195 }
196 }
197
198 fn star_color(color: RatingColor) -> Hsla {
199 match color {
200 RatingColor::Neutral => theme::text_strong(),
201 RatingColor::Marigold => theme::amber(),
202 }
203 }
204
205 fn star_icon(rating: f64, position: u32, pixels: f32, color: Hsla) -> AnyElement {
206 let position = f64::from(position);
207 if rating >= position {
208 icon(IconName::StarFill, pixels, color).into_any_element()
209 } else if rating >= position - HALF {
210 div()
211 .relative()
212 .size(px(pixels))
213 .child(icon(IconName::Star, pixels, theme::text_muted()))
214 .child(
215 div()
216 .absolute()
217 .top_0()
218 .left_0()
219 .w(px(pixels / 2.))
220 .h(px(pixels))
221 .overflow_hidden()
222 .child(icon(IconName::StarFill, pixels, color)),
223 )
224 .into_any_element()
225 } else {
226 icon(IconName::Star, pixels, theme::text_muted()).into_any_element()
227 }
228 }
229
230 fn rating_input_view(
231 rating: &RatingInput,
232 key: &str,
233 current: &str,
234 scope: &CardScope,
235 ) -> AnyElement {
236 let value = rating.rating(current);
237 let pixels = star_pixels(rating.size);
238 let color = star_color(rating.color);
239 h_flex()
240 .gap(px(STAR_GAP))
241 .children((1..=rating.max).map(|position| {
242 let zones: Vec<f64> = if rating.allow_half {
243 vec![f64::from(position) - HALF, f64::from(position)]
244 } else {
245 vec![f64::from(position)]
246 };
247 div()
248 .relative()
249 .flex_none()
250 .size(px(pixels))
251 .child(star_icon(value, position, pixels, color))
252 .child(
253 h_flex()
254 .absolute()
255 .inset_0()
256 .children(
257 zones
258 .into_iter()
259 .enumerate()
260 .map(|(zone_index, zone_value)| {
261 let (scope, input_key, rating) =
262 (scope.clone(), key.to_owned(), rating.clone());
263 div()
264 .id(ElementId::Name(
265 format!("{key}-star-{position}-{zone_index}").into(),
266 ))
267 .flex_1()
268 .h_full()
269 .cursor_pointer()
270 .on_click(move |_, _, cx| {
271 cx.stop_propagation();
272 pick(
273 &scope,
274 &input_key,
275 rating.value_text(zone_value),
276 cx,
277 );
278 })
279 }),
280 ),
281 )
282 }))
283 .into_any_element()
284 }
285
286 pub fn rating_display_view(display: &RatingDisplay) -> AnyElement {
287 let pixels = star_pixels(display.size);
288 let color = star_color(RatingColor::Marigold);
289 let count = display.count.map(|count| format!("({count})"));
290 let row = match display.style {
291 RatingStyle::Compact => h_flex()
292 .gap(px(RATING_TEXT_GAP))
293 .child(star_icon(display.value, 1, pixels, color))
294 .child(format!("{:.1}", display.value)),
295 RatingStyle::Default => h_flex().gap(px(STAR_GAP)).children(
296 (1..=display.max).map(|position| star_icon(display.value, position, pixels, color)),
297 ),
298 };
299 row.items_center()
300 .text_size(px(RATING_TEXT_SIZE))
301 .text_color(theme::text_strong())
302 .when_some(count, |row, count| {
303 row.child(
304 div()
305 .ml(px(RATING_TEXT_GAP - STAR_GAP))
306 .text_color(theme::text_muted())
307 .child(count),
308 )
309 })
310 .into_any_element()
311 }
312
96 313 fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
97 314 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
98 315 let (scope, input_key) = (scope.clone(), key.to_owned());
99 316 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
100 317 .label(toggle.title.clone())
101 318 .checked(toggle.is_on(current))
319 .when(!toggle.wrap, |checkbox| {
320 checkbox.whitespace_nowrap().text_ellipsis()
321 })
102 322 .on_click(move |checked, _, cx| {
103 323 let value = if *checked { &value_on } else { &value_off };
104 324 pick(&scope, &input_key, value.clone(), cx);
@@ -1,15 +1,22 @@
1use gpui_kit::assets::IconName;
1use gpui_kit::component::checkbox::Checkbox;
2use gpui_kit::component::checkbox::Checkbox;
3use gpui_kit::component::date_picker::DatePicker;
2use gpui_kit::component::input::{Input, Textarea};
4use gpui_kit::component::input::{Input, Textarea};
3use gpui_kit::component::radio::{Radio, RadioGroup};
5use gpui_kit::component::radio::{Radio, RadioGroup};
4use gpui_kit::component::select::Select;
6use gpui_kit::component::select::Select;
5use gpui_kit::component::v_flex;
7use gpui_kit::component::time_field::TimeField;
8use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
10use gpui_kit::*;
8use teams_core::{CardInput, CardInputKind, ChoiceInput, ToggleInput};
11use teams_core::{
12 CardActionKind, CardInput, CardInputKind, ChoiceInput, DATE_PLACEHOLDER, InlineAction,
13 RatingColor, RatingDisplay, RatingInput, RatingSize, RatingStyle, ToggleInput,
14};
9
15
16use super::widgets::{icon, symbol};
10use crate::app_state::AppHandle;
17use crate::app_state::AppHandle;
11use crate::card_inputs::{InputField, uses_select};
18use crate::card_inputs::{InputField, inline_action_key, uses_select};
12use crate::card_state::{CardScope, CardState};
19use crate::card_state::{ActionPhase, CardScope, CardState};
13use crate::theme;
20use crate::theme;
14
21
15const INPUT_GAP: f32 = 4.;
22const INPUT_GAP: f32 = 4.;
@@ -17,8 +24,22 @@ const LABEL_SIZE: f32 = 12.5;
17const ERROR_SIZE: f32 = 12.;
24const ERROR_SIZE: f32 = 12.;
18const FIELD_RADIUS: f32 = 6.;
25const FIELD_RADIUS: f32 = 6.;
19const CHOICE_GAP: f32 = 6.;
26const CHOICE_GAP: f32 = 6.;
27const STAR_GAP: f32 = 2.;
28const STAR_MEDIUM: f32 = 20.;
29const STAR_LARGE: f32 = 28.;
30const RATING_TEXT_SIZE: f32 = 13.;
31const RATING_TEXT_GAP: f32 = 6.;
32const HALF: f64 = 0.5;
33const INLINE_ICON_SIZE: f32 = 16.;
34const INLINE_BUTTON_PADDING: f32 = 4.;
35const INLINE_BUSY_OPACITY: f32 = 0.5;
20
36
21pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> AnyElement {
37pub fn input_view(
38 input: &CardInput,
39 scope: &CardScope,
40 state: &CardState,
41 inputs: &[CardInput],
42) -> AnyElement {
22 let key = scope.input_key(&input.id);
43 let key = scope.input_key(&input.id);
23 let error = state.input_error(&key).map(str::to_owned);
44 let error = state.input_error(&key).map(str::to_owned);
24 let label = input
45 let label = input
@@ -53,7 +74,7 @@ pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> An
53 } else {
74 } else {
54 transparent_black()
75 transparent_black()
55 })
76 })
56 .child(control_view(input, &key, scope, state)),
77 .child(control_view(input, &key, scope, state, inputs)),
57 )
78 )
58 .when_some(error, |column, error| {
79 .when_some(error, |column, error| {
59 column.child(
80 column.child(
@@ -66,16 +87,40 @@ pub fn input_view(input: &CardInput, scope: &CardScope, state: &CardState) -> An
66 .into_any_element()
87 .into_any_element()
67}
88}
68
89
69fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardState) -> AnyElement {
90fn control_view(
91 input: &CardInput,
92 key: &str,
93 scope: &CardScope,
94 state: &CardState,
95 inputs: &[CardInput],
96) -> AnyElement {
70 let current = state.input_value(key).to_owned();
97 let current = state.input_value(key).to_owned();
71 match &input.kind {
98 match &input.kind {
72 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
99 CardInputKind::Toggle(toggle) => toggle_view(toggle, key, &current, scope),
100 CardInputKind::Rating(rating) => rating_input_view(rating, key, &current, scope),
73 CardInputKind::Choice(choice) if !uses_select(choice) => {
101 CardInputKind::Choice(choice) if !uses_select(choice) => {
74 choices_view(choice, key, &current, scope)
102 choices_view(choice, key, &current, scope)
75 }
103 }
76 _ => match state.input_field(key) {
104 _ => match state.input_field(key) {
77 Some(InputField::Line(field)) => Input::new(field).into_any_element(),
105 Some(InputField::Line(field)) => {
106 let inline = match &input.kind {
107 CardInputKind::Text(text) => text.inline_action.as_ref(),
108 _ => None,
109 };
110 Input::new(field)
111 .when_some(inline, |line, inline| {
112 line.suffix(inline_action_view(inline, key, scope, state, inputs))
113 })
114 .into_any_element()
115 }
78 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
116 Some(InputField::Area(field)) => Textarea::new(field).into_any_element(),
117 Some(InputField::Date(field)) => DatePicker::new(field)
118 .placeholder(DATE_PLACEHOLDER)
119 .cleanable(!input.required)
120 .into_any_element(),
121 Some(InputField::Time(field)) => TimeField::new(field)
122 .invalid(state.input_error(key).is_some())
123 .into_any_element(),
79 Some(InputField::Select(field)) => {
124 Some(InputField::Select(field)) => {
80 let placeholder = match &input.kind {
125 let placeholder = match &input.kind {
81 CardInputKind::Choice(choice) => choice.placeholder.clone(),
126 CardInputKind::Choice(choice) => choice.placeholder.clone(),
@@ -93,12 +138,187 @@ fn control_view(input: &CardInput, key: &str, scope: &CardScope, state: &CardSta
93 }
138 }
94}
139}
95
140
141fn inline_action_view(
142 inline: &InlineAction,
143 key: &str,
144 scope: &CardScope,
145 state: &CardState,
146 inputs: &[CardInput],
147) -> AnyElement {
148 let action_key = inline_action_key(key);
149 let phase = state.phase(&action_key).cloned();
150 let glyph = match (&phase, &inline.icon_url) {
151 (Some(ActionPhase::Done), _) => {
152 symbol("done", INLINE_ICON_SIZE, theme::green()).into_any_element()
153 }
154 (_, Some(url)) if url.starts_with("https://") => img(url.clone())
155 .size(px(INLINE_ICON_SIZE))
156 .into_any_element(),
157 _ => {
158 let name = match inline.action.kind {
159 CardActionKind::OpenUrl(_) => IconName::ExternalLink,
160 _ => IconName::SendHorizontal,
161 };
162 icon(name, INLINE_ICON_SIZE, theme::accent_text()).into_any_element()
163 }
164 };
165 let (scope, action, inputs) = (scope.clone(), inline.action.clone(), inputs.to_vec());
166 div()
167 .id(ElementId::Name(action_key.clone().into()))
168 .p(px(INLINE_BUTTON_PADDING))
169 .rounded(px(FIELD_RADIUS))
170 .cursor_pointer()
171 .hover(|button| button.bg(theme::row_hover()))
172 .when(phase == Some(ActionPhase::Busy), |button| {
173 button.opacity(INLINE_BUSY_OPACITY)
174 })
175 .child(glyph)
176 .on_click(move |_, _, cx| {
177 cx.stop_propagation();
178 let (scope, action, action_key, inputs) = (
179 scope.clone(),
180 action.clone(),
181 action_key.clone(),
182 inputs.clone(),
183 );
184 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
185 state.run_inline_action(&scope, action_key, &action, &inputs, cx)
186 });
187 })
188 .into_any_element()
189}
190
191fn star_pixels(size: RatingSize) -> f32 {
192 match size {
193 RatingSize::Medium => STAR_MEDIUM,
194 RatingSize::Large => STAR_LARGE,
195 }
196}
197
198fn star_color(color: RatingColor) -> Hsla {
199 match color {
200 RatingColor::Neutral => theme::text_strong(),
201 RatingColor::Marigold => theme::amber(),
202 }
203}
204
205fn star_icon(rating: f64, position: u32, pixels: f32, color: Hsla) -> AnyElement {
206 let position = f64::from(position);
207 if rating >= position {
208 icon(IconName::StarFill, pixels, color).into_any_element()
209 } else if rating >= position - HALF {
210 div()
211 .relative()
212 .size(px(pixels))
213 .child(icon(IconName::Star, pixels, theme::text_muted()))
214 .child(
215 div()
216 .absolute()
217 .top_0()
218 .left_0()
219 .w(px(pixels / 2.))
220 .h(px(pixels))
221 .overflow_hidden()
222 .child(icon(IconName::StarFill, pixels, color)),
223 )
224 .into_any_element()
225 } else {
226 icon(IconName::Star, pixels, theme::text_muted()).into_any_element()
227 }
228}
229
230fn rating_input_view(
231 rating: &RatingInput,
232 key: &str,
233 current: &str,
234 scope: &CardScope,
235) -> AnyElement {
236 let value = rating.rating(current);
237 let pixels = star_pixels(rating.size);
238 let color = star_color(rating.color);
239 h_flex()
240 .gap(px(STAR_GAP))
241 .children((1..=rating.max).map(|position| {
242 let zones: Vec<f64> = if rating.allow_half {
243 vec![f64::from(position) - HALF, f64::from(position)]
244 } else {
245 vec![f64::from(position)]
246 };
247 div()
248 .relative()
249 .flex_none()
250 .size(px(pixels))
251 .child(star_icon(value, position, pixels, color))
252 .child(
253 h_flex()
254 .absolute()
255 .inset_0()
256 .children(
257 zones
258 .into_iter()
259 .enumerate()
260 .map(|(zone_index, zone_value)| {
261 let (scope, input_key, rating) =
262 (scope.clone(), key.to_owned(), rating.clone());
263 div()
264 .id(ElementId::Name(
265 format!("{key}-star-{position}-{zone_index}").into(),
266 ))
267 .flex_1()
268 .h_full()
269 .cursor_pointer()
270 .on_click(move |_, _, cx| {
271 cx.stop_propagation();
272 pick(
273 &scope,
274 &input_key,
275 rating.value_text(zone_value),
276 cx,
277 );
278 })
279 }),
280 ),
281 )
282 }))
283 .into_any_element()
284}
285
286pub fn rating_display_view(display: &RatingDisplay) -> AnyElement {
287 let pixels = star_pixels(display.size);
288 let color = star_color(RatingColor::Marigold);
289 let count = display.count.map(|count| format!("({count})"));
290 let row = match display.style {
291 RatingStyle::Compact => h_flex()
292 .gap(px(RATING_TEXT_GAP))
293 .child(star_icon(display.value, 1, pixels, color))
294 .child(format!("{:.1}", display.value)),
295 RatingStyle::Default => h_flex().gap(px(STAR_GAP)).children(
296 (1..=display.max).map(|position| star_icon(display.value, position, pixels, color)),
297 ),
298 };
299 row.items_center()
300 .text_size(px(RATING_TEXT_SIZE))
301 .text_color(theme::text_strong())
302 .when_some(count, |row, count| {
303 row.child(
304 div()
305 .ml(px(RATING_TEXT_GAP - STAR_GAP))
306 .text_color(theme::text_muted())
307 .child(count),
308 )
309 })
310 .into_any_element()
311}
312
96fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
313fn toggle_view(toggle: &ToggleInput, key: &str, current: &str, scope: &CardScope) -> AnyElement {
97 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
314 let (value_on, value_off) = (toggle.value_on.clone(), toggle.value_off.clone());
98 let (scope, input_key) = (scope.clone(), key.to_owned());
315 let (scope, input_key) = (scope.clone(), key.to_owned());
99 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
316 Checkbox::new(ElementId::Name(format!("{key}-toggle").into()))
100 .label(toggle.title.clone())
317 .label(toggle.title.clone())
101 .checked(toggle.is_on(current))
318 .checked(toggle.is_on(current))
319 .when(!toggle.wrap, |checkbox| {
320 checkbox.whitespace_nowrap().text_ellipsis()
321 })
102 .on_click(move |checked, _, cx| {
322 .on_click(move |checked, _, cx| {
103 let value = if *checked { &value_on } else { &value_off };
323 let value = if *checked { &value_on } else { &value_off };
104 pick(&scope, &input_key, value.clone(), cx);
324 pick(&scope, &input_key, value.clone(), cx);
crates/app/src/views/card_media.rs added +79 −0
@@ -0,0 +1,79 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::tooltip::Tooltip;
3 use gpui_kit::prelude::FluentBuilder as _;
4 use gpui_kit::*;
5 use teams_core::CardMedia;
6
7 use super::widgets::icon;
8 use crate::theme;
9
10 const MEDIA_WIDTH: f32 = 360.;
11 const MEDIA_HEIGHT: f32 = 202.;
12 const MEDIA_RADIUS: f32 = 6.;
13 const PLAY_BUTTON: f32 = 52.;
14 const PLAY_GLYPH: f32 = 24.;
15 const PLAY_BACKDROP: f32 = 0.6;
16 const HOVER_TINT: f32 = 0.12;
17
18 pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
19 let source_url = media.source_url.clone();
20 let alt_text = media.alt_text.clone();
21 let poster = match &media.poster_url {
22 Some(url) => img(url.clone())
23 .size_full()
24 .rounded(px(MEDIA_RADIUS))
25 .object_fit(ObjectFit::Cover)
26 .with_loading(placeholder)
27 .with_fallback(placeholder)
28 .into_any_element(),
29 None => placeholder(),
30 };
31 div()
32 .id(ElementId::Name(format!("{id}-media").into()))
33 .group(SharedString::from(format!("{id}-media")))
34 .relative()
35 .w(px(MEDIA_WIDTH))
36 .h(px(MEDIA_HEIGHT))
37 .max_w(relative(1.))
38 .flex_none()
39 .overflow_hidden()
40 .rounded(px(MEDIA_RADIUS))
41 .cursor_pointer()
42 .when_some(alt_text, |frame, alt_text| {
43 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
44 })
45 .on_click(move |_, _, cx| {
46 cx.stop_propagation();
47 cx.open_url(&source_url);
48 })
49 .child(poster)
50 .child(
51 div()
52 .absolute()
53 .inset_0()
54 .flex()
55 .items_center()
56 .justify_center()
57 .group_hover(SharedString::from(format!("{id}-media")), |tint| {
58 tint.bg(gpui_kit::white().opacity(HOVER_TINT))
59 })
60 .child(
61 div()
62 .size(px(PLAY_BUTTON))
63 .flex()
64 .items_center()
65 .justify_center()
66 .rounded_full()
67 .bg(gpui_kit::black().opacity(PLAY_BACKDROP))
68 .child(icon(IconName::Play, PLAY_GLYPH, gpui_kit::white())),
69 ),
70 )
71 .into_any_element()
72 }
73
74 fn placeholder() -> AnyElement {
75 div()
76 .size_full()
77 .bg(theme::surface_raised())
78 .into_any_element()
79 }
@@ -0,0 +1,79 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::tooltip::Tooltip;
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5use teams_core::CardMedia;
6
7use super::widgets::icon;
8use crate::theme;
9
10const MEDIA_WIDTH: f32 = 360.;
11const MEDIA_HEIGHT: f32 = 202.;
12const MEDIA_RADIUS: f32 = 6.;
13const PLAY_BUTTON: f32 = 52.;
14const PLAY_GLYPH: f32 = 24.;
15const PLAY_BACKDROP: f32 = 0.6;
16const HOVER_TINT: f32 = 0.12;
17
18pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
19 let source_url = media.source_url.clone();
20 let alt_text = media.alt_text.clone();
21 let poster = match &media.poster_url {
22 Some(url) => img(url.clone())
23 .size_full()
24 .rounded(px(MEDIA_RADIUS))
25 .object_fit(ObjectFit::Cover)
26 .with_loading(placeholder)
27 .with_fallback(placeholder)
28 .into_any_element(),
29 None => placeholder(),
30 };
31 div()
32 .id(ElementId::Name(format!("{id}-media").into()))
33 .group(SharedString::from(format!("{id}-media")))
34 .relative()
35 .w(px(MEDIA_WIDTH))
36 .h(px(MEDIA_HEIGHT))
37 .max_w(relative(1.))
38 .flex_none()
39 .overflow_hidden()
40 .rounded(px(MEDIA_RADIUS))
41 .cursor_pointer()
42 .when_some(alt_text, |frame, alt_text| {
43 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
44 })
45 .on_click(move |_, _, cx| {
46 cx.stop_propagation();
47 cx.open_url(&source_url);
48 })
49 .child(poster)
50 .child(
51 div()
52 .absolute()
53 .inset_0()
54 .flex()
55 .items_center()
56 .justify_center()
57 .group_hover(SharedString::from(format!("{id}-media")), |tint| {
58 tint.bg(gpui_kit::white().opacity(HOVER_TINT))
59 })
60 .child(
61 div()
62 .size(px(PLAY_BUTTON))
63 .flex()
64 .items_center()
65 .justify_center()
66 .rounded_full()
67 .bg(gpui_kit::black().opacity(PLAY_BACKDROP))
68 .child(icon(IconName::Play, PLAY_GLYPH, gpui_kit::white())),
69 ),
70 )
71 .into_any_element()
72}
73
74fn placeholder() -> AnyElement {
75 div()
76 .size_full()
77 .bg(theme::surface_raised())
78 .into_any_element()
79}
crates/app/src/views/card_table.rs added +80 −0
@@ -0,0 +1,80 @@
1 use gpui_kit::component::{h_flex, v_flex};
2 use gpui_kit::prelude::FluentBuilder as _;
3 use gpui_kit::*;
4 use teams_core::{CardTable, ContainerStyle, HorizontalAlignment, VerticalAlignment};
5
6 use super::adaptive_card::{CardContext, container_tint, items_view, selectable, sized_column};
7 use crate::theme;
8
9 const CELL_PADDING: f32 = 6.;
10 const GRID_RADIUS: f32 = 4.;
11
12 pub(super) fn table_view(table: &CardTable, id: &str, context: &CardContext) -> AnyElement {
13 let grid_color = grid_color(table.grid_style);
14 v_flex()
15 .w_full()
16 .overflow_hidden()
17 .rounded(px(GRID_RADIUS))
18 .when(table.show_grid_lines, |grid| {
19 grid.border_1().border_color(grid_color)
20 })
21 .children(table.rows.iter().enumerate().map(|(row_index, row)| {
22 let header = table.first_row_as_header && row_index == 0;
23 h_flex()
24 .w_full()
25 .items_stretch()
26 .when(header, |line| {
27 line.bg(theme::table_header())
28 .font_weight(FontWeight::SEMIBOLD)
29 })
30 .when_some(container_tint(row.style), |line, tint| line.bg(tint))
31 .when(row_index > 0 && table.show_grid_lines, |line| {
32 line.border_t_1().border_color(grid_color)
33 })
34 .children(row.cells.iter().enumerate().map(|(column_index, cell)| {
35 let cell_id = format!("{id}-{row_index}-{column_index}");
36 let body = selectable(
37 items_view(&cell.items, &cell_id, context, false).into_any_element(),
38 cell.select_action.as_ref(),
39 &cell_id,
40 false,
41 context,
42 );
43 let aligned = v_flex()
44 .min_w(px(0.))
45 .p(px(CELL_PADDING))
46 .overflow_hidden()
47 .when(column_index > 0 && table.show_grid_lines, |cell| {
48 cell.border_l_1().border_color(grid_color)
49 })
50 .when_some(container_tint(cell.style), |cell, tint| cell.bg(tint))
51 .map(|cell_box| {
52 match table.cell_vertical_alignment(row, cell, column_index) {
53 VerticalAlignment::Top => cell_box.justify_start(),
54 VerticalAlignment::Center => cell_box.justify_center(),
55 VerticalAlignment::Bottom => cell_box.justify_end(),
56 }
57 })
58 .map(
59 |cell_box| match table.cell_horizontal_alignment(row, column_index) {
60 HorizontalAlignment::Left => cell_box.text_left(),
61 HorizontalAlignment::Center => cell_box.text_center(),
62 HorizontalAlignment::Right => cell_box.text_right(),
63 },
64 );
65 sized_column(aligned, table.columns[column_index].width).child(body)
66 }))
67 }))
68 .into_any_element()
69 }
70
71 fn grid_color(style: ContainerStyle) -> Hsla {
72 match style {
73 ContainerStyle::Default => theme::border_strong(),
74 ContainerStyle::Emphasis => theme::text_faint(),
75 ContainerStyle::Accent => theme::accent(),
76 ContainerStyle::Good => theme::green(),
77 ContainerStyle::Warning => theme::amber(),
78 ContainerStyle::Attention => theme::red(),
79 }
80 }
@@ -0,0 +1,80 @@
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4use teams_core::{CardTable, ContainerStyle, HorizontalAlignment, VerticalAlignment};
5
6use super::adaptive_card::{CardContext, container_tint, items_view, selectable, sized_column};
7use crate::theme;
8
9const CELL_PADDING: f32 = 6.;
10const GRID_RADIUS: f32 = 4.;
11
12pub(super) fn table_view(table: &CardTable, id: &str, context: &CardContext) -> AnyElement {
13 let grid_color = grid_color(table.grid_style);
14 v_flex()
15 .w_full()
16 .overflow_hidden()
17 .rounded(px(GRID_RADIUS))
18 .when(table.show_grid_lines, |grid| {
19 grid.border_1().border_color(grid_color)
20 })
21 .children(table.rows.iter().enumerate().map(|(row_index, row)| {
22 let header = table.first_row_as_header && row_index == 0;
23 h_flex()
24 .w_full()
25 .items_stretch()
26 .when(header, |line| {
27 line.bg(theme::table_header())
28 .font_weight(FontWeight::SEMIBOLD)
29 })
30 .when_some(container_tint(row.style), |line, tint| line.bg(tint))
31 .when(row_index > 0 && table.show_grid_lines, |line| {
32 line.border_t_1().border_color(grid_color)
33 })
34 .children(row.cells.iter().enumerate().map(|(column_index, cell)| {
35 let cell_id = format!("{id}-{row_index}-{column_index}");
36 let body = selectable(
37 items_view(&cell.items, &cell_id, context, false).into_any_element(),
38 cell.select_action.as_ref(),
39 &cell_id,
40 false,
41 context,
42 );
43 let aligned = v_flex()
44 .min_w(px(0.))
45 .p(px(CELL_PADDING))
46 .overflow_hidden()
47 .when(column_index > 0 && table.show_grid_lines, |cell| {
48 cell.border_l_1().border_color(grid_color)
49 })
50 .when_some(container_tint(cell.style), |cell, tint| cell.bg(tint))
51 .map(|cell_box| {
52 match table.cell_vertical_alignment(row, cell, column_index) {
53 VerticalAlignment::Top => cell_box.justify_start(),
54 VerticalAlignment::Center => cell_box.justify_center(),
55 VerticalAlignment::Bottom => cell_box.justify_end(),
56 }
57 })
58 .map(
59 |cell_box| match table.cell_horizontal_alignment(row, column_index) {
60 HorizontalAlignment::Left => cell_box.text_left(),
61 HorizontalAlignment::Center => cell_box.text_center(),
62 HorizontalAlignment::Right => cell_box.text_right(),
63 },
64 );
65 sized_column(aligned, table.columns[column_index].width).child(body)
66 }))
67 }))
68 .into_any_element()
69}
70
71fn grid_color(style: ContainerStyle) -> Hsla {
72 match style {
73 ContainerStyle::Default => theme::border_strong(),
74 ContainerStyle::Emphasis => theme::text_faint(),
75 ContainerStyle::Accent => theme::accent(),
76 ContainerStyle::Good => theme::green(),
77 ContainerStyle::Warning => theme::amber(),
78 ContainerStyle::Attention => theme::red(),
79 }
80}
crates/app/src/views/card_widgets.rs added +296 −0
@@ -0,0 +1,296 @@
1 use std::time::Duration;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::tooltip::Tooltip;
5 use gpui_kit::component::{h_flex, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8 use teams_core::{
9 BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCompoundButton,
10 CardProgressBar, CardProgressRing, IconPosition, LabelPosition, RingSize, TextColor,
11 };
12
13 use super::adaptive_card::{CardContext, card_color, selectable};
14 use super::card_icon::glyph_view;
15 use super::widgets::icon;
16 use crate::theme;
17
18 const BADGE_TINT: f32 = 0.18;
19 const BADGE_ICON_GAP: f32 = 4.;
20 const BAR_HEIGHT: f32 = 6.;
21 const INDETERMINATE_WIDTH: f32 = 0.3;
22 const INDETERMINATE_PERIOD: Duration = Duration::from_millis(1400);
23 const RING_PERIOD: Duration = Duration::from_millis(1000);
24 const RING_LABEL_GAP: f32 = 8.;
25 const COMPOUND_PADDING: f32 = 10.;
26 const COMPOUND_GAP: f32 = 10.;
27 const COMPOUND_ICON_SIZE: f32 = 24.;
28 const COMPOUND_RADIUS: f32 = 6.;
29
30 struct BadgePalette {
31 fill: Hsla,
32 foreground: Hsla,
33 border: Option<Hsla>,
34 }
35
36 fn badge_palette(style: BadgeStyle, appearance: BadgeAppearance) -> BadgePalette {
37 let tinted = appearance == BadgeAppearance::Tint;
38 let semantic = |fill: Hsla, on_fill: Hsla, tint_text: Hsla| {
39 if tinted {
40 BadgePalette {
41 fill: fill.opacity(BADGE_TINT),
42 foreground: tint_text,
43 border: Some(fill.opacity(BADGE_TINT * 2.)),
44 }
45 } else {
46 BadgePalette {
47 fill,
48 foreground: on_fill,
49 border: None,
50 }
51 }
52 };
53 match style {
54 BadgeStyle::Accent => semantic(theme::accent(), theme::on_accent(), theme::accent_text()),
55 BadgeStyle::Good => semantic(theme::green(), theme::background(), theme::green()),
56 BadgeStyle::Attention => semantic(theme::red(), theme::white(), theme::red_soft()),
57 BadgeStyle::Warning => semantic(theme::amber(), theme::background(), theme::amber()),
58 BadgeStyle::Default => neutral(theme::badge_muted(), theme::text_strong(), tinted),
59 BadgeStyle::Informative => neutral(theme::surface_raised(), theme::text_soft(), tinted),
60 BadgeStyle::Subtle => BadgePalette {
61 fill: if tinted {
62 theme::surface_raised()
63 } else {
64 transparent_black()
65 },
66 foreground: theme::text_muted(),
67 border: Some(theme::border_strong()),
68 },
69 }
70 }
71
72 fn neutral(fill: Hsla, foreground: Hsla, tinted: bool) -> BadgePalette {
73 BadgePalette {
74 fill: if tinted { fill.opacity(0.5) } else { fill },
75 foreground,
76 border: tinted.then(theme::border_strong),
77 }
78 }
79
80 fn badge_metrics(size: BadgeSize) -> (f32, f32, f32, f32) {
81 match size {
82 BadgeSize::Medium => (20., 12., 6., 12.),
83 BadgeSize::Large => (24., 13., 8., 14.),
84 BadgeSize::ExtraLarge => (32., 14., 10., 18.),
85 }
86 }
87
88 pub(super) fn leading(element: AnyElement) -> AnyElement {
89 div()
90 .w_full()
91 .flex()
92 .flex_row()
93 .child(element)
94 .into_any_element()
95 }
96
97 pub(super) fn badge_view(badge: &CardBadge, id: &str) -> AnyElement {
98 let palette = badge_palette(badge.style, badge.appearance);
99 let (height, text_size, padding, icon_size) = badge_metrics(badge.size);
100 let glyph = badge
101 .icon
102 .as_deref()
103 .map(|name| glyph_view(name, icon_size, palette.foreground));
104 let (icon_before, icon_after) = match badge.icon_position {
105 IconPosition::Before => (glyph, None),
106 IconPosition::After => (None, glyph),
107 };
108 let text = (!badge.text.is_empty()).then(|| badge.text.clone());
109 let tooltip = badge.tooltip.clone();
110 h_flex()
111 .id(ElementId::Name(format!("{id}-badge").into()))
112 .flex_none()
113 .h(px(height))
114 .min_w(px(height))
115 .px(px(padding))
116 .gap(px(BADGE_ICON_GAP))
117 .items_center()
118 .justify_center()
119 .map(|frame| match badge.shape {
120 BadgeShape::Square => frame.rounded(px(2.)),
121 BadgeShape::Rounded => frame.rounded(px(height / 4.)),
122 BadgeShape::Circular => frame.rounded_full(),
123 })
124 .bg(palette.fill)
125 .when_some(palette.border, |frame, border| {
126 frame.border_1().border_color(border)
127 })
128 .text_color(palette.foreground)
129 .text_size(px(text_size))
130 .font_weight(FontWeight::SEMIBOLD)
131 .when_some(tooltip, |frame, tooltip| {
132 frame.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
133 })
134 .children(icon_before)
135 .children(text)
136 .children(icon_after)
137 .into_any_element()
138 }
139
140 pub(super) fn progress_bar_view(bar: &CardProgressBar, id: &str) -> AnyElement {
141 let fill = match bar.color {
142 TextColor::Default | TextColor::Dark | TextColor::Light => theme::accent(),
143 other => card_color(other, false),
144 };
145 let track = div()
146 .relative()
147 .w_full()
148 .h(px(BAR_HEIGHT))
149 .overflow_hidden()
150 .rounded_full()
151 .bg(theme::border_strong());
152 match bar.value {
153 Some(value) => track
154 .child(
155 div()
156 .h_full()
157 .w(relative(value / 100.))
158 .rounded_full()
159 .bg(fill),
160 )
161 .into_any_element(),
162 None => track
163 .child(
164 div()
165 .absolute()
166 .top_0()
167 .h_full()
168 .w(relative(INDETERMINATE_WIDTH))
169 .rounded_full()
170 .bg(fill)
171 .with_animation(
172 ElementId::Name(format!("{id}-pulse").into()),
173 Animation::new(INDETERMINATE_PERIOD).repeat(),
174 |segment, delta| {
175 let travel = 1. + INDETERMINATE_WIDTH;
176 segment.left(relative(
177 (delta + 0.3).fract() * travel - INDETERMINATE_WIDTH,
178 ))
179 },
180 ),
181 )
182 .into_any_element(),
183 }
184 }
185
186 fn ring_pixels(size: RingSize) -> f32 {
187 match size {
188 RingSize::Tiny => 16.,
189 RingSize::Small => 20.,
190 RingSize::Medium => 28.,
191 RingSize::Large => 40.,
192 }
193 }
194
195 pub(super) fn progress_ring_view(ring: &CardProgressRing, id: &str) -> AnyElement {
196 let pixels = ring_pixels(ring.size);
197 let spinner = icon(IconName::Loader, pixels, theme::accent_text()).with_animation(
198 ElementId::Name(format!("{id}-spin").into()),
199 Animation::new(RING_PERIOD).repeat(),
200 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
201 );
202 let label = ring.label.clone().map(|label| {
203 div()
204 .text_size(px(13.))
205 .text_color(theme::text_soft())
206 .child(label)
207 });
208 let vertical = matches!(
209 ring.label_position,
210 LabelPosition::Above | LabelPosition::Below
211 );
212 let (label_before, label_after) = match ring.label_position {
213 LabelPosition::Before | LabelPosition::Above => (label, None),
214 LabelPosition::After | LabelPosition::Below => (None, label),
215 };
216 div()
217 .flex()
218 .items_center()
219 .gap(px(RING_LABEL_GAP))
220 .map(|frame| {
221 if vertical {
222 frame.flex_col()
223 } else {
224 frame.flex_row()
225 }
226 })
227 .children(label_before)
228 .child(spinner)
229 .children(label_after)
230 .into_any_element()
231 }
232
233 pub(super) fn compound_button_view(
234 button: &CardCompoundButton,
235 id: &str,
236 context: &CardContext,
237 ) -> AnyElement {
238 let clickable = button
239 .select_action
240 .as_ref()
241 .is_some_and(|action| action.is_clickable());
242 let face = h_flex()
243 .w_full()
244 .items_center()
245 .gap(px(COMPOUND_GAP))
246 .p(px(COMPOUND_PADDING))
247 .rounded(px(COMPOUND_RADIUS))
248 .border_1()
249 .border_color(theme::border_strong())
250 .when(!clickable, |face| face.opacity(0.6))
251 .children(
252 button
253 .icon
254 .as_deref()
255 .map(|name| glyph_view(name, COMPOUND_ICON_SIZE, theme::accent_text())),
256 )
257 .child(
258 v_flex()
259 .flex_1()
260 .min_w(px(0.))
261 .child(
262 div()
263 .text_size(px(13.5))
264 .font_weight(FontWeight::SEMIBOLD)
265 .text_color(theme::text_strong())
266 .child(button.title.clone()),
267 )
268 .children(button.description.clone().map(|description| {
269 div()
270 .text_size(px(12.))
271 .text_color(theme::text_muted())
272 .child(description)
273 })),
274 )
275 .children(button.badge.clone().map(|badge| {
276 div()
277 .flex_none()
278 .px(px(6.))
279 .h(px(18.))
280 .flex()
281 .items_center()
282 .rounded_full()
283 .bg(theme::badge_muted())
284 .text_size(px(11.))
285 .font_weight(FontWeight::BOLD)
286 .text_color(theme::text_strong())
287 .child(badge)
288 }));
289 selectable(
290 face.into_any_element(),
291 button.select_action.as_ref(),
292 id,
293 false,
294 context,
295 )
296 }
@@ -0,0 +1,296 @@
1use std::time::Duration;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::tooltip::Tooltip;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{
9 BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCompoundButton,
10 CardProgressBar, CardProgressRing, IconPosition, LabelPosition, RingSize, TextColor,
11};
12
13use super::adaptive_card::{CardContext, card_color, selectable};
14use super::card_icon::glyph_view;
15use super::widgets::icon;
16use crate::theme;
17
18const BADGE_TINT: f32 = 0.18;
19const BADGE_ICON_GAP: f32 = 4.;
20const BAR_HEIGHT: f32 = 6.;
21const INDETERMINATE_WIDTH: f32 = 0.3;
22const INDETERMINATE_PERIOD: Duration = Duration::from_millis(1400);
23const RING_PERIOD: Duration = Duration::from_millis(1000);
24const RING_LABEL_GAP: f32 = 8.;
25const COMPOUND_PADDING: f32 = 10.;
26const COMPOUND_GAP: f32 = 10.;
27const COMPOUND_ICON_SIZE: f32 = 24.;
28const COMPOUND_RADIUS: f32 = 6.;
29
30struct BadgePalette {
31 fill: Hsla,
32 foreground: Hsla,
33 border: Option<Hsla>,
34}
35
36fn badge_palette(style: BadgeStyle, appearance: BadgeAppearance) -> BadgePalette {
37 let tinted = appearance == BadgeAppearance::Tint;
38 let semantic = |fill: Hsla, on_fill: Hsla, tint_text: Hsla| {
39 if tinted {
40 BadgePalette {
41 fill: fill.opacity(BADGE_TINT),
42 foreground: tint_text,
43 border: Some(fill.opacity(BADGE_TINT * 2.)),
44 }
45 } else {
46 BadgePalette {
47 fill,
48 foreground: on_fill,
49 border: None,
50 }
51 }
52 };
53 match style {
54 BadgeStyle::Accent => semantic(theme::accent(), theme::on_accent(), theme::accent_text()),
55 BadgeStyle::Good => semantic(theme::green(), theme::background(), theme::green()),
56 BadgeStyle::Attention => semantic(theme::red(), theme::white(), theme::red_soft()),
57 BadgeStyle::Warning => semantic(theme::amber(), theme::background(), theme::amber()),
58 BadgeStyle::Default => neutral(theme::badge_muted(), theme::text_strong(), tinted),
59 BadgeStyle::Informative => neutral(theme::surface_raised(), theme::text_soft(), tinted),
60 BadgeStyle::Subtle => BadgePalette {
61 fill: if tinted {
62 theme::surface_raised()
63 } else {
64 transparent_black()
65 },
66 foreground: theme::text_muted(),
67 border: Some(theme::border_strong()),
68 },
69 }
70}
71
72fn neutral(fill: Hsla, foreground: Hsla, tinted: bool) -> BadgePalette {
73 BadgePalette {
74 fill: if tinted { fill.opacity(0.5) } else { fill },
75 foreground,
76 border: tinted.then(theme::border_strong),
77 }
78}
79
80fn badge_metrics(size: BadgeSize) -> (f32, f32, f32, f32) {
81 match size {
82 BadgeSize::Medium => (20., 12., 6., 12.),
83 BadgeSize::Large => (24., 13., 8., 14.),
84 BadgeSize::ExtraLarge => (32., 14., 10., 18.),
85 }
86}
87
88pub(super) fn leading(element: AnyElement) -> AnyElement {
89 div()
90 .w_full()
91 .flex()
92 .flex_row()
93 .child(element)
94 .into_any_element()
95}
96
97pub(super) fn badge_view(badge: &CardBadge, id: &str) -> AnyElement {
98 let palette = badge_palette(badge.style, badge.appearance);
99 let (height, text_size, padding, icon_size) = badge_metrics(badge.size);
100 let glyph = badge
101 .icon
102 .as_deref()
103 .map(|name| glyph_view(name, icon_size, palette.foreground));
104 let (icon_before, icon_after) = match badge.icon_position {
105 IconPosition::Before => (glyph, None),
106 IconPosition::After => (None, glyph),
107 };
108 let text = (!badge.text.is_empty()).then(|| badge.text.clone());
109 let tooltip = badge.tooltip.clone();
110 h_flex()
111 .id(ElementId::Name(format!("{id}-badge").into()))
112 .flex_none()
113 .h(px(height))
114 .min_w(px(height))
115 .px(px(padding))
116 .gap(px(BADGE_ICON_GAP))
117 .items_center()
118 .justify_center()
119 .map(|frame| match badge.shape {
120 BadgeShape::Square => frame.rounded(px(2.)),
121 BadgeShape::Rounded => frame.rounded(px(height / 4.)),
122 BadgeShape::Circular => frame.rounded_full(),
123 })
124 .bg(palette.fill)
125 .when_some(palette.border, |frame, border| {
126 frame.border_1().border_color(border)
127 })
128 .text_color(palette.foreground)
129 .text_size(px(text_size))
130 .font_weight(FontWeight::SEMIBOLD)
131 .when_some(tooltip, |frame, tooltip| {
132 frame.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
133 })
134 .children(icon_before)
135 .children(text)
136 .children(icon_after)
137 .into_any_element()
138}
139
140pub(super) fn progress_bar_view(bar: &CardProgressBar, id: &str) -> AnyElement {
141 let fill = match bar.color {
142 TextColor::Default | TextColor::Dark | TextColor::Light => theme::accent(),
143 other => card_color(other, false),
144 };
145 let track = div()
146 .relative()
147 .w_full()
148 .h(px(BAR_HEIGHT))
149 .overflow_hidden()
150 .rounded_full()
151 .bg(theme::border_strong());
152 match bar.value {
153 Some(value) => track
154 .child(
155 div()
156 .h_full()
157 .w(relative(value / 100.))
158 .rounded_full()
159 .bg(fill),
160 )
161 .into_any_element(),
162 None => track
163 .child(
164 div()
165 .absolute()
166 .top_0()
167 .h_full()
168 .w(relative(INDETERMINATE_WIDTH))
169 .rounded_full()
170 .bg(fill)
171 .with_animation(
172 ElementId::Name(format!("{id}-pulse").into()),
173 Animation::new(INDETERMINATE_PERIOD).repeat(),
174 |segment, delta| {
175 let travel = 1. + INDETERMINATE_WIDTH;
176 segment.left(relative(
177 (delta + 0.3).fract() * travel - INDETERMINATE_WIDTH,
178 ))
179 },
180 ),
181 )
182 .into_any_element(),
183 }
184}
185
186fn ring_pixels(size: RingSize) -> f32 {
187 match size {
188 RingSize::Tiny => 16.,
189 RingSize::Small => 20.,
190 RingSize::Medium => 28.,
191 RingSize::Large => 40.,
192 }
193}
194
195pub(super) fn progress_ring_view(ring: &CardProgressRing, id: &str) -> AnyElement {
196 let pixels = ring_pixels(ring.size);
197 let spinner = icon(IconName::Loader, pixels, theme::accent_text()).with_animation(
198 ElementId::Name(format!("{id}-spin").into()),
199 Animation::new(RING_PERIOD).repeat(),
200 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
201 );
202 let label = ring.label.clone().map(|label| {
203 div()
204 .text_size(px(13.))
205 .text_color(theme::text_soft())
206 .child(label)
207 });
208 let vertical = matches!(
209 ring.label_position,
210 LabelPosition::Above | LabelPosition::Below
211 );
212 let (label_before, label_after) = match ring.label_position {
213 LabelPosition::Before | LabelPosition::Above => (label, None),
214 LabelPosition::After | LabelPosition::Below => (None, label),
215 };
216 div()
217 .flex()
218 .items_center()
219 .gap(px(RING_LABEL_GAP))
220 .map(|frame| {
221 if vertical {
222 frame.flex_col()
223 } else {
224 frame.flex_row()
225 }
226 })
227 .children(label_before)
228 .child(spinner)
229 .children(label_after)
230 .into_any_element()
231}
232
233pub(super) fn compound_button_view(
234 button: &CardCompoundButton,
235 id: &str,
236 context: &CardContext,
237) -> AnyElement {
238 let clickable = button
239 .select_action
240 .as_ref()
241 .is_some_and(|action| action.is_clickable());
242 let face = h_flex()
243 .w_full()
244 .items_center()
245 .gap(px(COMPOUND_GAP))
246 .p(px(COMPOUND_PADDING))
247 .rounded(px(COMPOUND_RADIUS))
248 .border_1()
249 .border_color(theme::border_strong())
250 .when(!clickable, |face| face.opacity(0.6))
251 .children(
252 button
253 .icon
254 .as_deref()
255 .map(|name| glyph_view(name, COMPOUND_ICON_SIZE, theme::accent_text())),
256 )
257 .child(
258 v_flex()
259 .flex_1()
260 .min_w(px(0.))
261 .child(
262 div()
263 .text_size(px(13.5))
264 .font_weight(FontWeight::SEMIBOLD)
265 .text_color(theme::text_strong())
266 .child(button.title.clone()),
267 )
268 .children(button.description.clone().map(|description| {
269 div()
270 .text_size(px(12.))
271 .text_color(theme::text_muted())
272 .child(description)
273 })),
274 )
275 .children(button.badge.clone().map(|badge| {
276 div()
277 .flex_none()
278 .px(px(6.))
279 .h(px(18.))
280 .flex()
281 .items_center()
282 .rounded_full()
283 .bg(theme::badge_muted())
284 .text_size(px(11.))
285 .font_weight(FontWeight::BOLD)
286 .text_color(theme::text_strong())
287 .child(badge)
288 }));
289 selectable(
290 face.into_any_element(),
291 button.select_action.as_ref(),
292 id,
293 false,
294 context,
295 )
296}
crates/app/src/views/conversation.rs +29 −1
@@ -17,7 +17,7 @@ use gpui_kit::component::{
17 17 use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 19 use store::{MessageRecord, OutboxState, OutboxTarget};
20 use teams_core::{FileCard, LinkPreview};
20 use teams_core::{ExecuteAction, FileCard, LinkPreview};
21 21
22 22 mod feed;
23 23 mod pins;
@@ -36,6 +36,7 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
36 36 use super::widgets::{icon, symbol};
37 37 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
38 38 use crate::backend::Engine;
39 use crate::card_state::CardScope;
39 40 use crate::data::{is_one_on_one, others};
40 41 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
41 42 use crate::emoji;
@@ -2500,6 +2501,22 @@ impl ConversationView {
2500 2501 }
2501 2502 }
2502 2503
2504 fn refresh_card(
2505 &mut self,
2506 key: &str,
2507 card_index: usize,
2508 action: ExecuteAction,
2509 cx: &mut Context<Self>,
2510 ) {
2511 let Some(conversation_id) = self.conversation_id() else {
2512 return;
2513 };
2514 let scope = CardScope::message(&conversation_id, key, card_index);
2515 self.app.update(cx, |state, cx| {
2516 state.refresh_card_manually(scope, action, cx)
2517 });
2518 }
2519
2503 2520 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2504 2521 self.app.update(cx, |state, cx| {
2505 2522 state.raise_notice(message.to_owned(), None, cx)
@@ -2531,6 +2548,7 @@ impl ConversationView {
2531 2548 key: &str,
2532 2549 own: bool,
2533 2550 mine: HashSet<String>,
2551 refresh: Option<(usize, ExecuteAction)>,
2534 2552 view: WeakEntity<Self>,
2535 2553 cx: &App,
2536 2554 ) -> MessageMenu {
@@ -2563,6 +2581,15 @@ impl ConversationView {
2563 2581 .ok();
2564 2582 })
2565 2583 };
2584 let refresh_card = refresh.map(|(card_index, refresh_action)| {
2585 let (view, key) = (view.clone(), key.to_owned());
2586 Rc::new(move |_: &mut Window, cx: &mut App| {
2587 view.update(cx, |this, cx| {
2588 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
2589 })
2590 .ok();
2591 }) as Action
2592 });
2566 2593 let chat_id = self.chat_id();
2567 2594 let state = self.app.read(cx);
2568 2595 let saved = self
@@ -2589,6 +2616,7 @@ impl ConversationView {
2589 2616 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2590 2617 mark_unread: (in_chat && !own)
2591 2618 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2619 refresh_card,
2592 2620 pin,
2593 2621 hover,
2594 2622 picker: self.picker.clone(),
@@ -17,7 +17,7 @@ use gpui_kit::component::{
17use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{MessageRecord, OutboxState, OutboxTarget};
19use store::{MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{FileCard, LinkPreview};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
21
22mod feed;
22mod feed;
23mod pins;
23mod pins;
@@ -36,6 +36,7 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
36use super::widgets::{icon, symbol};
36use super::widgets::{icon, symbol};
37use crate::app_state::{AppEvent, AppState, Selection, selection_title};
37use crate::app_state::{AppEvent, AppState, Selection, selection_title};
38use crate::backend::Engine;
38use crate::backend::Engine;
39use crate::card_state::CardScope;
39use crate::data::{is_one_on_one, others};
40use crate::data::{is_one_on_one, others};
40use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
41use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
41use crate::emoji;
42use crate::emoji;
@@ -2500,6 +2501,22 @@ impl ConversationView {
2500 }
2501 }
2501 }
2502 }
2502
2503
2504 fn refresh_card(
2505 &mut self,
2506 key: &str,
2507 card_index: usize,
2508 action: ExecuteAction,
2509 cx: &mut Context<Self>,
2510 ) {
2511 let Some(conversation_id) = self.conversation_id() else {
2512 return;
2513 };
2514 let scope = CardScope::message(&conversation_id, key, card_index);
2515 self.app.update(cx, |state, cx| {
2516 state.refresh_card_manually(scope, action, cx)
2517 });
2518 }
2519
2503 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2520 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2504 self.app.update(cx, |state, cx| {
2521 self.app.update(cx, |state, cx| {
2505 state.raise_notice(message.to_owned(), None, cx)
2522 state.raise_notice(message.to_owned(), None, cx)
@@ -2531,6 +2548,7 @@ impl ConversationView {
2531 key: &str,
2548 key: &str,
2532 own: bool,
2549 own: bool,
2533 mine: HashSet<String>,
2550 mine: HashSet<String>,
2551 refresh: Option<(usize, ExecuteAction)>,
2534 view: WeakEntity<Self>,
2552 view: WeakEntity<Self>,
2535 cx: &App,
2553 cx: &App,
2536 ) -> MessageMenu {
2554 ) -> MessageMenu {
@@ -2563,6 +2581,15 @@ impl ConversationView {
2563 .ok();
2581 .ok();
2564 })
2582 })
2565 };
2583 };
2584 let refresh_card = refresh.map(|(card_index, refresh_action)| {
2585 let (view, key) = (view.clone(), key.to_owned());
2586 Rc::new(move |_: &mut Window, cx: &mut App| {
2587 view.update(cx, |this, cx| {
2588 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
2589 })
2590 .ok();
2591 }) as Action
2592 });
2566 let chat_id = self.chat_id();
2593 let chat_id = self.chat_id();
2567 let state = self.app.read(cx);
2594 let state = self.app.read(cx);
2568 let saved = self
2595 let saved = self
@@ -2589,6 +2616,7 @@ impl ConversationView {
2589 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2616 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2590 mark_unread: (in_chat && !own)
2617 mark_unread: (in_chat && !own)
2591 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2618 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2619 refresh_card,
2592 pin,
2620 pin,
2593 hover,
2621 hover,
2594 picker: self.picker.clone(),
2622 picker: self.picker.clone(),
crates/app/src/views/conversation/render_env.rs +20 −2
@@ -11,7 +11,7 @@ use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
11 11 use crate::app_state::AppState;
12 12 use crate::rows::{Delivery, MessageRow, PostRow};
13 13 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14 use crate::views::adaptive_card::ensure_cards_inputs;
14 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
15 15 use crate::views::composer::Composer;
16 16 use crate::views::message_row::{DeliveryActions, RowActions};
17 17 use crate::views::post_card::{PostAction, PostActions};
@@ -153,7 +153,18 @@ impl RenderEnv {
153 153 .filter(|chip| chip.mine)
154 154 .map(|chip| chip.glyph())
155 155 .collect();
156 let menu = this.message_menu(&message.key, message.own, mine, view.clone(), cx);
156 let refresh =
157 message
158 .adaptive_cards
159 .iter()
160 .enumerate()
161 .find_map(|(index, card)| {
162 card.refresh
163 .as_ref()
164 .map(|refresh| (index, refresh.action.clone()))
165 });
166 let menu =
167 this.message_menu(&message.key, message.own, mine, refresh, view.clone(), cx);
157 168 let react = menu.react.clone();
158 169 let visible = this.toolbar_visible(&message.key);
159 170 let controls = (!message.reactions.is_empty())
@@ -190,6 +201,13 @@ impl RenderEnv {
190 201 window,
191 202 cx,
192 203 );
204 request_card_refreshes(
205 &self.app,
206 &message.adaptive_cards,
207 &message.conversation_id,
208 &message.key,
209 cx,
210 );
193 211 RowActions {
194 212 bot,
195 213 delivery,
@@ -11,7 +11,7 @@ use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
11use crate::app_state::AppState;
11use crate::app_state::AppState;
12use crate::rows::{Delivery, MessageRow, PostRow};
12use crate::rows::{Delivery, MessageRow, PostRow};
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14use crate::views::adaptive_card::ensure_cards_inputs;
14use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
15use crate::views::composer::Composer;
15use crate::views::composer::Composer;
16use crate::views::message_row::{DeliveryActions, RowActions};
16use crate::views::message_row::{DeliveryActions, RowActions};
17use crate::views::post_card::{PostAction, PostActions};
17use crate::views::post_card::{PostAction, PostActions};
@@ -153,7 +153,18 @@ impl RenderEnv {
153 .filter(|chip| chip.mine)
153 .filter(|chip| chip.mine)
154 .map(|chip| chip.glyph())
154 .map(|chip| chip.glyph())
155 .collect();
155 .collect();
156 let menu = this.message_menu(&message.key, message.own, mine, view.clone(), cx);
156 let refresh =
157 message
158 .adaptive_cards
159 .iter()
160 .enumerate()
161 .find_map(|(index, card)| {
162 card.refresh
163 .as_ref()
164 .map(|refresh| (index, refresh.action.clone()))
165 });
166 let menu =
167 this.message_menu(&message.key, message.own, mine, refresh, view.clone(), cx);
157 let react = menu.react.clone();
168 let react = menu.react.clone();
158 let visible = this.toolbar_visible(&message.key);
169 let visible = this.toolbar_visible(&message.key);
159 let controls = (!message.reactions.is_empty())
170 let controls = (!message.reactions.is_empty())
@@ -190,6 +201,13 @@ impl RenderEnv {
190 window,
201 window,
191 cx,
202 cx,
192 );
203 );
204 request_card_refreshes(
205 &self.app,
206 &message.adaptive_cards,
207 &message.conversation_id,
208 &message.key,
209 cx,
210 );
193 RowActions {
211 RowActions {
194 bot,
212 bot,
195 delivery,
213 delivery,
crates/app/src/views/message_actions.rs +18 −1
@@ -39,6 +39,7 @@ pub struct MessageMenu {
39 39 pub edit: Option<Action>,
40 40 pub delete: Option<Action>,
41 41 pub mark_unread: Option<Action>,
42 pub refresh_card: Option<Action>,
42 43 pub pin: OpenChange,
43 44 pub hover: HoverChange,
44 45 pub picker: Entity<ReactionPicker>,
@@ -113,7 +114,19 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {
113 114 }
114 115
115 116 fn more_button(menu: &MessageMenu) -> AnyElement {
116 let (reply, forward, copy_link, copy, save, toggle_pinned, edit, delete, mark_unread, pin) = (
117 let (
118 reply,
119 forward,
120 copy_link,
121 copy,
122 save,
123 toggle_pinned,
124 edit,
125 delete,
126 mark_unread,
127 refresh_card,
128 pin,
129 ) = (
117 130 menu.reply.clone(),
118 131 menu.forward.clone(),
119 132 menu.copy_link.clone(),
@@ -123,6 +136,7 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
123 136 menu.edit.clone(),
124 137 menu.delete.clone(),
125 138 menu.mark_unread.clone(),
139 menu.refresh_card.clone(),
126 140 menu.pin.clone(),
127 141 );
128 142 let (saved, pinned) = (menu.saved, menu.pinned);
@@ -147,6 +161,9 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
147 161 if let Some(copy_link) = copy_link.clone() {
148 162 popup = popup.item(item("Copy link", IconName::Link, copy_link));
149 163 }
164 if let Some(refresh_card) = refresh_card.clone() {
165 popup = popup.item(item("Refresh card", IconName::RefreshCw, refresh_card));
166 }
150 167 popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
151 168 if let Some(save) = save.clone() {
152 169 popup = popup.item(if saved {
@@ -39,6 +39,7 @@ pub struct MessageMenu {
39 pub edit: Option<Action>,
39 pub edit: Option<Action>,
40 pub delete: Option<Action>,
40 pub delete: Option<Action>,
41 pub mark_unread: Option<Action>,
41 pub mark_unread: Option<Action>,
42 pub refresh_card: Option<Action>,
42 pub pin: OpenChange,
43 pub pin: OpenChange,
43 pub hover: HoverChange,
44 pub hover: HoverChange,
44 pub picker: Entity<ReactionPicker>,
45 pub picker: Entity<ReactionPicker>,
@@ -113,7 +114,19 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {
113}
114}
114
115
115fn more_button(menu: &MessageMenu) -> AnyElement {
116fn more_button(menu: &MessageMenu) -> AnyElement {
116 let (reply, forward, copy_link, copy, save, toggle_pinned, edit, delete, mark_unread, pin) = (
117 let (
118 reply,
119 forward,
120 copy_link,
121 copy,
122 save,
123 toggle_pinned,
124 edit,
125 delete,
126 mark_unread,
127 refresh_card,
128 pin,
129 ) = (
117 menu.reply.clone(),
130 menu.reply.clone(),
118 menu.forward.clone(),
131 menu.forward.clone(),
119 menu.copy_link.clone(),
132 menu.copy_link.clone(),
@@ -123,6 +136,7 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
123 menu.edit.clone(),
136 menu.edit.clone(),
124 menu.delete.clone(),
137 menu.delete.clone(),
125 menu.mark_unread.clone(),
138 menu.mark_unread.clone(),
139 menu.refresh_card.clone(),
126 menu.pin.clone(),
140 menu.pin.clone(),
127 );
141 );
128 let (saved, pinned) = (menu.saved, menu.pinned);
142 let (saved, pinned) = (menu.saved, menu.pinned);
@@ -147,6 +161,9 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
147 if let Some(copy_link) = copy_link.clone() {
161 if let Some(copy_link) = copy_link.clone() {
148 popup = popup.item(item("Copy link", IconName::Link, copy_link));
162 popup = popup.item(item("Copy link", IconName::Link, copy_link));
149 }
163 }
164 if let Some(refresh_card) = refresh_card.clone() {
165 popup = popup.item(item("Refresh card", IconName::RefreshCw, refresh_card));
166 }
150 popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
167 popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
151 if let Some(save) = save.clone() {
168 if let Some(save) = save.clone() {
152 popup = popup.item(if saved {
169 popup = popup.item(if saved {
crates/app/src/views/mod.rs +7 −0
@@ -3,7 +3,14 @@ pub mod adaptive_card;
3 3 pub mod attachment_tray;
4 4 pub mod attachments;
5 5 pub mod avatar;
6 pub mod card_carousel;
7 pub mod card_chart;
8 pub mod card_code_block;
9 pub mod card_icon;
6 10 pub mod card_input;
11 pub mod card_media;
12 pub mod card_table;
13 pub mod card_widgets;
7 14 pub mod composer;
8 15 pub mod conversation;
9 16 pub mod dialog_overlay;
@@ -3,7 +3,14 @@ pub mod adaptive_card;
3pub mod attachment_tray;
3pub mod attachment_tray;
4pub mod attachments;
4pub mod attachments;
5pub mod avatar;
5pub mod avatar;
6pub mod card_carousel;
7pub mod card_chart;
8pub mod card_code_block;
9pub mod card_icon;
6pub mod card_input;
10pub mod card_input;
11pub mod card_media;
12pub mod card_table;
13pub mod card_widgets;
7pub mod composer;
14pub mod composer;
8pub mod conversation;
15pub mod conversation;
9pub mod dialog_overlay;
16pub mod dialog_overlay;
crates/chatsvc/src/cards.rs +15 −0
@@ -13,6 +13,7 @@ const BOT_MRI_PREFIX: &str = "28:";
13 13 const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";
14 14 const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";
15 15 const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";
16 const SEARCH_RESPONSE_TYPE: &str = "application/vnd.microsoft.search.searchResponse";
16 17 const ERROR_STATUS_FLOOR: u64 = 400;
17 18
18 19 pub fn spaces_scope() -> Scope {
@@ -75,6 +76,7 @@ pub enum InvokeResponse {
75 76 Empty,
76 77 Card(Value),
77 78 Message(String),
79 Search(Value),
78 80 Task(TaskResponse),
79 81 Failed { status_code: u16, message: String },
80 82 }
@@ -247,6 +249,7 @@ pub fn parse_invoke_response(body: &Value) -> InvokeResponse {
247 249 .map(|card| InvokeResponse::Card(card.clone()))
248 250 .unwrap_or(InvokeResponse::Empty),
249 251 Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),
252 Some(SEARCH_RESPONSE_TYPE) => InvokeResponse::Search(value.cloned().unwrap_or(Value::Null)),
250 253 _ => InvokeResponse::Empty,
251 254 }
252 255 }
@@ -536,6 +539,18 @@ mod tests {
536 539 );
537 540 }
538 541
542 #[test]
543 fn search_answers_carry_the_results_value() {
544 let value = json!({"results": [{"title": "Ada", "value": "ada"}]});
545 assert_eq!(
546 parse_invoke_response(&json!({
547 "type": "application/vnd.microsoft.search.searchResponse",
548 "value": value
549 })),
550 InvokeResponse::Search(value)
551 );
552 }
553
539 554 #[test]
540 555 fn universal_action_answers() {
541 556 assert_eq!(
@@ -13,6 +13,7 @@ const BOT_MRI_PREFIX: &str = "28:";
13const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";
13const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";
14const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";
14const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";
15const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";
15const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";
16const SEARCH_RESPONSE_TYPE: &str = "application/vnd.microsoft.search.searchResponse";
16const ERROR_STATUS_FLOOR: u64 = 400;
17const ERROR_STATUS_FLOOR: u64 = 400;
17
18
18pub fn spaces_scope() -> Scope {
19pub fn spaces_scope() -> Scope {
@@ -75,6 +76,7 @@ pub enum InvokeResponse {
75 Empty,
76 Empty,
76 Card(Value),
77 Card(Value),
77 Message(String),
78 Message(String),
79 Search(Value),
78 Task(TaskResponse),
80 Task(TaskResponse),
79 Failed { status_code: u16, message: String },
81 Failed { status_code: u16, message: String },
80}
82}
@@ -247,6 +249,7 @@ pub fn parse_invoke_response(body: &Value) -> InvokeResponse {
247 .map(|card| InvokeResponse::Card(card.clone()))
249 .map(|card| InvokeResponse::Card(card.clone()))
248 .unwrap_or(InvokeResponse::Empty),
250 .unwrap_or(InvokeResponse::Empty),
249 Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),
251 Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),
252 Some(SEARCH_RESPONSE_TYPE) => InvokeResponse::Search(value.cloned().unwrap_or(Value::Null)),
250 _ => InvokeResponse::Empty,
253 _ => InvokeResponse::Empty,
251 }
254 }
252}
255}
@@ -536,6 +539,18 @@ mod tests {
536 );
539 );
537 }
540 }
538
541
542 #[test]
543 fn search_answers_carry_the_results_value() {
544 let value = json!({"results": [{"title": "Ada", "value": "ada"}]});
545 assert_eq!(
546 parse_invoke_response(&json!({
547 "type": "application/vnd.microsoft.search.searchResponse",
548 "value": value
549 })),
550 InvokeResponse::Search(value)
551 );
552 }
553
539 #[test]
554 #[test]
540 fn universal_action_answers() {
555 fn universal_action_answers() {
541 assert_eq!(
556 assert_eq!(
crates/core/src/adaptive_card.rs +611 −100
@@ -2,13 +2,36 @@ use std::collections::HashMap;
2 2
3 3 use serde_json::{Map, Value, json};
4 4
5 use crate::card_inputs::{CardInput, merge_input_data, parse_input};
6 use crate::markdown::markdown_to_html;
7 use crate::spans::{Span, html_to_spans};
5 use crate::card_date::format_card_dates;
6 use crate::card_chart::{CardChart, is_chart_type, parse_chart};
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};
8 20 use crate::stored::push_plain;
9 21
10 22 const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
11 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;
12 35 const ACTION_TYPE_PREFIX: &str = "Action.";
13 36 const INPUT_TYPE_PREFIX: &str = "Input.";
14 37 const OPEN_URL_ACTION: &str = "Action.OpenUrl";
@@ -21,6 +44,13 @@ pub const CARD_THEME: &str = "dark";
21 44 const MESSAGE_BACK_NAME: &str = "messageback";
22 45 const TASK_FETCH_NAME: &str = "task/fetch";
23 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:";
24 54 const PIXEL_SUFFIX: &str = "px";
25 55
26 56 #[derive(Debug, Clone, PartialEq)]
@@ -28,6 +58,36 @@ pub struct AdaptiveCard {
28 58 pub full_width: bool,
29 59 pub items: Vec<CardItem>,
30 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)
31 91 }
32 92
33 93 #[derive(Debug, Clone, PartialEq)]
@@ -36,6 +96,8 @@ pub struct CardItem {
36 96 pub visible: bool,
37 97 pub separator: bool,
38 98 pub spacing: CardSpacing,
99 pub stretch: bool,
100 pub target_width: Option<TargetWidth>,
39 101 pub element: CardElement,
40 102 }
41 103
@@ -44,14 +106,29 @@ pub enum CardElement {
44 106 Text(CardText),
45 107 Image(CardImage),
46 108 ImageSet(Vec<CardImage>),
47 Columns(Vec<CardColumn>),
109 Columns {
110 columns: Vec<CardColumn>,
111 layout: ContainerLayout,
112 },
48 113 Container {
49 style: ContainerStyle,
114 layout: ContainerLayout,
50 115 items: Vec<CardItem>,
116 select_action: Option<CardAction>,
51 117 },
52 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),
53 128 Actions(Vec<CardAction>),
54 129 Input(CardInput),
130 Rating(RatingDisplay),
131 Chart(CardChart),
55 132 }
56 133
57 134 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -95,7 +172,20 @@ pub enum ImageSize {
95 172 }
96 173
97 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)]
98 187 pub enum ContainerStyle {
188 #[default]
99 189 Default,
100 190 Emphasis,
101 191 Accent,
@@ -104,8 +194,9 @@ pub enum ContainerStyle {
104 194 Attention,
105 195 }
106 196
107 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
197 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
108 198 pub enum VerticalAlignment {
199 #[default]
109 200 Top,
110 201 Center,
111 202 Bottom,
@@ -127,6 +218,9 @@ pub struct CardText {
127 218 pub color: TextColor,
128 219 pub subtle: bool,
129 220 pub wrap: bool,
221 pub max_lines: Option<usize>,
222 pub alignment: Option<HorizontalAlignment>,
223 pub monospace: bool,
130 224 }
131 225
132 226 #[derive(Debug, Clone, PartialEq)]
@@ -136,13 +230,35 @@ pub struct CardImage {
136 230 pub width: Option<f32>,
137 231 pub height: Option<f32>,
138 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>,
139 253 }
140 254
141 255 #[derive(Debug, Clone, PartialEq)]
142 256 pub struct CardColumn {
143 257 pub width: ColumnWidth,
144 pub vertical_alignment: VerticalAlignment,
258 pub layout: ContainerLayout,
259 pub target_width: Option<TargetWidth>,
145 260 pub items: Vec<CardItem>,
261 pub select_action: Option<CardAction>,
146 262 }
147 263
148 264 #[derive(Debug, Clone, PartialEq)]
@@ -159,6 +275,15 @@ pub struct CardAction {
159 275 pub enabled: bool,
160 276 pub visible: bool,
161 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),
162 287 }
163 288
164 289 #[derive(Debug, Clone, PartialEq)]
@@ -168,6 +293,7 @@ pub enum CardActionKind {
168 293 Execute(ExecuteAction),
169 294 ShowCard(Box<AdaptiveCard>),
170 295 ToggleVisibility(Vec<ToggleTarget>),
296 Unavailable(&'static str),
171 297 Unsupported,
172 298 }
173 299
@@ -191,10 +317,25 @@ pub struct ToggleTarget {
191 317
192 318 #[derive(Debug, Clone, PartialEq)]
193 319 pub struct InvokePayload {
194 pub name: &'static str,
320 pub name: String,
195 321 pub value: Value,
196 322 }
197 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
198 339 impl SubmitAction {
199 340 pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction {
200 341 let mut data = merge_input_data(&self.data, values);
@@ -221,6 +362,15 @@ impl SubmitAction {
221 362 self.data.get(TEAMS_SETTINGS_KEY)
222 363 }
223 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
224 374 pub fn is_task_fetch(&self) -> bool {
225 375 self.teams_settings()
226 376 .and_then(|settings| string_field(settings, "type"))
@@ -233,10 +383,19 @@ impl SubmitAction {
233 383 data.remove(TEAMS_SETTINGS_KEY);
234 384 data.insert("type".to_owned(), json!(TASK_FETCH_NAME));
235 385 return InvokePayload {
236 name: TASK_FETCH_NAME,
386 name: TASK_FETCH_NAME.to_owned(),
237 387 value: task_value(Value::Object(data)),
238 388 };
239 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 }
240 399 let message_back = self
241 400 .teams_settings()
242 401 .filter(|settings| {
@@ -246,7 +405,7 @@ impl SubmitAction {
246 405 })
247 406 .and_then(|settings| settings.get("value"));
248 407 InvokePayload {
249 name: MESSAGE_BACK_NAME,
408 name: MESSAGE_BACK_NAME.to_owned(),
250 409 value: message_back.unwrap_or(&self.data).clone(),
251 410 }
252 411 }
@@ -254,6 +413,10 @@ impl SubmitAction {
254 413
255 414 impl ExecuteAction {
256 415 pub fn payload(&self) -> InvokePayload {
416 self.payload_for(ExecuteTrigger::Manual)
417 }
418
419 pub fn payload_for(&self, trigger: ExecuteTrigger) -> InvokePayload {
257 420 let mut action = Map::new();
258 421 action.insert("type".to_owned(), json!(EXECUTE_ACTION));
259 422 if let Some(id) = &self.id {
@@ -262,8 +425,8 @@ impl ExecuteAction {
262 425 action.insert("verb".to_owned(), json!(self.verb));
263 426 action.insert("data".to_owned(), self.data.clone());
264 427 InvokePayload {
265 name: EXECUTE_NAME,
266 value: json!({"action": action, "trigger": "manual"}),
428 name: EXECUTE_NAME.to_owned(),
429 value: json!({"action": action, "trigger": trigger.as_str()}),
267 430 }
268 431 }
269 432 }
@@ -276,12 +439,10 @@ impl CardAction {
276 439 pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction {
277 440 let kind = match &self.kind {
278 441 CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)),
279 CardActionKind::Execute(execute) => {
280 CardActionKind::Execute(ExecuteAction {
281 data: merge_input_data(&execute.data, values),
282 ..execute.clone()
283 })
284 }
442 CardActionKind::Execute(execute) => CardActionKind::Execute(ExecuteAction {
443 data: merge_input_data(&execute.data, values),
444 ..execute.clone()
445 }),
285 446 other => other.clone(),
286 447 };
287 448 CardAction {
@@ -299,10 +460,42 @@ impl CardAction {
299 460 }
300 461
301 462 pub fn is_clickable(&self) -> bool {
302 self.enabled && !matches!(self.kind, CardActionKind::Unsupported)
463 self.enabled
464 && !matches!(
465 self.kind,
466 CardActionKind::Unsupported | CardActionKind::Unavailable(_)
467 )
303 468 }
304 469 }
305 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
306 499 impl AdaptiveCard {
307 500 pub fn parse(content: &str) -> Option<AdaptiveCard> {
308 501 Self::from_value(&serde_json::from_str(content).ok()?)
@@ -328,6 +521,9 @@ impl AdaptiveCard {
328 521 full_width,
329 522 items,
330 523 actions,
524 select_action: parse_select_action(root),
525 refresh: parse_refresh(root),
526 layout: ContainerLayout::parse(root),
331 527 })
332 528 }
333 529
@@ -376,13 +572,11 @@ fn collect_visibility(
376 572 if let Some(id) = &item.id {
377 573 visibility.insert(id.clone(), item.visible);
378 574 }
379 match &item.element {
380 CardElement::Columns(columns) => columns
381 .iter()
382 .for_each(|column| collect_visibility(&column.items, &[], visibility)),
383 CardElement::Container { items, .. } => collect_visibility(items, &[], visibility),
384 CardElement::Actions(actions) => collect_visibility(&[], actions, visibility),
385 _ => {}
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);
386 580 }
387 581 }
388 582 for action in actions {
@@ -397,26 +591,46 @@ fn collect_visibility(
397 591
398 592 fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) {
399 593 for item in items {
400 match &item.element {
401 CardElement::Input(input) => inputs.push(input.clone()),
402 CardElement::Columns(columns) => columns
403 .iter()
404 .for_each(|column| collect_inputs(&column.items, inputs)),
405 CardElement::Container { items, .. } => collect_inputs(items, inputs),
406 _ => {}
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);
407 599 }
408 600 }
409 601 }
410 602
411 603 fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) {
412 604 for item in items {
413 match &item.element {
414 CardElement::Actions(set) => actions.extend(set),
415 CardElement::Columns(columns) => columns
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
416 618 .iter()
417 .for_each(|column| collect_item_actions(&column.items, actions)),
418 CardElement::Container { items, .. } => collect_item_actions(items, actions),
419 _ => {}
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(),
420 634 }
421 635 }
422 636 }
@@ -429,10 +643,6 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
429 643 for item in items.iter().filter(|item| item.visible) {
430 644 match &item.element {
431 645 CardElement::Text(text) => push_line(lines, &text.spans),
432 CardElement::Columns(columns) => columns
433 .iter()
434 .for_each(|column| collect_lines(&column.items, lines)),
435 CardElement::Container { items, .. } => collect_lines(items, lines),
436 646 CardElement::Facts(facts) => {
437 647 for fact in facts {
438 648 let mut line = format!("{}: ", fact.title);
@@ -440,10 +650,17 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
440 650 lines.push(line.trim().to_owned());
441 651 }
442 652 }
443 CardElement::Image(_)
444 | CardElement::ImageSet(_)
445 | CardElement::Actions(_)
446 | CardElement::Input(_) => {}
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);
447 664 }
448 665 }
449 666 }
@@ -457,7 +674,7 @@ fn push_line(lines: &mut Vec<String>, spans: &[Span]) {
457 674 }
458 675 }
459 676
460 fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
677 pub(crate) fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
461 678 value
462 679 .and_then(Value::as_array)
463 680 .into_iter()
@@ -472,7 +689,31 @@ fn parse_item(value: &Value) -> Option<CardItem> {
472 689 if !visible && id.is_none() {
473 690 return None;
474 691 }
475 let element = match string_field(value, "type")? {
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")? {
476 717 "TextBlock" => parse_text_block(value),
477 718 "RichTextBlock" => parse_rich_text_block(value),
478 719 "Image" => parse_image(value).map(CardElement::Image),
@@ -480,23 +721,62 @@ fn parse_item(value: &Value) -> Option<CardItem> {
480 721 "ColumnSet" => parse_column_set(value),
481 722 "Container" => parse_container(value),
482 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),
483 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 }
484 738 input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => {
485 739 parse_input(value, input_type).map(CardElement::Input)
486 740 }
487 741 _ => None,
488 };
489 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
490 Some(CardItem {
491 id,
492 visible,
493 separator: value
494 .get("separator")
495 .and_then(Value::as_bool)
496 .unwrap_or(false),
497 spacing: parse_spacing(string_field(value, "spacing")),
498 element,
499 })
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)
500 780 }
501 781
502 782 fn fallback_item(value: &Value) -> Option<CardItem> {
@@ -506,6 +786,8 @@ fn fallback_item(value: &Value) -> Option<CardItem> {
506 786 visible: true,
507 787 separator: false,
508 788 spacing: CardSpacing::Default,
789 stretch: false,
790 target_width: None,
509 791 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
510 792 })
511 793 }
@@ -518,65 +800,139 @@ fn plain_text_block(spans: Vec<Span>) -> CardText {
518 800 color: TextColor::Default,
519 801 subtle: false,
520 802 wrap: true,
803 max_lines: None,
804 alignment: None,
805 monospace: false,
521 806 }
522 807 }
523 808
524 809 fn parse_text_block(value: &Value) -> Option<CardElement> {
525 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"));
526 815 Some(CardElement::Text(CardText {
527 spans: html_to_spans(&markdown_to_html(text)),
528 size: parse_text_size(string_field(value, "size")),
529 bold: string_field(value, "weight").is_some_and(is_bold_weight),
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),
530 822 color: parse_text_color(string_field(value, "color")),
531 823 subtle: bool_field(value, "isSubtle"),
532 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),
533 832 }))
534 833 }
535 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
536 839 fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
537 840 let spans: Vec<Span> = value
538 841 .get("inlines")?
539 842 .as_array()?
540 843 .iter()
541 .filter_map(parse_text_run)
844 .flat_map(parse_text_run)
542 845 .collect();
543 (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans)))
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 })
544 852 }
545 853
546 fn parse_text_run(value: &Value) -> Option<Span> {
547 let text = value
854 fn parse_text_run(value: &Value) -> Vec<Span> {
855 let Some(text) = value
548 856 .as_str()
549 857 .or_else(|| string_field(value, "text"))
550 .filter(|text| !text.is_empty())?;
551 let mut span = Span::Text(text.to_owned());
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 }
552 872 if string_field(value, "weight").is_some_and(is_bold_weight) {
553 span = Span::Bold(vec![span]);
873 spans = vec![Span::Bold(spans)];
554 874 }
555 875 if bool_field(value, "italic") {
556 span = Span::Italic(vec![span]);
876 spans = vec![Span::Italic(spans)];
557 877 }
558 878 if bool_field(value, "strikethrough") {
559 span = Span::Strike(vec![span]);
879 spans = vec![Span::Strike(spans)];
560 880 }
561 881 if bool_field(value, "underline") {
562 span = Span::Underline(vec![span]);
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 }];
563 896 }
564 897 let url = value
565 898 .get("selectAction")
566 899 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
567 900 .and_then(|action| string_field(action, "url"))
568 901 .filter(|url| is_supported_url(url));
569 Some(match url {
570 Some(url) => Span::Link {
902 match url {
903 Some(url) => vec![Span::Link {
571 904 url: url.to_owned(),
572 children: vec![span],
573 },
574 None => span,
575 })
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 }
576 932 }
577 933
578 934 fn parse_image(value: &Value) -> Option<CardImage> {
579 let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?;
935 let url = string_field(value, "url").filter(|url| is_supported_url(url))?;
580 936 Some(CardImage {
581 937 url: url.to_owned(),
582 938 size: parse_image_size(string_field(value, "size")),
@@ -584,6 +940,13 @@ fn parse_image(value: &Value) -> Option<CardImage> {
584 940 height: pixel_field(value, "height"),
585 941 person: string_field(value, "style")
586 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),
587 950 })
588 951 }
589 952
@@ -613,22 +976,25 @@ fn parse_column_set(value: &Value) -> Option<CardElement> {
613 976 let items = parse_items(column.get("items"));
614 977 (!items.is_empty()).then(|| CardColumn {
615 978 width: parse_column_width(column.get("width")),
616 vertical_alignment: parse_vertical_alignment(string_field(
617 column,
618 "verticalContentAlignment",
619 )),
979 layout: ContainerLayout::parse(column),
980 target_width: parse_target_width(column),
620 981 items,
982 select_action: parse_select_action(column),
621 983 })
622 984 })
623 985 .collect();
624 (!columns.is_empty()).then_some(CardElement::Columns(columns))
986 (!columns.is_empty()).then(|| CardElement::Columns {
987 columns,
988 layout: ContainerLayout::parse(value),
989 })
625 990 }
626 991
627 992 fn parse_container(value: &Value) -> Option<CardElement> {
628 993 let items = parse_items(value.get("items"));
629 994 (!items.is_empty()).then(|| CardElement::Container {
630 style: parse_container_style(string_field(value, "style")),
995 layout: ContainerLayout::parse(value),
631 996 items,
997 select_action: parse_select_action(value),
632 998 })
633 999 }
634 1000
@@ -641,14 +1007,77 @@ fn parse_fact_set(value: &Value) -> Option<CardElement> {
641 1007 let title = string_field(fact, "title")?;
642 1008 let text = string_field(fact, "value").unwrap_or_default();
643 1009 Some(CardFact {
644 title: title.to_owned(),
645 value: html_to_spans(&markdown_to_html(text)),
1010 title: format_card_dates(title),
1011 value: html_to_spans(&card_markdown_to_html(&format_card_dates(text))),
646 1012 })
647 1013 })
648 1014 .collect();
649 1015 (!facts.is_empty()).then_some(CardElement::Facts(facts))
650 1016 }
651 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 source_url: source_url.to_owned(),
1030 alt_text: string_field(value, "altText")
1031 .filter(|text| !text.trim().is_empty())
1032 .map(str::to_owned),
1033 })
1034 }
1035
1036 fn parse_icon(value: &Value) -> Option<CardIcon> {
1037 let name = string_field(value, "name").filter(|name| !name.trim().is_empty())?;
1038 Some(CardIcon {
1039 name: name.trim().to_owned(),
1040 size: parse_icon_size(string_field(value, "size")),
1041 color: parse_text_color(string_field(value, "color")),
1042 filled: string_field(value, "style")
1043 .is_some_and(|style| style.eq_ignore_ascii_case("filled")),
1044 select_action: parse_select_action(value),
1045 })
1046 }
1047
1048 pub(crate) fn parse_select_action(value: &Value) -> Option<CardAction> {
1049 let action = parse_action_titled(value.get("selectAction")?, false)?;
1050 matches!(
1051 action.kind,
1052 CardActionKind::OpenUrl(_)
1053 | CardActionKind::Submit(_)
1054 | CardActionKind::Execute(_)
1055 | CardActionKind::ToggleVisibility(_)
1056 )
1057 .then_some(action)
1058 }
1059
1060 fn parse_refresh(value: &Value) -> Option<CardRefresh> {
1061 let refresh = value.get("refresh")?;
1062 let action = parse_action_titled(refresh.get("action")?, false)?;
1063 let CardActionKind::Execute(execute) = action.kind else {
1064 return None;
1065 };
1066 Some(CardRefresh {
1067 action: execute,
1068 user_ids: refresh
1069 .get("userIds")
1070 .and_then(Value::as_array)
1071 .map(|user_ids| {
1072 user_ids
1073 .iter()
1074 .filter_map(Value::as_str)
1075 .map(str::to_owned)
1076 .collect()
1077 }),
1078 })
1079 }
1080
652 1081 fn parse_action_set(value: &Value) -> Option<CardElement> {
653 1082 let actions = parse_actions(value.get("actions"));
654 1083 (!actions.is_empty()).then_some(CardElement::Actions(actions))
@@ -663,7 +1092,11 @@ fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
663 1092 .collect()
664 1093 }
665 1094
666 fn parse_action(value: &Value) -> Option<CardAction> {
1095 pub(crate) fn parse_action(value: &Value) -> Option<CardAction> {
1096 parse_action_titled(value, true)
1097 }
1098
1099 fn parse_action_titled(value: &Value, title_required: bool) -> Option<CardAction> {
667 1100 let id = string_field(value, "id").map(str::to_owned);
668 1101 let visible = is_visible(value);
669 1102 if !visible && id.is_none() {
@@ -675,7 +1108,12 @@ fn parse_action(value: &Value) -> Option<CardAction> {
675 1108 }
676 1109 let title = string_field(value, "title")
677 1110 .map(str::trim)
678 .filter(|title| !title.is_empty())?;
1111 .filter(|title| !title.is_empty());
1112 let title = match title {
1113 Some(title) => title,
1114 None if title_required => return None,
1115 None => "",
1116 };
679 1117 let data = || value.get("data").cloned().unwrap_or(Value::Null);
680 1118 let kind = match action_type {
681 1119 OPEN_URL_ACTION => string_field(value, "url")
@@ -683,7 +1121,7 @@ fn parse_action(value: &Value) -> Option<CardAction> {
683 1121 .map_or(CardActionKind::Unsupported, |url| {
684 1122 CardActionKind::OpenUrl(url.to_owned())
685 1123 }),
686 SUBMIT_ACTION => CardActionKind::Submit(SubmitAction { data: data() }),
1124 SUBMIT_ACTION => submit_kind(data()),
687 1125 EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| {
688 1126 CardActionKind::Execute(ExecuteAction {
689 1127 id: id.clone(),
@@ -718,9 +1156,69 @@ fn parse_action(value: &Value) -> Option<CardAction> {
718 1156 visible,
719 1157 collects_inputs: !string_field(value, "associatedInputs")
720 1158 .is_some_and(|mode| mode.eq_ignore_ascii_case("none")),
1159 icon: string_field(value, "iconUrl").and_then(parse_action_icon),
1160 secondary: string_field(value, "mode")
1161 .is_some_and(|mode| mode.eq_ignore_ascii_case("secondary")),
1162 tooltip: string_field(value, "tooltip")
1163 .map(str::trim)
1164 .filter(|tooltip| !tooltip.is_empty())
1165 .map(str::to_owned),
721 1166 })
722 1167 }
723 1168
1169 fn parse_action_icon(icon_url: &str) -> Option<CardActionIcon> {
1170 match icon_url.strip_prefix(ICON_URL_PREFIX) {
1171 Some(name) => Some(name.split(',').next()?.trim())
1172 .filter(|name| !name.is_empty())
1173 .map(|name| CardActionIcon::Named(name.to_owned())),
1174 None => icon_url
1175 .starts_with(IMAGE_URL_SCHEME)
1176 .then(|| CardActionIcon::Url(icon_url.to_owned())),
1177 }
1178 }
1179
1180 fn submit_kind(data: Value) -> CardActionKind {
1181 let submit = SubmitAction { data };
1182 let settings_type = submit
1183 .teams_settings()
1184 .and_then(|settings| string_field(settings, "type"));
1185 let invoke_type = submit
1186 .invoke_value()
1187 .and_then(|value| string_field(value, "type"));
1188 let names_add_app = [settings_type, invoke_type]
1189 .into_iter()
1190 .flatten()
1191 .any(|name| {
1192 ADD_APP_TYPES
1193 .iter()
1194 .any(|known| known.eq_ignore_ascii_case(name))
1195 });
1196 if names_add_app {
1197 return CardActionKind::Unavailable(ADD_APP_UNAVAILABLE);
1198 }
1199 let open_url = |url: Option<&str>| {
1200 url.filter(|url| is_supported_url(url))
1201 .map_or(CardActionKind::Unsupported, |url| {
1202 CardActionKind::OpenUrl(url.to_owned())
1203 })
1204 };
1205 if settings_type.is_some_and(|name| name.eq_ignore_ascii_case(SIGN_IN_TYPE)) {
1206 let url = submit
1207 .teams_settings()
1208 .and_then(|settings| string_field(settings, "value"));
1209 return open_url(url);
1210 }
1211 if invoke_type == Some(TAB_INFO_TYPE) {
1212 let tab_info = submit.invoke_value().and_then(|value| value.get("tabInfo"));
1213 let url = tab_info
1214 .and_then(|info| string_field(info, "websiteUrl"))
1215 .filter(|url| is_supported_url(url))
1216 .or_else(|| tab_info.and_then(|info| string_field(info, "contentUrl")));
1217 return open_url(url);
1218 }
1219 CardActionKind::Submit(submit)
1220 }
1221
724 1222 fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> {
725 1223 value
726 1224 .and_then(Value::as_array)
@@ -743,7 +1241,7 @@ fn is_bold_weight(weight: &str) -> bool {
743 1241 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
744 1242 }
745 1243
746 fn is_supported_url(url: &str) -> bool {
1244 pub(crate) fn is_supported_url(url: &str) -> bool {
747 1245 SUPPORTED_URL_SCHEMES
748 1246 .iter()
749 1247 .any(|scheme| url.starts_with(scheme))
@@ -756,15 +1254,15 @@ fn is_visible(value: &Value) -> bool {
756 1254 .unwrap_or(true)
757 1255 }
758 1256
759 fn bool_field(value: &Value, key: &str) -> bool {
1257 pub(crate) fn bool_field(value: &Value, key: &str) -> bool {
760 1258 value.get(key).and_then(Value::as_bool).unwrap_or(false)
761 1259 }
762 1260
763 fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
1261 pub(crate) fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
764 1262 value.get(key)?.as_str()
765 1263 }
766 1264
767 fn pixel_field(value: &Value, key: &str) -> Option<f32> {
1265 pub(crate) fn pixel_field(value: &Value, key: &str) -> Option<f32> {
768 1266 let field = value.get(key)?;
769 1267 let pixels = match field.as_str() {
770 1268 Some(text) => text
@@ -778,7 +1276,7 @@ fn pixel_field(value: &Value, key: &str) -> Option<f32> {
778 1276 (pixels > 0.).then_some(pixels)
779 1277 }
780 1278
781 fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
1279 pub(crate) fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
782 1280 let Some(value) = value else {
783 1281 return ColumnWidth::Stretch;
784 1282 };
@@ -824,7 +1322,7 @@ fn parse_text_size(value: Option<&str>) -> TextSize {
824 1322 }
825 1323 }
826 1324
827 fn parse_text_color(value: Option<&str>) -> TextColor {
1325 pub(crate) fn parse_text_color(value: Option<&str>) -> TextColor {
828 1326 match value.map(str::to_ascii_lowercase).as_deref() {
829 1327 Some("dark") => TextColor::Dark,
830 1328 Some("light") => TextColor::Light,
@@ -846,7 +1344,20 @@ fn parse_image_size(value: Option<&str>) -> ImageSize {
846 1344 }
847 1345 }
848 1346
849 fn parse_container_style(value: Option<&str>) -> ContainerStyle {
1347 fn parse_icon_size(value: Option<&str>) -> IconSize {
1348 match value.map(str::to_ascii_lowercase).as_deref() {
1349 Some("xxsmall") => IconSize::ExtraExtraSmall,
1350 Some("xsmall") => IconSize::ExtraSmall,
1351 Some("small") => IconSize::Small,
1352 Some("medium") => IconSize::Medium,
1353 Some("large") => IconSize::Large,
1354 Some("xlarge") => IconSize::ExtraLarge,
1355 Some("xxlarge") => IconSize::ExtraExtraLarge,
1356 _ => IconSize::Standard,
1357 }
1358 }
1359
1360 pub(crate) fn parse_container_style(value: Option<&str>) -> ContainerStyle {
850 1361 match value.map(str::to_ascii_lowercase).as_deref() {
851 1362 Some("emphasis") => ContainerStyle::Emphasis,
852 1363 Some("accent") => ContainerStyle::Accent,
@@ -857,7 +1368,7 @@ fn parse_container_style(value: Option<&str>) -> ContainerStyle {
857 1368 }
858 1369 }
859 1370
860 fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
1371 pub(crate) fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
861 1372 match value.map(str::to_ascii_lowercase).as_deref() {
862 1373 Some("center") => VerticalAlignment::Center,
863 1374 Some("bottom") => VerticalAlignment::Bottom,
@@ -2,13 +2,36 @@ use std::collections::HashMap;
2
2
3use serde_json::{Map, Value, json};
3use serde_json::{Map, Value, json};
4
4
5use crate::card_inputs::{CardInput, merge_input_data, parse_input};
5use crate::card_date::format_card_dates;
6use crate::markdown::markdown_to_html;
6use crate::card_chart::{CardChart, is_chart_type, parse_chart};
7use crate::spans::{Span, html_to_spans};
7use crate::card_inputs::{CardInput, RatingDisplay, merge_input_data, parse_input, parse_rating};
8use crate::card_layout::{
9 ContainerLayout, HorizontalAlignment, parse_color_hex, parse_horizontal_alignment,
10};
11use crate::card_table::{CardTable, parse_table};
12use 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};
17use crate::card_width::TargetWidth;
18use crate::markdown::{card_markdown_to_html, split_mentions};
19use crate::spans::{FontSize, Span, html_to_spans};
8use crate::stored::push_plain;
20use crate::stored::push_plain;
9
21
10const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
22const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
11const IMAGE_URL_SCHEME: &str = "https://";
23const IMAGE_URL_SCHEME: &str = "https://";
24const SUPPORTED_CARD_VERSION: (u32, u32) = (1, 6);
25const ADAPTIVE_CARDS_FEATURE: &str = "adaptiveCards";
26const FALLBACK_DROP: &str = "drop";
27const MAX_PRIMARY_ACTIONS: usize = 6;
28const ACCENT_RUN_COLOR: u32 = 0xe08a5c;
29const GOOD_RUN_COLOR: u32 = 0x22c55e;
30const WARNING_RUN_COLOR: u32 = 0xfbbf24;
31const ATTENTION_RUN_COLOR: u32 = 0xf87171;
32const SUBTLE_RUN_COLOR: u32 = 0xa1a1a6;
33const HIGHLIGHT_BACKGROUND: u32 = 0xfacc15;
34const HIGHLIGHT_FOREGROUND: u32 = 0x18181b;
12const ACTION_TYPE_PREFIX: &str = "Action.";
35const ACTION_TYPE_PREFIX: &str = "Action.";
13const INPUT_TYPE_PREFIX: &str = "Input.";
36const INPUT_TYPE_PREFIX: &str = "Input.";
14const OPEN_URL_ACTION: &str = "Action.OpenUrl";
37const OPEN_URL_ACTION: &str = "Action.OpenUrl";
@@ -21,6 +44,13 @@ pub const CARD_THEME: &str = "dark";
21const MESSAGE_BACK_NAME: &str = "messageback";
44const MESSAGE_BACK_NAME: &str = "messageback";
22const TASK_FETCH_NAME: &str = "task/fetch";
45const TASK_FETCH_NAME: &str = "task/fetch";
23const EXECUTE_NAME: &str = "adaptiveCard/action";
46const EXECUTE_NAME: &str = "adaptiveCard/action";
47const INVOKE_TYPE: &str = "invoke";
48const SIGN_IN_TYPE: &str = "signin";
49const TAB_INFO_TYPE: &str = "tab/tabInfoAction";
50const ADD_APP_TYPES: [&str; 2] = ["appInstallToConversation", "addAppToConversation"];
51const ADD_APP_UNAVAILABLE: &str = "Adding apps is not supported";
52const AUTO_REFRESH_MEMBER_LIMIT: usize = 60;
53const ICON_URL_PREFIX: &str = "icon:";
24const PIXEL_SUFFIX: &str = "px";
54const PIXEL_SUFFIX: &str = "px";
25
55
26#[derive(Debug, Clone, PartialEq)]
56#[derive(Debug, Clone, PartialEq)]
@@ -28,6 +58,36 @@ pub struct AdaptiveCard {
28 pub full_width: bool,
58 pub full_width: bool,
29 pub items: Vec<CardItem>,
59 pub items: Vec<CardItem>,
30 pub actions: Vec<CardAction>,
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)]
67pub struct CardRefresh {
68 pub action: ExecuteAction,
69 pub user_ids: Option<Vec<String>>,
70}
71
72impl 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
89fn user_guid(user_id: &str) -> &str {
90 user_id.rsplit(':').next().unwrap_or(user_id)
31}
91}
32
92
33#[derive(Debug, Clone, PartialEq)]
93#[derive(Debug, Clone, PartialEq)]
@@ -36,6 +96,8 @@ pub struct CardItem {
36 pub visible: bool,
96 pub visible: bool,
37 pub separator: bool,
97 pub separator: bool,
38 pub spacing: CardSpacing,
98 pub spacing: CardSpacing,
99 pub stretch: bool,
100 pub target_width: Option<TargetWidth>,
39 pub element: CardElement,
101 pub element: CardElement,
40}
102}
41
103
@@ -44,14 +106,29 @@ pub enum CardElement {
44 Text(CardText),
106 Text(CardText),
45 Image(CardImage),
107 Image(CardImage),
46 ImageSet(Vec<CardImage>),
108 ImageSet(Vec<CardImage>),
47 Columns(Vec<CardColumn>),
109 Columns {
110 columns: Vec<CardColumn>,
111 layout: ContainerLayout,
112 },
48 Container {
113 Container {
49 style: ContainerStyle,
114 layout: ContainerLayout,
50 items: Vec<CardItem>,
115 items: Vec<CardItem>,
116 select_action: Option<CardAction>,
51 },
117 },
52 Facts(Vec<CardFact>),
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),
53 Actions(Vec<CardAction>),
128 Actions(Vec<CardAction>),
54 Input(CardInput),
129 Input(CardInput),
130 Rating(RatingDisplay),
131 Chart(CardChart),
55}
132}
56
133
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -95,7 +172,20 @@ pub enum ImageSize {
95}
172}
96
173
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub 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)]
98pub enum ContainerStyle {
187pub enum ContainerStyle {
188 #[default]
99 Default,
189 Default,
100 Emphasis,
190 Emphasis,
101 Accent,
191 Accent,
@@ -104,8 +194,9 @@ pub enum ContainerStyle {
104 Attention,
194 Attention,
105}
195}
106
196
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
108pub enum VerticalAlignment {
198pub enum VerticalAlignment {
199 #[default]
109 Top,
200 Top,
110 Center,
201 Center,
111 Bottom,
202 Bottom,
@@ -127,6 +218,9 @@ pub struct CardText {
127 pub color: TextColor,
218 pub color: TextColor,
128 pub subtle: bool,
219 pub subtle: bool,
129 pub wrap: bool,
220 pub wrap: bool,
221 pub max_lines: Option<usize>,
222 pub alignment: Option<HorizontalAlignment>,
223 pub monospace: bool,
130}
224}
131
225
132#[derive(Debug, Clone, PartialEq)]
226#[derive(Debug, Clone, PartialEq)]
@@ -136,13 +230,35 @@ pub struct CardImage {
136 pub width: Option<f32>,
230 pub width: Option<f32>,
137 pub height: Option<f32>,
231 pub height: Option<f32>,
138 pub person: bool,
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)]
240pub 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)]
247pub struct CardIcon {
248 pub name: String,
249 pub size: IconSize,
250 pub color: TextColor,
251 pub filled: bool,
252 pub select_action: Option<CardAction>,
139}
253}
140
254
141#[derive(Debug, Clone, PartialEq)]
255#[derive(Debug, Clone, PartialEq)]
142pub struct CardColumn {
256pub struct CardColumn {
143 pub width: ColumnWidth,
257 pub width: ColumnWidth,
144 pub vertical_alignment: VerticalAlignment,
258 pub layout: ContainerLayout,
259 pub target_width: Option<TargetWidth>,
145 pub items: Vec<CardItem>,
260 pub items: Vec<CardItem>,
261 pub select_action: Option<CardAction>,
146}
262}
147
263
148#[derive(Debug, Clone, PartialEq)]
264#[derive(Debug, Clone, PartialEq)]
@@ -159,6 +275,15 @@ pub struct CardAction {
159 pub enabled: bool,
275 pub enabled: bool,
160 pub visible: bool,
276 pub visible: bool,
161 pub collects_inputs: 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)]
284pub enum CardActionIcon {
285 Named(String),
286 Url(String),
162}
287}
163
288
164#[derive(Debug, Clone, PartialEq)]
289#[derive(Debug, Clone, PartialEq)]
@@ -168,6 +293,7 @@ pub enum CardActionKind {
168 Execute(ExecuteAction),
293 Execute(ExecuteAction),
169 ShowCard(Box<AdaptiveCard>),
294 ShowCard(Box<AdaptiveCard>),
170 ToggleVisibility(Vec<ToggleTarget>),
295 ToggleVisibility(Vec<ToggleTarget>),
296 Unavailable(&'static str),
171 Unsupported,
297 Unsupported,
172}
298}
173
299
@@ -191,10 +317,25 @@ pub struct ToggleTarget {
191
317
192#[derive(Debug, Clone, PartialEq)]
318#[derive(Debug, Clone, PartialEq)]
193pub struct InvokePayload {
319pub struct InvokePayload {
194 pub name: &'static str,
320 pub name: String,
195 pub value: Value,
321 pub value: Value,
196}
322}
197
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum ExecuteTrigger {
326 Manual,
327 Automatic,
328}
329
330impl ExecuteTrigger {
331 fn as_str(self) -> &'static str {
332 match self {
333 ExecuteTrigger::Manual => "manual",
334 ExecuteTrigger::Automatic => "automatic",
335 }
336 }
337}
338
198impl SubmitAction {
339impl SubmitAction {
199 pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction {
340 pub fn with_inputs(&self, values: &Map<String, Value>) -> SubmitAction {
200 let mut data = merge_input_data(&self.data, values);
341 let mut data = merge_input_data(&self.data, values);
@@ -221,6 +362,15 @@ impl SubmitAction {
221 self.data.get(TEAMS_SETTINGS_KEY)
362 self.data.get(TEAMS_SETTINGS_KEY)
222 }
363 }
223
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
224 pub fn is_task_fetch(&self) -> bool {
374 pub fn is_task_fetch(&self) -> bool {
225 self.teams_settings()
375 self.teams_settings()
226 .and_then(|settings| string_field(settings, "type"))
376 .and_then(|settings| string_field(settings, "type"))
@@ -233,10 +383,19 @@ impl SubmitAction {
233 data.remove(TEAMS_SETTINGS_KEY);
383 data.remove(TEAMS_SETTINGS_KEY);
234 data.insert("type".to_owned(), json!(TASK_FETCH_NAME));
384 data.insert("type".to_owned(), json!(TASK_FETCH_NAME));
235 return InvokePayload {
385 return InvokePayload {
236 name: TASK_FETCH_NAME,
386 name: TASK_FETCH_NAME.to_owned(),
237 value: task_value(Value::Object(data)),
387 value: task_value(Value::Object(data)),
238 };
388 };
239 }
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 }
240 let message_back = self
399 let message_back = self
241 .teams_settings()
400 .teams_settings()
242 .filter(|settings| {
401 .filter(|settings| {
@@ -246,7 +405,7 @@ impl SubmitAction {
246 })
405 })
247 .and_then(|settings| settings.get("value"));
406 .and_then(|settings| settings.get("value"));
248 InvokePayload {
407 InvokePayload {
249 name: MESSAGE_BACK_NAME,
408 name: MESSAGE_BACK_NAME.to_owned(),
250 value: message_back.unwrap_or(&self.data).clone(),
409 value: message_back.unwrap_or(&self.data).clone(),
251 }
410 }
252 }
411 }
@@ -254,6 +413,10 @@ impl SubmitAction {
254
413
255impl ExecuteAction {
414impl ExecuteAction {
256 pub fn payload(&self) -> InvokePayload {
415 pub fn payload(&self) -> InvokePayload {
416 self.payload_for(ExecuteTrigger::Manual)
417 }
418
419 pub fn payload_for(&self, trigger: ExecuteTrigger) -> InvokePayload {
257 let mut action = Map::new();
420 let mut action = Map::new();
258 action.insert("type".to_owned(), json!(EXECUTE_ACTION));
421 action.insert("type".to_owned(), json!(EXECUTE_ACTION));
259 if let Some(id) = &self.id {
422 if let Some(id) = &self.id {
@@ -262,8 +425,8 @@ impl ExecuteAction {
262 action.insert("verb".to_owned(), json!(self.verb));
425 action.insert("verb".to_owned(), json!(self.verb));
263 action.insert("data".to_owned(), self.data.clone());
426 action.insert("data".to_owned(), self.data.clone());
264 InvokePayload {
427 InvokePayload {
265 name: EXECUTE_NAME,
428 name: EXECUTE_NAME.to_owned(),
266 value: json!({"action": action, "trigger": "manual"}),
429 value: json!({"action": action, "trigger": trigger.as_str()}),
267 }
430 }
268 }
431 }
269}
432}
@@ -276,12 +439,10 @@ impl CardAction {
276 pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction {
439 pub fn with_inputs(&self, values: &Map<String, Value>) -> CardAction {
277 let kind = match &self.kind {
440 let kind = match &self.kind {
278 CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)),
441 CardActionKind::Submit(submit) => CardActionKind::Submit(submit.with_inputs(values)),
279 CardActionKind::Execute(execute) => {
442 CardActionKind::Execute(execute) => CardActionKind::Execute(ExecuteAction {
280 CardActionKind::Execute(ExecuteAction {
443 data: merge_input_data(&execute.data, values),
281 data: merge_input_data(&execute.data, values),
444 ..execute.clone()
282 ..execute.clone()
445 }),
283 })
284 }
285 other => other.clone(),
446 other => other.clone(),
286 };
447 };
287 CardAction {
448 CardAction {
@@ -299,10 +460,42 @@ impl CardAction {
299 }
460 }
300
461
301 pub fn is_clickable(&self) -> bool {
462 pub fn is_clickable(&self) -> bool {
302 self.enabled && !matches!(self.kind, CardActionKind::Unsupported)
463 self.enabled
464 && !matches!(
465 self.kind,
466 CardActionKind::Unsupported | CardActionKind::Unavailable(_)
467 )
303 }
468 }
304}
469}
305
470
471#[derive(Debug, Clone, PartialEq, Eq)]
472pub struct ActionSplit {
473 pub primary: Vec<usize>,
474 pub overflow: Vec<usize>,
475}
476
477pub 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
306impl AdaptiveCard {
499impl AdaptiveCard {
307 pub fn parse(content: &str) -> Option<AdaptiveCard> {
500 pub fn parse(content: &str) -> Option<AdaptiveCard> {
308 Self::from_value(&serde_json::from_str(content).ok()?)
501 Self::from_value(&serde_json::from_str(content).ok()?)
@@ -328,6 +521,9 @@ impl AdaptiveCard {
328 full_width,
521 full_width,
329 items,
522 items,
330 actions,
523 actions,
524 select_action: parse_select_action(root),
525 refresh: parse_refresh(root),
526 layout: ContainerLayout::parse(root),
331 })
527 })
332 }
528 }
333
529
@@ -376,13 +572,11 @@ fn collect_visibility(
376 if let Some(id) = &item.id {
572 if let Some(id) = &item.id {
377 visibility.insert(id.clone(), item.visible);
573 visibility.insert(id.clone(), item.visible);
378 }
574 }
379 match &item.element {
575 for nested in item.element.nested_items() {
380 CardElement::Columns(columns) => columns
576 collect_visibility(nested, &[], visibility);
381 .iter()
577 }
382 .for_each(|column| collect_visibility(&column.items, &[], visibility)),
578 if let CardElement::Actions(actions) = &item.element {
383 CardElement::Container { items, .. } => collect_visibility(items, &[], visibility),
579 collect_visibility(&[], actions, visibility);
384 CardElement::Actions(actions) => collect_visibility(&[], actions, visibility),
385 _ => {}
386 }
580 }
387 }
581 }
388 for action in actions {
582 for action in actions {
@@ -397,26 +591,46 @@ fn collect_visibility(
397
591
398fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) {
592fn collect_inputs(items: &[CardItem], inputs: &mut Vec<CardInput>) {
399 for item in items {
593 for item in items {
400 match &item.element {
594 if let CardElement::Input(input) = &item.element {
401 CardElement::Input(input) => inputs.push(input.clone()),
595 inputs.push(input.clone());
402 CardElement::Columns(columns) => columns
596 }
403 .iter()
597 for nested in item.element.nested_items() {
404 .for_each(|column| collect_inputs(&column.items, inputs)),
598 collect_inputs(nested, inputs);
405 CardElement::Container { items, .. } => collect_inputs(items, inputs),
406 _ => {}
407 }
599 }
408 }
600 }
409}
601}
410
602
411fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) {
603fn collect_item_actions<'card>(items: &'card [CardItem], actions: &mut Vec<&'card CardAction>) {
412 for item in items {
604 for item in items {
413 match &item.element {
605 if let CardElement::Actions(set) = &item.element {
414 CardElement::Actions(set) => actions.extend(set),
606 actions.extend(set);
415 CardElement::Columns(columns) => columns
607 }
608 for nested in item.element.nested_items() {
609 collect_item_actions(nested, actions);
610 }
611 }
612}
613
614impl CardElement {
615 fn nested_items(&self) -> Vec<&[CardItem]> {
616 match self {
617 CardElement::Columns { columns, .. } => columns
416 .iter()
618 .iter()
417 .for_each(|column| collect_item_actions(&column.items, actions)),
619 .map(|column| column.items.as_slice())
418 CardElement::Container { items, .. } => collect_item_actions(items, actions),
620 .collect(),
419 _ => {}
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(),
420 }
634 }
421 }
635 }
422}
636}
@@ -429,10 +643,6 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
429 for item in items.iter().filter(|item| item.visible) {
643 for item in items.iter().filter(|item| item.visible) {
430 match &item.element {
644 match &item.element {
431 CardElement::Text(text) => push_line(lines, &text.spans),
645 CardElement::Text(text) => push_line(lines, &text.spans),
432 CardElement::Columns(columns) => columns
433 .iter()
434 .for_each(|column| collect_lines(&column.items, lines)),
435 CardElement::Container { items, .. } => collect_lines(items, lines),
436 CardElement::Facts(facts) => {
646 CardElement::Facts(facts) => {
437 for fact in facts {
647 for fact in facts {
438 let mut line = format!("{}: ", fact.title);
648 let mut line = format!("{}: ", fact.title);
@@ -440,10 +650,17 @@ fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
440 lines.push(line.trim().to_owned());
650 lines.push(line.trim().to_owned());
441 }
651 }
442 }
652 }
443 CardElement::Image(_)
653 CardElement::CodeBlock(block) => lines.push(block.code.clone()),
444 | CardElement::ImageSet(_)
654 CardElement::Badge(badge) if !badge.text.is_empty() => lines.push(badge.text.clone()),
445 | CardElement::Actions(_)
655 CardElement::CompoundButton(button) => {
446 | CardElement::Input(_) => {}
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);
447 }
664 }
448 }
665 }
449}
666}
@@ -457,7 +674,7 @@ fn push_line(lines: &mut Vec<String>, spans: &[Span]) {
457 }
674 }
458}
675}
459
676
460fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
677pub(crate) fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
461 value
678 value
462 .and_then(Value::as_array)
679 .and_then(Value::as_array)
463 .into_iter()
680 .into_iter()
@@ -472,7 +689,31 @@ fn parse_item(value: &Value) -> Option<CardItem> {
472 if !visible && id.is_none() {
689 if !visible && id.is_none() {
473 return None;
690 return None;
474 }
691 }
475 let element = match string_field(value, "type")? {
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
708fn parse_target_width(value: &Value) -> Option<TargetWidth> {
709 string_field(value, "targetWidth").and_then(TargetWidth::parse)
710}
711
712fn parse_element(value: &Value) -> Option<CardElement> {
713 if !requirements_met(value) {
714 return None;
715 }
716 match string_field(value, "type")? {
476 "TextBlock" => parse_text_block(value),
717 "TextBlock" => parse_text_block(value),
477 "RichTextBlock" => parse_rich_text_block(value),
718 "RichTextBlock" => parse_rich_text_block(value),
478 "Image" => parse_image(value).map(CardElement::Image),
719 "Image" => parse_image(value).map(CardElement::Image),
@@ -480,23 +721,62 @@ fn parse_item(value: &Value) -> Option<CardItem> {
480 "ColumnSet" => parse_column_set(value),
721 "ColumnSet" => parse_column_set(value),
481 "Container" => parse_container(value),
722 "Container" => parse_container(value),
482 "FactSet" => parse_fact_set(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),
483 "ActionSet" => parse_action_set(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 }
484 input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => {
738 input_type if input_type.starts_with(INPUT_TYPE_PREFIX) => {
485 parse_input(value, input_type).map(CardElement::Input)
739 parse_input(value, input_type).map(CardElement::Input)
486 }
740 }
487 _ => None,
741 _ => None,
488 };
742 }
489 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
743}
490 Some(CardItem {
744
491 id,
745fn requirements_met(value: &Value) -> bool {
492 visible,
746 value
493 separator: value
747 .get("requires")
494 .get("separator")
748 .and_then(Value::as_object)
495 .and_then(Value::as_bool)
749 .is_none_or(|requires| {
496 .unwrap_or(false),
750 requires.iter().all(|(feature, version)| {
497 spacing: parse_spacing(string_field(value, "spacing")),
751 feature.eq_ignore_ascii_case(ADAPTIVE_CARDS_FEATURE)
498 element,
752 && version_supported(version.as_str().unwrap_or_default())
499 })
753 })
754 })
755}
756
757fn 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
769fn 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)
500}
780}
501
781
502fn fallback_item(value: &Value) -> Option<CardItem> {
782fn fallback_item(value: &Value) -> Option<CardItem> {
@@ -506,6 +786,8 @@ fn fallback_item(value: &Value) -> Option<CardItem> {
506 visible: true,
786 visible: true,
507 separator: false,
787 separator: false,
508 spacing: CardSpacing::Default,
788 spacing: CardSpacing::Default,
789 stretch: false,
790 target_width: None,
509 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
791 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
510 })
792 })
511}
793}
@@ -518,65 +800,139 @@ fn plain_text_block(spans: Vec<Span>) -> CardText {
518 color: TextColor::Default,
800 color: TextColor::Default,
519 subtle: false,
801 subtle: false,
520 wrap: true,
802 wrap: true,
803 max_lines: None,
804 alignment: None,
805 monospace: false,
521 }
806 }
522}
807}
523
808
524fn parse_text_block(value: &Value) -> Option<CardElement> {
809fn parse_text_block(value: &Value) -> Option<CardElement> {
525 let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?;
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"));
526 Some(CardElement::Text(CardText {
815 Some(CardElement::Text(CardText {
527 spans: html_to_spans(&markdown_to_html(text)),
816 spans: html_to_spans(&card_markdown_to_html(&text)),
528 size: parse_text_size(string_field(value, "size")),
817 size: match size {
529 bold: string_field(value, "weight").is_some_and(is_bold_weight),
818 TextSize::Default if heading => TextSize::Large,
819 other => other,
820 },
821 bold: heading || string_field(value, "weight").is_some_and(is_bold_weight),
530 color: parse_text_color(string_field(value, "color")),
822 color: parse_text_color(string_field(value, "color")),
531 subtle: bool_field(value, "isSubtle"),
823 subtle: bool_field(value, "isSubtle"),
532 wrap: bool_field(value, "wrap"),
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),
533 }))
832 }))
534}
833}
535
834
835fn is_monospace(value: &Value) -> bool {
836 string_field(value, "fontType").is_some_and(|font| font.eq_ignore_ascii_case("monospace"))
837}
838
536fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
839fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
537 let spans: Vec<Span> = value
840 let spans: Vec<Span> = value
538 .get("inlines")?
841 .get("inlines")?
539 .as_array()?
842 .as_array()?
540 .iter()
843 .iter()
541 .filter_map(parse_text_run)
844 .flat_map(parse_text_run)
542 .collect();
845 .collect();
543 (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans)))
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 })
544}
852}
545
853
546fn parse_text_run(value: &Value) -> Option<Span> {
854fn parse_text_run(value: &Value) -> Vec<Span> {
547 let text = value
855 let Some(text) = value
548 .as_str()
856 .as_str()
549 .or_else(|| string_field(value, "text"))
857 .or_else(|| string_field(value, "text"))
550 .filter(|text| !text.is_empty())?;
858 .filter(|text| !text.is_empty())
551 let mut span = Span::Text(text.to_owned());
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 }
552 if string_field(value, "weight").is_some_and(is_bold_weight) {
872 if string_field(value, "weight").is_some_and(is_bold_weight) {
553 span = Span::Bold(vec![span]);
873 spans = vec![Span::Bold(spans)];
554 }
874 }
555 if bool_field(value, "italic") {
875 if bool_field(value, "italic") {
556 span = Span::Italic(vec![span]);
876 spans = vec![Span::Italic(spans)];
557 }
877 }
558 if bool_field(value, "strikethrough") {
878 if bool_field(value, "strikethrough") {
559 span = Span::Strike(vec![span]);
879 spans = vec![Span::Strike(spans)];
560 }
880 }
561 if bool_field(value, "underline") {
881 if bool_field(value, "underline") {
562 span = Span::Underline(vec![span]);
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 }];
563 }
896 }
564 let url = value
897 let url = value
565 .get("selectAction")
898 .get("selectAction")
566 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
899 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
567 .and_then(|action| string_field(action, "url"))
900 .and_then(|action| string_field(action, "url"))
568 .filter(|url| is_supported_url(url));
901 .filter(|url| is_supported_url(url));
569 Some(match url {
902 match url {
570 Some(url) => Span::Link {
903 Some(url) => vec![Span::Link {
571 url: url.to_owned(),
904 url: url.to_owned(),
572 children: vec![span],
905 children: spans,
573 },
906 }],
574 None => span,
907 None => spans,
575 })
908 }
909}
910
911fn 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
922fn 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 }
576}
932}
577
933
578fn parse_image(value: &Value) -> Option<CardImage> {
934fn parse_image(value: &Value) -> Option<CardImage> {
579 let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?;
935 let url = string_field(value, "url").filter(|url| is_supported_url(url))?;
580 Some(CardImage {
936 Some(CardImage {
581 url: url.to_owned(),
937 url: url.to_owned(),
582 size: parse_image_size(string_field(value, "size")),
938 size: parse_image_size(string_field(value, "size")),
@@ -584,6 +940,13 @@ fn parse_image(value: &Value) -> Option<CardImage> {
584 height: pixel_field(value, "height"),
940 height: pixel_field(value, "height"),
585 person: string_field(value, "style")
941 person: string_field(value, "style")
586 .is_some_and(|style| style.eq_ignore_ascii_case("person")),
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),
587 })
950 })
588}
951}
589
952
@@ -613,22 +976,25 @@ fn parse_column_set(value: &Value) -> Option<CardElement> {
613 let items = parse_items(column.get("items"));
976 let items = parse_items(column.get("items"));
614 (!items.is_empty()).then(|| CardColumn {
977 (!items.is_empty()).then(|| CardColumn {
615 width: parse_column_width(column.get("width")),
978 width: parse_column_width(column.get("width")),
616 vertical_alignment: parse_vertical_alignment(string_field(
979 layout: ContainerLayout::parse(column),
617 column,
980 target_width: parse_target_width(column),
618 "verticalContentAlignment",
619 )),
620 items,
981 items,
982 select_action: parse_select_action(column),
621 })
983 })
622 })
984 })
623 .collect();
985 .collect();
624 (!columns.is_empty()).then_some(CardElement::Columns(columns))
986 (!columns.is_empty()).then(|| CardElement::Columns {
987 columns,
988 layout: ContainerLayout::parse(value),
989 })
625}
990}
626
991
627fn parse_container(value: &Value) -> Option<CardElement> {
992fn parse_container(value: &Value) -> Option<CardElement> {
628 let items = parse_items(value.get("items"));
993 let items = parse_items(value.get("items"));
629 (!items.is_empty()).then(|| CardElement::Container {
994 (!items.is_empty()).then(|| CardElement::Container {
630 style: parse_container_style(string_field(value, "style")),
995 layout: ContainerLayout::parse(value),
631 items,
996 items,
997 select_action: parse_select_action(value),
632 })
998 })
633}
999}
634
1000
@@ -641,14 +1007,77 @@ fn parse_fact_set(value: &Value) -> Option<CardElement> {
641 let title = string_field(fact, "title")?;
1007 let title = string_field(fact, "title")?;
642 let text = string_field(fact, "value").unwrap_or_default();
1008 let text = string_field(fact, "value").unwrap_or_default();
643 Some(CardFact {
1009 Some(CardFact {
644 title: title.to_owned(),
1010 title: format_card_dates(title),
645 value: html_to_spans(&markdown_to_html(text)),
1011 value: html_to_spans(&card_markdown_to_html(&format_card_dates(text))),
646 })
1012 })
647 })
1013 })
648 .collect();
1014 .collect();
649 (!facts.is_empty()).then_some(CardElement::Facts(facts))
1015 (!facts.is_empty()).then_some(CardElement::Facts(facts))
650}
1016}
651
1017
1018fn 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 source_url: source_url.to_owned(),
1030 alt_text: string_field(value, "altText")
1031 .filter(|text| !text.trim().is_empty())
1032 .map(str::to_owned),
1033 })
1034}
1035
1036fn parse_icon(value: &Value) -> Option<CardIcon> {
1037 let name = string_field(value, "name").filter(|name| !name.trim().is_empty())?;
1038 Some(CardIcon {
1039 name: name.trim().to_owned(),
1040 size: parse_icon_size(string_field(value, "size")),
1041 color: parse_text_color(string_field(value, "color")),
1042 filled: string_field(value, "style")
1043 .is_some_and(|style| style.eq_ignore_ascii_case("filled")),
1044 select_action: parse_select_action(value),
1045 })
1046}
1047
1048pub(crate) fn parse_select_action(value: &Value) -> Option<CardAction> {
1049 let action = parse_action_titled(value.get("selectAction")?, false)?;
1050 matches!(
1051 action.kind,
1052 CardActionKind::OpenUrl(_)
1053 | CardActionKind::Submit(_)
1054 | CardActionKind::Execute(_)
1055 | CardActionKind::ToggleVisibility(_)
1056 )
1057 .then_some(action)
1058}
1059
1060fn parse_refresh(value: &Value) -> Option<CardRefresh> {
1061 let refresh = value.get("refresh")?;
1062 let action = parse_action_titled(refresh.get("action")?, false)?;
1063 let CardActionKind::Execute(execute) = action.kind else {
1064 return None;
1065 };
1066 Some(CardRefresh {
1067 action: execute,
1068 user_ids: refresh
1069 .get("userIds")
1070 .and_then(Value::as_array)
1071 .map(|user_ids| {
1072 user_ids
1073 .iter()
1074 .filter_map(Value::as_str)
1075 .map(str::to_owned)
1076 .collect()
1077 }),
1078 })
1079}
1080
652fn parse_action_set(value: &Value) -> Option<CardElement> {
1081fn parse_action_set(value: &Value) -> Option<CardElement> {
653 let actions = parse_actions(value.get("actions"));
1082 let actions = parse_actions(value.get("actions"));
654 (!actions.is_empty()).then_some(CardElement::Actions(actions))
1083 (!actions.is_empty()).then_some(CardElement::Actions(actions))
@@ -663,7 +1092,11 @@ fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
663 .collect()
1092 .collect()
664}
1093}
665
1094
666fn parse_action(value: &Value) -> Option<CardAction> {
1095pub(crate) fn parse_action(value: &Value) -> Option<CardAction> {
1096 parse_action_titled(value, true)
1097}
1098
1099fn parse_action_titled(value: &Value, title_required: bool) -> Option<CardAction> {
667 let id = string_field(value, "id").map(str::to_owned);
1100 let id = string_field(value, "id").map(str::to_owned);
668 let visible = is_visible(value);
1101 let visible = is_visible(value);
669 if !visible && id.is_none() {
1102 if !visible && id.is_none() {
@@ -675,7 +1108,12 @@ fn parse_action(value: &Value) -> Option<CardAction> {
675 }
1108 }
676 let title = string_field(value, "title")
1109 let title = string_field(value, "title")
677 .map(str::trim)
1110 .map(str::trim)
678 .filter(|title| !title.is_empty())?;
1111 .filter(|title| !title.is_empty());
1112 let title = match title {
1113 Some(title) => title,
1114 None if title_required => return None,
1115 None => "",
1116 };
679 let data = || value.get("data").cloned().unwrap_or(Value::Null);
1117 let data = || value.get("data").cloned().unwrap_or(Value::Null);
680 let kind = match action_type {
1118 let kind = match action_type {
681 OPEN_URL_ACTION => string_field(value, "url")
1119 OPEN_URL_ACTION => string_field(value, "url")
@@ -683,7 +1121,7 @@ fn parse_action(value: &Value) -> Option<CardAction> {
683 .map_or(CardActionKind::Unsupported, |url| {
1121 .map_or(CardActionKind::Unsupported, |url| {
684 CardActionKind::OpenUrl(url.to_owned())
1122 CardActionKind::OpenUrl(url.to_owned())
685 }),
1123 }),
686 SUBMIT_ACTION => CardActionKind::Submit(SubmitAction { data: data() }),
1124 SUBMIT_ACTION => submit_kind(data()),
687 EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| {
1125 EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| {
688 CardActionKind::Execute(ExecuteAction {
1126 CardActionKind::Execute(ExecuteAction {
689 id: id.clone(),
1127 id: id.clone(),
@@ -718,9 +1156,69 @@ fn parse_action(value: &Value) -> Option<CardAction> {
718 visible,
1156 visible,
719 collects_inputs: !string_field(value, "associatedInputs")
1157 collects_inputs: !string_field(value, "associatedInputs")
720 .is_some_and(|mode| mode.eq_ignore_ascii_case("none")),
1158 .is_some_and(|mode| mode.eq_ignore_ascii_case("none")),
1159 icon: string_field(value, "iconUrl").and_then(parse_action_icon),
1160 secondary: string_field(value, "mode")
1161 .is_some_and(|mode| mode.eq_ignore_ascii_case("secondary")),
1162 tooltip: string_field(value, "tooltip")
1163 .map(str::trim)
1164 .filter(|tooltip| !tooltip.is_empty())
1165 .map(str::to_owned),
721 })
1166 })
722}
1167}
723
1168
1169fn parse_action_icon(icon_url: &str) -> Option<CardActionIcon> {
1170 match icon_url.strip_prefix(ICON_URL_PREFIX) {
1171 Some(name) => Some(name.split(',').next()?.trim())
1172 .filter(|name| !name.is_empty())
1173 .map(|name| CardActionIcon::Named(name.to_owned())),
1174 None => icon_url
1175 .starts_with(IMAGE_URL_SCHEME)
1176 .then(|| CardActionIcon::Url(icon_url.to_owned())),
1177 }
1178}
1179
1180fn submit_kind(data: Value) -> CardActionKind {
1181 let submit = SubmitAction { data };
1182 let settings_type = submit
1183 .teams_settings()
1184 .and_then(|settings| string_field(settings, "type"));
1185 let invoke_type = submit
1186 .invoke_value()
1187 .and_then(|value| string_field(value, "type"));
1188 let names_add_app = [settings_type, invoke_type]
1189 .into_iter()
1190 .flatten()
1191 .any(|name| {
1192 ADD_APP_TYPES
1193 .iter()
1194 .any(|known| known.eq_ignore_ascii_case(name))
1195 });
1196 if names_add_app {
1197 return CardActionKind::Unavailable(ADD_APP_UNAVAILABLE);
1198 }
1199 let open_url = |url: Option<&str>| {
1200 url.filter(|url| is_supported_url(url))
1201 .map_or(CardActionKind::Unsupported, |url| {
1202 CardActionKind::OpenUrl(url.to_owned())
1203 })
1204 };
1205 if settings_type.is_some_and(|name| name.eq_ignore_ascii_case(SIGN_IN_TYPE)) {
1206 let url = submit
1207 .teams_settings()
1208 .and_then(|settings| string_field(settings, "value"));
1209 return open_url(url);
1210 }
1211 if invoke_type == Some(TAB_INFO_TYPE) {
1212 let tab_info = submit.invoke_value().and_then(|value| value.get("tabInfo"));
1213 let url = tab_info
1214 .and_then(|info| string_field(info, "websiteUrl"))
1215 .filter(|url| is_supported_url(url))
1216 .or_else(|| tab_info.and_then(|info| string_field(info, "contentUrl")));
1217 return open_url(url);
1218 }
1219 CardActionKind::Submit(submit)
1220}
1221
724fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> {
1222fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> {
725 value
1223 value
726 .and_then(Value::as_array)
1224 .and_then(Value::as_array)
@@ -743,7 +1241,7 @@ fn is_bold_weight(weight: &str) -> bool {
743 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
1241 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
744}
1242}
745
1243
746fn is_supported_url(url: &str) -> bool {
1244pub(crate) fn is_supported_url(url: &str) -> bool {
747 SUPPORTED_URL_SCHEMES
1245 SUPPORTED_URL_SCHEMES
748 .iter()
1246 .iter()
749 .any(|scheme| url.starts_with(scheme))
1247 .any(|scheme| url.starts_with(scheme))
@@ -756,15 +1254,15 @@ fn is_visible(value: &Value) -> bool {
756 .unwrap_or(true)
1254 .unwrap_or(true)
757}
1255}
758
1256
759fn bool_field(value: &Value, key: &str) -> bool {
1257pub(crate) fn bool_field(value: &Value, key: &str) -> bool {
760 value.get(key).and_then(Value::as_bool).unwrap_or(false)
1258 value.get(key).and_then(Value::as_bool).unwrap_or(false)
761}
1259}
762
1260
763fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
1261pub(crate) fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
764 value.get(key)?.as_str()
1262 value.get(key)?.as_str()
765}
1263}
766
1264
767fn pixel_field(value: &Value, key: &str) -> Option<f32> {
1265pub(crate) fn pixel_field(value: &Value, key: &str) -> Option<f32> {
768 let field = value.get(key)?;
1266 let field = value.get(key)?;
769 let pixels = match field.as_str() {
1267 let pixels = match field.as_str() {
770 Some(text) => text
1268 Some(text) => text
@@ -778,7 +1276,7 @@ fn pixel_field(value: &Value, key: &str) -> Option<f32> {
778 (pixels > 0.).then_some(pixels)
1276 (pixels > 0.).then_some(pixels)
779}
1277}
780
1278
781fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
1279pub(crate) fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
782 let Some(value) = value else {
1280 let Some(value) = value else {
783 return ColumnWidth::Stretch;
1281 return ColumnWidth::Stretch;
784 };
1282 };
@@ -824,7 +1322,7 @@ fn parse_text_size(value: Option<&str>) -> TextSize {
824 }
1322 }
825}
1323}
826
1324
827fn parse_text_color(value: Option<&str>) -> TextColor {
1325pub(crate) fn parse_text_color(value: Option<&str>) -> TextColor {
828 match value.map(str::to_ascii_lowercase).as_deref() {
1326 match value.map(str::to_ascii_lowercase).as_deref() {
829 Some("dark") => TextColor::Dark,
1327 Some("dark") => TextColor::Dark,
830 Some("light") => TextColor::Light,
1328 Some("light") => TextColor::Light,
@@ -846,7 +1344,20 @@ fn parse_image_size(value: Option<&str>) -> ImageSize {
846 }
1344 }
847}
1345}
848
1346
849fn parse_container_style(value: Option<&str>) -> ContainerStyle {
1347fn parse_icon_size(value: Option<&str>) -> IconSize {
1348 match value.map(str::to_ascii_lowercase).as_deref() {
1349 Some("xxsmall") => IconSize::ExtraExtraSmall,
1350 Some("xsmall") => IconSize::ExtraSmall,
1351 Some("small") => IconSize::Small,
1352 Some("medium") => IconSize::Medium,
1353 Some("large") => IconSize::Large,
1354 Some("xlarge") => IconSize::ExtraLarge,
1355 Some("xxlarge") => IconSize::ExtraExtraLarge,
1356 _ => IconSize::Standard,
1357 }
1358}
1359
1360pub(crate) fn parse_container_style(value: Option<&str>) -> ContainerStyle {
850 match value.map(str::to_ascii_lowercase).as_deref() {
1361 match value.map(str::to_ascii_lowercase).as_deref() {
851 Some("emphasis") => ContainerStyle::Emphasis,
1362 Some("emphasis") => ContainerStyle::Emphasis,
852 Some("accent") => ContainerStyle::Accent,
1363 Some("accent") => ContainerStyle::Accent,
@@ -857,7 +1368,7 @@ fn parse_container_style(value: Option<&str>) -> ContainerStyle {
857 }
1368 }
858}
1369}
859
1370
860fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
1371pub(crate) fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
861 match value.map(str::to_ascii_lowercase).as_deref() {
1372 match value.map(str::to_ascii_lowercase).as_deref() {
862 Some("center") => VerticalAlignment::Center,
1373 Some("center") => VerticalAlignment::Center,
863 Some("bottom") => VerticalAlignment::Bottom,
1374 Some("bottom") => VerticalAlignment::Bottom,
crates/core/src/card_actions.rs +55 −7
@@ -1,7 +1,10 @@
1 1 use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse};
2 2 use serde_json::Value;
3 3
4 use crate::adaptive_card::{CardAction, task_value};
4 use crate::adaptive_card::{CardAction, ExecuteAction, ExecuteTrigger, task_value};
5 use crate::card_inputs::{
6 ChoiceQuery, InputChoice, SEARCH_INVOKE_NAME, parse_search_results, search_request_value,
7 };
5 8 use crate::engine::SyncEngine;
6 9 use crate::error::{Error, Result};
7 10 use crate::receipts::locked;
@@ -77,7 +80,19 @@ impl<R: Remote> SyncEngine<R> {
77 80 let payload = action
78 81 .invoke_payload()
79 82 .ok_or(Error::Unsupported("this card action"))?;
80 self.invoke_card(conversation_id, message_id, payload.name, payload.value)
83 self.invoke_card(conversation_id, message_id, &payload.name, payload.value)
84 .await
85 }
86
87 pub async fn card_refresh(
88 &self,
89 conversation_id: &str,
90 message_id: &str,
91 action: &ExecuteAction,
92 trigger: ExecuteTrigger,
93 ) -> Result<CardActionOutcome> {
94 let payload = action.payload_for(trigger);
95 self.invoke_card(conversation_id, message_id, &payload.name, payload.value)
81 96 .await
82 97 }
83 98
@@ -96,6 +111,28 @@ impl<R: Remote> SyncEngine<R> {
96 111 .await
97 112 }
98 113
114 pub async fn card_search(
115 &self,
116 conversation_id: &str,
117 message_id: &str,
118 query: &ChoiceQuery,
119 query_text: &str,
120 ) -> Result<Vec<InputChoice>> {
121 let response = self
122 .invoke_response(
123 conversation_id,
124 message_id,
125 SEARCH_INVOKE_NAME,
126 search_request_value(query, query_text),
127 )
128 .await?;
129 match response {
130 InvokeResponse::Search(value) => Ok(parse_search_results(&value)),
131 InvokeResponse::Failed { .. } => Err(Error::Unsupported("a search the app rejected")),
132 _ => Ok(Vec::new()),
133 }
134 }
135
99 136 async fn invoke_card(
100 137 &self,
101 138 conversation_id: &str,
@@ -103,11 +140,23 @@ impl<R: Remote> SyncEngine<R> {
103 140 name: &str,
104 141 value: Value,
105 142 ) -> Result<CardActionOutcome> {
143 let response = self
144 .invoke_response(conversation_id, message_id, name, value)
145 .await?;
146 Ok(outcome_of(response))
147 }
148
149 async fn invoke_response(
150 &self,
151 conversation_id: &str,
152 message_id: &str,
153 name: &str,
154 value: Value,
155 ) -> Result<InvokeResponse> {
106 156 let (app, bot_id) = self.card_app(conversation_id, message_id).await?;
107 157 self.ensure_display_name().await?;
108 158 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
109 let response = self
110 .remote
159 self.remote
111 160 .invoke_card(InvokeRequest {
112 161 bot_id,
113 162 app_id: app.app_id,
@@ -118,8 +167,7 @@ impl<R: Remote> SyncEngine<R> {
118 167 client_message_id: None,
119 168 conversation_id: conversation_id.to_owned(),
120 169 })
121 .await?;
122 Ok(outcome_of(response))
170 .await
123 171 }
124 172
125 173 pub async fn card_app(
@@ -152,7 +200,7 @@ impl<R: Remote> SyncEngine<R> {
152 200
153 201 fn outcome_of(response: InvokeResponse) -> CardActionOutcome {
154 202 match response {
155 InvokeResponse::Empty => CardActionOutcome::Sent,
203 InvokeResponse::Empty | InvokeResponse::Search(_) => CardActionOutcome::Sent,
156 204 InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()),
157 205 InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => {
158 206 CardActionOutcome::Message(text)
@@ -1,7 +1,10 @@
1use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse};
1use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse};
2use serde_json::Value;
2use serde_json::Value;
3
3
4use crate::adaptive_card::{CardAction, task_value};
4use crate::adaptive_card::{CardAction, ExecuteAction, ExecuteTrigger, task_value};
5use crate::card_inputs::{
6 ChoiceQuery, InputChoice, SEARCH_INVOKE_NAME, parse_search_results, search_request_value,
7};
5use crate::engine::SyncEngine;
8use crate::engine::SyncEngine;
6use crate::error::{Error, Result};
9use crate::error::{Error, Result};
7use crate::receipts::locked;
10use crate::receipts::locked;
@@ -77,7 +80,19 @@ impl<R: Remote> SyncEngine<R> {
77 let payload = action
80 let payload = action
78 .invoke_payload()
81 .invoke_payload()
79 .ok_or(Error::Unsupported("this card action"))?;
82 .ok_or(Error::Unsupported("this card action"))?;
80 self.invoke_card(conversation_id, message_id, payload.name, payload.value)
83 self.invoke_card(conversation_id, message_id, &payload.name, payload.value)
84 .await
85 }
86
87 pub async fn card_refresh(
88 &self,
89 conversation_id: &str,
90 message_id: &str,
91 action: &ExecuteAction,
92 trigger: ExecuteTrigger,
93 ) -> Result<CardActionOutcome> {
94 let payload = action.payload_for(trigger);
95 self.invoke_card(conversation_id, message_id, &payload.name, payload.value)
81 .await
96 .await
82 }
97 }
83
98
@@ -96,6 +111,28 @@ impl<R: Remote> SyncEngine<R> {
96 .await
111 .await
97 }
112 }
98
113
114 pub async fn card_search(
115 &self,
116 conversation_id: &str,
117 message_id: &str,
118 query: &ChoiceQuery,
119 query_text: &str,
120 ) -> Result<Vec<InputChoice>> {
121 let response = self
122 .invoke_response(
123 conversation_id,
124 message_id,
125 SEARCH_INVOKE_NAME,
126 search_request_value(query, query_text),
127 )
128 .await?;
129 match response {
130 InvokeResponse::Search(value) => Ok(parse_search_results(&value)),
131 InvokeResponse::Failed { .. } => Err(Error::Unsupported("a search the app rejected")),
132 _ => Ok(Vec::new()),
133 }
134 }
135
99 async fn invoke_card(
136 async fn invoke_card(
100 &self,
137 &self,
101 conversation_id: &str,
138 conversation_id: &str,
@@ -103,11 +140,23 @@ impl<R: Remote> SyncEngine<R> {
103 name: &str,
140 name: &str,
104 value: Value,
141 value: Value,
105 ) -> Result<CardActionOutcome> {
142 ) -> Result<CardActionOutcome> {
143 let response = self
144 .invoke_response(conversation_id, message_id, name, value)
145 .await?;
146 Ok(outcome_of(response))
147 }
148
149 async fn invoke_response(
150 &self,
151 conversation_id: &str,
152 message_id: &str,
153 name: &str,
154 value: Value,
155 ) -> Result<InvokeResponse> {
106 let (app, bot_id) = self.card_app(conversation_id, message_id).await?;
156 let (app, bot_id) = self.card_app(conversation_id, message_id).await?;
107 self.ensure_display_name().await?;
157 self.ensure_display_name().await?;
108 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
158 let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
109 let response = self
159 self.remote
110 .remote
111 .invoke_card(InvokeRequest {
160 .invoke_card(InvokeRequest {
112 bot_id,
161 bot_id,
113 app_id: app.app_id,
162 app_id: app.app_id,
@@ -118,8 +167,7 @@ impl<R: Remote> SyncEngine<R> {
118 client_message_id: None,
167 client_message_id: None,
119 conversation_id: conversation_id.to_owned(),
168 conversation_id: conversation_id.to_owned(),
120 })
169 })
121 .await?;
170 .await
122 Ok(outcome_of(response))
123 }
171 }
124
172
125 pub async fn card_app(
173 pub async fn card_app(
@@ -152,7 +200,7 @@ impl<R: Remote> SyncEngine<R> {
152
200
153fn outcome_of(response: InvokeResponse) -> CardActionOutcome {
201fn outcome_of(response: InvokeResponse) -> CardActionOutcome {
154 match response {
202 match response {
155 InvokeResponse::Empty => CardActionOutcome::Sent,
203 InvokeResponse::Empty | InvokeResponse::Search(_) => CardActionOutcome::Sent,
156 InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()),
204 InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()),
157 InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => {
205 InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => {
158 CardActionOutcome::Message(text)
206 CardActionOutcome::Message(text)
crates/core/src/card_chart.rs added +566 −0
@@ -0,0 +1,566 @@
1 use std::f32::consts::{FRAC_PI_2, TAU};
2
3 use serde_json::Value;
4
5 const CHART_TYPE_PREFIX: &str = "Chart.";
6 const DEFAULT_GAUGE_MAX: f64 = 100.;
7
8 #[derive(Debug, Clone, PartialEq)]
9 pub struct CardChart {
10 pub title: Option<String>,
11 pub x_axis_title: Option<String>,
12 pub y_axis_title: Option<String>,
13 pub show_legend: bool,
14 pub show_values: bool,
15 pub kind: ChartKind,
16 }
17
18 #[derive(Debug, Clone, PartialEq)]
19 pub enum ChartKind {
20 Donut(Vec<ChartPoint>),
21 Pie(Vec<ChartPoint>),
22 Gauge(ChartGauge),
23 Line(Vec<ChartSeries>),
24 VerticalBar(Vec<ChartPoint>),
25 GroupedBar {
26 series: Vec<ChartSeries>,
27 stacked: bool,
28 },
29 HorizontalBar {
30 bars: Vec<ChartPoint>,
31 mode: BarDisplayMode,
32 },
33 StackedHorizontalBar(Vec<ChartSeries>),
34 }
35
36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37 pub enum BarDisplayMode {
38 AbsoluteWithAxis,
39 AbsoluteNoAxis,
40 PartToWhole,
41 }
42
43 #[derive(Debug, Clone, PartialEq)]
44 pub struct ChartPoint {
45 pub label: String,
46 pub value: f64,
47 pub color: ChartColor,
48 }
49
50 #[derive(Debug, Clone, PartialEq)]
51 pub struct ChartSeries {
52 pub legend: String,
53 pub color: ChartColor,
54 pub points: Vec<ChartPoint>,
55 }
56
57 #[derive(Debug, Clone, PartialEq)]
58 pub struct ChartGauge {
59 pub minimum: f64,
60 pub maximum: f64,
61 pub value: f64,
62 pub segments: Vec<GaugeSegment>,
63 pub sub_label: Option<String>,
64 pub format: GaugeValueFormat,
65 pub show_min_max: bool,
66 }
67
68 #[derive(Debug, Clone, PartialEq)]
69 pub struct GaugeSegment {
70 pub legend: String,
71 pub size: f64,
72 pub color: ChartColor,
73 }
74
75 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76 pub enum GaugeValueFormat {
77 Percentage,
78 Fraction,
79 }
80
81 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
82 pub enum ChartColorSet {
83 Categorical,
84 Sequential,
85 Diverging,
86 }
87
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
89 pub enum ChartColor {
90 Good,
91 Warning,
92 Attention,
93 Neutral,
94 CategoricalRed,
95 CategoricalPurple,
96 CategoricalLavender,
97 CategoricalBlue,
98 CategoricalLightBlue,
99 CategoricalTeal,
100 CategoricalGreen,
101 CategoricalLime,
102 CategoricalMarigold,
103 Sequential1,
104 Sequential2,
105 Sequential3,
106 Sequential4,
107 Sequential5,
108 Sequential6,
109 Sequential7,
110 Sequential8,
111 DivergingBlue,
112 DivergingLightBlue,
113 DivergingCyan,
114 DivergingTeal,
115 DivergingYellow,
116 DivergingPeach,
117 DivergingLightRed,
118 DivergingRed,
119 DivergingMaroon,
120 DivergingGray,
121 }
122
123 #[derive(Debug, Clone, Copy, PartialEq)]
124 pub struct AxisScale {
125 pub maximum: f64,
126 pub step: f64,
127 }
128
129 const NAMED_COLORS: [(&str, ChartColor); 31] = [
130 ("good", ChartColor::Good),
131 ("warning", ChartColor::Warning),
132 ("attention", ChartColor::Attention),
133 ("neutral", ChartColor::Neutral),
134 ("categoricalred", ChartColor::CategoricalRed),
135 ("categoricalpurple", ChartColor::CategoricalPurple),
136 ("categoricallavender", ChartColor::CategoricalLavender),
137 ("categoricalblue", ChartColor::CategoricalBlue),
138 ("categoricallightblue", ChartColor::CategoricalLightBlue),
139 ("categoricalteal", ChartColor::CategoricalTeal),
140 ("categoricalgreen", ChartColor::CategoricalGreen),
141 ("categoricallime", ChartColor::CategoricalLime),
142 ("categoricalmarigold", ChartColor::CategoricalMarigold),
143 ("sequential1", ChartColor::Sequential1),
144 ("sequential2", ChartColor::Sequential2),
145 ("sequential3", ChartColor::Sequential3),
146 ("sequential4", ChartColor::Sequential4),
147 ("sequential5", ChartColor::Sequential5),
148 ("sequential6", ChartColor::Sequential6),
149 ("sequential7", ChartColor::Sequential7),
150 ("sequential8", ChartColor::Sequential8),
151 ("divergingblue", ChartColor::DivergingBlue),
152 ("diverginglightblue", ChartColor::DivergingLightBlue),
153 ("divergingcyan", ChartColor::DivergingCyan),
154 ("divergingteal", ChartColor::DivergingTeal),
155 ("divergingyellow", ChartColor::DivergingYellow),
156 ("divergingpeach", ChartColor::DivergingPeach),
157 ("diverginglightred", ChartColor::DivergingLightRed),
158 ("divergingred", ChartColor::DivergingRed),
159 ("divergingmaroon", ChartColor::DivergingMaroon),
160 ("diverginggray", ChartColor::DivergingGray),
161 ];
162
163 const CATEGORICAL_ORDER: [ChartColor; 9] = [
164 ChartColor::CategoricalBlue,
165 ChartColor::CategoricalTeal,
166 ChartColor::CategoricalMarigold,
167 ChartColor::CategoricalRed,
168 ChartColor::CategoricalPurple,
169 ChartColor::CategoricalGreen,
170 ChartColor::CategoricalLavender,
171 ChartColor::CategoricalLime,
172 ChartColor::CategoricalLightBlue,
173 ];
174
175 const SEQUENTIAL_ORDER: [ChartColor; 8] = [
176 ChartColor::Sequential3,
177 ChartColor::Sequential5,
178 ChartColor::Sequential7,
179 ChartColor::Sequential1,
180 ChartColor::Sequential4,
181 ChartColor::Sequential6,
182 ChartColor::Sequential2,
183 ChartColor::Sequential8,
184 ];
185
186 const DIVERGING_ORDER: [ChartColor; 10] = [
187 ChartColor::DivergingBlue,
188 ChartColor::DivergingRed,
189 ChartColor::DivergingTeal,
190 ChartColor::DivergingPeach,
191 ChartColor::DivergingLightBlue,
192 ChartColor::DivergingMaroon,
193 ChartColor::DivergingYellow,
194 ChartColor::DivergingCyan,
195 ChartColor::DivergingLightRed,
196 ChartColor::DivergingGray,
197 ];
198
199 impl ChartColor {
200 pub fn from_name(name: &str) -> Option<ChartColor> {
201 let lowered = name.trim().to_ascii_lowercase();
202 NAMED_COLORS
203 .iter()
204 .find(|(candidate, _)| *candidate == lowered)
205 .map(|(_, color)| *color)
206 }
207 }
208
209 impl ChartColorSet {
210 pub fn from_name(name: Option<&str>) -> ChartColorSet {
211 let lowered = name.unwrap_or_default().to_ascii_lowercase();
212 if lowered.starts_with("sequential") {
213 ChartColorSet::Sequential
214 } else if lowered.starts_with("diverging") {
215 ChartColorSet::Diverging
216 } else {
217 ChartColorSet::Categorical
218 }
219 }
220
221 pub fn color_at(self, index: usize) -> ChartColor {
222 match self {
223 ChartColorSet::Categorical => CATEGORICAL_ORDER[index % CATEGORICAL_ORDER.len()],
224 ChartColorSet::Sequential => SEQUENTIAL_ORDER[index % SEQUENTIAL_ORDER.len()],
225 ChartColorSet::Diverging => DIVERGING_ORDER[index % DIVERGING_ORDER.len()],
226 }
227 }
228 }
229
230 struct ColorPlan {
231 color_set: ChartColorSet,
232 uniform: Option<ChartColor>,
233 }
234
235 impl ColorPlan {
236 fn new(value: &Value) -> ColorPlan {
237 ColorPlan {
238 color_set: ChartColorSet::from_name(string_field(value, "colorSet")),
239 uniform: named_color(value),
240 }
241 }
242
243 fn resolve(&self, entry: &Value, index: usize) -> ChartColor {
244 named_color(entry)
245 .or(self.uniform)
246 .unwrap_or_else(|| self.color_set.color_at(index))
247 }
248 }
249
250 pub fn is_chart_type(element_type: &str) -> bool {
251 element_type.starts_with(CHART_TYPE_PREFIX)
252 }
253
254 pub fn parse_chart(value: &Value, element_type: &str) -> Option<CardChart> {
255 let plan = ColorPlan::new(value);
256 let kind = match element_type {
257 "Chart.Donut" => ChartKind::Donut(parse_slices(value, &plan)),
258 "Chart.Pie" => ChartKind::Pie(parse_slices(value, &plan)),
259 "Chart.Gauge" => ChartKind::Gauge(parse_gauge(value, &plan)),
260 "Chart.Line" => ChartKind::Line(parse_series(value, &plan)),
261 "Chart.VerticalBar" => ChartKind::VerticalBar(parse_xy_points(value, &plan)),
262 "Chart.VerticalBar.Grouped" => ChartKind::GroupedBar {
263 series: parse_series(value, &plan),
264 stacked: bool_field(value, "stacked", false),
265 },
266 "Chart.HorizontalBar" => ChartKind::HorizontalBar {
267 bars: parse_xy_points(value, &plan),
268 mode: parse_display_mode(string_field(value, "displayMode")),
269 },
270 "Chart.HorizontalBar.Stacked" => {
271 ChartKind::StackedHorizontalBar(parse_stacked_rows(value, &plan))
272 }
273 _ => return None,
274 };
275 Some(CardChart {
276 title: text_field(value, "title"),
277 x_axis_title: text_field(value, "xAxisTitle"),
278 y_axis_title: text_field(value, "yAxisTitle"),
279 show_legend: bool_field(value, "showLegend", true),
280 show_values: bool_field(value, "showBarValues", false),
281 kind,
282 })
283 }
284
285 impl CardChart {
286 pub fn legend_entries(&self) -> Vec<(String, ChartColor)> {
287 match &self.kind {
288 ChartKind::Donut(points) | ChartKind::Pie(points) => {
289 points.iter().map(point_legend).collect()
290 }
291 ChartKind::Gauge(gauge) => gauge
292 .segments
293 .iter()
294 .filter(|segment| !segment.legend.is_empty())
295 .map(|segment| (segment.legend.clone(), segment.color))
296 .collect(),
297 ChartKind::Line(series) | ChartKind::GroupedBar { series, .. } => series
298 .iter()
299 .map(|entry| (entry.legend.clone(), entry.color))
300 .collect(),
301 ChartKind::StackedHorizontalBar(rows) => {
302 let mut entries: Vec<(String, ChartColor)> = Vec::new();
303 for point in rows.iter().flat_map(|row| &row.points) {
304 if !entries.iter().any(|(legend, _)| *legend == point.label) {
305 entries.push(point_legend(point));
306 }
307 }
308 entries
309 }
310 ChartKind::VerticalBar(_) | ChartKind::HorizontalBar { .. } => Vec::new(),
311 }
312 }
313 }
314
315 fn point_legend(point: &ChartPoint) -> (String, ChartColor) {
316 (point.label.clone(), point.color)
317 }
318
319 fn parse_slices(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
320 array_field(value, "data")
321 .iter()
322 .enumerate()
323 .map(|(index, entry)| ChartPoint {
324 label: text_field(entry, "legend").unwrap_or_default(),
325 value: number_field(entry, "value").unwrap_or(0.),
326 color: plan.resolve(entry, index),
327 })
328 .collect()
329 }
330
331 fn parse_xy_points(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
332 array_field(value, "data")
333 .iter()
334 .enumerate()
335 .map(|(index, entry)| ChartPoint {
336 label: label_field(entry, "x"),
337 value: number_field(entry, "y").unwrap_or(0.),
338 color: plan.resolve(entry, index),
339 })
340 .collect()
341 }
342
343 fn parse_series(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
344 array_field(value, "data")
345 .iter()
346 .enumerate()
347 .map(|(index, entry)| {
348 let color = plan.resolve(entry, index);
349 ChartSeries {
350 legend: text_field(entry, "legend").unwrap_or_default(),
351 color,
352 points: array_field(entry, "values")
353 .iter()
354 .map(|point| ChartPoint {
355 label: label_field(point, "x"),
356 value: number_field(point, "y").unwrap_or(0.),
357 color,
358 })
359 .collect(),
360 }
361 })
362 .collect()
363 }
364
365 fn parse_stacked_rows(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
366 array_field(value, "data")
367 .iter()
368 .enumerate()
369 .map(|(index, row)| ChartSeries {
370 legend: text_field(row, "title").unwrap_or_default(),
371 color: plan.resolve(row, index),
372 points: parse_slices(row, plan),
373 })
374 .collect()
375 }
376
377 fn parse_gauge(value: &Value, plan: &ColorPlan) -> ChartGauge {
378 let segments: Vec<GaugeSegment> = array_field(value, "segments")
379 .iter()
380 .enumerate()
381 .map(|(index, entry)| GaugeSegment {
382 legend: text_field(entry, "legend").unwrap_or_default(),
383 size: number_field(entry, "size")
384 .or_else(|| number_field(entry, "value"))
385 .unwrap_or(0.)
386 .max(0.),
387 color: plan.resolve(entry, index),
388 })
389 .collect();
390 let segment_total: f64 = segments.iter().map(|segment| segment.size).sum();
391 let minimum = number_field(value, "min").unwrap_or(0.);
392 let default_maximum = if segment_total > 0. {
393 minimum + segment_total
394 } else {
395 DEFAULT_GAUGE_MAX
396 };
397 let format = match string_field(value, "valueFormat") {
398 Some(format) if format.eq_ignore_ascii_case("fraction") => GaugeValueFormat::Fraction,
399 _ => GaugeValueFormat::Percentage,
400 };
401 ChartGauge {
402 minimum,
403 maximum: number_field(value, "max").unwrap_or(default_maximum),
404 value: number_field(value, "value").unwrap_or(0.),
405 segments,
406 sub_label: text_field(value, "subLabel"),
407 format,
408 show_min_max: bool_field(value, "showMinMax", true),
409 }
410 }
411
412 fn parse_display_mode(mode: Option<&str>) -> BarDisplayMode {
413 match mode.map(str::to_ascii_lowercase).as_deref() {
414 Some("absolutenoaxis") => BarDisplayMode::AbsoluteNoAxis,
415 Some("parttowhole") => BarDisplayMode::PartToWhole,
416 _ => BarDisplayMode::AbsoluteWithAxis,
417 }
418 }
419
420 fn array_field<'value>(value: &'value Value, key: &str) -> &'value [Value] {
421 value
422 .get(key)
423 .and_then(Value::as_array)
424 .map_or(&[], Vec::as_slice)
425 }
426
427 fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
428 value.get(key)?.as_str()
429 }
430
431 fn text_field(value: &Value, key: &str) -> Option<String> {
432 string_field(value, key)
433 .map(str::trim)
434 .filter(|text| !text.is_empty())
435 .map(str::to_owned)
436 }
437
438 fn bool_field(value: &Value, key: &str, default: bool) -> bool {
439 value.get(key).and_then(Value::as_bool).unwrap_or(default)
440 }
441
442 fn number_field(value: &Value, key: &str) -> Option<f64> {
443 value.get(key)?.as_f64().filter(|number| number.is_finite())
444 }
445
446 fn label_field(value: &Value, key: &str) -> String {
447 match value.get(key) {
448 Some(Value::String(text)) => text.clone(),
449 Some(Value::Number(number)) => number.as_f64().map(format_chart_value).unwrap_or_default(),
450 _ => String::new(),
451 }
452 }
453
454 fn named_color(value: &Value) -> Option<ChartColor> {
455 ChartColor::from_name(string_field(value, "color")?)
456 }
457
458 pub fn format_chart_value(value: f64) -> String {
459 if (value - value.round()).abs() < 1e-9 {
460 format!("{}", value.round() as i64)
461 } else {
462 let formatted = format!("{value:.2}");
463 formatted
464 .trim_end_matches('0')
465 .trim_end_matches('.')
466 .to_owned()
467 }
468 }
469
470 pub fn slice_angles(values: &[f64]) -> Vec<(f32, f32)> {
471 let total: f64 = values.iter().map(|value| value.max(0.)).sum();
472 let mut start = -FRAC_PI_2;
473 values
474 .iter()
475 .map(|value| {
476 let sweep = if total > 0. {
477 (value.max(0.) / total) as f32 * TAU
478 } else {
479 0.
480 };
481 let angles = (start, start + sweep);
482 start += sweep;
483 angles
484 })
485 .collect()
486 }
487
488 pub fn unit_fraction(value: f64, minimum: f64, maximum: f64) -> f32 {
489 let range = maximum - minimum;
490 if range <= 0. {
491 return 0.;
492 }
493 ((value - minimum) / range).clamp(0., 1.) as f32
494 }
495
496 pub fn nice_scale(maximum_value: f64, target_steps: usize) -> AxisScale {
497 if maximum_value <= 0. || target_steps == 0 {
498 return AxisScale {
499 maximum: 1.,
500 step: 1.,
501 };
502 }
503 let rough_step = maximum_value / target_steps as f64;
504 let magnitude = 10f64.powf(rough_step.log10().floor());
505 let normalized = rough_step / magnitude;
506 let factor = [1., 2., 2.5, 5., 10.]
507 .into_iter()
508 .find(|candidate| *candidate >= normalized - 1e-9)
509 .unwrap_or(10.);
510 let step = factor * magnitude;
511 AxisScale {
512 maximum: (maximum_value / step - 1e-9).ceil().max(1.) * step,
513 step,
514 }
515 }
516
517 impl AxisScale {
518 pub fn ticks(&self) -> Vec<f64> {
519 let count = (self.maximum / self.step).round() as usize;
520 (0..=count).map(|index| index as f64 * self.step).collect()
521 }
522 }
523
524 pub fn label_stride(count: usize, slot_width: f32, label_width: f32) -> usize {
525 if count == 0 || slot_width <= 0. {
526 return 1;
527 }
528 (label_width / slot_width).ceil().max(1.) as usize
529 }
530
531 pub fn series_categories(series: &[ChartSeries]) -> Vec<String> {
532 let mut categories: Vec<String> = Vec::new();
533 for point in series.iter().flat_map(|entry| &entry.points) {
534 if !categories.contains(&point.label) {
535 categories.push(point.label.clone());
536 }
537 }
538 categories
539 }
540
541 pub fn series_value(series: &ChartSeries, category: &str) -> f64 {
542 series
543 .points
544 .iter()
545 .find(|point| point.label == category)
546 .map_or(0., |point| point.value)
547 }
548
549 pub fn series_maximum(series: &[ChartSeries], stacked: bool) -> f64 {
550 if stacked {
551 return series_categories(series)
552 .iter()
553 .map(|category| {
554 series
555 .iter()
556 .map(|entry| series_value(entry, category).max(0.))
557 .sum::<f64>()
558 })
559 .fold(0., f64::max);
560 }
561 series
562 .iter()
563 .flat_map(|entry| &entry.points)
564 .map(|point| point.value)
565 .fold(0., f64::max)
566 }
@@ -0,0 +1,566 @@
1use std::f32::consts::{FRAC_PI_2, TAU};
2
3use serde_json::Value;
4
5const CHART_TYPE_PREFIX: &str = "Chart.";
6const DEFAULT_GAUGE_MAX: f64 = 100.;
7
8#[derive(Debug, Clone, PartialEq)]
9pub struct CardChart {
10 pub title: Option<String>,
11 pub x_axis_title: Option<String>,
12 pub y_axis_title: Option<String>,
13 pub show_legend: bool,
14 pub show_values: bool,
15 pub kind: ChartKind,
16}
17
18#[derive(Debug, Clone, PartialEq)]
19pub enum ChartKind {
20 Donut(Vec<ChartPoint>),
21 Pie(Vec<ChartPoint>),
22 Gauge(ChartGauge),
23 Line(Vec<ChartSeries>),
24 VerticalBar(Vec<ChartPoint>),
25 GroupedBar {
26 series: Vec<ChartSeries>,
27 stacked: bool,
28 },
29 HorizontalBar {
30 bars: Vec<ChartPoint>,
31 mode: BarDisplayMode,
32 },
33 StackedHorizontalBar(Vec<ChartSeries>),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum BarDisplayMode {
38 AbsoluteWithAxis,
39 AbsoluteNoAxis,
40 PartToWhole,
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct ChartPoint {
45 pub label: String,
46 pub value: f64,
47 pub color: ChartColor,
48}
49
50#[derive(Debug, Clone, PartialEq)]
51pub struct ChartSeries {
52 pub legend: String,
53 pub color: ChartColor,
54 pub points: Vec<ChartPoint>,
55}
56
57#[derive(Debug, Clone, PartialEq)]
58pub struct ChartGauge {
59 pub minimum: f64,
60 pub maximum: f64,
61 pub value: f64,
62 pub segments: Vec<GaugeSegment>,
63 pub sub_label: Option<String>,
64 pub format: GaugeValueFormat,
65 pub show_min_max: bool,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct GaugeSegment {
70 pub legend: String,
71 pub size: f64,
72 pub color: ChartColor,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum GaugeValueFormat {
77 Percentage,
78 Fraction,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ChartColorSet {
83 Categorical,
84 Sequential,
85 Diverging,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum ChartColor {
90 Good,
91 Warning,
92 Attention,
93 Neutral,
94 CategoricalRed,
95 CategoricalPurple,
96 CategoricalLavender,
97 CategoricalBlue,
98 CategoricalLightBlue,
99 CategoricalTeal,
100 CategoricalGreen,
101 CategoricalLime,
102 CategoricalMarigold,
103 Sequential1,
104 Sequential2,
105 Sequential3,
106 Sequential4,
107 Sequential5,
108 Sequential6,
109 Sequential7,
110 Sequential8,
111 DivergingBlue,
112 DivergingLightBlue,
113 DivergingCyan,
114 DivergingTeal,
115 DivergingYellow,
116 DivergingPeach,
117 DivergingLightRed,
118 DivergingRed,
119 DivergingMaroon,
120 DivergingGray,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq)]
124pub struct AxisScale {
125 pub maximum: f64,
126 pub step: f64,
127}
128
129const NAMED_COLORS: [(&str, ChartColor); 31] = [
130 ("good", ChartColor::Good),
131 ("warning", ChartColor::Warning),
132 ("attention", ChartColor::Attention),
133 ("neutral", ChartColor::Neutral),
134 ("categoricalred", ChartColor::CategoricalRed),
135 ("categoricalpurple", ChartColor::CategoricalPurple),
136 ("categoricallavender", ChartColor::CategoricalLavender),
137 ("categoricalblue", ChartColor::CategoricalBlue),
138 ("categoricallightblue", ChartColor::CategoricalLightBlue),
139 ("categoricalteal", ChartColor::CategoricalTeal),
140 ("categoricalgreen", ChartColor::CategoricalGreen),
141 ("categoricallime", ChartColor::CategoricalLime),
142 ("categoricalmarigold", ChartColor::CategoricalMarigold),
143 ("sequential1", ChartColor::Sequential1),
144 ("sequential2", ChartColor::Sequential2),
145 ("sequential3", ChartColor::Sequential3),
146 ("sequential4", ChartColor::Sequential4),
147 ("sequential5", ChartColor::Sequential5),
148 ("sequential6", ChartColor::Sequential6),
149 ("sequential7", ChartColor::Sequential7),
150 ("sequential8", ChartColor::Sequential8),
151 ("divergingblue", ChartColor::DivergingBlue),
152 ("diverginglightblue", ChartColor::DivergingLightBlue),
153 ("divergingcyan", ChartColor::DivergingCyan),
154 ("divergingteal", ChartColor::DivergingTeal),
155 ("divergingyellow", ChartColor::DivergingYellow),
156 ("divergingpeach", ChartColor::DivergingPeach),
157 ("diverginglightred", ChartColor::DivergingLightRed),
158 ("divergingred", ChartColor::DivergingRed),
159 ("divergingmaroon", ChartColor::DivergingMaroon),
160 ("diverginggray", ChartColor::DivergingGray),
161];
162
163const CATEGORICAL_ORDER: [ChartColor; 9] = [
164 ChartColor::CategoricalBlue,
165 ChartColor::CategoricalTeal,
166 ChartColor::CategoricalMarigold,
167 ChartColor::CategoricalRed,
168 ChartColor::CategoricalPurple,
169 ChartColor::CategoricalGreen,
170 ChartColor::CategoricalLavender,
171 ChartColor::CategoricalLime,
172 ChartColor::CategoricalLightBlue,
173];
174
175const SEQUENTIAL_ORDER: [ChartColor; 8] = [
176 ChartColor::Sequential3,
177 ChartColor::Sequential5,
178 ChartColor::Sequential7,
179 ChartColor::Sequential1,
180 ChartColor::Sequential4,
181 ChartColor::Sequential6,
182 ChartColor::Sequential2,
183 ChartColor::Sequential8,
184];
185
186const DIVERGING_ORDER: [ChartColor; 10] = [
187 ChartColor::DivergingBlue,
188 ChartColor::DivergingRed,
189 ChartColor::DivergingTeal,
190 ChartColor::DivergingPeach,
191 ChartColor::DivergingLightBlue,
192 ChartColor::DivergingMaroon,
193 ChartColor::DivergingYellow,
194 ChartColor::DivergingCyan,
195 ChartColor::DivergingLightRed,
196 ChartColor::DivergingGray,
197];
198
199impl ChartColor {
200 pub fn from_name(name: &str) -> Option<ChartColor> {
201 let lowered = name.trim().to_ascii_lowercase();
202 NAMED_COLORS
203 .iter()
204 .find(|(candidate, _)| *candidate == lowered)
205 .map(|(_, color)| *color)
206 }
207}
208
209impl ChartColorSet {
210 pub fn from_name(name: Option<&str>) -> ChartColorSet {
211 let lowered = name.unwrap_or_default().to_ascii_lowercase();
212 if lowered.starts_with("sequential") {
213 ChartColorSet::Sequential
214 } else if lowered.starts_with("diverging") {
215 ChartColorSet::Diverging
216 } else {
217 ChartColorSet::Categorical
218 }
219 }
220
221 pub fn color_at(self, index: usize) -> ChartColor {
222 match self {
223 ChartColorSet::Categorical => CATEGORICAL_ORDER[index % CATEGORICAL_ORDER.len()],
224 ChartColorSet::Sequential => SEQUENTIAL_ORDER[index % SEQUENTIAL_ORDER.len()],
225 ChartColorSet::Diverging => DIVERGING_ORDER[index % DIVERGING_ORDER.len()],
226 }
227 }
228}
229
230struct ColorPlan {
231 color_set: ChartColorSet,
232 uniform: Option<ChartColor>,
233}
234
235impl ColorPlan {
236 fn new(value: &Value) -> ColorPlan {
237 ColorPlan {
238 color_set: ChartColorSet::from_name(string_field(value, "colorSet")),
239 uniform: named_color(value),
240 }
241 }
242
243 fn resolve(&self, entry: &Value, index: usize) -> ChartColor {
244 named_color(entry)
245 .or(self.uniform)
246 .unwrap_or_else(|| self.color_set.color_at(index))
247 }
248}
249
250pub fn is_chart_type(element_type: &str) -> bool {
251 element_type.starts_with(CHART_TYPE_PREFIX)
252}
253
254pub fn parse_chart(value: &Value, element_type: &str) -> Option<CardChart> {
255 let plan = ColorPlan::new(value);
256 let kind = match element_type {
257 "Chart.Donut" => ChartKind::Donut(parse_slices(value, &plan)),
258 "Chart.Pie" => ChartKind::Pie(parse_slices(value, &plan)),
259 "Chart.Gauge" => ChartKind::Gauge(parse_gauge(value, &plan)),
260 "Chart.Line" => ChartKind::Line(parse_series(value, &plan)),
261 "Chart.VerticalBar" => ChartKind::VerticalBar(parse_xy_points(value, &plan)),
262 "Chart.VerticalBar.Grouped" => ChartKind::GroupedBar {
263 series: parse_series(value, &plan),
264 stacked: bool_field(value, "stacked", false),
265 },
266 "Chart.HorizontalBar" => ChartKind::HorizontalBar {
267 bars: parse_xy_points(value, &plan),
268 mode: parse_display_mode(string_field(value, "displayMode")),
269 },
270 "Chart.HorizontalBar.Stacked" => {
271 ChartKind::StackedHorizontalBar(parse_stacked_rows(value, &plan))
272 }
273 _ => return None,
274 };
275 Some(CardChart {
276 title: text_field(value, "title"),
277 x_axis_title: text_field(value, "xAxisTitle"),
278 y_axis_title: text_field(value, "yAxisTitle"),
279 show_legend: bool_field(value, "showLegend", true),
280 show_values: bool_field(value, "showBarValues", false),
281 kind,
282 })
283}
284
285impl CardChart {
286 pub fn legend_entries(&self) -> Vec<(String, ChartColor)> {
287 match &self.kind {
288 ChartKind::Donut(points) | ChartKind::Pie(points) => {
289 points.iter().map(point_legend).collect()
290 }
291 ChartKind::Gauge(gauge) => gauge
292 .segments
293 .iter()
294 .filter(|segment| !segment.legend.is_empty())
295 .map(|segment| (segment.legend.clone(), segment.color))
296 .collect(),
297 ChartKind::Line(series) | ChartKind::GroupedBar { series, .. } => series
298 .iter()
299 .map(|entry| (entry.legend.clone(), entry.color))
300 .collect(),
301 ChartKind::StackedHorizontalBar(rows) => {
302 let mut entries: Vec<(String, ChartColor)> = Vec::new();
303 for point in rows.iter().flat_map(|row| &row.points) {
304 if !entries.iter().any(|(legend, _)| *legend == point.label) {
305 entries.push(point_legend(point));
306 }
307 }
308 entries
309 }
310 ChartKind::VerticalBar(_) | ChartKind::HorizontalBar { .. } => Vec::new(),
311 }
312 }
313}
314
315fn point_legend(point: &ChartPoint) -> (String, ChartColor) {
316 (point.label.clone(), point.color)
317}
318
319fn parse_slices(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
320 array_field(value, "data")
321 .iter()
322 .enumerate()
323 .map(|(index, entry)| ChartPoint {
324 label: text_field(entry, "legend").unwrap_or_default(),
325 value: number_field(entry, "value").unwrap_or(0.),
326 color: plan.resolve(entry, index),
327 })
328 .collect()
329}
330
331fn parse_xy_points(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
332 array_field(value, "data")
333 .iter()
334 .enumerate()
335 .map(|(index, entry)| ChartPoint {
336 label: label_field(entry, "x"),
337 value: number_field(entry, "y").unwrap_or(0.),
338 color: plan.resolve(entry, index),
339 })
340 .collect()
341}
342
343fn parse_series(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
344 array_field(value, "data")
345 .iter()
346 .enumerate()
347 .map(|(index, entry)| {
348 let color = plan.resolve(entry, index);
349 ChartSeries {
350 legend: text_field(entry, "legend").unwrap_or_default(),
351 color,
352 points: array_field(entry, "values")
353 .iter()
354 .map(|point| ChartPoint {
355 label: label_field(point, "x"),
356 value: number_field(point, "y").unwrap_or(0.),
357 color,
358 })
359 .collect(),
360 }
361 })
362 .collect()
363}
364
365fn parse_stacked_rows(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
366 array_field(value, "data")
367 .iter()
368 .enumerate()
369 .map(|(index, row)| ChartSeries {
370 legend: text_field(row, "title").unwrap_or_default(),
371 color: plan.resolve(row, index),
372 points: parse_slices(row, plan),
373 })
374 .collect()
375}
376
377fn parse_gauge(value: &Value, plan: &ColorPlan) -> ChartGauge {
378 let segments: Vec<GaugeSegment> = array_field(value, "segments")
379 .iter()
380 .enumerate()
381 .map(|(index, entry)| GaugeSegment {
382 legend: text_field(entry, "legend").unwrap_or_default(),
383 size: number_field(entry, "size")
384 .or_else(|| number_field(entry, "value"))
385 .unwrap_or(0.)
386 .max(0.),
387 color: plan.resolve(entry, index),
388 })
389 .collect();
390 let segment_total: f64 = segments.iter().map(|segment| segment.size).sum();
391 let minimum = number_field(value, "min").unwrap_or(0.);
392 let default_maximum = if segment_total > 0. {
393 minimum + segment_total
394 } else {
395 DEFAULT_GAUGE_MAX
396 };
397 let format = match string_field(value, "valueFormat") {
398 Some(format) if format.eq_ignore_ascii_case("fraction") => GaugeValueFormat::Fraction,
399 _ => GaugeValueFormat::Percentage,
400 };
401 ChartGauge {
402 minimum,
403 maximum: number_field(value, "max").unwrap_or(default_maximum),
404 value: number_field(value, "value").unwrap_or(0.),
405 segments,
406 sub_label: text_field(value, "subLabel"),
407 format,
408 show_min_max: bool_field(value, "showMinMax", true),
409 }
410}
411
412fn parse_display_mode(mode: Option<&str>) -> BarDisplayMode {
413 match mode.map(str::to_ascii_lowercase).as_deref() {
414 Some("absolutenoaxis") => BarDisplayMode::AbsoluteNoAxis,
415 Some("parttowhole") => BarDisplayMode::PartToWhole,
416 _ => BarDisplayMode::AbsoluteWithAxis,
417 }
418}
419
420fn array_field<'value>(value: &'value Value, key: &str) -> &'value [Value] {
421 value
422 .get(key)
423 .and_then(Value::as_array)
424 .map_or(&[], Vec::as_slice)
425}
426
427fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
428 value.get(key)?.as_str()
429}
430
431fn text_field(value: &Value, key: &str) -> Option<String> {
432 string_field(value, key)
433 .map(str::trim)
434 .filter(|text| !text.is_empty())
435 .map(str::to_owned)
436}
437
438fn bool_field(value: &Value, key: &str, default: bool) -> bool {
439 value.get(key).and_then(Value::as_bool).unwrap_or(default)
440}
441
442fn number_field(value: &Value, key: &str) -> Option<f64> {
443 value.get(key)?.as_f64().filter(|number| number.is_finite())
444}
445
446fn label_field(value: &Value, key: &str) -> String {
447 match value.get(key) {
448 Some(Value::String(text)) => text.clone(),
449 Some(Value::Number(number)) => number.as_f64().map(format_chart_value).unwrap_or_default(),
450 _ => String::new(),
451 }
452}
453
454fn named_color(value: &Value) -> Option<ChartColor> {
455 ChartColor::from_name(string_field(value, "color")?)
456}
457
458pub fn format_chart_value(value: f64) -> String {
459 if (value - value.round()).abs() < 1e-9 {
460 format!("{}", value.round() as i64)
461 } else {
462 let formatted = format!("{value:.2}");
463 formatted
464 .trim_end_matches('0')
465 .trim_end_matches('.')
466 .to_owned()
467 }
468}
469
470pub fn slice_angles(values: &[f64]) -> Vec<(f32, f32)> {
471 let total: f64 = values.iter().map(|value| value.max(0.)).sum();
472 let mut start = -FRAC_PI_2;
473 values
474 .iter()
475 .map(|value| {
476 let sweep = if total > 0. {
477 (value.max(0.) / total) as f32 * TAU
478 } else {
479 0.
480 };
481 let angles = (start, start + sweep);
482 start += sweep;
483 angles
484 })
485 .collect()
486}
487
488pub fn unit_fraction(value: f64, minimum: f64, maximum: f64) -> f32 {
489 let range = maximum - minimum;
490 if range <= 0. {
491 return 0.;
492 }
493 ((value - minimum) / range).clamp(0., 1.) as f32
494}
495
496pub fn nice_scale(maximum_value: f64, target_steps: usize) -> AxisScale {
497 if maximum_value <= 0. || target_steps == 0 {
498 return AxisScale {
499 maximum: 1.,
500 step: 1.,
501 };
502 }
503 let rough_step = maximum_value / target_steps as f64;
504 let magnitude = 10f64.powf(rough_step.log10().floor());
505 let normalized = rough_step / magnitude;
506 let factor = [1., 2., 2.5, 5., 10.]
507 .into_iter()
508 .find(|candidate| *candidate >= normalized - 1e-9)
509 .unwrap_or(10.);
510 let step = factor * magnitude;
511 AxisScale {
512 maximum: (maximum_value / step - 1e-9).ceil().max(1.) * step,
513 step,
514 }
515}
516
517impl AxisScale {
518 pub fn ticks(&self) -> Vec<f64> {
519 let count = (self.maximum / self.step).round() as usize;
520 (0..=count).map(|index| index as f64 * self.step).collect()
521 }
522}
523
524pub fn label_stride(count: usize, slot_width: f32, label_width: f32) -> usize {
525 if count == 0 || slot_width <= 0. {
526 return 1;
527 }
528 (label_width / slot_width).ceil().max(1.) as usize
529}
530
531pub fn series_categories(series: &[ChartSeries]) -> Vec<String> {
532 let mut categories: Vec<String> = Vec::new();
533 for point in series.iter().flat_map(|entry| &entry.points) {
534 if !categories.contains(&point.label) {
535 categories.push(point.label.clone());
536 }
537 }
538 categories
539}
540
541pub fn series_value(series: &ChartSeries, category: &str) -> f64 {
542 series
543 .points
544 .iter()
545 .find(|point| point.label == category)
546 .map_or(0., |point| point.value)
547}
548
549pub fn series_maximum(series: &[ChartSeries], stacked: bool) -> f64 {
550 if stacked {
551 return series_categories(series)
552 .iter()
553 .map(|category| {
554 series
555 .iter()
556 .map(|entry| series_value(entry, category).max(0.))
557 .sum::<f64>()
558 })
559 .fold(0., f64::max);
560 }
561 series
562 .iter()
563 .flat_map(|entry| &entry.points)
564 .map(|point| point.value)
565 .fold(0., f64::max)
566}
crates/core/src/card_date.rs added +48 −0
@@ -0,0 +1,48 @@
1 use std::fmt::Display;
2 use std::sync::LazyLock;
3
4 use chrono::{DateTime, Local, TimeZone};
5 use regex::{Captures, Regex};
6
7 const COMPACT_FORMAT: &str = "%Y-%m-%d";
8 const SHORT_FORMAT: &str = "%a, %b %-d, %Y";
9 const LONG_FORMAT: &str = "%A, %B %-d, %Y";
10 const TIME_FORMAT: &str = "%H:%M";
11
12 static DATE_TIME_FUNCTION: LazyLock<Regex> = LazyLock::new(|| {
13 Regex::new(r"(?:\{\{\s*)?\b(DATE|TIME)\(\s*([^,()\s]+)\s*(?:,\s*(SHORT|LONG|COMPACT)\s*)?\)(?:\s*\}\})?")
14 .unwrap()
15 });
16
17 pub fn format_card_dates(text: &str) -> String {
18 format_card_dates_in(text, &Local)
19 }
20
21 pub fn format_card_dates_in<Zone>(text: &str, zone: &Zone) -> String
22 where
23 Zone: TimeZone,
24 Zone::Offset: Display,
25 {
26 DATE_TIME_FUNCTION
27 .replace_all(text, |captures: &Captures| {
28 format_function(captures, zone).unwrap_or_else(|| captures[0].to_owned())
29 })
30 .into_owned()
31 }
32
33 fn format_function<Zone>(captures: &Captures, zone: &Zone) -> Option<String>
34 where
35 Zone: TimeZone,
36 Zone::Offset: Display,
37 {
38 let moment = DateTime::parse_from_rfc3339(&captures[2])
39 .ok()?
40 .with_timezone(zone);
41 let pattern = match (&captures[1], captures.get(3).map(|style| style.as_str())) {
42 ("TIME", _) => TIME_FORMAT,
43 (_, Some("SHORT")) => SHORT_FORMAT,
44 (_, Some("LONG")) => LONG_FORMAT,
45 _ => COMPACT_FORMAT,
46 };
47 Some(moment.format(pattern).to_string())
48 }
@@ -0,0 +1,48 @@
1use std::fmt::Display;
2use std::sync::LazyLock;
3
4use chrono::{DateTime, Local, TimeZone};
5use regex::{Captures, Regex};
6
7const COMPACT_FORMAT: &str = "%Y-%m-%d";
8const SHORT_FORMAT: &str = "%a, %b %-d, %Y";
9const LONG_FORMAT: &str = "%A, %B %-d, %Y";
10const TIME_FORMAT: &str = "%H:%M";
11
12static DATE_TIME_FUNCTION: LazyLock<Regex> = LazyLock::new(|| {
13 Regex::new(r"(?:\{\{\s*)?\b(DATE|TIME)\(\s*([^,()\s]+)\s*(?:,\s*(SHORT|LONG|COMPACT)\s*)?\)(?:\s*\}\})?")
14 .unwrap()
15});
16
17pub fn format_card_dates(text: &str) -> String {
18 format_card_dates_in(text, &Local)
19}
20
21pub fn format_card_dates_in<Zone>(text: &str, zone: &Zone) -> String
22where
23 Zone: TimeZone,
24 Zone::Offset: Display,
25{
26 DATE_TIME_FUNCTION
27 .replace_all(text, |captures: &Captures| {
28 format_function(captures, zone).unwrap_or_else(|| captures[0].to_owned())
29 })
30 .into_owned()
31}
32
33fn format_function<Zone>(captures: &Captures, zone: &Zone) -> Option<String>
34where
35 Zone: TimeZone,
36 Zone::Offset: Display,
37{
38 let moment = DateTime::parse_from_rfc3339(&captures[2])
39 .ok()?
40 .with_timezone(zone);
41 let pattern = match (&captures[1], captures.get(3).map(|style| style.as_str())) {
42 ("TIME", _) => TIME_FORMAT,
43 (_, Some("SHORT")) => SHORT_FORMAT,
44 (_, Some("LONG")) => LONG_FORMAT,
45 _ => COMPACT_FORMAT,
46 };
47 Some(moment.format(pattern).to_string())
48}
crates/core/src/card_inputs.rs +489 −7
@@ -1,6 +1,8 @@
1 1 use chrono::{NaiveDate, NaiveTime};
2 2 use regex::Regex;
3 use serde_json::{Map, Value};
3 use serde_json::{Map, Number, Value, json};
4
5 use crate::adaptive_card::{CardAction, CardActionKind, parse_action};
4 6
5 7 const DATE_FORMAT: &str = "%Y-%m-%d";
6 8 const TIME_FORMAT: &str = "%H:%M";
@@ -9,6 +11,13 @@ const DEFAULT_VALUE_OFF: &str = "false";
9 11 const CHOICE_SEPARATOR: char = ',';
10 12 const REQUIRED_MESSAGE: &str = "Required";
11 13 const INVALID_MESSAGE: &str = "Invalid value";
14 const INLINE_ACTION_TITLE: &str = "Go";
15 const DEFAULT_SEARCH_COUNT: usize = 15;
16 const DEFAULT_RATING_MAX: u32 = 5;
17 const MAX_RATING_MAX: u32 = 10;
18 const WHOLE_NUMBER_LIMIT: f64 = 1e15;
19 const DATA_QUERY_TYPE: &str = "Data.Query";
20 pub const SEARCH_INVOKE_NAME: &str = "application/search";
12 21 pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD";
13 22 pub const TIME_PLACEHOLDER: &str = "HH:MM";
14 23
@@ -29,6 +38,7 @@ pub enum CardInputKind {
29 38 Time(MomentInput),
30 39 Toggle(ToggleInput),
31 40 Choice(ChoiceInput),
41 Rating(RatingInput),
32 42 }
33 43
34 44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -48,6 +58,13 @@ pub struct TextInput {
48 58 pub max_length: Option<usize>,
49 59 pub style: TextStyle,
50 60 pub regex: Option<String>,
61 pub inline_action: Option<Box<InlineAction>>,
62 }
63
64 #[derive(Debug, Clone, PartialEq)]
65 pub struct InlineAction {
66 pub action: CardAction,
67 pub icon_url: Option<String>,
51 68 }
52 69
53 70 #[derive(Debug, Clone, PartialEq)]
@@ -71,6 +88,7 @@ pub struct ToggleInput {
71 88 pub value: String,
72 89 pub value_on: String,
73 90 pub value_off: String,
91 pub wrap: bool,
74 92 }
75 93
76 94 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -87,6 +105,49 @@ pub struct ChoiceInput {
87 105 pub style: ChoiceStyle,
88 106 pub placeholder: Option<String>,
89 107 pub value: String,
108 pub query: Option<ChoiceQuery>,
109 }
110
111 #[derive(Debug, Clone, PartialEq, Eq)]
112 pub struct ChoiceQuery {
113 pub dataset: String,
114 pub count: usize,
115 }
116
117 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
118 pub enum RatingColor {
119 Neutral,
120 Marigold,
121 }
122
123 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
124 pub enum RatingSize {
125 Medium,
126 Large,
127 }
128
129 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
130 pub enum RatingStyle {
131 Default,
132 Compact,
133 }
134
135 #[derive(Debug, Clone, PartialEq)]
136 pub struct RatingInput {
137 pub max: u32,
138 pub value: String,
139 pub color: RatingColor,
140 pub size: RatingSize,
141 pub allow_half: bool,
142 }
143
144 #[derive(Debug, Clone, PartialEq)]
145 pub struct RatingDisplay {
146 pub value: f64,
147 pub max: u32,
148 pub count: Option<u64>,
149 pub size: RatingSize,
150 pub style: RatingStyle,
90 151 }
91 152
92 153 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -123,6 +184,47 @@ impl ChoiceStyle {
123 184 }
124 185 }
125 186
187 impl RatingColor {
188 fn parse(value: Option<&str>) -> Self {
189 match value.map(str::to_ascii_lowercase).as_deref() {
190 Some("marigold") => RatingColor::Marigold,
191 _ => RatingColor::Neutral,
192 }
193 }
194 }
195
196 impl RatingSize {
197 fn parse(value: Option<&str>) -> Self {
198 match value.map(str::to_ascii_lowercase).as_deref() {
199 Some("large") => RatingSize::Large,
200 _ => RatingSize::Medium,
201 }
202 }
203 }
204
205 impl RatingStyle {
206 fn parse(value: Option<&str>) -> Self {
207 match value.map(str::to_ascii_lowercase).as_deref() {
208 Some("compact") => RatingStyle::Compact,
209 _ => RatingStyle::Default,
210 }
211 }
212 }
213
214 impl RatingInput {
215 pub fn rating(&self, current: &str) -> f64 {
216 current.trim().parse::<f64>().unwrap_or(0.)
217 }
218
219 pub fn value_text(&self, rating: f64) -> String {
220 if rating <= 0. {
221 String::new()
222 } else {
223 number_value(rating.min(f64::from(self.max))).to_string()
224 }
225 }
226 }
227
126 228 impl ToggleInput {
127 229 pub fn is_on(&self, current: &str) -> bool {
128 230 current == self.value_on
@@ -182,6 +284,23 @@ impl CardInput {
182 284 CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(),
183 285 CardInputKind::Toggle(toggle) => toggle.value.clone(),
184 286 CardInputKind::Choice(choice) => choice.value.clone(),
287 CardInputKind::Rating(rating) => rating.value.clone(),
288 }
289 }
290
291 pub fn submitted_value(&self, value: &str) -> Value {
292 match (&self.kind, value.trim().parse::<f64>()) {
293 (CardInputKind::Rating(_), Ok(number)) if number.is_finite() => {
294 Value::Number(number_value(number))
295 }
296 _ => Value::String(value.to_owned()),
297 }
298 }
299
300 fn is_blank(&self, value: &str) -> bool {
301 match &self.kind {
302 CardInputKind::Rating(rating) => value.is_empty() || rating.rating(value) <= 0.,
303 _ => value.is_empty(),
185 304 }
186 305 }
187 306
@@ -191,7 +310,7 @@ impl CardInput {
191 310 .clone()
192 311 .filter(|message| !message.trim().is_empty())
193 312 };
194 if value.is_empty() {
313 if self.is_blank(value) {
195 314 return (self.required)
196 315 .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned()));
197 316 }
@@ -202,6 +321,7 @@ impl CardInput {
202 321 CardInputKind::Time(moment) => moment.accepts(value, parse_time),
203 322 CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value),
204 323 CardInputKind::Choice(_) => true,
324 CardInputKind::Rating(rating) => !self.required || rating.rating(value) > 0.,
205 325 };
206 326 (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned()))
207 327 }
@@ -230,6 +350,22 @@ impl NumberInput {
230 350 }
231 351
232 352 impl MomentInput {
353 pub fn initial_date(&self) -> Option<NaiveDate> {
354 parse_date(&self.value)
355 }
356
357 pub fn min_date(&self) -> Option<NaiveDate> {
358 self.min.as_deref().and_then(parse_date)
359 }
360
361 pub fn max_date(&self) -> Option<NaiveDate> {
362 self.max.as_deref().and_then(parse_date)
363 }
364
365 pub fn initial_time(&self) -> Option<NaiveTime> {
366 parse_time(&self.value)
367 }
368
233 369 fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool {
234 370 let Some(moment) = parse(value) else {
235 371 return false;
@@ -246,6 +382,14 @@ impl MomentInput {
246 382 }
247 383 }
248 384
385 pub fn format_date(date: NaiveDate) -> String {
386 date.format(DATE_FORMAT).to_string()
387 }
388
389 pub fn format_time(time: NaiveTime) -> String {
390 time.format(TIME_FORMAT).to_string()
391 }
392
249 393 fn parse_date(value: &str) -> Option<NaiveDate> {
250 394 NaiveDate::parse_from_str(value, DATE_FORMAT).ok()
251 395 }
@@ -268,7 +412,7 @@ pub fn collect_input_values(
268 412 message,
269 413 }),
270 414 None => {
271 values.insert(input.id.clone(), Value::String(value));
415 values.insert(input.id.clone(), input.submitted_value(&value));
272 416 }
273 417 }
274 418 }
@@ -291,6 +435,81 @@ pub fn merge_input_data(data: &Value, values: &Map<String, Value>) -> Value {
291 435 }
292 436 }
293 437
438 pub fn search_request_value(query: &ChoiceQuery, query_text: &str) -> Value {
439 json!({
440 "queryText": query_text,
441 "queryOptions": {"skip": 0, "top": query.count},
442 "dataset": query.dataset,
443 })
444 }
445
446 pub fn parse_search_results(response_value: &Value) -> Vec<InputChoice> {
447 response_value
448 .get("results")
449 .and_then(Value::as_array)
450 .into_iter()
451 .flatten()
452 .filter_map(|result| {
453 Some(InputChoice {
454 title: text_field(result, "title")?,
455 value: text_field(result, "value")?,
456 })
457 })
458 .collect()
459 }
460
461 pub(crate) fn parse_rating(value: &Value) -> RatingDisplay {
462 RatingDisplay {
463 value: value.get("value").and_then(Value::as_f64).unwrap_or(0.),
464 max: rating_max(value),
465 count: value.get("count").and_then(Value::as_u64),
466 size: RatingSize::parse(value.get("size").and_then(Value::as_str)),
467 style: RatingStyle::parse(value.get("style").and_then(Value::as_str)),
468 }
469 }
470
471 fn rating_max(value: &Value) -> u32 {
472 value
473 .get("max")
474 .and_then(Value::as_u64)
475 .map_or(DEFAULT_RATING_MAX, |max| {
476 max.clamp(1, MAX_RATING_MAX.into()) as u32
477 })
478 }
479
480 fn parse_choice_query(value: &Value) -> Option<ChoiceQuery> {
481 let data = value.get("choices.data")?;
482 if text_field(data, "type")? != DATA_QUERY_TYPE {
483 return None;
484 }
485 Some(ChoiceQuery {
486 dataset: text_field(data, "dataset")?,
487 count: data
488 .get("count")
489 .and_then(Value::as_u64)
490 .filter(|count| *count > 0)
491 .map_or(DEFAULT_SEARCH_COUNT, |count| count as usize),
492 })
493 }
494
495 fn parse_inline_action(value: &Value) -> Option<Box<InlineAction>> {
496 let mut action_value = value.get("inlineAction")?.clone();
497 if text_field(&action_value, "title").is_none_or(|title| title.trim().is_empty()) {
498 action_value["title"] = json!(INLINE_ACTION_TITLE);
499 }
500 let action = parse_action(&action_value)?;
501 matches!(
502 action.kind,
503 CardActionKind::Submit(_) | CardActionKind::Execute(_) | CardActionKind::OpenUrl(_)
504 )
505 .then(|| {
506 Box::new(InlineAction {
507 action,
508 icon_url: text_field(&action_value, "iconUrl"),
509 })
510 })
511 }
512
294 513 pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> {
295 514 let id = text_field(value, "id")?;
296 515 let placeholder = text_field(value, "placeholder");
@@ -306,6 +525,7 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
306 525 .map(|max_length| max_length as usize),
307 526 style: TextStyle::parse(value.get("style").and_then(Value::as_str)),
308 527 regex: text_field(value, "regex"),
528 inline_action: parse_inline_action(value),
309 529 }),
310 530 "Input.Number" => CardInputKind::Number(NumberInput {
311 531 placeholder,
@@ -325,13 +545,16 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
325 545 value: text_field(value, "value").unwrap_or_else(|| value_off.clone()),
326 546 value_on,
327 547 value_off,
548 wrap: bool_field(value, "wrap"),
328 549 })
329 550 }
330 551 "Input.ChoiceSet" => {
552 let query = parse_choice_query(value);
331 553 let choices: Vec<InputChoice> = value
332 .get("choices")?
333 .as_array()?
334 .iter()
554 .get("choices")
555 .and_then(Value::as_array)
556 .into_iter()
557 .flatten()
335 558 .filter_map(|choice| {
336 559 Some(InputChoice {
337 560 title: text_field(choice, "title")?,
@@ -339,7 +562,7 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
339 562 })
340 563 })
341 564 .collect();
342 if choices.is_empty() {
565 if choices.is_empty() && query.is_none() {
343 566 return None;
344 567 }
345 568 CardInputKind::Choice(ChoiceInput {
@@ -348,6 +571,22 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
348 571 style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)),
349 572 placeholder,
350 573 value: text_field(value, "value").unwrap_or_default(),
574 query,
575 })
576 }
577 "Input.Rating" => {
578 let max = rating_max(value);
579 let rating = RatingInput {
580 max,
581 value: String::new(),
582 color: RatingColor::parse(value.get("color").and_then(Value::as_str)),
583 size: RatingSize::parse(value.get("size").and_then(Value::as_str)),
584 allow_half: bool_field(value, "allowHalf"),
585 };
586 let initial = value.get("value").and_then(Value::as_f64).unwrap_or(0.);
587 CardInputKind::Rating(RatingInput {
588 value: rating.value_text(initial),
589 ..rating
351 590 })
352 591 }
353 592 _ => return None,
@@ -384,3 +623,246 @@ fn number_text(value: Option<&Value>) -> String {
384 623 _ => String::new(),
385 624 }
386 625 }
626
627 fn number_value(number: f64) -> Number {
628 if number.fract() == 0. && number.abs() < WHOLE_NUMBER_LIMIT {
629 Number::from(number as i64)
630 } else {
631 Number::from_f64(number).unwrap_or_else(|| Number::from(0))
632 }
633 }
634
635 #[cfg(test)]
636 mod tests {
637 use serde_json::json;
638
639 use super::*;
640
641 fn input(value: Value) -> CardInput {
642 let input_type = value["type"].as_str().unwrap().to_owned();
643 parse_input(&value, &input_type).unwrap()
644 }
645
646 #[test]
647 fn required_empty_text_shows_the_error_message_or_a_default() {
648 let custom = input(
649 json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Fill me"}),
650 );
651 assert_eq!(custom.validate("").as_deref(), Some("Fill me"));
652 let plain = input(json!({"type": "Input.Text", "id": "a", "isRequired": true}));
653 assert_eq!(plain.validate("").as_deref(), Some(REQUIRED_MESSAGE));
654 assert_eq!(plain.validate("x"), None);
655 }
656
657 #[test]
658 fn text_regex_and_max_length_are_checked() {
659 let ticket = input(
660 json!({"type": "Input.Text", "id": "t", "regex": "^[A-Z]{3}-\\d+$", "maxLength": 6, "errorMessage": "Bad ticket"}),
661 );
662 assert_eq!(ticket.validate("ABC-12"), None);
663 assert_eq!(ticket.validate("abc-12").as_deref(), Some("Bad ticket"));
664 assert_eq!(ticket.validate("ABC-1234").as_deref(), Some("Bad ticket"));
665 assert_eq!(ticket.validate(""), None);
666 }
667
668 #[test]
669 fn number_bounds_are_inclusive() {
670 let servers = input(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 20}));
671 assert_eq!(servers.validate("1"), None);
672 assert_eq!(servers.validate("20"), None);
673 assert_eq!(servers.validate("0").as_deref(), Some(INVALID_MESSAGE));
674 assert_eq!(servers.validate("21").as_deref(), Some(INVALID_MESSAGE));
675 assert_eq!(servers.validate("1.").as_deref(), None);
676 assert_eq!(servers.validate("-").as_deref(), Some(INVALID_MESSAGE));
677 }
678
679 #[test]
680 fn date_and_time_bounds_are_checked() {
681 let day = input(
682 json!({"type": "Input.Date", "id": "d", "min": "2026-10-01", "max": "2026-12-31"}),
683 );
684 assert_eq!(day.validate("2026-10-01"), None);
685 assert_eq!(day.validate("2026-12-31"), None);
686 assert!(day.validate("2026-09-30").is_some());
687 assert!(day.validate("2027-01-01").is_some());
688 assert!(day.validate("tomorrow").is_some());
689 let start = input(json!({"type": "Input.Time", "id": "s", "min": "06:00", "max": "20:00"}));
690 assert_eq!(start.validate("06:00"), None);
691 assert!(start.validate("05:59").is_some());
692 assert!(start.validate("20:01").is_some());
693 }
694
695 #[test]
696 fn moments_are_formatted_as_the_bot_expects() {
697 let day = NaiveDate::from_ymd_opt(2026, 3, 7).unwrap();
698 let time = NaiveTime::from_hms_opt(9, 5, 0).unwrap();
699 assert_eq!(format_date(day), "2026-03-07");
700 assert_eq!(format_time(time), "09:05");
701 let moment = MomentInput {
702 value: "2026-03-07".into(),
703 min: Some("2026-03-01".into()),
704 max: None,
705 };
706 assert_eq!(moment.initial_date(), Some(day));
707 assert_eq!(moment.min_date(), NaiveDate::from_ymd_opt(2026, 3, 1));
708 assert_eq!(moment.max_date(), None);
709 }
710
711 #[test]
712 fn rating_parses_with_defaults_and_clamps_the_value() {
713 let rating = input(
714 json!({"type": "Input.Rating", "id": "r", "value": 9, "color": "marigold", "size": "large", "allowHalf": true}),
715 );
716 let CardInputKind::Rating(parsed) = &rating.kind else {
717 panic!("rating expected");
718 };
719 assert_eq!(parsed.max, 5);
720 assert_eq!(parsed.value, "5");
721 assert_eq!(parsed.color, RatingColor::Marigold);
722 assert_eq!(parsed.size, RatingSize::Large);
723 assert!(parsed.allow_half);
724 let ten = input(json!({"type": "Input.Rating", "id": "r", "max": 40}));
725 let CardInputKind::Rating(parsed) = &ten.kind else {
726 panic!("rating expected");
727 };
728 assert_eq!(parsed.max, MAX_RATING_MAX);
729 assert_eq!(parsed.value, "");
730 }
731
732 #[test]
733 fn rating_is_submitted_as_a_number_and_required_means_above_zero() {
734 let rating = input(
735 json!({"type": "Input.Rating", "id": "r", "isRequired": true, "allowHalf": true}),
736 );
737 assert_eq!(rating.submitted_value("3"), json!(3));
738 assert_eq!(rating.submitted_value("3.5"), json!(3.5));
739 assert!(rating.validate("").is_some());
740 assert!(rating.validate("0").is_some());
741 assert_eq!(rating.validate("0.5"), None);
742 let CardInputKind::Rating(parsed) = &rating.kind else {
743 panic!("rating expected");
744 };
745 assert_eq!(parsed.value_text(2.5), "2.5");
746 assert_eq!(parsed.value_text(0.), "");
747 }
748
749 #[test]
750 fn numbers_and_text_are_submitted_as_text() {
751 let count = input(json!({"type": "Input.Number", "id": "n"}));
752 assert_eq!(count.submitted_value("4"), json!("4"));
753 assert_eq!(count.submitted_value("4.25"), json!("4.25"));
754 assert_eq!(count.submitted_value(""), json!(""));
755 let text = input(json!({"type": "Input.Text", "id": "t"}));
756 assert_eq!(text.submitted_value("4"), json!("4"));
757 }
758
759 #[test]
760 fn collected_values_use_their_submitted_types() {
761 let inputs = vec![
762 input(json!({"type": "Input.Rating", "id": "r", "value": 4})),
763 input(json!({"type": "Input.Number", "id": "n", "value": 7})),
764 ];
765 let values = collect_input_values(&inputs, CardInput::initial_value).unwrap();
766 assert_eq!(Value::Object(values), json!({"r": 4, "n": "7"}));
767 }
768
769 #[test]
770 fn data_query_choice_sets_keep_their_input_without_static_choices() {
771 let choice = input(json!({
772 "type": "Input.ChoiceSet", "id": "c",
773 "choices.data": {"type": "Data.Query", "dataset": "people", "count": 7}
774 }));
775 let CardInputKind::Choice(parsed) = &choice.kind else {
776 panic!("choice set expected");
777 };
778 assert!(parsed.choices.is_empty());
779 assert_eq!(
780 parsed.query,
781 Some(ChoiceQuery {
782 dataset: "people".into(),
783 count: 7
784 })
785 );
786 assert!(
787 parse_input(
788 &json!({"type": "Input.ChoiceSet", "id": "c"}),
789 "Input.ChoiceSet"
790 )
791 .is_none()
792 );
793 }
794
795 #[test]
796 fn search_request_carries_query_options_and_dataset() {
797 let query = ChoiceQuery {
798 dataset: "people".into(),
799 count: 15,
800 };
801 assert_eq!(
802 search_request_value(&query, "ad"),
803 json!({"queryText": "ad", "queryOptions": {"skip": 0, "top": 15}, "dataset": "people"})
804 );
805 }
806
807 #[test]
808 fn search_results_keep_only_complete_title_value_pairs() {
809 let response = json!({"results": [
810 {"title": "Ada", "value": "ada"},
811 {"title": "No value"},
812 {"title": "Bob", "value": "bob"}
813 ]});
814 let titles: Vec<String> = parse_search_results(&response)
815 .into_iter()
816 .map(|choice| choice.value)
817 .collect();
818 assert_eq!(titles, ["ada", "bob"]);
819 assert!(parse_search_results(&Value::Null).is_empty());
820 }
821
822 #[test]
823 fn inline_action_defaults_its_title_and_rejects_other_kinds() {
824 let with_action = input(json!({
825 "type": "Input.Text", "id": "t",
826 "inlineAction": {"type": "Action.Submit", "iconUrl": "https://example.com/i.png", "data": {"go": 1}}
827 }));
828 let CardInputKind::Text(text) = &with_action.kind else {
829 panic!("text expected");
830 };
831 let inline = text.inline_action.as_ref().unwrap();
832 assert_eq!(inline.action.title, INLINE_ACTION_TITLE);
833 assert_eq!(
834 inline.icon_url.as_deref(),
835 Some("https://example.com/i.png")
836 );
837 let toggling = input(json!({
838 "type": "Input.Text", "id": "t",
839 "inlineAction": {"type": "Action.ToggleVisibility", "title": "x", "targetElements": ["a"]}
840 }));
841 let CardInputKind::Text(text) = &toggling.kind else {
842 panic!("text expected");
843 };
844 assert!(text.inline_action.is_none());
845 }
846
847 #[test]
848 fn toggle_wrap_is_parsed() {
849 let toggle =
850 input(json!({"type": "Input.Toggle", "id": "t", "title": "Long", "wrap": true}));
851 let CardInputKind::Toggle(parsed) = &toggle.kind else {
852 panic!("toggle expected");
853 };
854 assert!(parsed.wrap);
855 }
856
857 #[test]
858 fn rating_element_reads_value_count_and_style() {
859 let display = parse_rating(
860 &json!({"type": "Rating", "value": 4.5, "count": 120, "style": "compact", "size": "large"}),
861 );
862 assert_eq!(display.value, 4.5);
863 assert_eq!(display.max, 5);
864 assert_eq!(display.count, Some(120));
865 assert_eq!(display.style, RatingStyle::Compact);
866 assert_eq!(display.size, RatingSize::Large);
867 }
868 }
@@ -1,6 +1,8 @@
1use chrono::{NaiveDate, NaiveTime};
1use chrono::{NaiveDate, NaiveTime};
2use regex::Regex;
2use regex::Regex;
3use serde_json::{Map, Value};
3use serde_json::{Map, Number, Value, json};
4
5use crate::adaptive_card::{CardAction, CardActionKind, parse_action};
4
6
5const DATE_FORMAT: &str = "%Y-%m-%d";
7const DATE_FORMAT: &str = "%Y-%m-%d";
6const TIME_FORMAT: &str = "%H:%M";
8const TIME_FORMAT: &str = "%H:%M";
@@ -9,6 +11,13 @@ const DEFAULT_VALUE_OFF: &str = "false";
9const CHOICE_SEPARATOR: char = ',';
11const CHOICE_SEPARATOR: char = ',';
10const REQUIRED_MESSAGE: &str = "Required";
12const REQUIRED_MESSAGE: &str = "Required";
11const INVALID_MESSAGE: &str = "Invalid value";
13const INVALID_MESSAGE: &str = "Invalid value";
14const INLINE_ACTION_TITLE: &str = "Go";
15const DEFAULT_SEARCH_COUNT: usize = 15;
16const DEFAULT_RATING_MAX: u32 = 5;
17const MAX_RATING_MAX: u32 = 10;
18const WHOLE_NUMBER_LIMIT: f64 = 1e15;
19const DATA_QUERY_TYPE: &str = "Data.Query";
20pub const SEARCH_INVOKE_NAME: &str = "application/search";
12pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD";
21pub const DATE_PLACEHOLDER: &str = "YYYY-MM-DD";
13pub const TIME_PLACEHOLDER: &str = "HH:MM";
22pub const TIME_PLACEHOLDER: &str = "HH:MM";
14
23
@@ -29,6 +38,7 @@ pub enum CardInputKind {
29 Time(MomentInput),
38 Time(MomentInput),
30 Toggle(ToggleInput),
39 Toggle(ToggleInput),
31 Choice(ChoiceInput),
40 Choice(ChoiceInput),
41 Rating(RatingInput),
32}
42}
33
43
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -48,6 +58,13 @@ pub struct TextInput {
48 pub max_length: Option<usize>,
58 pub max_length: Option<usize>,
49 pub style: TextStyle,
59 pub style: TextStyle,
50 pub regex: Option<String>,
60 pub regex: Option<String>,
61 pub inline_action: Option<Box<InlineAction>>,
62}
63
64#[derive(Debug, Clone, PartialEq)]
65pub struct InlineAction {
66 pub action: CardAction,
67 pub icon_url: Option<String>,
51}
68}
52
69
53#[derive(Debug, Clone, PartialEq)]
70#[derive(Debug, Clone, PartialEq)]
@@ -71,6 +88,7 @@ pub struct ToggleInput {
71 pub value: String,
88 pub value: String,
72 pub value_on: String,
89 pub value_on: String,
73 pub value_off: String,
90 pub value_off: String,
91 pub wrap: bool,
74}
92}
75
93
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -87,6 +105,49 @@ pub struct ChoiceInput {
87 pub style: ChoiceStyle,
105 pub style: ChoiceStyle,
88 pub placeholder: Option<String>,
106 pub placeholder: Option<String>,
89 pub value: String,
107 pub value: String,
108 pub query: Option<ChoiceQuery>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct ChoiceQuery {
113 pub dataset: String,
114 pub count: usize,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum RatingColor {
119 Neutral,
120 Marigold,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum RatingSize {
125 Medium,
126 Large,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum RatingStyle {
131 Default,
132 Compact,
133}
134
135#[derive(Debug, Clone, PartialEq)]
136pub struct RatingInput {
137 pub max: u32,
138 pub value: String,
139 pub color: RatingColor,
140 pub size: RatingSize,
141 pub allow_half: bool,
142}
143
144#[derive(Debug, Clone, PartialEq)]
145pub struct RatingDisplay {
146 pub value: f64,
147 pub max: u32,
148 pub count: Option<u64>,
149 pub size: RatingSize,
150 pub style: RatingStyle,
90}
151}
91
152
92#[derive(Debug, Clone, PartialEq, Eq)]
153#[derive(Debug, Clone, PartialEq, Eq)]
@@ -123,6 +184,47 @@ impl ChoiceStyle {
123 }
184 }
124}
185}
125
186
187impl RatingColor {
188 fn parse(value: Option<&str>) -> Self {
189 match value.map(str::to_ascii_lowercase).as_deref() {
190 Some("marigold") => RatingColor::Marigold,
191 _ => RatingColor::Neutral,
192 }
193 }
194}
195
196impl RatingSize {
197 fn parse(value: Option<&str>) -> Self {
198 match value.map(str::to_ascii_lowercase).as_deref() {
199 Some("large") => RatingSize::Large,
200 _ => RatingSize::Medium,
201 }
202 }
203}
204
205impl RatingStyle {
206 fn parse(value: Option<&str>) -> Self {
207 match value.map(str::to_ascii_lowercase).as_deref() {
208 Some("compact") => RatingStyle::Compact,
209 _ => RatingStyle::Default,
210 }
211 }
212}
213
214impl RatingInput {
215 pub fn rating(&self, current: &str) -> f64 {
216 current.trim().parse::<f64>().unwrap_or(0.)
217 }
218
219 pub fn value_text(&self, rating: f64) -> String {
220 if rating <= 0. {
221 String::new()
222 } else {
223 number_value(rating.min(f64::from(self.max))).to_string()
224 }
225 }
226}
227
126impl ToggleInput {
228impl ToggleInput {
127 pub fn is_on(&self, current: &str) -> bool {
229 pub fn is_on(&self, current: &str) -> bool {
128 current == self.value_on
230 current == self.value_on
@@ -182,6 +284,23 @@ impl CardInput {
182 CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(),
284 CardInputKind::Date(moment) | CardInputKind::Time(moment) => moment.value.clone(),
183 CardInputKind::Toggle(toggle) => toggle.value.clone(),
285 CardInputKind::Toggle(toggle) => toggle.value.clone(),
184 CardInputKind::Choice(choice) => choice.value.clone(),
286 CardInputKind::Choice(choice) => choice.value.clone(),
287 CardInputKind::Rating(rating) => rating.value.clone(),
288 }
289 }
290
291 pub fn submitted_value(&self, value: &str) -> Value {
292 match (&self.kind, value.trim().parse::<f64>()) {
293 (CardInputKind::Rating(_), Ok(number)) if number.is_finite() => {
294 Value::Number(number_value(number))
295 }
296 _ => Value::String(value.to_owned()),
297 }
298 }
299
300 fn is_blank(&self, value: &str) -> bool {
301 match &self.kind {
302 CardInputKind::Rating(rating) => value.is_empty() || rating.rating(value) <= 0.,
303 _ => value.is_empty(),
185 }
304 }
186 }
305 }
187
306
@@ -191,7 +310,7 @@ impl CardInput {
191 .clone()
310 .clone()
192 .filter(|message| !message.trim().is_empty())
311 .filter(|message| !message.trim().is_empty())
193 };
312 };
194 if value.is_empty() {
313 if self.is_blank(value) {
195 return (self.required)
314 return (self.required)
196 .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned()));
315 .then(|| message().unwrap_or_else(|| REQUIRED_MESSAGE.to_owned()));
197 }
316 }
@@ -202,6 +321,7 @@ impl CardInput {
202 CardInputKind::Time(moment) => moment.accepts(value, parse_time),
321 CardInputKind::Time(moment) => moment.accepts(value, parse_time),
203 CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value),
322 CardInputKind::Toggle(toggle) => !self.required || toggle.is_on(value),
204 CardInputKind::Choice(_) => true,
323 CardInputKind::Choice(_) => true,
324 CardInputKind::Rating(rating) => !self.required || rating.rating(value) > 0.,
205 };
325 };
206 (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned()))
326 (!valid).then(|| message().unwrap_or_else(|| INVALID_MESSAGE.to_owned()))
207 }
327 }
@@ -230,6 +350,22 @@ impl NumberInput {
230}
350}
231
351
232impl MomentInput {
352impl MomentInput {
353 pub fn initial_date(&self) -> Option<NaiveDate> {
354 parse_date(&self.value)
355 }
356
357 pub fn min_date(&self) -> Option<NaiveDate> {
358 self.min.as_deref().and_then(parse_date)
359 }
360
361 pub fn max_date(&self) -> Option<NaiveDate> {
362 self.max.as_deref().and_then(parse_date)
363 }
364
365 pub fn initial_time(&self) -> Option<NaiveTime> {
366 parse_time(&self.value)
367 }
368
233 fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool {
369 fn accepts<Moment: PartialOrd>(&self, value: &str, parse: fn(&str) -> Option<Moment>) -> bool {
234 let Some(moment) = parse(value) else {
370 let Some(moment) = parse(value) else {
235 return false;
371 return false;
@@ -246,6 +382,14 @@ impl MomentInput {
246 }
382 }
247}
383}
248
384
385pub fn format_date(date: NaiveDate) -> String {
386 date.format(DATE_FORMAT).to_string()
387}
388
389pub fn format_time(time: NaiveTime) -> String {
390 time.format(TIME_FORMAT).to_string()
391}
392
249fn parse_date(value: &str) -> Option<NaiveDate> {
393fn parse_date(value: &str) -> Option<NaiveDate> {
250 NaiveDate::parse_from_str(value, DATE_FORMAT).ok()
394 NaiveDate::parse_from_str(value, DATE_FORMAT).ok()
251}
395}
@@ -268,7 +412,7 @@ pub fn collect_input_values(
268 message,
412 message,
269 }),
413 }),
270 None => {
414 None => {
271 values.insert(input.id.clone(), Value::String(value));
415 values.insert(input.id.clone(), input.submitted_value(&value));
272 }
416 }
273 }
417 }
274 }
418 }
@@ -291,6 +435,81 @@ pub fn merge_input_data(data: &Value, values: &Map<String, Value>) -> Value {
291 }
435 }
292}
436}
293
437
438pub fn search_request_value(query: &ChoiceQuery, query_text: &str) -> Value {
439 json!({
440 "queryText": query_text,
441 "queryOptions": {"skip": 0, "top": query.count},
442 "dataset": query.dataset,
443 })
444}
445
446pub fn parse_search_results(response_value: &Value) -> Vec<InputChoice> {
447 response_value
448 .get("results")
449 .and_then(Value::as_array)
450 .into_iter()
451 .flatten()
452 .filter_map(|result| {
453 Some(InputChoice {
454 title: text_field(result, "title")?,
455 value: text_field(result, "value")?,
456 })
457 })
458 .collect()
459}
460
461pub(crate) fn parse_rating(value: &Value) -> RatingDisplay {
462 RatingDisplay {
463 value: value.get("value").and_then(Value::as_f64).unwrap_or(0.),
464 max: rating_max(value),
465 count: value.get("count").and_then(Value::as_u64),
466 size: RatingSize::parse(value.get("size").and_then(Value::as_str)),
467 style: RatingStyle::parse(value.get("style").and_then(Value::as_str)),
468 }
469}
470
471fn rating_max(value: &Value) -> u32 {
472 value
473 .get("max")
474 .and_then(Value::as_u64)
475 .map_or(DEFAULT_RATING_MAX, |max| {
476 max.clamp(1, MAX_RATING_MAX.into()) as u32
477 })
478}
479
480fn parse_choice_query(value: &Value) -> Option<ChoiceQuery> {
481 let data = value.get("choices.data")?;
482 if text_field(data, "type")? != DATA_QUERY_TYPE {
483 return None;
484 }
485 Some(ChoiceQuery {
486 dataset: text_field(data, "dataset")?,
487 count: data
488 .get("count")
489 .and_then(Value::as_u64)
490 .filter(|count| *count > 0)
491 .map_or(DEFAULT_SEARCH_COUNT, |count| count as usize),
492 })
493}
494
495fn parse_inline_action(value: &Value) -> Option<Box<InlineAction>> {
496 let mut action_value = value.get("inlineAction")?.clone();
497 if text_field(&action_value, "title").is_none_or(|title| title.trim().is_empty()) {
498 action_value["title"] = json!(INLINE_ACTION_TITLE);
499 }
500 let action = parse_action(&action_value)?;
501 matches!(
502 action.kind,
503 CardActionKind::Submit(_) | CardActionKind::Execute(_) | CardActionKind::OpenUrl(_)
504 )
505 .then(|| {
506 Box::new(InlineAction {
507 action,
508 icon_url: text_field(&action_value, "iconUrl"),
509 })
510 })
511}
512
294pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> {
513pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput> {
295 let id = text_field(value, "id")?;
514 let id = text_field(value, "id")?;
296 let placeholder = text_field(value, "placeholder");
515 let placeholder = text_field(value, "placeholder");
@@ -306,6 +525,7 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
306 .map(|max_length| max_length as usize),
525 .map(|max_length| max_length as usize),
307 style: TextStyle::parse(value.get("style").and_then(Value::as_str)),
526 style: TextStyle::parse(value.get("style").and_then(Value::as_str)),
308 regex: text_field(value, "regex"),
527 regex: text_field(value, "regex"),
528 inline_action: parse_inline_action(value),
309 }),
529 }),
310 "Input.Number" => CardInputKind::Number(NumberInput {
530 "Input.Number" => CardInputKind::Number(NumberInput {
311 placeholder,
531 placeholder,
@@ -325,13 +545,16 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
325 value: text_field(value, "value").unwrap_or_else(|| value_off.clone()),
545 value: text_field(value, "value").unwrap_or_else(|| value_off.clone()),
326 value_on,
546 value_on,
327 value_off,
547 value_off,
548 wrap: bool_field(value, "wrap"),
328 })
549 })
329 }
550 }
330 "Input.ChoiceSet" => {
551 "Input.ChoiceSet" => {
552 let query = parse_choice_query(value);
331 let choices: Vec<InputChoice> = value
553 let choices: Vec<InputChoice> = value
332 .get("choices")?
554 .get("choices")
333 .as_array()?
555 .and_then(Value::as_array)
334 .iter()
556 .into_iter()
557 .flatten()
335 .filter_map(|choice| {
558 .filter_map(|choice| {
336 Some(InputChoice {
559 Some(InputChoice {
337 title: text_field(choice, "title")?,
560 title: text_field(choice, "title")?,
@@ -339,7 +562,7 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
339 })
562 })
340 })
563 })
341 .collect();
564 .collect();
342 if choices.is_empty() {
565 if choices.is_empty() && query.is_none() {
343 return None;
566 return None;
344 }
567 }
345 CardInputKind::Choice(ChoiceInput {
568 CardInputKind::Choice(ChoiceInput {
@@ -348,6 +571,22 @@ pub(crate) fn parse_input(value: &Value, input_type: &str) -> Option<CardInput>
348 style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)),
571 style: ChoiceStyle::parse(value.get("style").and_then(Value::as_str)),
349 placeholder,
572 placeholder,
350 value: text_field(value, "value").unwrap_or_default(),
573 value: text_field(value, "value").unwrap_or_default(),
574 query,
575 })
576 }
577 "Input.Rating" => {
578 let max = rating_max(value);
579 let rating = RatingInput {
580 max,
581 value: String::new(),
582 color: RatingColor::parse(value.get("color").and_then(Value::as_str)),
583 size: RatingSize::parse(value.get("size").and_then(Value::as_str)),
584 allow_half: bool_field(value, "allowHalf"),
585 };
586 let initial = value.get("value").and_then(Value::as_f64).unwrap_or(0.);
587 CardInputKind::Rating(RatingInput {
588 value: rating.value_text(initial),
589 ..rating
351 })
590 })
352 }
591 }
353 _ => return None,
592 _ => return None,
@@ -384,3 +623,246 @@ fn number_text(value: Option<&Value>) -> String {
384 _ => String::new(),
623 _ => String::new(),
385 }
624 }
386}
625}
626
627fn number_value(number: f64) -> Number {
628 if number.fract() == 0. && number.abs() < WHOLE_NUMBER_LIMIT {
629 Number::from(number as i64)
630 } else {
631 Number::from_f64(number).unwrap_or_else(|| Number::from(0))
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use serde_json::json;
638
639 use super::*;
640
641 fn input(value: Value) -> CardInput {
642 let input_type = value["type"].as_str().unwrap().to_owned();
643 parse_input(&value, &input_type).unwrap()
644 }
645
646 #[test]
647 fn required_empty_text_shows_the_error_message_or_a_default() {
648 let custom = input(
649 json!({"type": "Input.Text", "id": "a", "isRequired": true, "errorMessage": "Fill me"}),
650 );
651 assert_eq!(custom.validate("").as_deref(), Some("Fill me"));
652 let plain = input(json!({"type": "Input.Text", "id": "a", "isRequired": true}));
653 assert_eq!(plain.validate("").as_deref(), Some(REQUIRED_MESSAGE));
654 assert_eq!(plain.validate("x"), None);
655 }
656
657 #[test]
658 fn text_regex_and_max_length_are_checked() {
659 let ticket = input(
660 json!({"type": "Input.Text", "id": "t", "regex": "^[A-Z]{3}-\\d+$", "maxLength": 6, "errorMessage": "Bad ticket"}),
661 );
662 assert_eq!(ticket.validate("ABC-12"), None);
663 assert_eq!(ticket.validate("abc-12").as_deref(), Some("Bad ticket"));
664 assert_eq!(ticket.validate("ABC-1234").as_deref(), Some("Bad ticket"));
665 assert_eq!(ticket.validate(""), None);
666 }
667
668 #[test]
669 fn number_bounds_are_inclusive() {
670 let servers = input(json!({"type": "Input.Number", "id": "n", "min": 1, "max": 20}));
671 assert_eq!(servers.validate("1"), None);
672 assert_eq!(servers.validate("20"), None);
673 assert_eq!(servers.validate("0").as_deref(), Some(INVALID_MESSAGE));
674 assert_eq!(servers.validate("21").as_deref(), Some(INVALID_MESSAGE));
675 assert_eq!(servers.validate("1.").as_deref(), None);
676 assert_eq!(servers.validate("-").as_deref(), Some(INVALID_MESSAGE));
677 }
678
679 #[test]
680 fn date_and_time_bounds_are_checked() {
681 let day = input(
682 json!({"type": "Input.Date", "id": "d", "min": "2026-10-01", "max": "2026-12-31"}),
683 );
684 assert_eq!(day.validate("2026-10-01"), None);
685 assert_eq!(day.validate("2026-12-31"), None);
686 assert!(day.validate("2026-09-30").is_some());
687 assert!(day.validate("2027-01-01").is_some());
688 assert!(day.validate("tomorrow").is_some());
689 let start = input(json!({"type": "Input.Time", "id": "s", "min": "06:00", "max": "20:00"}));
690 assert_eq!(start.validate("06:00"), None);
691 assert!(start.validate("05:59").is_some());
692 assert!(start.validate("20:01").is_some());
693 }
694
695 #[test]
696 fn moments_are_formatted_as_the_bot_expects() {
697 let day = NaiveDate::from_ymd_opt(2026, 3, 7).unwrap();
698 let time = NaiveTime::from_hms_opt(9, 5, 0).unwrap();
699 assert_eq!(format_date(day), "2026-03-07");
700 assert_eq!(format_time(time), "09:05");
701 let moment = MomentInput {
702 value: "2026-03-07".into(),
703 min: Some("2026-03-01".into()),
704 max: None,
705 };
706 assert_eq!(moment.initial_date(), Some(day));
707 assert_eq!(moment.min_date(), NaiveDate::from_ymd_opt(2026, 3, 1));
708 assert_eq!(moment.max_date(), None);
709 }
710
711 #[test]
712 fn rating_parses_with_defaults_and_clamps_the_value() {
713 let rating = input(
714 json!({"type": "Input.Rating", "id": "r", "value": 9, "color": "marigold", "size": "large", "allowHalf": true}),
715 );
716 let CardInputKind::Rating(parsed) = &rating.kind else {
717 panic!("rating expected");
718 };
719 assert_eq!(parsed.max, 5);
720 assert_eq!(parsed.value, "5");
721 assert_eq!(parsed.color, RatingColor::Marigold);
722 assert_eq!(parsed.size, RatingSize::Large);
723 assert!(parsed.allow_half);
724 let ten = input(json!({"type": "Input.Rating", "id": "r", "max": 40}));
725 let CardInputKind::Rating(parsed) = &ten.kind else {
726 panic!("rating expected");
727 };
728 assert_eq!(parsed.max, MAX_RATING_MAX);
729 assert_eq!(parsed.value, "");
730 }
731
732 #[test]
733 fn rating_is_submitted_as_a_number_and_required_means_above_zero() {
734 let rating = input(
735 json!({"type": "Input.Rating", "id": "r", "isRequired": true, "allowHalf": true}),
736 );
737 assert_eq!(rating.submitted_value("3"), json!(3));
738 assert_eq!(rating.submitted_value("3.5"), json!(3.5));
739 assert!(rating.validate("").is_some());
740 assert!(rating.validate("0").is_some());
741 assert_eq!(rating.validate("0.5"), None);
742 let CardInputKind::Rating(parsed) = &rating.kind else {
743 panic!("rating expected");
744 };
745 assert_eq!(parsed.value_text(2.5), "2.5");
746 assert_eq!(parsed.value_text(0.), "");
747 }
748
749 #[test]
750 fn numbers_and_text_are_submitted_as_text() {
751 let count = input(json!({"type": "Input.Number", "id": "n"}));
752 assert_eq!(count.submitted_value("4"), json!("4"));
753 assert_eq!(count.submitted_value("4.25"), json!("4.25"));
754 assert_eq!(count.submitted_value(""), json!(""));
755 let text = input(json!({"type": "Input.Text", "id": "t"}));
756 assert_eq!(text.submitted_value("4"), json!("4"));
757 }
758
759 #[test]
760 fn collected_values_use_their_submitted_types() {
761 let inputs = vec![
762 input(json!({"type": "Input.Rating", "id": "r", "value": 4})),
763 input(json!({"type": "Input.Number", "id": "n", "value": 7})),
764 ];
765 let values = collect_input_values(&inputs, CardInput::initial_value).unwrap();
766 assert_eq!(Value::Object(values), json!({"r": 4, "n": "7"}));
767 }
768
769 #[test]
770 fn data_query_choice_sets_keep_their_input_without_static_choices() {
771 let choice = input(json!({
772 "type": "Input.ChoiceSet", "id": "c",
773 "choices.data": {"type": "Data.Query", "dataset": "people", "count": 7}
774 }));
775 let CardInputKind::Choice(parsed) = &choice.kind else {
776 panic!("choice set expected");
777 };
778 assert!(parsed.choices.is_empty());
779 assert_eq!(
780 parsed.query,
781 Some(ChoiceQuery {
782 dataset: "people".into(),
783 count: 7
784 })
785 );
786 assert!(
787 parse_input(
788 &json!({"type": "Input.ChoiceSet", "id": "c"}),
789 "Input.ChoiceSet"
790 )
791 .is_none()
792 );
793 }
794
795 #[test]
796 fn search_request_carries_query_options_and_dataset() {
797 let query = ChoiceQuery {
798 dataset: "people".into(),
799 count: 15,
800 };
801 assert_eq!(
802 search_request_value(&query, "ad"),
803 json!({"queryText": "ad", "queryOptions": {"skip": 0, "top": 15}, "dataset": "people"})
804 );
805 }
806
807 #[test]
808 fn search_results_keep_only_complete_title_value_pairs() {
809 let response = json!({"results": [
810 {"title": "Ada", "value": "ada"},
811 {"title": "No value"},
812 {"title": "Bob", "value": "bob"}
813 ]});
814 let titles: Vec<String> = parse_search_results(&response)
815 .into_iter()
816 .map(|choice| choice.value)
817 .collect();
818 assert_eq!(titles, ["ada", "bob"]);
819 assert!(parse_search_results(&Value::Null).is_empty());
820 }
821
822 #[test]
823 fn inline_action_defaults_its_title_and_rejects_other_kinds() {
824 let with_action = input(json!({
825 "type": "Input.Text", "id": "t",
826 "inlineAction": {"type": "Action.Submit", "iconUrl": "https://example.com/i.png", "data": {"go": 1}}
827 }));
828 let CardInputKind::Text(text) = &with_action.kind else {
829 panic!("text expected");
830 };
831 let inline = text.inline_action.as_ref().unwrap();
832 assert_eq!(inline.action.title, INLINE_ACTION_TITLE);
833 assert_eq!(
834 inline.icon_url.as_deref(),
835 Some("https://example.com/i.png")
836 );
837 let toggling = input(json!({
838 "type": "Input.Text", "id": "t",
839 "inlineAction": {"type": "Action.ToggleVisibility", "title": "x", "targetElements": ["a"]}
840 }));
841 let CardInputKind::Text(text) = &toggling.kind else {
842 panic!("text expected");
843 };
844 assert!(text.inline_action.is_none());
845 }
846
847 #[test]
848 fn toggle_wrap_is_parsed() {
849 let toggle =
850 input(json!({"type": "Input.Toggle", "id": "t", "title": "Long", "wrap": true}));
851 let CardInputKind::Toggle(parsed) = &toggle.kind else {
852 panic!("toggle expected");
853 };
854 assert!(parsed.wrap);
855 }
856
857 #[test]
858 fn rating_element_reads_value_count_and_style() {
859 let display = parse_rating(
860 &json!({"type": "Rating", "value": 4.5, "count": 120, "style": "compact", "size": "large"}),
861 );
862 assert_eq!(display.value, 4.5);
863 assert_eq!(display.max, 5);
864 assert_eq!(display.count, Some(120));
865 assert_eq!(display.style, RatingStyle::Compact);
866 assert_eq!(display.size, RatingSize::Large);
867 }
868}
crates/core/src/card_layout.rs added +66 −0
@@ -0,0 +1,66 @@
1 use serde_json::Value;
2
3 use crate::adaptive_card::{
4 ContainerStyle, VerticalAlignment, bool_field, is_supported_url, parse_container_style,
5 parse_vertical_alignment, pixel_field, string_field,
6 };
7
8 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
9 pub enum HorizontalAlignment {
10 #[default]
11 Left,
12 Center,
13 Right,
14 }
15
16 #[derive(Debug, Clone, Default, PartialEq)]
17 pub struct ContainerLayout {
18 pub style: ContainerStyle,
19 pub min_height: Option<f32>,
20 pub vertical_alignment: VerticalAlignment,
21 pub background_image: Option<String>,
22 pub bleed: bool,
23 pub rtl: bool,
24 }
25
26 impl ContainerLayout {
27 pub fn parse(value: &Value) -> ContainerLayout {
28 ContainerLayout {
29 style: parse_container_style(string_field(value, "style")),
30 min_height: pixel_field(value, "minHeight"),
31 vertical_alignment: parse_vertical_alignment(string_field(
32 value,
33 "verticalContentAlignment",
34 )),
35 background_image: parse_background_image(value),
36 bleed: bool_field(value, "bleed"),
37 rtl: bool_field(value, "rtl"),
38 }
39 }
40 }
41
42 pub(crate) fn parse_horizontal_alignment(value: Option<&str>) -> Option<HorizontalAlignment> {
43 match value.map(str::to_ascii_lowercase).as_deref() {
44 Some("left") => Some(HorizontalAlignment::Left),
45 Some("center") => Some(HorizontalAlignment::Center),
46 Some("right") => Some(HorizontalAlignment::Right),
47 _ => None,
48 }
49 }
50
51 fn parse_background_image(value: &Value) -> Option<String> {
52 let image = value.get("backgroundImage")?;
53 let url = image.as_str().or_else(|| string_field(image, "url"))?;
54 is_supported_url(url).then(|| url.to_owned())
55 }
56
57 /// `#RRGGBB` or `#AARRGGBB` as `0xRRGGBBAA`.
58 pub(crate) fn parse_color_hex(value: &str) -> Option<u32> {
59 let digits = value.trim().strip_prefix('#')?;
60 let parsed = u32::from_str_radix(digits, 16).ok()?;
61 match digits.len() {
62 6 => Some(parsed << 8 | 0xff),
63 8 => Some(parsed.rotate_left(8)),
64 _ => None,
65 }
66 }
@@ -0,0 +1,66 @@
1use serde_json::Value;
2
3use crate::adaptive_card::{
4 ContainerStyle, VerticalAlignment, bool_field, is_supported_url, parse_container_style,
5 parse_vertical_alignment, pixel_field, string_field,
6};
7
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
9pub enum HorizontalAlignment {
10 #[default]
11 Left,
12 Center,
13 Right,
14}
15
16#[derive(Debug, Clone, Default, PartialEq)]
17pub struct ContainerLayout {
18 pub style: ContainerStyle,
19 pub min_height: Option<f32>,
20 pub vertical_alignment: VerticalAlignment,
21 pub background_image: Option<String>,
22 pub bleed: bool,
23 pub rtl: bool,
24}
25
26impl ContainerLayout {
27 pub fn parse(value: &Value) -> ContainerLayout {
28 ContainerLayout {
29 style: parse_container_style(string_field(value, "style")),
30 min_height: pixel_field(value, "minHeight"),
31 vertical_alignment: parse_vertical_alignment(string_field(
32 value,
33 "verticalContentAlignment",
34 )),
35 background_image: parse_background_image(value),
36 bleed: bool_field(value, "bleed"),
37 rtl: bool_field(value, "rtl"),
38 }
39 }
40}
41
42pub(crate) fn parse_horizontal_alignment(value: Option<&str>) -> Option<HorizontalAlignment> {
43 match value.map(str::to_ascii_lowercase).as_deref() {
44 Some("left") => Some(HorizontalAlignment::Left),
45 Some("center") => Some(HorizontalAlignment::Center),
46 Some("right") => Some(HorizontalAlignment::Right),
47 _ => None,
48 }
49}
50
51fn parse_background_image(value: &Value) -> Option<String> {
52 let image = value.get("backgroundImage")?;
53 let url = image.as_str().or_else(|| string_field(image, "url"))?;
54 is_supported_url(url).then(|| url.to_owned())
55}
56
57/// `#RRGGBB` or `#AARRGGBB` as `0xRRGGBBAA`.
58pub(crate) fn parse_color_hex(value: &str) -> Option<u32> {
59 let digits = value.trim().strip_prefix('#')?;
60 let parsed = u32::from_str_radix(digits, 16).ok()?;
61 match digits.len() {
62 6 => Some(parsed << 8 | 0xff),
63 8 => Some(parsed.rotate_left(8)),
64 _ => None,
65 }
66}
crates/core/src/card_table.rs added +168 −0
@@ -0,0 +1,168 @@
1 use serde_json::Value;
2
3 use crate::adaptive_card::{
4 CardAction, CardElement, CardItem, ColumnWidth, ContainerStyle, VerticalAlignment,
5 parse_column_width, parse_container_style, parse_items, parse_select_action,
6 parse_vertical_alignment, string_field,
7 };
8 use crate::card_layout::{HorizontalAlignment, parse_horizontal_alignment};
9
10 #[derive(Debug, Clone, PartialEq)]
11 pub struct CardTable {
12 pub columns: Vec<TableColumn>,
13 pub rows: Vec<TableRow>,
14 pub first_row_as_header: bool,
15 pub show_grid_lines: bool,
16 pub grid_style: ContainerStyle,
17 pub horizontal_alignment: Option<HorizontalAlignment>,
18 pub vertical_alignment: Option<VerticalAlignment>,
19 }
20
21 #[derive(Debug, Clone, PartialEq)]
22 pub struct TableColumn {
23 pub width: ColumnWidth,
24 pub horizontal_alignment: Option<HorizontalAlignment>,
25 pub vertical_alignment: Option<VerticalAlignment>,
26 }
27
28 #[derive(Debug, Clone, PartialEq)]
29 pub struct TableRow {
30 pub cells: Vec<TableCell>,
31 pub style: ContainerStyle,
32 pub horizontal_alignment: Option<HorizontalAlignment>,
33 pub vertical_alignment: Option<VerticalAlignment>,
34 }
35
36 #[derive(Debug, Clone, PartialEq)]
37 pub struct TableCell {
38 pub items: Vec<CardItem>,
39 pub style: ContainerStyle,
40 pub vertical_alignment: Option<VerticalAlignment>,
41 pub select_action: Option<CardAction>,
42 }
43
44 impl CardTable {
45 pub fn cell_horizontal_alignment(
46 &self,
47 row: &TableRow,
48 column_index: usize,
49 ) -> HorizontalAlignment {
50 row.horizontal_alignment
51 .or_else(|| self.columns.get(column_index)?.horizontal_alignment)
52 .or(self.horizontal_alignment)
53 .unwrap_or_default()
54 }
55
56 pub fn cell_vertical_alignment(
57 &self,
58 row: &TableRow,
59 cell: &TableCell,
60 column_index: usize,
61 ) -> VerticalAlignment {
62 cell.vertical_alignment
63 .or(row.vertical_alignment)
64 .or_else(|| self.columns.get(column_index)?.vertical_alignment)
65 .or(self.vertical_alignment)
66 .unwrap_or_default()
67 }
68 }
69
70 pub(crate) fn parse_table(value: &Value) -> Option<CardElement> {
71 let rows: Vec<TableRow> = value
72 .get("rows")?
73 .as_array()?
74 .iter()
75 .filter_map(parse_row)
76 .collect();
77 if rows.is_empty() {
78 return None;
79 }
80 let column_count = rows.iter().map(|row| row.cells.len()).max().unwrap_or(0);
81 let declared: Vec<TableColumn> = value
82 .get("columns")
83 .and_then(Value::as_array)
84 .into_iter()
85 .flatten()
86 .map(parse_column)
87 .collect();
88 let columns = (0..column_count.max(declared.len()))
89 .map(|index| declared.get(index).cloned().unwrap_or_else(default_column))
90 .collect();
91 Some(CardElement::Table(CardTable {
92 columns,
93 rows,
94 first_row_as_header: value
95 .get("firstRowAsHeader")
96 .and_then(Value::as_bool)
97 .unwrap_or(true),
98 show_grid_lines: value
99 .get("showGridLines")
100 .and_then(Value::as_bool)
101 .unwrap_or(true),
102 grid_style: parse_container_style(string_field(value, "gridStyle")),
103 horizontal_alignment: parse_horizontal_alignment(string_field(
104 value,
105 "horizontalCellContentAlignment",
106 )),
107 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
108 }))
109 }
110
111 fn default_column() -> TableColumn {
112 TableColumn {
113 width: ColumnWidth::Weighted(1.),
114 horizontal_alignment: None,
115 vertical_alignment: None,
116 }
117 }
118
119 fn parse_column(value: &Value) -> TableColumn {
120 let width = value
121 .get("width")
122 .map_or(ColumnWidth::Weighted(1.), |width| {
123 parse_column_width(Some(width))
124 });
125 TableColumn {
126 width,
127 horizontal_alignment: parse_horizontal_alignment(string_field(
128 value,
129 "horizontalCellContentAlignment",
130 )),
131 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
132 }
133 }
134
135 fn parse_row(value: &Value) -> Option<TableRow> {
136 if value.get("isVisible").and_then(Value::as_bool) == Some(false) {
137 return None;
138 }
139 let cells: Vec<TableCell> = value
140 .get("cells")?
141 .as_array()?
142 .iter()
143 .map(parse_cell)
144 .collect();
145 (!cells.is_empty()).then(|| TableRow {
146 cells,
147 style: parse_container_style(string_field(value, "style")),
148 horizontal_alignment: parse_horizontal_alignment(string_field(
149 value,
150 "horizontalCellContentAlignment",
151 )),
152 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
153 })
154 }
155
156 fn parse_cell(value: &Value) -> TableCell {
157 TableCell {
158 items: parse_items(value.get("items")),
159 style: parse_container_style(string_field(value, "style")),
160 vertical_alignment: parse_optional_vertical(value, "verticalContentAlignment"),
161 select_action: parse_select_action(value),
162 }
163 }
164
165 fn parse_optional_vertical(value: &Value, key: &str) -> Option<VerticalAlignment> {
166 string_field(value, key)?;
167 Some(parse_vertical_alignment(string_field(value, key)))
168 }
@@ -0,0 +1,168 @@
1use serde_json::Value;
2
3use crate::adaptive_card::{
4 CardAction, CardElement, CardItem, ColumnWidth, ContainerStyle, VerticalAlignment,
5 parse_column_width, parse_container_style, parse_items, parse_select_action,
6 parse_vertical_alignment, string_field,
7};
8use crate::card_layout::{HorizontalAlignment, parse_horizontal_alignment};
9
10#[derive(Debug, Clone, PartialEq)]
11pub struct CardTable {
12 pub columns: Vec<TableColumn>,
13 pub rows: Vec<TableRow>,
14 pub first_row_as_header: bool,
15 pub show_grid_lines: bool,
16 pub grid_style: ContainerStyle,
17 pub horizontal_alignment: Option<HorizontalAlignment>,
18 pub vertical_alignment: Option<VerticalAlignment>,
19}
20
21#[derive(Debug, Clone, PartialEq)]
22pub struct TableColumn {
23 pub width: ColumnWidth,
24 pub horizontal_alignment: Option<HorizontalAlignment>,
25 pub vertical_alignment: Option<VerticalAlignment>,
26}
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct TableRow {
30 pub cells: Vec<TableCell>,
31 pub style: ContainerStyle,
32 pub horizontal_alignment: Option<HorizontalAlignment>,
33 pub vertical_alignment: Option<VerticalAlignment>,
34}
35
36#[derive(Debug, Clone, PartialEq)]
37pub struct TableCell {
38 pub items: Vec<CardItem>,
39 pub style: ContainerStyle,
40 pub vertical_alignment: Option<VerticalAlignment>,
41 pub select_action: Option<CardAction>,
42}
43
44impl CardTable {
45 pub fn cell_horizontal_alignment(
46 &self,
47 row: &TableRow,
48 column_index: usize,
49 ) -> HorizontalAlignment {
50 row.horizontal_alignment
51 .or_else(|| self.columns.get(column_index)?.horizontal_alignment)
52 .or(self.horizontal_alignment)
53 .unwrap_or_default()
54 }
55
56 pub fn cell_vertical_alignment(
57 &self,
58 row: &TableRow,
59 cell: &TableCell,
60 column_index: usize,
61 ) -> VerticalAlignment {
62 cell.vertical_alignment
63 .or(row.vertical_alignment)
64 .or_else(|| self.columns.get(column_index)?.vertical_alignment)
65 .or(self.vertical_alignment)
66 .unwrap_or_default()
67 }
68}
69
70pub(crate) fn parse_table(value: &Value) -> Option<CardElement> {
71 let rows: Vec<TableRow> = value
72 .get("rows")?
73 .as_array()?
74 .iter()
75 .filter_map(parse_row)
76 .collect();
77 if rows.is_empty() {
78 return None;
79 }
80 let column_count = rows.iter().map(|row| row.cells.len()).max().unwrap_or(0);
81 let declared: Vec<TableColumn> = value
82 .get("columns")
83 .and_then(Value::as_array)
84 .into_iter()
85 .flatten()
86 .map(parse_column)
87 .collect();
88 let columns = (0..column_count.max(declared.len()))
89 .map(|index| declared.get(index).cloned().unwrap_or_else(default_column))
90 .collect();
91 Some(CardElement::Table(CardTable {
92 columns,
93 rows,
94 first_row_as_header: value
95 .get("firstRowAsHeader")
96 .and_then(Value::as_bool)
97 .unwrap_or(true),
98 show_grid_lines: value
99 .get("showGridLines")
100 .and_then(Value::as_bool)
101 .unwrap_or(true),
102 grid_style: parse_container_style(string_field(value, "gridStyle")),
103 horizontal_alignment: parse_horizontal_alignment(string_field(
104 value,
105 "horizontalCellContentAlignment",
106 )),
107 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
108 }))
109}
110
111fn default_column() -> TableColumn {
112 TableColumn {
113 width: ColumnWidth::Weighted(1.),
114 horizontal_alignment: None,
115 vertical_alignment: None,
116 }
117}
118
119fn parse_column(value: &Value) -> TableColumn {
120 let width = value
121 .get("width")
122 .map_or(ColumnWidth::Weighted(1.), |width| {
123 parse_column_width(Some(width))
124 });
125 TableColumn {
126 width,
127 horizontal_alignment: parse_horizontal_alignment(string_field(
128 value,
129 "horizontalCellContentAlignment",
130 )),
131 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
132 }
133}
134
135fn parse_row(value: &Value) -> Option<TableRow> {
136 if value.get("isVisible").and_then(Value::as_bool) == Some(false) {
137 return None;
138 }
139 let cells: Vec<TableCell> = value
140 .get("cells")?
141 .as_array()?
142 .iter()
143 .map(parse_cell)
144 .collect();
145 (!cells.is_empty()).then(|| TableRow {
146 cells,
147 style: parse_container_style(string_field(value, "style")),
148 horizontal_alignment: parse_horizontal_alignment(string_field(
149 value,
150 "horizontalCellContentAlignment",
151 )),
152 vertical_alignment: parse_optional_vertical(value, "verticalCellContentAlignment"),
153 })
154}
155
156fn parse_cell(value: &Value) -> TableCell {
157 TableCell {
158 items: parse_items(value.get("items")),
159 style: parse_container_style(string_field(value, "style")),
160 vertical_alignment: parse_optional_vertical(value, "verticalContentAlignment"),
161 select_action: parse_select_action(value),
162 }
163}
164
165fn parse_optional_vertical(value: &Value, key: &str) -> Option<VerticalAlignment> {
166 string_field(value, key)?;
167 Some(parse_vertical_alignment(string_field(value, key)))
168}
crates/core/src/card_widgets.rs added +249 −0
@@ -0,0 +1,249 @@
1 use serde_json::Value;
2
3 use crate::adaptive_card::{
4 CardAction, CardElement, CardItem, TextColor, parse_items, parse_select_action,
5 parse_text_color, string_field,
6 };
7 use crate::card_layout::ContainerLayout;
8
9 const ICON_NAME_SEPARATOR: char = ',';
10 const MAX_PROGRESS: f32 = 100.;
11
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub struct CardCodeBlock {
14 pub code: String,
15 pub language: Option<String>,
16 pub start_line: usize,
17 }
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 pub enum BadgeStyle {
21 Default,
22 Accent,
23 Good,
24 Attention,
25 Warning,
26 Subtle,
27 Informative,
28 }
29
30 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 pub enum BadgeAppearance {
32 Filled,
33 Tint,
34 }
35
36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37 pub enum BadgeShape {
38 Square,
39 Rounded,
40 Circular,
41 }
42
43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
44 pub enum BadgeSize {
45 Medium,
46 Large,
47 ExtraLarge,
48 }
49
50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
51 pub enum IconPosition {
52 Before,
53 After,
54 }
55
56 #[derive(Debug, Clone, PartialEq, Eq)]
57 pub struct CardBadge {
58 pub text: String,
59 pub icon: Option<String>,
60 pub style: BadgeStyle,
61 pub appearance: BadgeAppearance,
62 pub shape: BadgeShape,
63 pub size: BadgeSize,
64 pub icon_position: IconPosition,
65 pub tooltip: Option<String>,
66 }
67
68 #[derive(Debug, Clone, PartialEq)]
69 pub struct CardProgressBar {
70 pub value: Option<f32>,
71 pub color: TextColor,
72 }
73
74 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75 pub enum RingSize {
76 Tiny,
77 Small,
78 Medium,
79 Large,
80 }
81
82 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
83 pub enum LabelPosition {
84 Before,
85 After,
86 Above,
87 Below,
88 }
89
90 #[derive(Debug, Clone, PartialEq, Eq)]
91 pub struct CardProgressRing {
92 pub label: Option<String>,
93 pub label_position: LabelPosition,
94 pub size: RingSize,
95 }
96
97 #[derive(Debug, Clone, PartialEq)]
98 pub struct CardCompoundButton {
99 pub icon: Option<String>,
100 pub title: String,
101 pub description: Option<String>,
102 pub badge: Option<String>,
103 pub select_action: Option<CardAction>,
104 }
105
106 #[derive(Debug, Clone, PartialEq)]
107 pub struct CardCarousel {
108 pub pages: Vec<CardCarouselPage>,
109 pub initial_page: usize,
110 }
111
112 #[derive(Debug, Clone, PartialEq)]
113 pub struct CardCarouselPage {
114 pub items: Vec<CardItem>,
115 pub layout: ContainerLayout,
116 pub select_action: Option<CardAction>,
117 }
118
119 fn non_blank(value: &Value, key: &str) -> Option<String> {
120 string_field(value, key)
121 .map(str::trim)
122 .filter(|text| !text.is_empty())
123 .map(str::to_owned)
124 }
125
126 fn icon_name(value: &Value, key: &str) -> Option<String> {
127 let name = string_field(value, key)?
128 .split(ICON_NAME_SEPARATOR)
129 .next()?;
130 let name = name.trim();
131 (!name.is_empty()).then(|| name.to_owned())
132 }
133
134 pub(crate) fn parse_code_block(value: &Value) -> Option<CardElement> {
135 let code = string_field(value, "codeSnippet").filter(|code| !code.trim().is_empty())?;
136 Some(CardElement::CodeBlock(CardCodeBlock {
137 code: code.trim_end_matches('\n').to_owned(),
138 language: non_blank(value, "language"),
139 start_line: value
140 .get("startLineNumber")
141 .and_then(Value::as_u64)
142 .map_or(1, |line| line as usize),
143 }))
144 }
145
146 pub(crate) fn parse_badge(value: &Value) -> Option<CardElement> {
147 let text = non_blank(value, "text");
148 let icon = icon_name(value, "icon");
149 if text.is_none() && icon.is_none() {
150 return None;
151 }
152 let lowered = |key: &str| string_field(value, key).map(str::to_ascii_lowercase);
153 Some(CardElement::Badge(CardBadge {
154 text: text.unwrap_or_default(),
155 icon,
156 style: match lowered("style").as_deref() {
157 Some("accent") => BadgeStyle::Accent,
158 Some("good") => BadgeStyle::Good,
159 Some("attention") => BadgeStyle::Attention,
160 Some("warning") => BadgeStyle::Warning,
161 Some("subtle") => BadgeStyle::Subtle,
162 Some("informative") => BadgeStyle::Informative,
163 _ => BadgeStyle::Default,
164 },
165 appearance: match lowered("appearance").as_deref() {
166 Some("tint") => BadgeAppearance::Tint,
167 _ => BadgeAppearance::Filled,
168 },
169 shape: match lowered("shape").as_deref() {
170 Some("square") => BadgeShape::Square,
171 Some("rounded") => BadgeShape::Rounded,
172 _ => BadgeShape::Circular,
173 },
174 size: match lowered("size").as_deref() {
175 Some("large") => BadgeSize::Large,
176 Some("extralarge") => BadgeSize::ExtraLarge,
177 _ => BadgeSize::Medium,
178 },
179 icon_position: match lowered("iconPosition").as_deref() {
180 Some("after") => IconPosition::After,
181 _ => IconPosition::Before,
182 },
183 tooltip: non_blank(value, "tooltip"),
184 }))
185 }
186
187 pub(crate) fn parse_progress_bar(value: &Value) -> Option<CardElement> {
188 Some(CardElement::ProgressBar(CardProgressBar {
189 value: value
190 .get("value")
191 .and_then(Value::as_f64)
192 .map(|progress| (progress as f32).clamp(0., MAX_PROGRESS)),
193 color: parse_text_color(string_field(value, "color")),
194 }))
195 }
196
197 pub(crate) fn parse_progress_ring(value: &Value) -> Option<CardElement> {
198 let lowered = |key: &str| string_field(value, key).map(str::to_ascii_lowercase);
199 Some(CardElement::ProgressRing(CardProgressRing {
200 label: non_blank(value, "label"),
201 label_position: match lowered("labelPosition").as_deref() {
202 Some("before") => LabelPosition::Before,
203 Some("above") => LabelPosition::Above,
204 Some("below") => LabelPosition::Below,
205 _ => LabelPosition::After,
206 },
207 size: match lowered("size").as_deref() {
208 Some("tiny") => RingSize::Tiny,
209 Some("small") => RingSize::Small,
210 Some("large") => RingSize::Large,
211 _ => RingSize::Medium,
212 },
213 }))
214 }
215
216 pub(crate) fn parse_compound_button(value: &Value) -> Option<CardElement> {
217 Some(CardElement::CompoundButton(CardCompoundButton {
218 icon: icon_name(value, "icon"),
219 title: non_blank(value, "title")?,
220 description: non_blank(value, "description"),
221 badge: non_blank(value, "badge"),
222 select_action: parse_select_action(value),
223 }))
224 }
225
226 pub(crate) fn parse_carousel(value: &Value) -> Option<CardElement> {
227 let pages: Vec<CardCarouselPage> = value
228 .get("pages")?
229 .as_array()?
230 .iter()
231 .filter_map(|page| {
232 let items = parse_items(page.get("items"));
233 (!items.is_empty()).then(|| CardCarouselPage {
234 items,
235 layout: ContainerLayout::parse(page),
236 select_action: parse_select_action(page),
237 })
238 })
239 .collect();
240 let initial_page = value
241 .get("initialPageIndex")
242 .and_then(Value::as_u64)
243 .map_or(0, |index| index as usize)
244 .min(pages.len().saturating_sub(1));
245 (!pages.is_empty()).then_some(CardElement::Carousel(CardCarousel {
246 pages,
247 initial_page,
248 }))
249 }
@@ -0,0 +1,249 @@
1use serde_json::Value;
2
3use crate::adaptive_card::{
4 CardAction, CardElement, CardItem, TextColor, parse_items, parse_select_action,
5 parse_text_color, string_field,
6};
7use crate::card_layout::ContainerLayout;
8
9const ICON_NAME_SEPARATOR: char = ',';
10const MAX_PROGRESS: f32 = 100.;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct CardCodeBlock {
14 pub code: String,
15 pub language: Option<String>,
16 pub start_line: usize,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum BadgeStyle {
21 Default,
22 Accent,
23 Good,
24 Attention,
25 Warning,
26 Subtle,
27 Informative,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum BadgeAppearance {
32 Filled,
33 Tint,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum BadgeShape {
38 Square,
39 Rounded,
40 Circular,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum BadgeSize {
45 Medium,
46 Large,
47 ExtraLarge,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum IconPosition {
52 Before,
53 After,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct CardBadge {
58 pub text: String,
59 pub icon: Option<String>,
60 pub style: BadgeStyle,
61 pub appearance: BadgeAppearance,
62 pub shape: BadgeShape,
63 pub size: BadgeSize,
64 pub icon_position: IconPosition,
65 pub tooltip: Option<String>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct CardProgressBar {
70 pub value: Option<f32>,
71 pub color: TextColor,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum RingSize {
76 Tiny,
77 Small,
78 Medium,
79 Large,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum LabelPosition {
84 Before,
85 After,
86 Above,
87 Below,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct CardProgressRing {
92 pub label: Option<String>,
93 pub label_position: LabelPosition,
94 pub size: RingSize,
95}
96
97#[derive(Debug, Clone, PartialEq)]
98pub struct CardCompoundButton {
99 pub icon: Option<String>,
100 pub title: String,
101 pub description: Option<String>,
102 pub badge: Option<String>,
103 pub select_action: Option<CardAction>,
104}
105
106#[derive(Debug, Clone, PartialEq)]
107pub struct CardCarousel {
108 pub pages: Vec<CardCarouselPage>,
109 pub initial_page: usize,
110}
111
112#[derive(Debug, Clone, PartialEq)]
113pub struct CardCarouselPage {
114 pub items: Vec<CardItem>,
115 pub layout: ContainerLayout,
116 pub select_action: Option<CardAction>,
117}
118
119fn non_blank(value: &Value, key: &str) -> Option<String> {
120 string_field(value, key)
121 .map(str::trim)
122 .filter(|text| !text.is_empty())
123 .map(str::to_owned)
124}
125
126fn icon_name(value: &Value, key: &str) -> Option<String> {
127 let name = string_field(value, key)?
128 .split(ICON_NAME_SEPARATOR)
129 .next()?;
130 let name = name.trim();
131 (!name.is_empty()).then(|| name.to_owned())
132}
133
134pub(crate) fn parse_code_block(value: &Value) -> Option<CardElement> {
135 let code = string_field(value, "codeSnippet").filter(|code| !code.trim().is_empty())?;
136 Some(CardElement::CodeBlock(CardCodeBlock {
137 code: code.trim_end_matches('\n').to_owned(),
138 language: non_blank(value, "language"),
139 start_line: value
140 .get("startLineNumber")
141 .and_then(Value::as_u64)
142 .map_or(1, |line| line as usize),
143 }))
144}
145
146pub(crate) fn parse_badge(value: &Value) -> Option<CardElement> {
147 let text = non_blank(value, "text");
148 let icon = icon_name(value, "icon");
149 if text.is_none() && icon.is_none() {
150 return None;
151 }
152 let lowered = |key: &str| string_field(value, key).map(str::to_ascii_lowercase);
153 Some(CardElement::Badge(CardBadge {
154 text: text.unwrap_or_default(),
155 icon,
156 style: match lowered("style").as_deref() {
157 Some("accent") => BadgeStyle::Accent,
158 Some("good") => BadgeStyle::Good,
159 Some("attention") => BadgeStyle::Attention,
160 Some("warning") => BadgeStyle::Warning,
161 Some("subtle") => BadgeStyle::Subtle,
162 Some("informative") => BadgeStyle::Informative,
163 _ => BadgeStyle::Default,
164 },
165 appearance: match lowered("appearance").as_deref() {
166 Some("tint") => BadgeAppearance::Tint,
167 _ => BadgeAppearance::Filled,
168 },
169 shape: match lowered("shape").as_deref() {
170 Some("square") => BadgeShape::Square,
171 Some("rounded") => BadgeShape::Rounded,
172 _ => BadgeShape::Circular,
173 },
174 size: match lowered("size").as_deref() {
175 Some("large") => BadgeSize::Large,
176 Some("extralarge") => BadgeSize::ExtraLarge,
177 _ => BadgeSize::Medium,
178 },
179 icon_position: match lowered("iconPosition").as_deref() {
180 Some("after") => IconPosition::After,
181 _ => IconPosition::Before,
182 },
183 tooltip: non_blank(value, "tooltip"),
184 }))
185}
186
187pub(crate) fn parse_progress_bar(value: &Value) -> Option<CardElement> {
188 Some(CardElement::ProgressBar(CardProgressBar {
189 value: value
190 .get("value")
191 .and_then(Value::as_f64)
192 .map(|progress| (progress as f32).clamp(0., MAX_PROGRESS)),
193 color: parse_text_color(string_field(value, "color")),
194 }))
195}
196
197pub(crate) fn parse_progress_ring(value: &Value) -> Option<CardElement> {
198 let lowered = |key: &str| string_field(value, key).map(str::to_ascii_lowercase);
199 Some(CardElement::ProgressRing(CardProgressRing {
200 label: non_blank(value, "label"),
201 label_position: match lowered("labelPosition").as_deref() {
202 Some("before") => LabelPosition::Before,
203 Some("above") => LabelPosition::Above,
204 Some("below") => LabelPosition::Below,
205 _ => LabelPosition::After,
206 },
207 size: match lowered("size").as_deref() {
208 Some("tiny") => RingSize::Tiny,
209 Some("small") => RingSize::Small,
210 Some("large") => RingSize::Large,
211 _ => RingSize::Medium,
212 },
213 }))
214}
215
216pub(crate) fn parse_compound_button(value: &Value) -> Option<CardElement> {
217 Some(CardElement::CompoundButton(CardCompoundButton {
218 icon: icon_name(value, "icon"),
219 title: non_blank(value, "title")?,
220 description: non_blank(value, "description"),
221 badge: non_blank(value, "badge"),
222 select_action: parse_select_action(value),
223 }))
224}
225
226pub(crate) fn parse_carousel(value: &Value) -> Option<CardElement> {
227 let pages: Vec<CardCarouselPage> = value
228 .get("pages")?
229 .as_array()?
230 .iter()
231 .filter_map(|page| {
232 let items = parse_items(page.get("items"));
233 (!items.is_empty()).then(|| CardCarouselPage {
234 items,
235 layout: ContainerLayout::parse(page),
236 select_action: parse_select_action(page),
237 })
238 })
239 .collect();
240 let initial_page = value
241 .get("initialPageIndex")
242 .and_then(Value::as_u64)
243 .map_or(0, |index| index as usize)
244 .min(pages.len().saturating_sub(1));
245 (!pages.is_empty()).then_some(CardElement::Carousel(CardCarousel {
246 pages,
247 initial_page,
248 }))
249}
crates/core/src/card_width.rs added +71 −0
@@ -0,0 +1,71 @@
1 const VERY_NARROW_MAX_WIDTH: f32 = 216.;
2 const NARROW_MAX_WIDTH: f32 = 348.;
3 const STANDARD_MAX_WIDTH: f32 = 540.;
4 const AT_LEAST_PREFIX: &str = "atleast:";
5 const AT_MOST_PREFIX: &str = "atmost:";
6
7 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8 pub enum WidthClass {
9 VeryNarrow,
10 Narrow,
11 Standard,
12 Wide,
13 }
14
15 impl WidthClass {
16 pub fn from_pixels(width: f32) -> WidthClass {
17 if width <= VERY_NARROW_MAX_WIDTH {
18 WidthClass::VeryNarrow
19 } else if width <= NARROW_MAX_WIDTH {
20 WidthClass::Narrow
21 } else if width <= STANDARD_MAX_WIDTH {
22 WidthClass::Standard
23 } else {
24 WidthClass::Wide
25 }
26 }
27
28 fn parse(name: &str) -> Option<WidthClass> {
29 match name.trim() {
30 "verynarrow" => Some(WidthClass::VeryNarrow),
31 "narrow" => Some(WidthClass::Narrow),
32 "standard" => Some(WidthClass::Standard),
33 "wide" => Some(WidthClass::Wide),
34 _ => None,
35 }
36 }
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 pub struct TargetWidth {
41 at_least: Option<WidthClass>,
42 at_most: Option<WidthClass>,
43 }
44
45 impl TargetWidth {
46 pub fn parse(value: &str) -> Option<TargetWidth> {
47 let value = value.trim().to_ascii_lowercase();
48 if let Some(name) = value.strip_prefix(AT_LEAST_PREFIX) {
49 return Some(TargetWidth {
50 at_least: Some(WidthClass::parse(name)?),
51 at_most: None,
52 });
53 }
54 if let Some(name) = value.strip_prefix(AT_MOST_PREFIX) {
55 return Some(TargetWidth {
56 at_least: None,
57 at_most: Some(WidthClass::parse(name)?),
58 });
59 }
60 let exact = WidthClass::parse(&value)?;
61 Some(TargetWidth {
62 at_least: Some(exact),
63 at_most: Some(exact),
64 })
65 }
66
67 pub fn matches(&self, width: WidthClass) -> bool {
68 self.at_least.is_none_or(|lowest| width >= lowest)
69 && self.at_most.is_none_or(|highest| width <= highest)
70 }
71 }
@@ -0,0 +1,71 @@
1const VERY_NARROW_MAX_WIDTH: f32 = 216.;
2const NARROW_MAX_WIDTH: f32 = 348.;
3const STANDARD_MAX_WIDTH: f32 = 540.;
4const AT_LEAST_PREFIX: &str = "atleast:";
5const AT_MOST_PREFIX: &str = "atmost:";
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8pub enum WidthClass {
9 VeryNarrow,
10 Narrow,
11 Standard,
12 Wide,
13}
14
15impl WidthClass {
16 pub fn from_pixels(width: f32) -> WidthClass {
17 if width <= VERY_NARROW_MAX_WIDTH {
18 WidthClass::VeryNarrow
19 } else if width <= NARROW_MAX_WIDTH {
20 WidthClass::Narrow
21 } else if width <= STANDARD_MAX_WIDTH {
22 WidthClass::Standard
23 } else {
24 WidthClass::Wide
25 }
26 }
27
28 fn parse(name: &str) -> Option<WidthClass> {
29 match name.trim() {
30 "verynarrow" => Some(WidthClass::VeryNarrow),
31 "narrow" => Some(WidthClass::Narrow),
32 "standard" => Some(WidthClass::Standard),
33 "wide" => Some(WidthClass::Wide),
34 _ => None,
35 }
36 }
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct TargetWidth {
41 at_least: Option<WidthClass>,
42 at_most: Option<WidthClass>,
43}
44
45impl TargetWidth {
46 pub fn parse(value: &str) -> Option<TargetWidth> {
47 let value = value.trim().to_ascii_lowercase();
48 if let Some(name) = value.strip_prefix(AT_LEAST_PREFIX) {
49 return Some(TargetWidth {
50 at_least: Some(WidthClass::parse(name)?),
51 at_most: None,
52 });
53 }
54 if let Some(name) = value.strip_prefix(AT_MOST_PREFIX) {
55 return Some(TargetWidth {
56 at_least: None,
57 at_most: Some(WidthClass::parse(name)?),
58 });
59 }
60 let exact = WidthClass::parse(&value)?;
61 Some(TargetWidth {
62 at_least: Some(exact),
63 at_most: Some(exact),
64 })
65 }
66
67 pub fn matches(&self, width: WidthClass) -> bool {
68 self.at_least.is_none_or(|lowest| width >= lowest)
69 && self.at_most.is_none_or(|highest| width <= highest)
70 }
71}
crates/core/src/italic.rs added +134 −0
@@ -0,0 +1,134 @@
1 const MARKERS: [char; 2] = ['*', '_'];
2 const CODE_OPEN: &str = "<code>";
3 const CODE_CLOSE: &str = "</code>";
4 const LINE_BREAK: &str = "<br>";
5 const LINK_TARGET_OPEN: &str = "](";
6 const URL_SCHEMES: [&str; 2] = ["https://", "http://"];
7
8 pub(crate) fn italicize(escaped: &str) -> String {
9 let characters: Vec<char> = escaped.chars().collect();
10 let mut output = String::with_capacity(escaped.len());
11 let mut index = 0;
12 while index < characters.len() {
13 if let Some(end) = protected_end(&characters, index) {
14 output.extend(&characters[index..end]);
15 index = end;
16 continue;
17 }
18 let character = characters[index];
19 if let Some(close) = italic_close(&characters, index) {
20 output.push_str("<i>");
21 output.extend(&characters[index + 1..close]);
22 output.push_str("</i>");
23 index = close + 1;
24 continue;
25 }
26 output.push(character);
27 index += 1;
28 }
29 output
30 }
31
32 fn starts_with(characters: &[char], index: usize, text: &str) -> bool {
33 text.chars()
34 .enumerate()
35 .all(|(offset, expected)| characters.get(index + offset) == Some(&expected))
36 }
37
38 fn protected_end(characters: &[char], index: usize) -> Option<usize> {
39 if starts_with(characters, index, CODE_OPEN) {
40 let close =
41 (index..characters.len()).find(|&at| starts_with(characters, at, CODE_CLOSE))?;
42 return Some(close + CODE_CLOSE.chars().count());
43 }
44 if characters[index] == ']' && starts_with(characters, index, LINK_TARGET_OPEN) {
45 let close = (index..characters.len()).find(|&at| characters[at] == ')')?;
46 return Some(close + 1);
47 }
48 let boundary = index == 0 || !characters[index - 1].is_alphanumeric();
49 if boundary
50 && URL_SCHEMES
51 .iter()
52 .any(|scheme| starts_with(characters, index, scheme))
53 {
54 let end = (index..characters.len())
55 .find(|&at| characters[at].is_whitespace() || characters[at] == '<')
56 .unwrap_or(characters.len());
57 return Some(end);
58 }
59 None
60 }
61
62 fn italic_close(characters: &[char], open: usize) -> Option<usize> {
63 let marker = characters[open];
64 if !MARKERS.contains(&marker) {
65 return None;
66 }
67 if open > 0 && characters[open - 1].is_alphanumeric() {
68 return None;
69 }
70 let first = *characters.get(open + 1)?;
71 if first.is_whitespace() || MARKERS.contains(&first) {
72 return None;
73 }
74 for close in open + 2..characters.len() {
75 let character = characters[close];
76 if character == '\n' || starts_with(characters, close, LINE_BREAK) {
77 return None;
78 }
79 if character != marker || characters[close - 1].is_whitespace() {
80 continue;
81 }
82 let closes = characters
83 .get(close + 1)
84 .is_none_or(|next| !next.is_alphanumeric() && *next != marker);
85 if closes {
86 return Some(close);
87 }
88 }
89 None
90 }
91
92 #[cfg(test)]
93 mod tests {
94 use super::italicize;
95
96 #[test]
97 fn underscore_and_star_pairs_become_italic() {
98 assert_eq!(italicize("a _b_ c"), "a <i>b</i> c");
99 assert_eq!(italicize("a *b c* d"), "a <i>b c</i> d");
100 assert_eq!(italicize("_a_ _b_"), "<i>a</i> <i>b</i>");
101 }
102
103 #[test]
104 fn snake_case_and_inner_underscores_stay() {
105 assert_eq!(italicize("snake_case_word"), "snake_case_word");
106 assert_eq!(italicize("_x_y"), "_x_y");
107 assert_eq!(italicize("2*3*4"), "2*3*4");
108 }
109
110 #[test]
111 fn urls_code_and_link_targets_stay() {
112 assert_eq!(
113 italicize("see https://a.example/_x_/_y_ now"),
114 "see https://a.example/_x_/_y_ now"
115 );
116 assert_eq!(
117 italicize("<code>_x_</code> _y_"),
118 "<code>_x_</code> <i>y</i>"
119 );
120 assert_eq!(
121 italicize("<a>[t](https://a.example/_x_)</a>"),
122 "<a>[t](https://a.example/_x_)</a>"
123 );
124 }
125
126 #[test]
127 fn unpaired_and_spaced_markers_stay() {
128 assert_eq!(italicize("_a"), "_a");
129 assert_eq!(italicize("* item"), "* item");
130 assert_eq!(italicize("a _ b _"), "a _ b _");
131 assert_eq!(italicize("**"), "**");
132 assert_eq!(italicize("_a<br>b_"), "_a<br>b_");
133 }
134 }
@@ -0,0 +1,134 @@
1const MARKERS: [char; 2] = ['*', '_'];
2const CODE_OPEN: &str = "<code>";
3const CODE_CLOSE: &str = "</code>";
4const LINE_BREAK: &str = "<br>";
5const LINK_TARGET_OPEN: &str = "](";
6const URL_SCHEMES: [&str; 2] = ["https://", "http://"];
7
8pub(crate) fn italicize(escaped: &str) -> String {
9 let characters: Vec<char> = escaped.chars().collect();
10 let mut output = String::with_capacity(escaped.len());
11 let mut index = 0;
12 while index < characters.len() {
13 if let Some(end) = protected_end(&characters, index) {
14 output.extend(&characters[index..end]);
15 index = end;
16 continue;
17 }
18 let character = characters[index];
19 if let Some(close) = italic_close(&characters, index) {
20 output.push_str("<i>");
21 output.extend(&characters[index + 1..close]);
22 output.push_str("</i>");
23 index = close + 1;
24 continue;
25 }
26 output.push(character);
27 index += 1;
28 }
29 output
30}
31
32fn starts_with(characters: &[char], index: usize, text: &str) -> bool {
33 text.chars()
34 .enumerate()
35 .all(|(offset, expected)| characters.get(index + offset) == Some(&expected))
36}
37
38fn protected_end(characters: &[char], index: usize) -> Option<usize> {
39 if starts_with(characters, index, CODE_OPEN) {
40 let close =
41 (index..characters.len()).find(|&at| starts_with(characters, at, CODE_CLOSE))?;
42 return Some(close + CODE_CLOSE.chars().count());
43 }
44 if characters[index] == ']' && starts_with(characters, index, LINK_TARGET_OPEN) {
45 let close = (index..characters.len()).find(|&at| characters[at] == ')')?;
46 return Some(close + 1);
47 }
48 let boundary = index == 0 || !characters[index - 1].is_alphanumeric();
49 if boundary
50 && URL_SCHEMES
51 .iter()
52 .any(|scheme| starts_with(characters, index, scheme))
53 {
54 let end = (index..characters.len())
55 .find(|&at| characters[at].is_whitespace() || characters[at] == '<')
56 .unwrap_or(characters.len());
57 return Some(end);
58 }
59 None
60}
61
62fn italic_close(characters: &[char], open: usize) -> Option<usize> {
63 let marker = characters[open];
64 if !MARKERS.contains(&marker) {
65 return None;
66 }
67 if open > 0 && characters[open - 1].is_alphanumeric() {
68 return None;
69 }
70 let first = *characters.get(open + 1)?;
71 if first.is_whitespace() || MARKERS.contains(&first) {
72 return None;
73 }
74 for close in open + 2..characters.len() {
75 let character = characters[close];
76 if character == '\n' || starts_with(characters, close, LINE_BREAK) {
77 return None;
78 }
79 if character != marker || characters[close - 1].is_whitespace() {
80 continue;
81 }
82 let closes = characters
83 .get(close + 1)
84 .is_none_or(|next| !next.is_alphanumeric() && *next != marker);
85 if closes {
86 return Some(close);
87 }
88 }
89 None
90}
91
92#[cfg(test)]
93mod tests {
94 use super::italicize;
95
96 #[test]
97 fn underscore_and_star_pairs_become_italic() {
98 assert_eq!(italicize("a _b_ c"), "a <i>b</i> c");
99 assert_eq!(italicize("a *b c* d"), "a <i>b c</i> d");
100 assert_eq!(italicize("_a_ _b_"), "<i>a</i> <i>b</i>");
101 }
102
103 #[test]
104 fn snake_case_and_inner_underscores_stay() {
105 assert_eq!(italicize("snake_case_word"), "snake_case_word");
106 assert_eq!(italicize("_x_y"), "_x_y");
107 assert_eq!(italicize("2*3*4"), "2*3*4");
108 }
109
110 #[test]
111 fn urls_code_and_link_targets_stay() {
112 assert_eq!(
113 italicize("see https://a.example/_x_/_y_ now"),
114 "see https://a.example/_x_/_y_ now"
115 );
116 assert_eq!(
117 italicize("<code>_x_</code> _y_"),
118 "<code>_x_</code> <i>y</i>"
119 );
120 assert_eq!(
121 italicize("<a>[t](https://a.example/_x_)</a>"),
122 "<a>[t](https://a.example/_x_)</a>"
123 );
124 }
125
126 #[test]
127 fn unpaired_and_spaced_markers_stay() {
128 assert_eq!(italicize("_a"), "_a");
129 assert_eq!(italicize("* item"), "* item");
130 assert_eq!(italicize("a _ b _"), "a _ b _");
131 assert_eq!(italicize("**"), "**");
132 assert_eq!(italicize("_a<br>b_"), "_a<br>b_");
133 }
134}
crates/core/src/lib.rs +32 −8
@@ -2,7 +2,13 @@ mod actions;
2 2 mod adaptive_card;
3 3 mod avatars;
4 4 mod card_actions;
5 mod card_chart;
6 mod card_date;
5 7 mod card_inputs;
8 mod card_layout;
9 mod card_table;
10 mod card_widgets;
11 mod card_width;
6 12 mod channel_sync;
7 13 mod download;
8 14 mod draft;
@@ -17,6 +23,7 @@ mod images;
17 23 mod link_sync;
18 24 mod links;
19 25 mod mapping;
26 mod italic;
20 27 mod markdown;
21 28 mod mentions;
22 29 mod message_actions;
@@ -33,17 +40,34 @@ mod spans;
33 40 mod stored;
34 41
35 42 pub use adaptive_card::{
36 AdaptiveCard, CARD_THEME, CardAction, CardActionKind, CardColumn, CardElement, CardFact,
37 CardImage, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ExecuteAction,
38 ImageSize, InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
39 card_content_text, task_value,
43 ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn, CardElement,
44 CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing, CardText,
45 ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,
46 InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
47 card_content_text, split_overflow, task_value,
40 48 };
49 pub use card_date::{format_card_dates, format_card_dates_in};
50 pub use card_layout::{ContainerLayout, HorizontalAlignment};
51 pub use card_table::{CardTable, TableCell, TableColumn, TableRow};
52 pub use card_widgets::{
53 BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,
54 CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,
55 LabelPosition, RingSize,
56 };
57 pub use card_width::{TargetWidth, WidthClass};
41 58 pub use avatars::Avatar;
42 59 pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
60 pub use card_chart::{
61 AxisScale, BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint,
62 ChartSeries, GaugeSegment, GaugeValueFormat, format_chart_value, label_stride, nice_scale,
63 series_categories, series_maximum, series_value, slice_angles, unit_fraction,
64 };
43 65 pub use card_inputs::{
44 CardInput, CardInputKind, ChoiceInput, ChoiceStyle, DATE_PLACEHOLDER, InputChoice, InputError,
45 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
46 collect_input_values, merge_input_data,
66 CardInput, CardInputKind, ChoiceInput, ChoiceQuery, ChoiceStyle, DATE_PLACEHOLDER,
67 InlineAction, InputChoice, InputError, MomentInput, NumberInput, RatingColor, RatingDisplay,
68 RatingInput, RatingSize, RatingStyle, SEARCH_INVOKE_NAME, TIME_PLACEHOLDER, TextInput,
69 TextStyle, ToggleInput, collect_input_values, format_date, format_time, merge_input_data,
70 parse_search_results, search_request_value,
47 71 };
48 72 pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};
49 73 pub use draft::{
@@ -62,7 +86,7 @@ pub use graph::{
62 86 pub use images::StoredImage;
63 87 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
64 88 pub use mapping::{chat_record, message_record};
65 pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
89 pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
66 90 pub use mentions::MentionInput;
67 91 pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
68 92 pub use people::{MentionCandidate, PersonCandidate, PersonSource};
@@ -2,7 +2,13 @@ mod actions;
2mod adaptive_card;
2mod adaptive_card;
3mod avatars;
3mod avatars;
4mod card_actions;
4mod card_actions;
5mod card_chart;
6mod card_date;
5mod card_inputs;
7mod card_inputs;
8mod card_layout;
9mod card_table;
10mod card_widgets;
11mod card_width;
6mod channel_sync;
12mod channel_sync;
7mod download;
13mod download;
8mod draft;
14mod draft;
@@ -17,6 +23,7 @@ mod images;
17mod link_sync;
23mod link_sync;
18mod links;
24mod links;
19mod mapping;
25mod mapping;
26mod italic;
20mod markdown;
27mod markdown;
21mod mentions;
28mod mentions;
22mod message_actions;
29mod message_actions;
@@ -33,17 +40,34 @@ mod spans;
33mod stored;
40mod stored;
34
41
35pub use adaptive_card::{
42pub use adaptive_card::{
36 AdaptiveCard, CARD_THEME, CardAction, CardActionKind, CardColumn, CardElement, CardFact,
43 ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn, CardElement,
37 CardImage, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ExecuteAction,
44 CardFact, CardIcon, CardImage, CardItem, CardMedia, CardRefresh, CardSpacing, CardText,
38 ImageSize, InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
45 ColumnWidth, ContainerStyle, ExecuteAction, ExecuteTrigger, IconSize, ImageSize,
39 card_content_text, task_value,
46 InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
47 card_content_text, split_overflow, task_value,
40};
48};
49pub use card_date::{format_card_dates, format_card_dates_in};
50pub use card_layout::{ContainerLayout, HorizontalAlignment};
51pub use card_table::{CardTable, TableCell, TableColumn, TableRow};
52pub use card_widgets::{
53 BadgeAppearance, BadgeShape, BadgeSize, BadgeStyle, CardBadge, CardCarousel, CardCarouselPage,
54 CardCodeBlock, CardCompoundButton, CardProgressBar, CardProgressRing, IconPosition,
55 LabelPosition, RingSize,
56};
57pub use card_width::{TargetWidth, WidthClass};
41pub use avatars::Avatar;
58pub use avatars::Avatar;
42pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
59pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
60pub use card_chart::{
61 AxisScale, BarDisplayMode, CardChart, ChartColor, ChartGauge, ChartKind, ChartPoint,
62 ChartSeries, GaugeSegment, GaugeValueFormat, format_chart_value, label_stride, nice_scale,
63 series_categories, series_maximum, series_value, slice_angles, unit_fraction,
64};
43pub use card_inputs::{
65pub use card_inputs::{
44 CardInput, CardInputKind, ChoiceInput, ChoiceStyle, DATE_PLACEHOLDER, InputChoice, InputError,
66 CardInput, CardInputKind, ChoiceInput, ChoiceQuery, ChoiceStyle, DATE_PLACEHOLDER,
45 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
67 InlineAction, InputChoice, InputError, MomentInput, NumberInput, RatingColor, RatingDisplay,
46 collect_input_values, merge_input_data,
68 RatingInput, RatingSize, RatingStyle, SEARCH_INVOKE_NAME, TIME_PLACEHOLDER, TextInput,
69 TextStyle, ToggleInput, collect_input_values, format_date, format_time, merge_input_data,
70 parse_search_results, search_request_value,
47};
71};
48pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};
72pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};
49pub use draft::{
73pub use draft::{
@@ -62,7 +86,7 @@ pub use graph::{
62pub use images::StoredImage;
86pub use images::StoredImage;
63pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
87pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
64pub use mapping::{chat_record, message_record};
88pub use mapping::{chat_record, message_record};
65pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
89pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
66pub use mentions::MentionInput;
90pub use mentions::MentionInput;
67pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
91pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
68pub use people::{MentionCandidate, PersonCandidate, PersonSource};
92pub use people::{MentionCandidate, PersonCandidate, PersonSource};
crates/core/src/markdown.rs +77 −14
@@ -2,6 +2,9 @@ use std::sync::LazyLock;
2 2
3 3 use regex::Regex;
4 4
5 use crate::italic::italicize;
6 use crate::spans::Span;
7
5 8 static CODE_FENCE: LazyLock<Regex> =
6 9 LazyLock::new(|| Regex::new(r"(?s)```[^\n`]*\n(.*?)```").unwrap());
7 10 static INLINE_CODE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`([^`\n]+)`").unwrap());
@@ -9,6 +12,9 @@ static BOLD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*([^*\n]+)\*\*")
9 12 static LINK: LazyLock<Regex> =
10 13 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)").unwrap());
11 14
15 static MENTION: LazyLock<Regex> =
16 LazyLock::new(|| Regex::new(r"<at>([^<>\n]{1,100})</at>").unwrap());
17
12 18 const LIST_MARKER: &str = "- ";
13 19
14 20 pub fn escape_html(text: &str) -> String {
@@ -30,40 +36,55 @@ pub fn plain_text_to_html(text: &str) -> String {
30 36 escape_html(text).replace('\n', "<br>")
31 37 }
32 38
39 #[derive(Clone, Copy, PartialEq, Eq)]
40 enum Dialect {
41 Message,
42 Card,
43 }
44
33 45 /// Teams chat HTML for light markdown, plus `- ` list lines as `<ul><li>`.
34 46 pub fn markdown_to_html(text: &str) -> String {
47 render(text, Dialect::Message)
48 }
49
50 /// Like `markdown_to_html`, plus `_italic_`, `*italic*` and `<at>Name</at>` mentions.
51 pub fn card_markdown_to_html(text: &str) -> String {
52 render(text, Dialect::Card)
53 }
54
55 fn render(text: &str, dialect: Dialect) -> String {
35 56 let mut html = String::new();
36 57 let mut position = 0;
37 58 for fence in CODE_FENCE.captures_iter(text) {
38 59 let whole = fence.get(0).expect("group 0 always exists");
39 html.push_str(&block_html(&text[position..whole.start()]));
60 html.push_str(&block_html(&text[position..whole.start()], dialect));
40 61 html.push_str("<pre>");
41 62 html.push_str(&escape_html(fence[1].trim_end_matches('\n')));
42 63 html.push_str("</pre>");
43 64 position = whole.end();
44 65 }
45 html.push_str(&block_html(&text[position..]));
66 html.push_str(&block_html(&text[position..], dialect));
46 67 html
47 68 }
48 69
49 fn block_html(segment: &str) -> String {
70 fn block_html(segment: &str, dialect: Dialect) -> String {
50 71 if !segment.lines().any(is_list_line) {
51 return inline_html(segment);
72 return inline_html(segment, dialect);
52 73 }
53 74 let mut html = String::new();
54 75 let mut text_run: Vec<&str> = Vec::new();
55 76 let mut list_run: Vec<&str> = Vec::new();
56 77 for line in segment.split('\n') {
57 78 if is_list_line(line) {
58 flush_text(&mut html, &mut text_run);
79 flush_text(&mut html, &mut text_run, dialect);
59 80 list_run.push(&line[LIST_MARKER.len()..]);
60 81 } else {
61 flush_list(&mut html, &mut list_run);
82 flush_list(&mut html, &mut list_run, dialect);
62 83 text_run.push(line);
63 84 }
64 85 }
65 flush_list(&mut html, &mut list_run);
66 flush_text(&mut html, &mut text_run);
86 flush_list(&mut html, &mut list_run, dialect);
87 flush_text(&mut html, &mut text_run, dialect);
67 88 html
68 89 }
69 90
@@ -71,30 +92,72 @@ fn is_list_line(line: &str) -> bool {
71 92 line.starts_with(LIST_MARKER)
72 93 }
73 94
74 fn flush_text(html: &mut String, run: &mut Vec<&str>) {
95 fn flush_text(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
75 96 if !run.is_empty() {
76 html.push_str(&inline_html(&run.join("\n")));
97 html.push_str(&inline_html(&run.join("\n"), dialect));
77 98 run.clear();
78 99 }
79 100 }
80 101
81 fn flush_list(html: &mut String, run: &mut Vec<&str>) {
102 fn flush_list(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
82 103 if run.is_empty() {
83 104 return;
84 105 }
85 106 html.push_str("<ul>");
86 107 for item in run.drain(..) {
87 108 html.push_str("<li>");
88 html.push_str(&inline_html(item));
109 html.push_str(&inline_html(item, dialect));
89 110 html.push_str("</li>");
90 111 }
91 112 html.push_str("</ul>");
92 113 }
93 114
94 fn inline_html(text: &str) -> String {
115 pub(crate) fn split_mentions(text: &str) -> Vec<Span> {
116 let mut spans = Vec::new();
117 let mut position = 0;
118 for mention in MENTION.captures_iter(text) {
119 let whole = mention.get(0).expect("group 0 always exists");
120 if whole.start() > position {
121 spans.push(Span::Text(text[position..whole.start()].to_owned()));
122 }
123 spans.push(Span::Mention {
124 name: mention[1].trim().to_owned(),
125 id: None,
126 });
127 position = whole.end();
128 }
129 if position < text.len() {
130 spans.push(Span::Text(text[position..].to_owned()));
131 }
132 spans
133 }
134
135 fn inline_html(text: &str, dialect: Dialect) -> String {
136 if dialect == Dialect::Message {
137 return inline_markdown(text, dialect);
138 }
139 let mut html = String::new();
140 let mut position = 0;
141 for mention in MENTION.captures_iter(text) {
142 let whole = mention.get(0).expect("group 0 always exists");
143 html.push_str(&inline_markdown(&text[position..whole.start()], dialect));
144 html.push_str("<at>");
145 html.push_str(&escape_html(&mention[1]));
146 html.push_str("</at>");
147 position = whole.end();
148 }
149 html.push_str(&inline_markdown(&text[position..], dialect));
150 html
151 }
152
153 fn inline_markdown(text: &str, dialect: Dialect) -> String {
95 154 let escaped = plain_text_to_html(text);
96 155 let coded = INLINE_CODE.replace_all(&escaped, "<code>${1}</code>");
97 156 let bolded = BOLD.replace_all(&coded, "<b>${1}</b>");
98 LINK.replace_all(&bolded, r#"<a href="${2}">${1}</a>"#)
157 let styled = match dialect {
158 Dialect::Message => bolded.into_owned(),
159 Dialect::Card => italicize(&bolded),
160 };
161 LINK.replace_all(&styled, r#"<a href="${2}">${1}</a>"#)
99 162 .into_owned()
100 163 }
@@ -2,6 +2,9 @@ use std::sync::LazyLock;
2
2
3use regex::Regex;
3use regex::Regex;
4
4
5use crate::italic::italicize;
6use crate::spans::Span;
7
5static CODE_FENCE: LazyLock<Regex> =
8static CODE_FENCE: LazyLock<Regex> =
6 LazyLock::new(|| Regex::new(r"(?s)```[^\n`]*\n(.*?)```").unwrap());
9 LazyLock::new(|| Regex::new(r"(?s)```[^\n`]*\n(.*?)```").unwrap());
7static INLINE_CODE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`([^`\n]+)`").unwrap());
10static INLINE_CODE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`([^`\n]+)`").unwrap());
@@ -9,6 +12,9 @@ static BOLD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*([^*\n]+)\*\*")
9static LINK: LazyLock<Regex> =
12static LINK: LazyLock<Regex> =
10 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)").unwrap());
13 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)").unwrap());
11
14
15static MENTION: LazyLock<Regex> =
16 LazyLock::new(|| Regex::new(r"<at>([^<>\n]{1,100})</at>").unwrap());
17
12const LIST_MARKER: &str = "- ";
18const LIST_MARKER: &str = "- ";
13
19
14pub fn escape_html(text: &str) -> String {
20pub fn escape_html(text: &str) -> String {
@@ -30,40 +36,55 @@ pub fn plain_text_to_html(text: &str) -> String {
30 escape_html(text).replace('\n', "<br>")
36 escape_html(text).replace('\n', "<br>")
31}
37}
32
38
39#[derive(Clone, Copy, PartialEq, Eq)]
40enum Dialect {
41 Message,
42 Card,
43}
44
33/// Teams chat HTML for light markdown, plus `- ` list lines as `<ul><li>`.
45/// Teams chat HTML for light markdown, plus `- ` list lines as `<ul><li>`.
34pub fn markdown_to_html(text: &str) -> String {
46pub fn markdown_to_html(text: &str) -> String {
47 render(text, Dialect::Message)
48}
49
50/// Like `markdown_to_html`, plus `_italic_`, `*italic*` and `<at>Name</at>` mentions.
51pub fn card_markdown_to_html(text: &str) -> String {
52 render(text, Dialect::Card)
53}
54
55fn render(text: &str, dialect: Dialect) -> String {
35 let mut html = String::new();
56 let mut html = String::new();
36 let mut position = 0;
57 let mut position = 0;
37 for fence in CODE_FENCE.captures_iter(text) {
58 for fence in CODE_FENCE.captures_iter(text) {
38 let whole = fence.get(0).expect("group 0 always exists");
59 let whole = fence.get(0).expect("group 0 always exists");
39 html.push_str(&block_html(&text[position..whole.start()]));
60 html.push_str(&block_html(&text[position..whole.start()], dialect));
40 html.push_str("<pre>");
61 html.push_str("<pre>");
41 html.push_str(&escape_html(fence[1].trim_end_matches('\n')));
62 html.push_str(&escape_html(fence[1].trim_end_matches('\n')));
42 html.push_str("</pre>");
63 html.push_str("</pre>");
43 position = whole.end();
64 position = whole.end();
44 }
65 }
45 html.push_str(&block_html(&text[position..]));
66 html.push_str(&block_html(&text[position..], dialect));
46 html
67 html
47}
68}
48
69
49fn block_html(segment: &str) -> String {
70fn block_html(segment: &str, dialect: Dialect) -> String {
50 if !segment.lines().any(is_list_line) {
71 if !segment.lines().any(is_list_line) {
51 return inline_html(segment);
72 return inline_html(segment, dialect);
52 }
73 }
53 let mut html = String::new();
74 let mut html = String::new();
54 let mut text_run: Vec<&str> = Vec::new();
75 let mut text_run: Vec<&str> = Vec::new();
55 let mut list_run: Vec<&str> = Vec::new();
76 let mut list_run: Vec<&str> = Vec::new();
56 for line in segment.split('\n') {
77 for line in segment.split('\n') {
57 if is_list_line(line) {
78 if is_list_line(line) {
58 flush_text(&mut html, &mut text_run);
79 flush_text(&mut html, &mut text_run, dialect);
59 list_run.push(&line[LIST_MARKER.len()..]);
80 list_run.push(&line[LIST_MARKER.len()..]);
60 } else {
81 } else {
61 flush_list(&mut html, &mut list_run);
82 flush_list(&mut html, &mut list_run, dialect);
62 text_run.push(line);
83 text_run.push(line);
63 }
84 }
64 }
85 }
65 flush_list(&mut html, &mut list_run);
86 flush_list(&mut html, &mut list_run, dialect);
66 flush_text(&mut html, &mut text_run);
87 flush_text(&mut html, &mut text_run, dialect);
67 html
88 html
68}
89}
69
90
@@ -71,30 +92,72 @@ fn is_list_line(line: &str) -> bool {
71 line.starts_with(LIST_MARKER)
92 line.starts_with(LIST_MARKER)
72}
93}
73
94
74fn flush_text(html: &mut String, run: &mut Vec<&str>) {
95fn flush_text(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
75 if !run.is_empty() {
96 if !run.is_empty() {
76 html.push_str(&inline_html(&run.join("\n")));
97 html.push_str(&inline_html(&run.join("\n"), dialect));
77 run.clear();
98 run.clear();
78 }
99 }
79}
100}
80
101
81fn flush_list(html: &mut String, run: &mut Vec<&str>) {
102fn flush_list(html: &mut String, run: &mut Vec<&str>, dialect: Dialect) {
82 if run.is_empty() {
103 if run.is_empty() {
83 return;
104 return;
84 }
105 }
85 html.push_str("<ul>");
106 html.push_str("<ul>");
86 for item in run.drain(..) {
107 for item in run.drain(..) {
87 html.push_str("<li>");
108 html.push_str("<li>");
88 html.push_str(&inline_html(item));
109 html.push_str(&inline_html(item, dialect));
89 html.push_str("</li>");
110 html.push_str("</li>");
90 }
111 }
91 html.push_str("</ul>");
112 html.push_str("</ul>");
92}
113}
93
114
94fn inline_html(text: &str) -> String {
115pub(crate) fn split_mentions(text: &str) -> Vec<Span> {
116 let mut spans = Vec::new();
117 let mut position = 0;
118 for mention in MENTION.captures_iter(text) {
119 let whole = mention.get(0).expect("group 0 always exists");
120 if whole.start() > position {
121 spans.push(Span::Text(text[position..whole.start()].to_owned()));
122 }
123 spans.push(Span::Mention {
124 name: mention[1].trim().to_owned(),
125 id: None,
126 });
127 position = whole.end();
128 }
129 if position < text.len() {
130 spans.push(Span::Text(text[position..].to_owned()));
131 }
132 spans
133}
134
135fn inline_html(text: &str, dialect: Dialect) -> String {
136 if dialect == Dialect::Message {
137 return inline_markdown(text, dialect);
138 }
139 let mut html = String::new();
140 let mut position = 0;
141 for mention in MENTION.captures_iter(text) {
142 let whole = mention.get(0).expect("group 0 always exists");
143 html.push_str(&inline_markdown(&text[position..whole.start()], dialect));
144 html.push_str("<at>");
145 html.push_str(&escape_html(&mention[1]));
146 html.push_str("</at>");
147 position = whole.end();
148 }
149 html.push_str(&inline_markdown(&text[position..], dialect));
150 html
151}
152
153fn inline_markdown(text: &str, dialect: Dialect) -> String {
95 let escaped = plain_text_to_html(text);
154 let escaped = plain_text_to_html(text);
96 let coded = INLINE_CODE.replace_all(&escaped, "<code>${1}</code>");
155 let coded = INLINE_CODE.replace_all(&escaped, "<code>${1}</code>");
97 let bolded = BOLD.replace_all(&coded, "<b>${1}</b>");
156 let bolded = BOLD.replace_all(&coded, "<b>${1}</b>");
98 LINK.replace_all(&bolded, r#"<a href="${2}">${1}</a>"#)
157 let styled = match dialect {
158 Dialect::Message => bolded.into_owned(),
159 Dialect::Card => italicize(&bolded),
160 };
161 LINK.replace_all(&styled, r#"<a href="${2}">${1}</a>"#)
99 .into_owned()
162 .into_owned()
100}
163}
crates/core/tests/adaptive_card.rs +257 −6
@@ -1,7 +1,8 @@
1 1 use serde_json::json;
2 2 use teams_core::{
3 AdaptiveCard, CardAction, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor,
4 TextSize, ToggleTarget, VerticalAlignment, card_content_text,
3 AdaptiveCard, CardAction, CardActionIcon, CardActionKind, CardElement, ColumnWidth,
4 ExecuteTrigger, IconSize, ImageSize, Span, TextColor, TextSize, ToggleTarget,
5 VerticalAlignment, card_content_text,
5 6 };
6 7
7 8 fn digest_card() -> String {
@@ -43,11 +44,11 @@ fn digest_card_keeps_layout_text_and_actions() {
43 44 assert!(card.full_width);
44 45 assert_eq!(card.items.len(), 3);
45 46
46 let CardElement::Columns(columns) = &card.items[0].element else {
47 let CardElement::Columns { columns, .. } = &card.items[0].element else {
47 48 panic!("first item is a column set");
48 49 };
49 50 assert_eq!(columns[0].width, ColumnWidth::Auto);
50 assert_eq!(columns[0].vertical_alignment, VerticalAlignment::Center);
51 assert_eq!(columns[0].layout.vertical_alignment, VerticalAlignment::Center);
51 52 let CardElement::Image(image) = &columns[0].items[0].element else {
52 53 panic!("avatar column holds an image");
53 54 };
@@ -61,7 +62,7 @@ fn digest_card_keeps_layout_text_and_actions() {
61 62 assert_eq!(title.size, TextSize::Medium);
62 63
63 64 assert!(card.items[1].separator);
64 let CardElement::Columns(columns) = &card.items[1].element else {
65 let CardElement::Columns { columns, .. } = &card.items[1].element else {
65 66 panic!("second item is a column set");
66 67 };
67 68 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
@@ -134,7 +135,10 @@ fn message_back_and_im_back_send_the_teams_value() {
134 135 {"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}
135 136 ]));
136 137 let first = actions[0].invoke_payload().unwrap();
137 assert_eq!((first.name, first.value), ("messageback", json!({"k": 1})));
138 assert_eq!(
139 (first.name.as_str(), first.value),
140 ("messageback", json!({"k": 1}))
141 );
138 142 let second = actions[1].invoke_payload().unwrap();
139 143 assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));
140 144 }
@@ -293,3 +297,250 @@ fn element_visibility_covers_items_actions_and_nested_cards() {
293 297 assert!(!visibility["later"]);
294 298 assert!(!visibility["nested"]);
295 299 }
300
301 fn parse(card: serde_json::Value) -> AdaptiveCard {
302 AdaptiveCard::parse(&card.to_string()).unwrap()
303 }
304
305 fn refresh_card(user_ids: Option<serde_json::Value>) -> AdaptiveCard {
306 let mut refresh =
307 json!({"action": {"type": "Action.Execute", "verb": "refreshView", "data": {"k": 1}}});
308 if let Some(user_ids) = user_ids {
309 refresh["userIds"] = user_ids;
310 }
311 parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": refresh}))
312 }
313
314 #[test]
315 fn refresh_parses_the_execute_action_and_user_ids() {
316 let card = refresh_card(Some(json!(["8:orgid:ABC"])));
317 let refresh = card.refresh.unwrap();
318 assert_eq!(refresh.action.verb, "refreshView");
319 assert_eq!(refresh.user_ids, Some(vec!["8:orgid:ABC".to_owned()]));
320 assert!(parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": {"action": {"type": "Action.OpenUrl", "url": "https://a.example"}}})).refresh.is_none());
321 }
322
323 #[test]
324 fn refresh_runs_for_small_chats_without_user_ids() {
325 let refresh = refresh_card(None).refresh.unwrap();
326 assert!(refresh.runs_automatically(Some(2), None));
327 assert!(refresh.runs_automatically(Some(60), Some("8:orgid:me")));
328 assert!(!refresh.runs_automatically(Some(61), Some("8:orgid:me")));
329 assert!(!refresh.runs_automatically(None, Some("8:orgid:me")));
330 }
331
332 #[test]
333 fn refresh_with_user_ids_runs_only_for_listed_users() {
334 let refresh = refresh_card(Some(json!(["8:orgid:ABC-1", "8:orgid:other"])))
335 .refresh
336 .unwrap();
337 assert!(refresh.runs_automatically(Some(500), Some("abc-1")));
338 assert!(refresh.runs_automatically(Some(500), Some("8:orgid:abc-1")));
339 assert!(!refresh.runs_automatically(Some(2), Some("8:orgid:nobody")));
340 assert!(!refresh.runs_automatically(Some(2), None));
341 }
342
343 #[test]
344 fn execute_payload_carries_the_trigger() {
345 let refresh = refresh_card(None).refresh.unwrap();
346 assert_eq!(refresh.action.payload().value["trigger"], "manual");
347 let automatic = refresh.action.payload_for(ExecuteTrigger::Automatic);
348 assert_eq!(automatic.name, "adaptiveCard/action");
349 assert_eq!(automatic.value["trigger"], "automatic");
350 }
351
352 #[test]
353 fn tab_info_and_sign_in_submits_open_a_url() {
354 let actions = card_actions(json!([
355 {"type": "Action.Submit", "title": "Tab", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c", "websiteUrl": "https://site.example/w", "name": "n", "entityId": "e"}}}}},
356 {"type": "Action.Submit", "title": "Tab content", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c"}}}}},
357 {"type": "Action.Submit", "title": "Tab bad", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"websiteUrl": "javascript:x"}}}}},
358 {"type": "Action.Submit", "title": "Sign in", "data": {"msteams": {"type": "signin", "value": "https://login.example/start"}}}
359 ]));
360 assert_eq!(
361 actions[0].kind,
362 CardActionKind::OpenUrl("https://site.example/w".into())
363 );
364 assert_eq!(
365 actions[1].kind,
366 CardActionKind::OpenUrl("https://content.example/c".into())
367 );
368 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
369 assert_eq!(
370 actions[3].kind,
371 CardActionKind::OpenUrl("https://login.example/start".into())
372 );
373 }
374
375 #[test]
376 fn other_invoke_submits_send_the_value_named_by_its_type() {
377 let actions = card_actions(json!([
378 {"type": "Action.Submit", "title": "Go", "data": {"msteams": {"type": "invoke", "value": {"type": "custom/thing", "payload": 1}}}}
379 ]));
380 let payload = actions[0].invoke_payload().unwrap();
381 assert_eq!(payload.name, "custom/thing");
382 assert_eq!(payload.value, json!({"type": "custom/thing", "payload": 1}));
383 }
384
385 #[test]
386 fn add_app_submits_stay_as_unavailable_buttons() {
387 let actions = card_actions(json!([
388 {"type": "Action.Submit", "title": "Add", "data": {"msteams": {"type": "invoke", "value": {"type": "appInstallToConversation"}}}},
389 {"type": "Action.Submit", "title": "Add 2", "data": {"msteams": {"type": "addAppToConversation"}}}
390 ]));
391 for action in &actions {
392 assert_eq!(
393 action.kind,
394 CardActionKind::Unavailable("Adding apps is not supported")
395 );
396 assert!(!action.is_clickable());
397 }
398 }
399
400 #[test]
401 fn select_actions_are_parsed_on_card_image_container_and_column() {
402 let select = json!({"type": "Action.OpenUrl", "url": "https://a.example"});
403 let card = parse(json!({
404 "selectAction": select,
405 "body": [
406 {"type": "Image", "url": "https://img.example/a.png", "selectAction": {"type": "Action.Submit", "data": {"a": 1}}},
407 {"type": "Container", "selectAction": {"type": "Action.ToggleVisibility", "targetElements": ["x"]}, "items": [{"type": "TextBlock", "text": "t"}]},
408 {"type": "ColumnSet", "columns": [{"type": "Column", "selectAction": {"type": "Action.Execute", "verb": "v"}, "items": [{"type": "TextBlock", "text": "t"}]}]},
409 {"type": "Image", "url": "https://img.example/b.png", "selectAction": {"type": "Action.ShowCard", "card": {"body": [{"type": "TextBlock", "text": "t"}]}}}
410 ]
411 }));
412 assert!(matches!(
413 card.select_action.unwrap().kind,
414 CardActionKind::OpenUrl(_)
415 ));
416 let CardElement::Image(image) = &card.items[0].element else {
417 panic!("image")
418 };
419 assert!(matches!(
420 image.select_action.as_ref().unwrap().kind,
421 CardActionKind::Submit(_)
422 ));
423 let CardElement::Container { select_action, .. } = &card.items[1].element else {
424 panic!("container")
425 };
426 assert!(matches!(
427 select_action.as_ref().unwrap().kind,
428 CardActionKind::ToggleVisibility(_)
429 ));
430 let CardElement::Columns { columns, .. } = &card.items[2].element else {
431 panic!("columns")
432 };
433 assert!(matches!(
434 columns[0].select_action.as_ref().unwrap().kind,
435 CardActionKind::Execute(_)
436 ));
437 let CardElement::Image(image) = &card.items[3].element else {
438 panic!("image")
439 };
440 assert!(image.select_action.is_none());
441 }
442
443 #[test]
444 fn media_takes_the_first_web_source_and_poster() {
445 let card = parse(json!({"body": [
446 {"type": "Media", "poster": "https://img.example/p.png", "altText": "Intro", "sources": [
447 {"mimeType": "video/mp4", "url": "ftp://x"}, {"mimeType": "video/mp4", "url": "https://v.example/a.mp4"}, {"url": "https://v.example/b.mp4"}
448 ]},
449 {"type": "Media", "sources": []},
450 {"type": "TextBlock", "text": "after"}
451 ]}));
452 assert_eq!(card.items.len(), 2);
453 let CardElement::Media(media) = &card.items[0].element else {
454 panic!("media")
455 };
456 assert_eq!(media.source_url, "https://v.example/a.mp4");
457 assert_eq!(
458 media.poster_url.as_deref(),
459 Some("https://img.example/p.png")
460 );
461 assert_eq!(media.alt_text.as_deref(), Some("Intro"));
462 }
463
464 #[test]
465 fn icon_elements_and_action_icons_are_parsed() {
466 let card = parse(json!({
467 "body": [
468 {"type": "Icon", "name": "Calendar", "size": "xxLarge", "color": "accent", "style": "Filled", "selectAction": {"type": "Action.OpenUrl", "url": "https://a.example"}},
469 {"type": "Icon", "name": "Mail"}
470 ],
471 "actions": [
472 {"type": "Action.OpenUrl", "title": "A", "url": "https://a.example", "iconUrl": "icon:Send,Filled"},
473 {"type": "Action.OpenUrl", "title": "B", "url": "https://a.example", "iconUrl": "https://img.example/i.png"},
474 {"type": "Action.OpenUrl", "title": "C", "url": "https://a.example", "iconUrl": "data:image/png;base64,AA"}
475 ]
476 }));
477 let CardElement::Icon(icon) = &card.items[0].element else {
478 panic!("icon")
479 };
480 assert_eq!(
481 (icon.name.as_str(), icon.size, icon.color, icon.filled),
482 (
483 "Calendar",
484 IconSize::ExtraExtraLarge,
485 TextColor::Accent,
486 true
487 )
488 );
489 assert!(icon.select_action.is_some());
490 let CardElement::Icon(plain) = &card.items[1].element else {
491 panic!("icon")
492 };
493 assert_eq!((plain.size, plain.filled), (IconSize::Standard, false));
494 assert_eq!(
495 card.actions[0].icon,
496 Some(CardActionIcon::Named("Send".into()))
497 );
498 assert_eq!(
499 card.actions[1].icon,
500 Some(CardActionIcon::Url("https://img.example/i.png".into()))
501 );
502 assert_eq!(card.actions[2].icon, None);
503 }
504
505 #[test]
506 fn mentions_and_italic_survive_in_text_fact_and_rich_text() {
507 let card = parse(json!({"body": [
508 {"type": "TextBlock", "text": "Hi <at>Ada</at>, this is _soft_ and snake_case_x"},
509 {"type": "FactSet", "facts": [{"title": "Owner", "value": "<at>Bob</at>"}]},
510 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "cc <at>Cy</at>", "weight": "bolder"}]}
511 ]}));
512 let CardElement::Text(text) = &card.items[0].element else {
513 panic!("text")
514 };
515 assert!(text.spans.contains(&Span::Mention {
516 name: "Ada".into(),
517 id: None
518 }));
519 assert!(
520 text.spans
521 .contains(&Span::Italic(vec![Span::Text("soft".into())]))
522 );
523 let CardElement::Facts(facts) = &card.items[1].element else {
524 panic!("facts")
525 };
526 assert_eq!(
527 facts[0].value,
528 vec![Span::Mention {
529 name: "Bob".into(),
530 id: None
531 }]
532 );
533 let CardElement::Text(rich) = &card.items[2].element else {
534 panic!("rich")
535 };
536 assert_eq!(
537 rich.spans,
538 vec![Span::Bold(vec![
539 Span::Text("cc ".into()),
540 Span::Mention {
541 name: "Cy".into(),
542 id: None
543 }
544 ])]
545 );
546 }
@@ -1,7 +1,8 @@
1use serde_json::json;
1use serde_json::json;
2use teams_core::{
2use teams_core::{
3 AdaptiveCard, CardAction, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor,
3 AdaptiveCard, CardAction, CardActionIcon, CardActionKind, CardElement, ColumnWidth,
4 TextSize, ToggleTarget, VerticalAlignment, card_content_text,
4 ExecuteTrigger, IconSize, ImageSize, Span, TextColor, TextSize, ToggleTarget,
5 VerticalAlignment, card_content_text,
5};
6};
6
7
7fn digest_card() -> String {
8fn digest_card() -> String {
@@ -43,11 +44,11 @@ fn digest_card_keeps_layout_text_and_actions() {
43 assert!(card.full_width);
44 assert!(card.full_width);
44 assert_eq!(card.items.len(), 3);
45 assert_eq!(card.items.len(), 3);
45
46
46 let CardElement::Columns(columns) = &card.items[0].element else {
47 let CardElement::Columns { columns, .. } = &card.items[0].element else {
47 panic!("first item is a column set");
48 panic!("first item is a column set");
48 };
49 };
49 assert_eq!(columns[0].width, ColumnWidth::Auto);
50 assert_eq!(columns[0].width, ColumnWidth::Auto);
50 assert_eq!(columns[0].vertical_alignment, VerticalAlignment::Center);
51 assert_eq!(columns[0].layout.vertical_alignment, VerticalAlignment::Center);
51 let CardElement::Image(image) = &columns[0].items[0].element else {
52 let CardElement::Image(image) = &columns[0].items[0].element else {
52 panic!("avatar column holds an image");
53 panic!("avatar column holds an image");
53 };
54 };
@@ -61,7 +62,7 @@ fn digest_card_keeps_layout_text_and_actions() {
61 assert_eq!(title.size, TextSize::Medium);
62 assert_eq!(title.size, TextSize::Medium);
62
63
63 assert!(card.items[1].separator);
64 assert!(card.items[1].separator);
64 let CardElement::Columns(columns) = &card.items[1].element else {
65 let CardElement::Columns { columns, .. } = &card.items[1].element else {
65 panic!("second item is a column set");
66 panic!("second item is a column set");
66 };
67 };
67 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
68 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
@@ -134,7 +135,10 @@ fn message_back_and_im_back_send_the_teams_value() {
134 {"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}
135 {"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}
135 ]));
136 ]));
136 let first = actions[0].invoke_payload().unwrap();
137 let first = actions[0].invoke_payload().unwrap();
137 assert_eq!((first.name, first.value), ("messageback", json!({"k": 1})));
138 assert_eq!(
139 (first.name.as_str(), first.value),
140 ("messageback", json!({"k": 1}))
141 );
138 let second = actions[1].invoke_payload().unwrap();
142 let second = actions[1].invoke_payload().unwrap();
139 assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));
143 assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));
140}
144}
@@ -293,3 +297,250 @@ fn element_visibility_covers_items_actions_and_nested_cards() {
293 assert!(!visibility["later"]);
297 assert!(!visibility["later"]);
294 assert!(!visibility["nested"]);
298 assert!(!visibility["nested"]);
295}
299}
300
301fn parse(card: serde_json::Value) -> AdaptiveCard {
302 AdaptiveCard::parse(&card.to_string()).unwrap()
303}
304
305fn refresh_card(user_ids: Option<serde_json::Value>) -> AdaptiveCard {
306 let mut refresh =
307 json!({"action": {"type": "Action.Execute", "verb": "refreshView", "data": {"k": 1}}});
308 if let Some(user_ids) = user_ids {
309 refresh["userIds"] = user_ids;
310 }
311 parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": refresh}))
312}
313
314#[test]
315fn refresh_parses_the_execute_action_and_user_ids() {
316 let card = refresh_card(Some(json!(["8:orgid:ABC"])));
317 let refresh = card.refresh.unwrap();
318 assert_eq!(refresh.action.verb, "refreshView");
319 assert_eq!(refresh.user_ids, Some(vec!["8:orgid:ABC".to_owned()]));
320 assert!(parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "refresh": {"action": {"type": "Action.OpenUrl", "url": "https://a.example"}}})).refresh.is_none());
321}
322
323#[test]
324fn refresh_runs_for_small_chats_without_user_ids() {
325 let refresh = refresh_card(None).refresh.unwrap();
326 assert!(refresh.runs_automatically(Some(2), None));
327 assert!(refresh.runs_automatically(Some(60), Some("8:orgid:me")));
328 assert!(!refresh.runs_automatically(Some(61), Some("8:orgid:me")));
329 assert!(!refresh.runs_automatically(None, Some("8:orgid:me")));
330}
331
332#[test]
333fn refresh_with_user_ids_runs_only_for_listed_users() {
334 let refresh = refresh_card(Some(json!(["8:orgid:ABC-1", "8:orgid:other"])))
335 .refresh
336 .unwrap();
337 assert!(refresh.runs_automatically(Some(500), Some("abc-1")));
338 assert!(refresh.runs_automatically(Some(500), Some("8:orgid:abc-1")));
339 assert!(!refresh.runs_automatically(Some(2), Some("8:orgid:nobody")));
340 assert!(!refresh.runs_automatically(Some(2), None));
341}
342
343#[test]
344fn execute_payload_carries_the_trigger() {
345 let refresh = refresh_card(None).refresh.unwrap();
346 assert_eq!(refresh.action.payload().value["trigger"], "manual");
347 let automatic = refresh.action.payload_for(ExecuteTrigger::Automatic);
348 assert_eq!(automatic.name, "adaptiveCard/action");
349 assert_eq!(automatic.value["trigger"], "automatic");
350}
351
352#[test]
353fn tab_info_and_sign_in_submits_open_a_url() {
354 let actions = card_actions(json!([
355 {"type": "Action.Submit", "title": "Tab", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c", "websiteUrl": "https://site.example/w", "name": "n", "entityId": "e"}}}}},
356 {"type": "Action.Submit", "title": "Tab content", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"contentUrl": "https://content.example/c"}}}}},
357 {"type": "Action.Submit", "title": "Tab bad", "data": {"msteams": {"type": "invoke", "value": {"type": "tab/tabInfoAction", "tabInfo": {"websiteUrl": "javascript:x"}}}}},
358 {"type": "Action.Submit", "title": "Sign in", "data": {"msteams": {"type": "signin", "value": "https://login.example/start"}}}
359 ]));
360 assert_eq!(
361 actions[0].kind,
362 CardActionKind::OpenUrl("https://site.example/w".into())
363 );
364 assert_eq!(
365 actions[1].kind,
366 CardActionKind::OpenUrl("https://content.example/c".into())
367 );
368 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
369 assert_eq!(
370 actions[3].kind,
371 CardActionKind::OpenUrl("https://login.example/start".into())
372 );
373}
374
375#[test]
376fn other_invoke_submits_send_the_value_named_by_its_type() {
377 let actions = card_actions(json!([
378 {"type": "Action.Submit", "title": "Go", "data": {"msteams": {"type": "invoke", "value": {"type": "custom/thing", "payload": 1}}}}
379 ]));
380 let payload = actions[0].invoke_payload().unwrap();
381 assert_eq!(payload.name, "custom/thing");
382 assert_eq!(payload.value, json!({"type": "custom/thing", "payload": 1}));
383}
384
385#[test]
386fn add_app_submits_stay_as_unavailable_buttons() {
387 let actions = card_actions(json!([
388 {"type": "Action.Submit", "title": "Add", "data": {"msteams": {"type": "invoke", "value": {"type": "appInstallToConversation"}}}},
389 {"type": "Action.Submit", "title": "Add 2", "data": {"msteams": {"type": "addAppToConversation"}}}
390 ]));
391 for action in &actions {
392 assert_eq!(
393 action.kind,
394 CardActionKind::Unavailable("Adding apps is not supported")
395 );
396 assert!(!action.is_clickable());
397 }
398}
399
400#[test]
401fn select_actions_are_parsed_on_card_image_container_and_column() {
402 let select = json!({"type": "Action.OpenUrl", "url": "https://a.example"});
403 let card = parse(json!({
404 "selectAction": select,
405 "body": [
406 {"type": "Image", "url": "https://img.example/a.png", "selectAction": {"type": "Action.Submit", "data": {"a": 1}}},
407 {"type": "Container", "selectAction": {"type": "Action.ToggleVisibility", "targetElements": ["x"]}, "items": [{"type": "TextBlock", "text": "t"}]},
408 {"type": "ColumnSet", "columns": [{"type": "Column", "selectAction": {"type": "Action.Execute", "verb": "v"}, "items": [{"type": "TextBlock", "text": "t"}]}]},
409 {"type": "Image", "url": "https://img.example/b.png", "selectAction": {"type": "Action.ShowCard", "card": {"body": [{"type": "TextBlock", "text": "t"}]}}}
410 ]
411 }));
412 assert!(matches!(
413 card.select_action.unwrap().kind,
414 CardActionKind::OpenUrl(_)
415 ));
416 let CardElement::Image(image) = &card.items[0].element else {
417 panic!("image")
418 };
419 assert!(matches!(
420 image.select_action.as_ref().unwrap().kind,
421 CardActionKind::Submit(_)
422 ));
423 let CardElement::Container { select_action, .. } = &card.items[1].element else {
424 panic!("container")
425 };
426 assert!(matches!(
427 select_action.as_ref().unwrap().kind,
428 CardActionKind::ToggleVisibility(_)
429 ));
430 let CardElement::Columns { columns, .. } = &card.items[2].element else {
431 panic!("columns")
432 };
433 assert!(matches!(
434 columns[0].select_action.as_ref().unwrap().kind,
435 CardActionKind::Execute(_)
436 ));
437 let CardElement::Image(image) = &card.items[3].element else {
438 panic!("image")
439 };
440 assert!(image.select_action.is_none());
441}
442
443#[test]
444fn media_takes_the_first_web_source_and_poster() {
445 let card = parse(json!({"body": [
446 {"type": "Media", "poster": "https://img.example/p.png", "altText": "Intro", "sources": [
447 {"mimeType": "video/mp4", "url": "ftp://x"}, {"mimeType": "video/mp4", "url": "https://v.example/a.mp4"}, {"url": "https://v.example/b.mp4"}
448 ]},
449 {"type": "Media", "sources": []},
450 {"type": "TextBlock", "text": "after"}
451 ]}));
452 assert_eq!(card.items.len(), 2);
453 let CardElement::Media(media) = &card.items[0].element else {
454 panic!("media")
455 };
456 assert_eq!(media.source_url, "https://v.example/a.mp4");
457 assert_eq!(
458 media.poster_url.as_deref(),
459 Some("https://img.example/p.png")
460 );
461 assert_eq!(media.alt_text.as_deref(), Some("Intro"));
462}
463
464#[test]
465fn icon_elements_and_action_icons_are_parsed() {
466 let card = parse(json!({
467 "body": [
468 {"type": "Icon", "name": "Calendar", "size": "xxLarge", "color": "accent", "style": "Filled", "selectAction": {"type": "Action.OpenUrl", "url": "https://a.example"}},
469 {"type": "Icon", "name": "Mail"}
470 ],
471 "actions": [
472 {"type": "Action.OpenUrl", "title": "A", "url": "https://a.example", "iconUrl": "icon:Send,Filled"},
473 {"type": "Action.OpenUrl", "title": "B", "url": "https://a.example", "iconUrl": "https://img.example/i.png"},
474 {"type": "Action.OpenUrl", "title": "C", "url": "https://a.example", "iconUrl": "data:image/png;base64,AA"}
475 ]
476 }));
477 let CardElement::Icon(icon) = &card.items[0].element else {
478 panic!("icon")
479 };
480 assert_eq!(
481 (icon.name.as_str(), icon.size, icon.color, icon.filled),
482 (
483 "Calendar",
484 IconSize::ExtraExtraLarge,
485 TextColor::Accent,
486 true
487 )
488 );
489 assert!(icon.select_action.is_some());
490 let CardElement::Icon(plain) = &card.items[1].element else {
491 panic!("icon")
492 };
493 assert_eq!((plain.size, plain.filled), (IconSize::Standard, false));
494 assert_eq!(
495 card.actions[0].icon,
496 Some(CardActionIcon::Named("Send".into()))
497 );
498 assert_eq!(
499 card.actions[1].icon,
500 Some(CardActionIcon::Url("https://img.example/i.png".into()))
501 );
502 assert_eq!(card.actions[2].icon, None);
503}
504
505#[test]
506fn mentions_and_italic_survive_in_text_fact_and_rich_text() {
507 let card = parse(json!({"body": [
508 {"type": "TextBlock", "text": "Hi <at>Ada</at>, this is _soft_ and snake_case_x"},
509 {"type": "FactSet", "facts": [{"title": "Owner", "value": "<at>Bob</at>"}]},
510 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "cc <at>Cy</at>", "weight": "bolder"}]}
511 ]}));
512 let CardElement::Text(text) = &card.items[0].element else {
513 panic!("text")
514 };
515 assert!(text.spans.contains(&Span::Mention {
516 name: "Ada".into(),
517 id: None
518 }));
519 assert!(
520 text.spans
521 .contains(&Span::Italic(vec![Span::Text("soft".into())]))
522 );
523 let CardElement::Facts(facts) = &card.items[1].element else {
524 panic!("facts")
525 };
526 assert_eq!(
527 facts[0].value,
528 vec![Span::Mention {
529 name: "Bob".into(),
530 id: None
531 }]
532 );
533 let CardElement::Text(rich) = &card.items[2].element else {
534 panic!("rich")
535 };
536 assert_eq!(
537 rich.spans,
538 vec![Span::Bold(vec![
539 Span::Text("cc ".into()),
540 Span::Mention {
541 name: "Cy".into(),
542 id: None
543 }
544 ])]
545 );
546}
crates/core/tests/card_behaviour.rs added +532 −0
@@ -0,0 +1,532 @@
1 use chrono::FixedOffset;
2 use serde_json::json;
3 use teams_core::{
4 AdaptiveCard, BadgeAppearance, BadgeShape, BadgeStyle, CardElement, ColumnWidth,
5 ContainerStyle, FontSize, HorizontalAlignment, IconPosition, LabelPosition, Span, TargetWidth,
6 TextColor, TextSize, VerticalAlignment, WidthClass, format_card_dates_in, split_overflow,
7 };
8
9 fn parse(card: serde_json::Value) -> AdaptiveCard {
10 AdaptiveCard::parse(&card.to_string()).unwrap()
11 }
12
13 fn first_element(body: serde_json::Value) -> CardElement {
14 parse(json!({"body": [body]})).items.remove(0).element
15 }
16
17 #[test]
18 fn text_blocks_default_to_one_truncated_line() {
19 let CardElement::Text(text) =
20 first_element(json!({"type": "TextBlock", "text": "a long line"}))
21 else {
22 panic!("text")
23 };
24 assert!(!text.wrap);
25 assert_eq!(text.max_lines, None);
26 assert_eq!(text.alignment, None);
27 assert!(!text.monospace);
28 }
29
30 #[test]
31 fn text_block_layout_properties_are_parsed() {
32 let CardElement::Text(text) = first_element(json!({
33 "type": "TextBlock", "text": "x", "wrap": true, "maxLines": 2,
34 "horizontalAlignment": "Center", "fontType": "Monospace"
35 })) else {
36 panic!("text")
37 };
38 assert!(text.wrap && text.monospace);
39 assert_eq!(text.max_lines, Some(2));
40 assert_eq!(text.alignment, Some(HorizontalAlignment::Center));
41 }
42
43 #[test]
44 fn heading_style_is_bold_and_larger_unless_sized() {
45 let CardElement::Text(heading) =
46 first_element(json!({"type": "TextBlock", "text": "h", "style": "heading"}))
47 else {
48 panic!("text")
49 };
50 assert!(heading.bold);
51 assert_eq!(heading.size, TextSize::Large);
52 let CardElement::Text(sized) = first_element(
53 json!({"type": "TextBlock", "text": "h", "style": "heading", "size": "small"}),
54 ) else {
55 panic!("text")
56 };
57 assert_eq!(sized.size, TextSize::Small);
58 }
59
60 #[test]
61 fn text_runs_carry_highlight_color_size_and_monospace() {
62 let CardElement::Text(text) = first_element(json!({"type": "RichTextBlock", "inlines": [
63 {"type": "TextRun", "text": "mark", "highlight": true},
64 {"type": "TextRun", "text": "good", "color": "good", "size": "large", "fontType": "monospace"},
65 {"type": "TextRun", "text": "quiet", "isSubtle": true}
66 ]})) else {
67 panic!("text")
68 };
69 let Span::Colored {
70 color, background, ..
71 } = &text.spans[0]
72 else {
73 panic!("highlight is a colored span")
74 };
75 assert!(color.is_some() && background.is_some());
76 let Span::Colored {
77 color: Some(_),
78 background: None,
79 children,
80 } = &text.spans[1]
81 else {
82 panic!("colored run")
83 };
84 assert_eq!(
85 children[0],
86 Span::Sized(FontSize::Pixels(18), vec![Span::Code("good".to_owned())])
87 );
88 assert!(matches!(
89 &text.spans[2],
90 Span::Colored {
91 color: Some(_),
92 background: None,
93 ..
94 }
95 ));
96 }
97
98 #[test]
99 fn images_carry_alt_text_alignment_and_background() {
100 let CardElement::Image(image) = first_element(json!({
101 "type": "Image", "url": "http://img.example/a.png", "altText": "Logo",
102 "horizontalAlignment": "right", "backgroundColor": "#80102030"
103 })) else {
104 panic!("image")
105 };
106 assert_eq!(image.url, "http://img.example/a.png");
107 assert_eq!(image.alt_text.as_deref(), Some("Logo"));
108 assert_eq!(image.alignment, HorizontalAlignment::Right);
109 assert_eq!(image.background_color, Some(0x10203080));
110 let CardElement::Image(opaque) = first_element(
111 json!({"type": "Image", "url": "https://img.example/a.png", "backgroundColor": "#102030"}),
112 ) else {
113 panic!("image")
114 };
115 assert_eq!(opaque.background_color, Some(0x102030ff));
116 assert_eq!(opaque.alignment, HorizontalAlignment::Left);
117 }
118
119 #[test]
120 fn containers_columns_and_the_card_keep_layout_properties() {
121 let card = parse(json!({
122 "minHeight": "120px",
123 "verticalContentAlignment": "center",
124 "backgroundImage": {"url": "https://img.example/bg.png", "fillMode": "repeat"},
125 "body": [
126 {"type": "Container", "style": "good", "bleed": true, "rtl": true, "minHeight": "80px",
127 "verticalContentAlignment": "bottom", "backgroundImage": "https://img.example/c.png",
128 "height": "stretch",
129 "items": [{"type": "TextBlock", "text": "x"}]},
130 {"type": "ColumnSet", "style": "emphasis", "columns": [
131 {"type": "Column", "style": "accent", "minHeight": "40px", "items": [{"type": "TextBlock", "text": "y"}]}
132 ]}
133 ]
134 }));
135 assert_eq!(card.layout.min_height, Some(120.));
136 assert_eq!(card.layout.vertical_alignment, VerticalAlignment::Center);
137 assert_eq!(
138 card.layout.background_image.as_deref(),
139 Some("https://img.example/bg.png")
140 );
141 assert!(card.items[0].stretch);
142 let CardElement::Container { layout, .. } = &card.items[0].element else {
143 panic!("container")
144 };
145 assert_eq!(layout.style, ContainerStyle::Good);
146 assert!(layout.bleed && layout.rtl);
147 assert_eq!(layout.min_height, Some(80.));
148 assert_eq!(layout.vertical_alignment, VerticalAlignment::Bottom);
149 assert_eq!(
150 layout.background_image.as_deref(),
151 Some("https://img.example/c.png")
152 );
153 let CardElement::Columns { columns, layout } = &card.items[1].element else {
154 panic!("columns")
155 };
156 assert_eq!(layout.style, ContainerStyle::Emphasis);
157 assert_eq!(columns[0].layout.style, ContainerStyle::Accent);
158 assert_eq!(columns[0].layout.min_height, Some(40.));
159 }
160
161 #[test]
162 fn unknown_elements_without_fallback_are_dropped() {
163 let card = parse(json!({"body": [
164 {"type": "Hologram", "text": "x"},
165 {"type": "TextBlock", "text": "kept"}
166 ]}));
167 assert_eq!(card.items.len(), 1);
168 }
169
170 #[test]
171 fn fallback_elements_replace_unknown_or_unmet_elements() {
172 let card = parse(json!({"body": [
173 {"type": "Hologram", "fallback": {"type": "TextBlock", "text": "plain"}},
174 {"type": "Hologram", "fallback": "drop", "fallbackText": "never"},
175 {"type": "TextBlock", "text": "future", "requires": {"adaptiveCards": "1.9"},
176 "fallback": {"type": "TextBlock", "text": "older"}},
177 {"type": "TextBlock", "text": "custom", "requires": {"acTest": "1.0"}, "fallback": "drop"},
178 {"type": "Hologram", "fallback": {"type": "Hologram", "fallback": {"type": "TextBlock", "text": "deep"}}}
179 ]}));
180 let texts: Vec<String> = card
181 .items
182 .iter()
183 .map(|item| match &item.element {
184 CardElement::Text(text) => match &text.spans[0] {
185 Span::Text(text) => text.clone(),
186 other => panic!("unexpected span {other:?}"),
187 },
188 other => panic!("unexpected element {other:?}"),
189 })
190 .collect();
191 assert_eq!(texts, ["plain", "older", "deep"]);
192 }
193
194 #[test]
195 fn requirements_up_to_version_1_6_are_met() {
196 let card = parse(json!({"body": [
197 {"type": "TextBlock", "text": "a", "requires": {"adaptiveCards": "1.x"}},
198 {"type": "TextBlock", "text": "b", "requires": {"adaptiveCards": "1.6"}},
199 {"type": "TextBlock", "text": "c", "requires": {"adaptiveCards": "*"}},
200 {"type": "TextBlock", "text": "d", "requires": {"adaptiveCards": "1.7"}}
201 ]}));
202 assert_eq!(card.items.len(), 3);
203 }
204
205 #[test]
206 fn the_whole_card_keeps_its_fallback_text() {
207 let card = parse(json!({"body": [{"type": "Hologram", "fallbackText": "Open elsewhere"}]}));
208 let CardElement::Text(text) = &card.items[0].element else {
209 panic!("text")
210 };
211 assert_eq!(text.spans, vec![Span::Text("Open elsewhere".to_owned())]);
212 }
213
214 #[test]
215 fn width_classes_follow_the_breakpoints() {
216 assert_eq!(WidthClass::from_pixels(180.), WidthClass::VeryNarrow);
217 assert_eq!(WidthClass::from_pixels(300.), WidthClass::Narrow);
218 assert_eq!(WidthClass::from_pixels(480.), WidthClass::Standard);
219 assert_eq!(WidthClass::from_pixels(720.), WidthClass::Wide);
220 }
221
222 #[test]
223 fn target_width_matches_exact_and_ranged_classes() {
224 let exact = TargetWidth::parse("narrow").unwrap();
225 assert!(exact.matches(WidthClass::Narrow));
226 assert!(!exact.matches(WidthClass::Standard));
227 let at_least = TargetWidth::parse("atLeast:standard").unwrap();
228 assert!(!at_least.matches(WidthClass::Narrow));
229 assert!(at_least.matches(WidthClass::Standard) && at_least.matches(WidthClass::Wide));
230 let at_most = TargetWidth::parse("atMost:narrow").unwrap();
231 assert!(at_most.matches(WidthClass::VeryNarrow) && at_most.matches(WidthClass::Narrow));
232 assert!(!at_most.matches(WidthClass::Standard));
233 assert_eq!(TargetWidth::parse("gigantic"), None);
234 }
235
236 #[test]
237 fn target_width_is_kept_on_items_and_columns() {
238 let card = parse(json!({"body": [
239 {"type": "TextBlock", "text": "wide only", "targetWidth": "atLeast:wide"},
240 {"type": "ColumnSet", "columns": [
241 {"type": "Column", "targetWidth": "veryNarrow", "items": [{"type": "TextBlock", "text": "x"}]}
242 ]}
243 ]}));
244 assert!(
245 card.items[0]
246 .target_width
247 .unwrap()
248 .matches(WidthClass::Wide)
249 );
250 let CardElement::Columns { columns, .. } = &card.items[1].element else {
251 panic!("columns")
252 };
253 assert!(
254 columns[0]
255 .target_width
256 .unwrap()
257 .matches(WidthClass::VeryNarrow)
258 );
259 }
260
261 #[test]
262 fn tables_resolve_widths_header_and_alignment() {
263 let CardElement::Table(table) = first_element(json!({
264 "type": "Table",
265 "columns": [{"width": 2}, {"width": "80px", "horizontalCellContentAlignment": "right"}],
266 "firstRowAsHeader": false, "showGridLines": false, "gridStyle": "accent",
267 "horizontalCellContentAlignment": "center", "verticalCellContentAlignment": "bottom",
268 "rows": [
269 {"type": "TableRow", "style": "emphasis", "cells": [
270 {"type": "TableCell", "items": [{"type": "TextBlock", "text": "a"}]},
271 {"type": "TableCell", "verticalContentAlignment": "top", "items": [{"type": "TextBlock", "text": "b"}]}
272 ]},
273 {"type": "TableRow", "cells": [{"type": "TableCell", "items": [{"type": "TextBlock", "text": "c"}]}]}
274 ]
275 })) else {
276 panic!("table")
277 };
278 assert_eq!(table.columns[0].width, ColumnWidth::Weighted(2.));
279 assert_eq!(table.columns[1].width, ColumnWidth::Pixels(80.));
280 assert!(!table.first_row_as_header && !table.show_grid_lines);
281 assert_eq!(table.grid_style, ContainerStyle::Accent);
282 assert_eq!(table.rows[0].style, ContainerStyle::Emphasis);
283 let row = &table.rows[0];
284 assert_eq!(
285 table.cell_horizontal_alignment(row, 0),
286 HorizontalAlignment::Center
287 );
288 assert_eq!(
289 table.cell_horizontal_alignment(row, 1),
290 HorizontalAlignment::Right
291 );
292 assert_eq!(
293 table.cell_vertical_alignment(row, &row.cells[0], 0),
294 VerticalAlignment::Bottom
295 );
296 assert_eq!(
297 table.cell_vertical_alignment(row, &row.cells[1], 1),
298 VerticalAlignment::Top
299 );
300 }
301
302 #[test]
303 fn tables_pad_missing_columns_and_expose_cell_text() {
304 let card = parse(json!({"body": [{
305 "type": "Table",
306 "rows": [
307 {"cells": [{"items": [{"type": "TextBlock", "text": "a"}]}, {"items": [{"type": "TextBlock", "text": "b"}]}]},
308 {"cells": [{"items": [{"type": "TextBlock", "text": "c"}]}]}
309 ]
310 }]}));
311 let CardElement::Table(table) = &card.items[0].element else {
312 panic!("table")
313 };
314 assert_eq!(table.columns.len(), 2);
315 assert!(table.first_row_as_header && table.show_grid_lines);
316 assert_eq!(card.plain_text().unwrap(), "a\nb\nc");
317 }
318
319 #[test]
320 fn code_blocks_keep_snippet_language_and_start_line() {
321 let CardElement::CodeBlock(block) = first_element(json!({
322 "type": "CodeBlock", "codeSnippet": "let a = 1;\nlet b = 2;\n", "language": "Rust", "startLineNumber": 7
323 })) else {
324 panic!("code block")
325 };
326 assert_eq!(block.code, "let a = 1;\nlet b = 2;");
327 assert_eq!(block.language.as_deref(), Some("Rust"));
328 assert_eq!(block.start_line, 7);
329 let CardElement::CodeBlock(plain) =
330 first_element(json!({"type": "CodeBlock", "codeSnippet": "x"}))
331 else {
332 panic!("code block")
333 };
334 assert_eq!(plain.start_line, 1);
335 }
336
337 #[test]
338 fn badges_parse_style_shape_and_icon() {
339 let CardElement::Badge(badge) = first_element(json!({
340 "type": "Badge", "text": "Done", "icon": "CheckmarkCircle,Filled", "style": "Good",
341 "appearance": "tint", "shape": "rounded", "size": "large", "iconPosition": "After",
342 "tooltip": "All good"
343 })) else {
344 panic!("badge")
345 };
346 assert_eq!(badge.style, BadgeStyle::Good);
347 assert_eq!(badge.appearance, BadgeAppearance::Tint);
348 assert_eq!(badge.shape, BadgeShape::Rounded);
349 assert_eq!(badge.icon.as_deref(), Some("CheckmarkCircle"));
350 assert_eq!(badge.icon_position, IconPosition::After);
351 assert_eq!(badge.tooltip.as_deref(), Some("All good"));
352 let CardElement::Badge(plain) = first_element(json!({"type": "Badge", "text": "New"})) else {
353 panic!("badge")
354 };
355 assert_eq!(plain.appearance, BadgeAppearance::Filled);
356 assert_eq!(plain.shape, BadgeShape::Circular);
357 assert!(AdaptiveCard::parse(&json!({"body": [{"type": "Badge"}]}).to_string()).is_none());
358 }
359
360 #[test]
361 fn progress_elements_parse_value_color_and_label() {
362 let CardElement::ProgressBar(bar) =
363 first_element(json!({"type": "ProgressBar", "value": 140, "color": "good"}))
364 else {
365 panic!("bar")
366 };
367 assert_eq!(bar.value, Some(100.));
368 assert_eq!(bar.color, TextColor::Good);
369 let CardElement::ProgressBar(indeterminate) = first_element(json!({"type": "ProgressBar"}))
370 else {
371 panic!("bar")
372 };
373 assert_eq!(indeterminate.value, None);
374 let CardElement::ProgressRing(ring) = first_element(
375 json!({"type": "ProgressRing", "label": "Loading", "labelPosition": "Below", "size": "large"}),
376 ) else {
377 panic!("ring")
378 };
379 assert_eq!(ring.label.as_deref(), Some("Loading"));
380 assert_eq!(ring.label_position, LabelPosition::Below);
381 }
382
383 #[test]
384 fn compound_buttons_need_a_title() {
385 let CardElement::CompoundButton(button) = first_element(json!({
386 "type": "CompoundButton", "title": "Open", "description": "Opens the page", "icon": "Open",
387 "badge": "New", "selectAction": {"type": "Action.OpenUrl", "url": "https://a.example"}
388 })) else {
389 panic!("button")
390 };
391 assert_eq!(button.title, "Open");
392 assert_eq!(button.badge.as_deref(), Some("New"));
393 assert!(button.select_action.is_some());
394 assert!(
395 AdaptiveCard::parse(
396 &json!({"body": [{"type": "CompoundButton", "description": "x"}]}).to_string()
397 )
398 .is_none()
399 );
400 }
401
402 #[test]
403 fn carousels_hold_pages_and_ignore_the_timer() {
404 let card = parse(json!({"body": [{
405 "type": "Carousel", "timer": 5000, "initialPageIndex": 1,
406 "pages": [
407 {"type": "CarouselPage", "items": [{"type": "TextBlock", "text": "one"}]},
408 {"type": "CarouselPage", "items": [{"type": "TextBlock", "text": "two"}]},
409 {"type": "CarouselPage", "items": []}
410 ]
411 }]}));
412 let CardElement::Carousel(carousel) = &card.items[0].element else {
413 panic!("carousel")
414 };
415 assert_eq!(carousel.pages.len(), 2);
416 assert_eq!(carousel.initial_page, 1);
417 assert_eq!(card.plain_text().unwrap(), "one\ntwo");
418 }
419
420 #[test]
421 fn action_mode_tooltip_and_style_are_parsed() {
422 let card = parse(
423 json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [
424 {"type": "Action.OpenUrl", "title": "A", "url": "https://a.example", "style": "destructive", "tooltip": "Open A"},
425 {"type": "Action.OpenUrl", "title": "B", "url": "https://b.example", "mode": "secondary"}
426 ]}),
427 );
428 assert!(!card.actions[0].secondary);
429 assert_eq!(card.actions[0].tooltip.as_deref(), Some("Open A"));
430 assert!(card.actions[1].secondary);
431 assert!(card.actions[1].is_clickable());
432 }
433
434 fn numbered_actions(count: usize, secondary: &[usize]) -> Vec<teams_core::CardAction> {
435 let actions: Vec<_> = (0..count)
436 .map(|index| {
437 let mut action = json!({"type": "Action.OpenUrl", "title": format!("A{index}"), "url": "https://a.example"});
438 if secondary.contains(&index) {
439 action["mode"] = json!("secondary");
440 }
441 action
442 })
443 .collect();
444 parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": actions})).actions
445 }
446
447 #[test]
448 fn secondary_actions_go_to_the_overflow() {
449 let actions = numbered_actions(4, &[1]);
450 let split = split_overflow(&actions, |_| true);
451 assert_eq!(split.primary, [0, 2, 3]);
452 assert_eq!(split.overflow, [1]);
453 }
454
455 #[test]
456 fn primary_actions_beyond_six_go_to_the_overflow_in_order() {
457 let actions = numbered_actions(8, &[3]);
458 let split = split_overflow(&actions, |_| true);
459 assert_eq!(split.primary, [0, 1, 2, 4, 5, 6]);
460 assert_eq!(split.overflow, [3, 7]);
461 }
462
463 #[test]
464 fn hidden_actions_are_left_out_of_the_split() {
465 let actions = numbered_actions(3, &[]);
466 let split = split_overflow(&actions, |action| action.title != "A1");
467 assert_eq!(split.primary, [0, 2]);
468 assert!(split.overflow.is_empty());
469 }
470
471 fn local(text: &str) -> String {
472 format_card_dates_in(text, &FixedOffset::east_opt(2 * 3600).unwrap())
473 }
474
475 #[test]
476 fn dates_format_in_the_given_zone() {
477 let iso = "2026-10-09T12:05:00Z";
478 assert_eq!(
479 local(&format!("{{{{DATE({iso}, SHORT)}}}}")),
480 "Fri, Oct 9, 2026"
481 );
482 assert_eq!(
483 local(&format!("{{{{DATE({iso},LONG)}}}}")),
484 "Friday, October 9, 2026"
485 );
486 assert_eq!(
487 local(&format!("{{{{DATE({iso}, COMPACT)}}}}")),
488 "2026-10-09"
489 );
490 assert_eq!(local(&format!("{{{{DATE({iso})}}}}")), "2026-10-09");
491 assert_eq!(local(&format!("{{{{TIME({iso})}}}}")), "14:05");
492 }
493
494 #[test]
495 fn the_zone_can_move_the_date() {
496 assert_eq!(
497 local("{{DATE(2026-10-09T23:30:00Z, SHORT)}}"),
498 "Sat, Oct 10, 2026"
499 );
500 }
501
502 #[test]
503 fn dates_work_without_braces_inside_longer_text() {
504 assert_eq!(
505 local("Due DATE(2026-10-09T12:05:00Z, SHORT) at TIME(2026-10-09T12:05:00Z)."),
506 "Due Fri, Oct 9, 2026 at 14:05."
507 );
508 }
509
510 #[test]
511 fn malformed_dates_stay_literal() {
512 for text in [
513 "{{DATE(yesterday, SHORT)}}",
514 "{{DATE(2026-10-09, SHORT)}}",
515 "{{TIME()}}",
516 "{{DATE(2026-10-09T12:05:00Z, WEEKLY)}}",
517 ] {
518 assert_eq!(local(text), text);
519 }
520 }
521
522 #[test]
523 fn text_blocks_and_facts_format_dates() {
524 let card = parse(json!({"body": [
525 {"type": "TextBlock", "text": "On {{DATE(2026-10-09T12:05:00Z, LONG)}}"},
526 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "{{TIME(2026-10-09T12:05:00Z)}}"}]},
527 {"type": "FactSet", "facts": [{"title": "Due", "value": "{{DATE(2026-10-09T12:05:00Z, COMPACT)}}"}]}
528 ]}));
529 let text = card.plain_text().unwrap();
530 assert!(!text.contains("{{"), "{text}");
531 assert!(text.contains("2026"));
532 }
@@ -0,0 +1,532 @@
1use chrono::FixedOffset;
2use serde_json::json;
3use teams_core::{
4 AdaptiveCard, BadgeAppearance, BadgeShape, BadgeStyle, CardElement, ColumnWidth,
5 ContainerStyle, FontSize, HorizontalAlignment, IconPosition, LabelPosition, Span, TargetWidth,
6 TextColor, TextSize, VerticalAlignment, WidthClass, format_card_dates_in, split_overflow,
7};
8
9fn parse(card: serde_json::Value) -> AdaptiveCard {
10 AdaptiveCard::parse(&card.to_string()).unwrap()
11}
12
13fn first_element(body: serde_json::Value) -> CardElement {
14 parse(json!({"body": [body]})).items.remove(0).element
15}
16
17#[test]
18fn text_blocks_default_to_one_truncated_line() {
19 let CardElement::Text(text) =
20 first_element(json!({"type": "TextBlock", "text": "a long line"}))
21 else {
22 panic!("text")
23 };
24 assert!(!text.wrap);
25 assert_eq!(text.max_lines, None);
26 assert_eq!(text.alignment, None);
27 assert!(!text.monospace);
28}
29
30#[test]
31fn text_block_layout_properties_are_parsed() {
32 let CardElement::Text(text) = first_element(json!({
33 "type": "TextBlock", "text": "x", "wrap": true, "maxLines": 2,
34 "horizontalAlignment": "Center", "fontType": "Monospace"
35 })) else {
36 panic!("text")
37 };
38 assert!(text.wrap && text.monospace);
39 assert_eq!(text.max_lines, Some(2));
40 assert_eq!(text.alignment, Some(HorizontalAlignment::Center));
41}
42
43#[test]
44fn heading_style_is_bold_and_larger_unless_sized() {
45 let CardElement::Text(heading) =
46 first_element(json!({"type": "TextBlock", "text": "h", "style": "heading"}))
47 else {
48 panic!("text")
49 };
50 assert!(heading.bold);
51 assert_eq!(heading.size, TextSize::Large);
52 let CardElement::Text(sized) = first_element(
53 json!({"type": "TextBlock", "text": "h", "style": "heading", "size": "small"}),
54 ) else {
55 panic!("text")
56 };
57 assert_eq!(sized.size, TextSize::Small);
58}
59
60#[test]
61fn text_runs_carry_highlight_color_size_and_monospace() {
62 let CardElement::Text(text) = first_element(json!({"type": "RichTextBlock", "inlines": [
63 {"type": "TextRun", "text": "mark", "highlight": true},
64 {"type": "TextRun", "text": "good", "color": "good", "size": "large", "fontType": "monospace"},
65 {"type": "TextRun", "text": "quiet", "isSubtle": true}
66 ]})) else {
67 panic!("text")
68 };
69 let Span::Colored {
70 color, background, ..
71 } = &text.spans[0]
72 else {
73 panic!("highlight is a colored span")
74 };
75 assert!(color.is_some() && background.is_some());
76 let Span::Colored {
77 color: Some(_),
78 background: None,
79 children,
80 } = &text.spans[1]
81 else {
82 panic!("colored run")
83 };
84 assert_eq!(
85 children[0],
86 Span::Sized(FontSize::Pixels(18), vec![Span::Code("good".to_owned())])
87 );
88 assert!(matches!(
89 &text.spans[2],
90 Span::Colored {
91 color: Some(_),
92 background: None,
93 ..
94 }
95 ));
96}
97
98#[test]
99fn images_carry_alt_text_alignment_and_background() {
100 let CardElement::Image(image) = first_element(json!({
101 "type": "Image", "url": "http://img.example/a.png", "altText": "Logo",
102 "horizontalAlignment": "right", "backgroundColor": "#80102030"
103 })) else {
104 panic!("image")
105 };
106 assert_eq!(image.url, "http://img.example/a.png");
107 assert_eq!(image.alt_text.as_deref(), Some("Logo"));
108 assert_eq!(image.alignment, HorizontalAlignment::Right);
109 assert_eq!(image.background_color, Some(0x10203080));
110 let CardElement::Image(opaque) = first_element(
111 json!({"type": "Image", "url": "https://img.example/a.png", "backgroundColor": "#102030"}),
112 ) else {
113 panic!("image")
114 };
115 assert_eq!(opaque.background_color, Some(0x102030ff));
116 assert_eq!(opaque.alignment, HorizontalAlignment::Left);
117}
118
119#[test]
120fn containers_columns_and_the_card_keep_layout_properties() {
121 let card = parse(json!({
122 "minHeight": "120px",
123 "verticalContentAlignment": "center",
124 "backgroundImage": {"url": "https://img.example/bg.png", "fillMode": "repeat"},
125 "body": [
126 {"type": "Container", "style": "good", "bleed": true, "rtl": true, "minHeight": "80px",
127 "verticalContentAlignment": "bottom", "backgroundImage": "https://img.example/c.png",
128 "height": "stretch",
129 "items": [{"type": "TextBlock", "text": "x"}]},
130 {"type": "ColumnSet", "style": "emphasis", "columns": [
131 {"type": "Column", "style": "accent", "minHeight": "40px", "items": [{"type": "TextBlock", "text": "y"}]}
132 ]}
133 ]
134 }));
135 assert_eq!(card.layout.min_height, Some(120.));
136 assert_eq!(card.layout.vertical_alignment, VerticalAlignment::Center);
137 assert_eq!(
138 card.layout.background_image.as_deref(),
139 Some("https://img.example/bg.png")
140 );
141 assert!(card.items[0].stretch);
142 let CardElement::Container { layout, .. } = &card.items[0].element else {
143 panic!("container")
144 };
145 assert_eq!(layout.style, ContainerStyle::Good);
146 assert!(layout.bleed && layout.rtl);
147 assert_eq!(layout.min_height, Some(80.));
148 assert_eq!(layout.vertical_alignment, VerticalAlignment::Bottom);
149 assert_eq!(
150 layout.background_image.as_deref(),
151 Some("https://img.example/c.png")
152 );
153 let CardElement::Columns { columns, layout } = &card.items[1].element else {
154 panic!("columns")
155 };
156 assert_eq!(layout.style, ContainerStyle::Emphasis);
157 assert_eq!(columns[0].layout.style, ContainerStyle::Accent);
158 assert_eq!(columns[0].layout.min_height, Some(40.));
159}
160
161#[test]
162fn unknown_elements_without_fallback_are_dropped() {
163 let card = parse(json!({"body": [
164 {"type": "Hologram", "text": "x"},
165 {"type": "TextBlock", "text": "kept"}
166 ]}));
167 assert_eq!(card.items.len(), 1);
168}
169
170#[test]
171fn fallback_elements_replace_unknown_or_unmet_elements() {
172 let card = parse(json!({"body": [
173 {"type": "Hologram", "fallback": {"type": "TextBlock", "text": "plain"}},
174 {"type": "Hologram", "fallback": "drop", "fallbackText": "never"},
175 {"type": "TextBlock", "text": "future", "requires": {"adaptiveCards": "1.9"},
176 "fallback": {"type": "TextBlock", "text": "older"}},
177 {"type": "TextBlock", "text": "custom", "requires": {"acTest": "1.0"}, "fallback": "drop"},
178 {"type": "Hologram", "fallback": {"type": "Hologram", "fallback": {"type": "TextBlock", "text": "deep"}}}
179 ]}));
180 let texts: Vec<String> = card
181 .items
182 .iter()
183 .map(|item| match &item.element {
184 CardElement::Text(text) => match &text.spans[0] {
185 Span::Text(text) => text.clone(),
186 other => panic!("unexpected span {other:?}"),
187 },
188 other => panic!("unexpected element {other:?}"),
189 })
190 .collect();
191 assert_eq!(texts, ["plain", "older", "deep"]);
192}
193
194#[test]
195fn requirements_up_to_version_1_6_are_met() {
196 let card = parse(json!({"body": [
197 {"type": "TextBlock", "text": "a", "requires": {"adaptiveCards": "1.x"}},
198 {"type": "TextBlock", "text": "b", "requires": {"adaptiveCards": "1.6"}},
199 {"type": "TextBlock", "text": "c", "requires": {"adaptiveCards": "*"}},
200 {"type": "TextBlock", "text": "d", "requires": {"adaptiveCards": "1.7"}}
201 ]}));
202 assert_eq!(card.items.len(), 3);
203}
204
205#[test]
206fn the_whole_card_keeps_its_fallback_text() {
207 let card = parse(json!({"body": [{"type": "Hologram", "fallbackText": "Open elsewhere"}]}));
208 let CardElement::Text(text) = &card.items[0].element else {
209 panic!("text")
210 };
211 assert_eq!(text.spans, vec![Span::Text("Open elsewhere".to_owned())]);
212}
213
214#[test]
215fn width_classes_follow_the_breakpoints() {
216 assert_eq!(WidthClass::from_pixels(180.), WidthClass::VeryNarrow);
217 assert_eq!(WidthClass::from_pixels(300.), WidthClass::Narrow);
218 assert_eq!(WidthClass::from_pixels(480.), WidthClass::Standard);
219 assert_eq!(WidthClass::from_pixels(720.), WidthClass::Wide);
220}
221
222#[test]
223fn target_width_matches_exact_and_ranged_classes() {
224 let exact = TargetWidth::parse("narrow").unwrap();
225 assert!(exact.matches(WidthClass::Narrow));
226 assert!(!exact.matches(WidthClass::Standard));
227 let at_least = TargetWidth::parse("atLeast:standard").unwrap();
228 assert!(!at_least.matches(WidthClass::Narrow));
229 assert!(at_least.matches(WidthClass::Standard) && at_least.matches(WidthClass::Wide));
230 let at_most = TargetWidth::parse("atMost:narrow").unwrap();
231 assert!(at_most.matches(WidthClass::VeryNarrow) && at_most.matches(WidthClass::Narrow));
232 assert!(!at_most.matches(WidthClass::Standard));
233 assert_eq!(TargetWidth::parse("gigantic"), None);
234}
235
236#[test]
237fn target_width_is_kept_on_items_and_columns() {
238 let card = parse(json!({"body": [
239 {"type": "TextBlock", "text": "wide only", "targetWidth": "atLeast:wide"},
240 {"type": "ColumnSet", "columns": [
241 {"type": "Column", "targetWidth": "veryNarrow", "items": [{"type": "TextBlock", "text": "x"}]}
242 ]}
243 ]}));
244 assert!(
245 card.items[0]
246 .target_width
247 .unwrap()
248 .matches(WidthClass::Wide)
249 );
250 let CardElement::Columns { columns, .. } = &card.items[1].element else {
251 panic!("columns")
252 };
253 assert!(
254 columns[0]
255 .target_width
256 .unwrap()
257 .matches(WidthClass::VeryNarrow)
258 );
259}
260
261#[test]
262fn tables_resolve_widths_header_and_alignment() {
263 let CardElement::Table(table) = first_element(json!({
264 "type": "Table",
265 "columns": [{"width": 2}, {"width": "80px", "horizontalCellContentAlignment": "right"}],
266 "firstRowAsHeader": false, "showGridLines": false, "gridStyle": "accent",
267 "horizontalCellContentAlignment": "center", "verticalCellContentAlignment": "bottom",
268 "rows": [
269 {"type": "TableRow", "style": "emphasis", "cells": [
270 {"type": "TableCell", "items": [{"type": "TextBlock", "text": "a"}]},
271 {"type": "TableCell", "verticalContentAlignment": "top", "items": [{"type": "TextBlock", "text": "b"}]}
272 ]},
273 {"type": "TableRow", "cells": [{"type": "TableCell", "items": [{"type": "TextBlock", "text": "c"}]}]}
274 ]
275 })) else {
276 panic!("table")
277 };
278 assert_eq!(table.columns[0].width, ColumnWidth::Weighted(2.));
279 assert_eq!(table.columns[1].width, ColumnWidth::Pixels(80.));
280 assert!(!table.first_row_as_header && !table.show_grid_lines);
281 assert_eq!(table.grid_style, ContainerStyle::Accent);
282 assert_eq!(table.rows[0].style, ContainerStyle::Emphasis);
283 let row = &table.rows[0];
284 assert_eq!(
285 table.cell_horizontal_alignment(row, 0),
286 HorizontalAlignment::Center
287 );
288 assert_eq!(
289 table.cell_horizontal_alignment(row, 1),
290 HorizontalAlignment::Right
291 );
292 assert_eq!(
293 table.cell_vertical_alignment(row, &row.cells[0], 0),
294 VerticalAlignment::Bottom
295 );
296 assert_eq!(
297 table.cell_vertical_alignment(row, &row.cells[1], 1),
298 VerticalAlignment::Top
299 );
300}
301
302#[test]
303fn tables_pad_missing_columns_and_expose_cell_text() {
304 let card = parse(json!({"body": [{
305 "type": "Table",
306 "rows": [
307 {"cells": [{"items": [{"type": "TextBlock", "text": "a"}]}, {"items": [{"type": "TextBlock", "text": "b"}]}]},
308 {"cells": [{"items": [{"type": "TextBlock", "text": "c"}]}]}
309 ]
310 }]}));
311 let CardElement::Table(table) = &card.items[0].element else {
312 panic!("table")
313 };
314 assert_eq!(table.columns.len(), 2);
315 assert!(table.first_row_as_header && table.show_grid_lines);
316 assert_eq!(card.plain_text().unwrap(), "a\nb\nc");
317}
318
319#[test]
320fn code_blocks_keep_snippet_language_and_start_line() {
321 let CardElement::CodeBlock(block) = first_element(json!({
322 "type": "CodeBlock", "codeSnippet": "let a = 1;\nlet b = 2;\n", "language": "Rust", "startLineNumber": 7
323 })) else {
324 panic!("code block")
325 };
326 assert_eq!(block.code, "let a = 1;\nlet b = 2;");
327 assert_eq!(block.language.as_deref(), Some("Rust"));
328 assert_eq!(block.start_line, 7);
329 let CardElement::CodeBlock(plain) =
330 first_element(json!({"type": "CodeBlock", "codeSnippet": "x"}))
331 else {
332 panic!("code block")
333 };
334 assert_eq!(plain.start_line, 1);
335}
336
337#[test]
338fn badges_parse_style_shape_and_icon() {
339 let CardElement::Badge(badge) = first_element(json!({
340 "type": "Badge", "text": "Done", "icon": "CheckmarkCircle,Filled", "style": "Good",
341 "appearance": "tint", "shape": "rounded", "size": "large", "iconPosition": "After",
342 "tooltip": "All good"
343 })) else {
344 panic!("badge")
345 };
346 assert_eq!(badge.style, BadgeStyle::Good);
347 assert_eq!(badge.appearance, BadgeAppearance::Tint);
348 assert_eq!(badge.shape, BadgeShape::Rounded);
349 assert_eq!(badge.icon.as_deref(), Some("CheckmarkCircle"));
350 assert_eq!(badge.icon_position, IconPosition::After);
351 assert_eq!(badge.tooltip.as_deref(), Some("All good"));
352 let CardElement::Badge(plain) = first_element(json!({"type": "Badge", "text": "New"})) else {
353 panic!("badge")
354 };
355 assert_eq!(plain.appearance, BadgeAppearance::Filled);
356 assert_eq!(plain.shape, BadgeShape::Circular);
357 assert!(AdaptiveCard::parse(&json!({"body": [{"type": "Badge"}]}).to_string()).is_none());
358}
359
360#[test]
361fn progress_elements_parse_value_color_and_label() {
362 let CardElement::ProgressBar(bar) =
363 first_element(json!({"type": "ProgressBar", "value": 140, "color": "good"}))
364 else {
365 panic!("bar")
366 };
367 assert_eq!(bar.value, Some(100.));
368 assert_eq!(bar.color, TextColor::Good);
369 let CardElement::ProgressBar(indeterminate) = first_element(json!({"type": "ProgressBar"}))
370 else {
371 panic!("bar")
372 };
373 assert_eq!(indeterminate.value, None);
374 let CardElement::ProgressRing(ring) = first_element(
375 json!({"type": "ProgressRing", "label": "Loading", "labelPosition": "Below", "size": "large"}),
376 ) else {
377 panic!("ring")
378 };
379 assert_eq!(ring.label.as_deref(), Some("Loading"));
380 assert_eq!(ring.label_position, LabelPosition::Below);
381}
382
383#[test]
384fn compound_buttons_need_a_title() {
385 let CardElement::CompoundButton(button) = first_element(json!({
386 "type": "CompoundButton", "title": "Open", "description": "Opens the page", "icon": "Open",
387 "badge": "New", "selectAction": {"type": "Action.OpenUrl", "url": "https://a.example"}
388 })) else {
389 panic!("button")
390 };
391 assert_eq!(button.title, "Open");
392 assert_eq!(button.badge.as_deref(), Some("New"));
393 assert!(button.select_action.is_some());
394 assert!(
395 AdaptiveCard::parse(
396 &json!({"body": [{"type": "CompoundButton", "description": "x"}]}).to_string()
397 )
398 .is_none()
399 );
400}
401
402#[test]
403fn carousels_hold_pages_and_ignore_the_timer() {
404 let card = parse(json!({"body": [{
405 "type": "Carousel", "timer": 5000, "initialPageIndex": 1,
406 "pages": [
407 {"type": "CarouselPage", "items": [{"type": "TextBlock", "text": "one"}]},
408 {"type": "CarouselPage", "items": [{"type": "TextBlock", "text": "two"}]},
409 {"type": "CarouselPage", "items": []}
410 ]
411 }]}));
412 let CardElement::Carousel(carousel) = &card.items[0].element else {
413 panic!("carousel")
414 };
415 assert_eq!(carousel.pages.len(), 2);
416 assert_eq!(carousel.initial_page, 1);
417 assert_eq!(card.plain_text().unwrap(), "one\ntwo");
418}
419
420#[test]
421fn action_mode_tooltip_and_style_are_parsed() {
422 let card = parse(
423 json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [
424 {"type": "Action.OpenUrl", "title": "A", "url": "https://a.example", "style": "destructive", "tooltip": "Open A"},
425 {"type": "Action.OpenUrl", "title": "B", "url": "https://b.example", "mode": "secondary"}
426 ]}),
427 );
428 assert!(!card.actions[0].secondary);
429 assert_eq!(card.actions[0].tooltip.as_deref(), Some("Open A"));
430 assert!(card.actions[1].secondary);
431 assert!(card.actions[1].is_clickable());
432}
433
434fn numbered_actions(count: usize, secondary: &[usize]) -> Vec<teams_core::CardAction> {
435 let actions: Vec<_> = (0..count)
436 .map(|index| {
437 let mut action = json!({"type": "Action.OpenUrl", "title": format!("A{index}"), "url": "https://a.example"});
438 if secondary.contains(&index) {
439 action["mode"] = json!("secondary");
440 }
441 action
442 })
443 .collect();
444 parse(json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": actions})).actions
445}
446
447#[test]
448fn secondary_actions_go_to_the_overflow() {
449 let actions = numbered_actions(4, &[1]);
450 let split = split_overflow(&actions, |_| true);
451 assert_eq!(split.primary, [0, 2, 3]);
452 assert_eq!(split.overflow, [1]);
453}
454
455#[test]
456fn primary_actions_beyond_six_go_to_the_overflow_in_order() {
457 let actions = numbered_actions(8, &[3]);
458 let split = split_overflow(&actions, |_| true);
459 assert_eq!(split.primary, [0, 1, 2, 4, 5, 6]);
460 assert_eq!(split.overflow, [3, 7]);
461}
462
463#[test]
464fn hidden_actions_are_left_out_of_the_split() {
465 let actions = numbered_actions(3, &[]);
466 let split = split_overflow(&actions, |action| action.title != "A1");
467 assert_eq!(split.primary, [0, 2]);
468 assert!(split.overflow.is_empty());
469}
470
471fn local(text: &str) -> String {
472 format_card_dates_in(text, &FixedOffset::east_opt(2 * 3600).unwrap())
473}
474
475#[test]
476fn dates_format_in_the_given_zone() {
477 let iso = "2026-10-09T12:05:00Z";
478 assert_eq!(
479 local(&format!("{{{{DATE({iso}, SHORT)}}}}")),
480 "Fri, Oct 9, 2026"
481 );
482 assert_eq!(
483 local(&format!("{{{{DATE({iso},LONG)}}}}")),
484 "Friday, October 9, 2026"
485 );
486 assert_eq!(
487 local(&format!("{{{{DATE({iso}, COMPACT)}}}}")),
488 "2026-10-09"
489 );
490 assert_eq!(local(&format!("{{{{DATE({iso})}}}}")), "2026-10-09");
491 assert_eq!(local(&format!("{{{{TIME({iso})}}}}")), "14:05");
492}
493
494#[test]
495fn the_zone_can_move_the_date() {
496 assert_eq!(
497 local("{{DATE(2026-10-09T23:30:00Z, SHORT)}}"),
498 "Sat, Oct 10, 2026"
499 );
500}
501
502#[test]
503fn dates_work_without_braces_inside_longer_text() {
504 assert_eq!(
505 local("Due DATE(2026-10-09T12:05:00Z, SHORT) at TIME(2026-10-09T12:05:00Z)."),
506 "Due Fri, Oct 9, 2026 at 14:05."
507 );
508}
509
510#[test]
511fn malformed_dates_stay_literal() {
512 for text in [
513 "{{DATE(yesterday, SHORT)}}",
514 "{{DATE(2026-10-09, SHORT)}}",
515 "{{TIME()}}",
516 "{{DATE(2026-10-09T12:05:00Z, WEEKLY)}}",
517 ] {
518 assert_eq!(local(text), text);
519 }
520}
521
522#[test]
523fn text_blocks_and_facts_format_dates() {
524 let card = parse(json!({"body": [
525 {"type": "TextBlock", "text": "On {{DATE(2026-10-09T12:05:00Z, LONG)}}"},
526 {"type": "RichTextBlock", "inlines": [{"type": "TextRun", "text": "{{TIME(2026-10-09T12:05:00Z)}}"}]},
527 {"type": "FactSet", "facts": [{"title": "Due", "value": "{{DATE(2026-10-09T12:05:00Z, COMPACT)}}"}]}
528 ]}));
529 let text = card.plain_text().unwrap();
530 assert!(!text.contains("{{"), "{text}");
531 assert!(text.contains("2026"));
532}
crates/core/tests/card_chart.rs added +296 −0
@@ -0,0 +1,296 @@
1 use serde_json::{Value, json};
2 use teams_core::{
3 AdaptiveCard, BarDisplayMode, CardChart, CardElement, ChartColor, ChartKind, GaugeValueFormat,
4 format_chart_value, label_stride, nice_scale, series_categories, series_maximum, slice_angles,
5 unit_fraction,
6 };
7
8 fn parse_chart(element: Value) -> CardChart {
9 let card = json!({"type": "AdaptiveCard", "version": "1.5", "body": [element]});
10 let card = AdaptiveCard::parse(&card.to_string()).expect("card parses");
11 match &card.items[0].element {
12 CardElement::Chart(chart) => chart.clone(),
13 other => panic!("expected chart, got {other:?}"),
14 }
15 }
16
17 fn fruit_slices() -> Value {
18 json!([
19 {"legend": "Pear", "value": 59},
20 {"legend": "Banana", "value": 292},
21 {"legend": "Apple", "value": 143, "color": "good"}
22 ])
23 }
24
25 fn days_series() -> Value {
26 json!([
27 {"legend": "Outlook", "values": [
28 {"x": "2023-05-01", "y": 24}, {"x": "2023-05-02", "y": 27}, {"x": "2023-05-03", "y": 18}
29 ]},
30 {"legend": "Teams", "values": [
31 {"x": "2023-05-01", "y": 9}, {"x": "2023-05-02", "y": 100}, {"x": "2023-05-03", "y": 22}
32 ]}
33 ])
34 }
35
36 #[test]
37 fn donut_parses_slices_and_explicit_color() {
38 let chart =
39 parse_chart(json!({"type": "Chart.Donut", "title": "Fruit", "data": fruit_slices()}));
40 assert_eq!(chart.title.as_deref(), Some("Fruit"));
41 let ChartKind::Donut(slices) = &chart.kind else {
42 panic!("expected donut");
43 };
44 assert_eq!(slices.len(), 3);
45 assert_eq!(slices[1].label, "Banana");
46 assert_eq!(slices[1].value, 292.);
47 assert_eq!(slices[2].color, ChartColor::Good);
48 assert_ne!(slices[0].color, slices[1].color);
49 assert!(chart.show_legend);
50 }
51
52 #[test]
53 fn pie_parses_slices() {
54 let chart = parse_chart(
55 json!({"type": "Chart.Pie", "colorSet": "categorical", "data": fruit_slices()}),
56 );
57 let ChartKind::Pie(slices) = &chart.kind else {
58 panic!("expected pie");
59 };
60 assert_eq!(slices.len(), 3);
61 assert_eq!(chart.legend_entries().len(), 3);
62 }
63
64 #[test]
65 fn gauge_parses_segments_and_defaults() {
66 let chart = parse_chart(json!({
67 "type": "Chart.Gauge", "value": 50, "subLabel": "CPU",
68 "segments": [
69 {"legend": "Low risk", "size": 33, "color": "good"},
70 {"legend": "Medium risk", "size": 34, "color": "warning"},
71 {"legend": "High risk", "size": 33, "color": "attention"}
72 ]
73 }));
74 let ChartKind::Gauge(gauge) = &chart.kind else {
75 panic!("expected gauge");
76 };
77 assert_eq!(gauge.value, 50.);
78 assert_eq!(gauge.minimum, 0.);
79 assert_eq!(gauge.maximum, 100.);
80 assert_eq!(gauge.format, GaugeValueFormat::Percentage);
81 assert_eq!(gauge.sub_label.as_deref(), Some("CPU"));
82 assert!(gauge.show_min_max);
83 assert_eq!(gauge.segments[2].color, ChartColor::Attention);
84 }
85
86 #[test]
87 fn gauge_reads_fraction_format_and_value_key() {
88 let chart = parse_chart(json!({
89 "type": "Chart.Gauge", "value": 35, "valueFormat": "fraction", "min": 10, "showLegend": false,
90 "segments": [{"legend": "Used", "value": 35}, {"legend": "Unused", "value": 65, "color": "neutral"}]
91 }));
92 let ChartKind::Gauge(gauge) = &chart.kind else {
93 panic!("expected gauge");
94 };
95 assert_eq!(gauge.format, GaugeValueFormat::Fraction);
96 assert_eq!(gauge.maximum, 110.);
97 assert_eq!(gauge.segments[0].size, 35.);
98 assert_eq!(gauge.segments[1].color, ChartColor::Neutral);
99 assert!(!chart.show_legend);
100 }
101
102 #[test]
103 fn line_parses_series_with_axis_titles() {
104 let chart = parse_chart(json!({
105 "type": "Chart.Line", "title": "Sample", "xAxisTitle": "Days", "yAxisTitle": "Sales",
106 "colorSet": "categorical", "data": days_series()
107 }));
108 assert_eq!(chart.x_axis_title.as_deref(), Some("Days"));
109 assert_eq!(chart.y_axis_title.as_deref(), Some("Sales"));
110 let ChartKind::Line(series) = &chart.kind else {
111 panic!("expected line");
112 };
113 assert_eq!(series.len(), 2);
114 assert_eq!(series[1].legend, "Teams");
115 assert_eq!(series[1].points[1].value, 100.);
116 assert_eq!(series[0].points[0].color, series[0].color);
117 }
118
119 #[test]
120 fn line_accepts_numeric_x_values() {
121 let chart = parse_chart(json!({
122 "type": "Chart.Line",
123 "data": [{"legend": "A", "values": [{"x": 1, "y": 2}, {"x": 2.5, "y": 3}]}]
124 }));
125 let ChartKind::Line(series) = &chart.kind else {
126 panic!("expected line");
127 };
128 assert_eq!(series[0].points[0].label, "1");
129 assert_eq!(series[0].points[1].label, "2.5");
130 }
131
132 #[test]
133 fn vertical_bar_parses_points_and_show_values() {
134 let chart = parse_chart(json!({
135 "type": "Chart.VerticalBar", "showBarValues": true, "color": "categoricalPurple",
136 "data": [{"x": "Pear", "y": 59}, {"x": "Banana", "y": 292}]
137 }));
138 assert!(chart.show_values);
139 let ChartKind::VerticalBar(bars) = &chart.kind else {
140 panic!("expected vertical bar");
141 };
142 assert_eq!(bars[1].label, "Banana");
143 assert_eq!(bars[1].color, ChartColor::CategoricalPurple);
144 }
145
146 #[test]
147 fn grouped_bar_parses_stacked_flag() {
148 let grouped = parse_chart(json!({"type": "Chart.VerticalBar.Grouped", "data": days_series()}));
149 let stacked = parse_chart(
150 json!({"type": "Chart.VerticalBar.Grouped", "stacked": true, "colorSet": "diverging", "data": days_series()}),
151 );
152 assert!(matches!(
153 grouped.kind,
154 ChartKind::GroupedBar { stacked: false, .. }
155 ));
156 let ChartKind::GroupedBar {
157 series,
158 stacked: true,
159 } = &stacked.kind
160 else {
161 panic!("expected stacked grouped bar");
162 };
163 assert_eq!(series.len(), 2);
164 assert_eq!(stacked.legend_entries().len(), 2);
165 }
166
167 #[test]
168 fn horizontal_bar_parses_display_modes() {
169 let data = json!([{"x": "Pear", "y": 59}]);
170 for (name, expected) in [
171 ("AbsoluteWithAxis", BarDisplayMode::AbsoluteWithAxis),
172 ("AbsoluteNoAxis", BarDisplayMode::AbsoluteNoAxis),
173 ("PartToWhole", BarDisplayMode::PartToWhole),
174 ] {
175 let chart =
176 parse_chart(json!({"type": "Chart.HorizontalBar", "displayMode": name, "data": data}));
177 let ChartKind::HorizontalBar { mode, .. } = chart.kind else {
178 panic!("expected horizontal bar");
179 };
180 assert_eq!(mode, expected);
181 }
182 let chart = parse_chart(json!({"type": "Chart.HorizontalBar", "data": data}));
183 assert!(matches!(
184 chart.kind,
185 ChartKind::HorizontalBar {
186 mode: BarDisplayMode::AbsoluteWithAxis,
187 ..
188 }
189 ));
190 }
191
192 #[test]
193 fn stacked_horizontal_bar_parses_rows_and_legend() {
194 let chart = parse_chart(json!({
195 "type": "Chart.HorizontalBar.Stacked", "title": "Sample",
196 "data": [
197 {"title": "Outlook", "data": [
198 {"legend": "2023-05-01", "value": 24, "color": "good"},
199 {"legend": "2023-05-02", "value": 27, "color": "warning"}
200 ]},
201 {"title": "Teams", "data": [
202 {"legend": "2023-05-01", "value": 9, "color": "good"},
203 {"legend": "2023-05-02", "value": 100, "color": "warning"}
204 ]}
205 ]
206 }));
207 let ChartKind::StackedHorizontalBar(rows) = &chart.kind else {
208 panic!("expected stacked horizontal bar");
209 };
210 assert_eq!(rows.len(), 2);
211 assert_eq!(rows[1].legend, "Teams");
212 assert_eq!(rows[1].points[1].value, 100.);
213 assert_eq!(rows[1].points[1].color, ChartColor::Warning);
214 assert_eq!(chart.legend_entries().len(), 2);
215 }
216
217 #[test]
218 fn unknown_chart_type_falls_back_to_nothing() {
219 let card = json!({"type": "AdaptiveCard", "body": [{"type": "Chart.Radar", "data": []}]});
220 assert!(AdaptiveCard::parse(&card.to_string()).is_none());
221 }
222
223 #[test]
224 fn slice_angles_cover_full_circle_in_order() {
225 let angles = slice_angles(&[59., 292., 143.]);
226 let (first_start, _) = angles[0];
227 let (_, last_end) = angles[2];
228 assert!((first_start + std::f32::consts::FRAC_PI_2).abs() < 1e-6);
229 assert!((last_end - first_start - std::f32::consts::TAU).abs() < 1e-4);
230 assert_eq!(angles[0].1, angles[1].0);
231 }
232
233 #[test]
234 fn slice_angles_ignore_negative_and_empty_totals() {
235 let angles = slice_angles(&[-5., 10.]);
236 assert_eq!(angles[0].0, angles[0].1);
237 assert!((angles[1].1 - angles[1].0 - std::f32::consts::TAU).abs() < 1e-4);
238 assert!(
239 slice_angles(&[0., 0.])
240 .iter()
241 .all(|(start, end)| start == end)
242 );
243 }
244
245 #[test]
246 fn unit_fraction_clamps_gauge_values() {
247 assert_eq!(unit_fraction(50., 0., 100.), 0.5);
248 assert_eq!(unit_fraction(-20., 0., 100.), 0.);
249 assert_eq!(unit_fraction(250., 0., 100.), 1.);
250 assert_eq!(unit_fraction(60., 20., 100.), 0.5);
251 assert_eq!(unit_fraction(5., 10., 10.), 0.);
252 }
253
254 #[test]
255 fn nice_scale_rounds_up_to_round_steps() {
256 let scale = nice_scale(292., 4);
257 assert_eq!(scale.step, 100.);
258 assert_eq!(scale.maximum, 300.);
259 assert_eq!(scale.ticks(), vec![0., 100., 200., 300.]);
260 let small = nice_scale(0.9, 4);
261 assert!(small.maximum >= 0.9);
262 assert_eq!(nice_scale(0., 4).maximum, 1.);
263 assert_eq!(nice_scale(100., 4).maximum, 100.);
264 }
265
266 #[test]
267 fn bar_scaling_is_proportional_to_scale_maximum() {
268 let scale = nice_scale(292., 4);
269 assert!((unit_fraction(150., 0., scale.maximum) - 0.5).abs() < 1e-6);
270 assert!(unit_fraction(292., 0., scale.maximum) < 1.);
271 }
272
273 #[test]
274 fn label_stride_skips_labels_that_do_not_fit() {
275 assert_eq!(label_stride(8, 60., 40.), 1);
276 assert_eq!(label_stride(8, 30., 62.), 3);
277 assert_eq!(label_stride(0, 30., 62.), 1);
278 }
279
280 #[test]
281 fn series_helpers_union_categories_and_stack_totals() {
282 let chart = parse_chart(json!({"type": "Chart.VerticalBar.Grouped", "data": days_series()}));
283 let ChartKind::GroupedBar { series, .. } = &chart.kind else {
284 panic!("expected grouped bar");
285 };
286 assert_eq!(series_categories(series).len(), 3);
287 assert_eq!(series_maximum(series, false), 100.);
288 assert_eq!(series_maximum(series, true), 127.);
289 }
290
291 #[test]
292 fn chart_values_format_without_trailing_zeros() {
293 assert_eq!(format_chart_value(292.), "292");
294 assert_eq!(format_chart_value(2.5), "2.5");
295 assert_eq!(format_chart_value(0.333333), "0.33");
296 }
@@ -0,0 +1,296 @@
1use serde_json::{Value, json};
2use teams_core::{
3 AdaptiveCard, BarDisplayMode, CardChart, CardElement, ChartColor, ChartKind, GaugeValueFormat,
4 format_chart_value, label_stride, nice_scale, series_categories, series_maximum, slice_angles,
5 unit_fraction,
6};
7
8fn parse_chart(element: Value) -> CardChart {
9 let card = json!({"type": "AdaptiveCard", "version": "1.5", "body": [element]});
10 let card = AdaptiveCard::parse(&card.to_string()).expect("card parses");
11 match &card.items[0].element {
12 CardElement::Chart(chart) => chart.clone(),
13 other => panic!("expected chart, got {other:?}"),
14 }
15}
16
17fn fruit_slices() -> Value {
18 json!([
19 {"legend": "Pear", "value": 59},
20 {"legend": "Banana", "value": 292},
21 {"legend": "Apple", "value": 143, "color": "good"}
22 ])
23}
24
25fn days_series() -> Value {
26 json!([
27 {"legend": "Outlook", "values": [
28 {"x": "2023-05-01", "y": 24}, {"x": "2023-05-02", "y": 27}, {"x": "2023-05-03", "y": 18}
29 ]},
30 {"legend": "Teams", "values": [
31 {"x": "2023-05-01", "y": 9}, {"x": "2023-05-02", "y": 100}, {"x": "2023-05-03", "y": 22}
32 ]}
33 ])
34}
35
36#[test]
37fn donut_parses_slices_and_explicit_color() {
38 let chart =
39 parse_chart(json!({"type": "Chart.Donut", "title": "Fruit", "data": fruit_slices()}));
40 assert_eq!(chart.title.as_deref(), Some("Fruit"));
41 let ChartKind::Donut(slices) = &chart.kind else {
42 panic!("expected donut");
43 };
44 assert_eq!(slices.len(), 3);
45 assert_eq!(slices[1].label, "Banana");
46 assert_eq!(slices[1].value, 292.);
47 assert_eq!(slices[2].color, ChartColor::Good);
48 assert_ne!(slices[0].color, slices[1].color);
49 assert!(chart.show_legend);
50}
51
52#[test]
53fn pie_parses_slices() {
54 let chart = parse_chart(
55 json!({"type": "Chart.Pie", "colorSet": "categorical", "data": fruit_slices()}),
56 );
57 let ChartKind::Pie(slices) = &chart.kind else {
58 panic!("expected pie");
59 };
60 assert_eq!(slices.len(), 3);
61 assert_eq!(chart.legend_entries().len(), 3);
62}
63
64#[test]
65fn gauge_parses_segments_and_defaults() {
66 let chart = parse_chart(json!({
67 "type": "Chart.Gauge", "value": 50, "subLabel": "CPU",
68 "segments": [
69 {"legend": "Low risk", "size": 33, "color": "good"},
70 {"legend": "Medium risk", "size": 34, "color": "warning"},
71 {"legend": "High risk", "size": 33, "color": "attention"}
72 ]
73 }));
74 let ChartKind::Gauge(gauge) = &chart.kind else {
75 panic!("expected gauge");
76 };
77 assert_eq!(gauge.value, 50.);
78 assert_eq!(gauge.minimum, 0.);
79 assert_eq!(gauge.maximum, 100.);
80 assert_eq!(gauge.format, GaugeValueFormat::Percentage);
81 assert_eq!(gauge.sub_label.as_deref(), Some("CPU"));
82 assert!(gauge.show_min_max);
83 assert_eq!(gauge.segments[2].color, ChartColor::Attention);
84}
85
86#[test]
87fn gauge_reads_fraction_format_and_value_key() {
88 let chart = parse_chart(json!({
89 "type": "Chart.Gauge", "value": 35, "valueFormat": "fraction", "min": 10, "showLegend": false,
90 "segments": [{"legend": "Used", "value": 35}, {"legend": "Unused", "value": 65, "color": "neutral"}]
91 }));
92 let ChartKind::Gauge(gauge) = &chart.kind else {
93 panic!("expected gauge");
94 };
95 assert_eq!(gauge.format, GaugeValueFormat::Fraction);
96 assert_eq!(gauge.maximum, 110.);
97 assert_eq!(gauge.segments[0].size, 35.);
98 assert_eq!(gauge.segments[1].color, ChartColor::Neutral);
99 assert!(!chart.show_legend);
100}
101
102#[test]
103fn line_parses_series_with_axis_titles() {
104 let chart = parse_chart(json!({
105 "type": "Chart.Line", "title": "Sample", "xAxisTitle": "Days", "yAxisTitle": "Sales",
106 "colorSet": "categorical", "data": days_series()
107 }));
108 assert_eq!(chart.x_axis_title.as_deref(), Some("Days"));
109 assert_eq!(chart.y_axis_title.as_deref(), Some("Sales"));
110 let ChartKind::Line(series) = &chart.kind else {
111 panic!("expected line");
112 };
113 assert_eq!(series.len(), 2);
114 assert_eq!(series[1].legend, "Teams");
115 assert_eq!(series[1].points[1].value, 100.);
116 assert_eq!(series[0].points[0].color, series[0].color);
117}
118
119#[test]
120fn line_accepts_numeric_x_values() {
121 let chart = parse_chart(json!({
122 "type": "Chart.Line",
123 "data": [{"legend": "A", "values": [{"x": 1, "y": 2}, {"x": 2.5, "y": 3}]}]
124 }));
125 let ChartKind::Line(series) = &chart.kind else {
126 panic!("expected line");
127 };
128 assert_eq!(series[0].points[0].label, "1");
129 assert_eq!(series[0].points[1].label, "2.5");
130}
131
132#[test]
133fn vertical_bar_parses_points_and_show_values() {
134 let chart = parse_chart(json!({
135 "type": "Chart.VerticalBar", "showBarValues": true, "color": "categoricalPurple",
136 "data": [{"x": "Pear", "y": 59}, {"x": "Banana", "y": 292}]
137 }));
138 assert!(chart.show_values);
139 let ChartKind::VerticalBar(bars) = &chart.kind else {
140 panic!("expected vertical bar");
141 };
142 assert_eq!(bars[1].label, "Banana");
143 assert_eq!(bars[1].color, ChartColor::CategoricalPurple);
144}
145
146#[test]
147fn grouped_bar_parses_stacked_flag() {
148 let grouped = parse_chart(json!({"type": "Chart.VerticalBar.Grouped", "data": days_series()}));
149 let stacked = parse_chart(
150 json!({"type": "Chart.VerticalBar.Grouped", "stacked": true, "colorSet": "diverging", "data": days_series()}),
151 );
152 assert!(matches!(
153 grouped.kind,
154 ChartKind::GroupedBar { stacked: false, .. }
155 ));
156 let ChartKind::GroupedBar {
157 series,
158 stacked: true,
159 } = &stacked.kind
160 else {
161 panic!("expected stacked grouped bar");
162 };
163 assert_eq!(series.len(), 2);
164 assert_eq!(stacked.legend_entries().len(), 2);
165}
166
167#[test]
168fn horizontal_bar_parses_display_modes() {
169 let data = json!([{"x": "Pear", "y": 59}]);
170 for (name, expected) in [
171 ("AbsoluteWithAxis", BarDisplayMode::AbsoluteWithAxis),
172 ("AbsoluteNoAxis", BarDisplayMode::AbsoluteNoAxis),
173 ("PartToWhole", BarDisplayMode::PartToWhole),
174 ] {
175 let chart =
176 parse_chart(json!({"type": "Chart.HorizontalBar", "displayMode": name, "data": data}));
177 let ChartKind::HorizontalBar { mode, .. } = chart.kind else {
178 panic!("expected horizontal bar");
179 };
180 assert_eq!(mode, expected);
181 }
182 let chart = parse_chart(json!({"type": "Chart.HorizontalBar", "data": data}));
183 assert!(matches!(
184 chart.kind,
185 ChartKind::HorizontalBar {
186 mode: BarDisplayMode::AbsoluteWithAxis,
187 ..
188 }
189 ));
190}
191
192#[test]
193fn stacked_horizontal_bar_parses_rows_and_legend() {
194 let chart = parse_chart(json!({
195 "type": "Chart.HorizontalBar.Stacked", "title": "Sample",
196 "data": [
197 {"title": "Outlook", "data": [
198 {"legend": "2023-05-01", "value": 24, "color": "good"},
199 {"legend": "2023-05-02", "value": 27, "color": "warning"}
200 ]},
201 {"title": "Teams", "data": [
202 {"legend": "2023-05-01", "value": 9, "color": "good"},
203 {"legend": "2023-05-02", "value": 100, "color": "warning"}
204 ]}
205 ]
206 }));
207 let ChartKind::StackedHorizontalBar(rows) = &chart.kind else {
208 panic!("expected stacked horizontal bar");
209 };
210 assert_eq!(rows.len(), 2);
211 assert_eq!(rows[1].legend, "Teams");
212 assert_eq!(rows[1].points[1].value, 100.);
213 assert_eq!(rows[1].points[1].color, ChartColor::Warning);
214 assert_eq!(chart.legend_entries().len(), 2);
215}
216
217#[test]
218fn unknown_chart_type_falls_back_to_nothing() {
219 let card = json!({"type": "AdaptiveCard", "body": [{"type": "Chart.Radar", "data": []}]});
220 assert!(AdaptiveCard::parse(&card.to_string()).is_none());
221}
222
223#[test]
224fn slice_angles_cover_full_circle_in_order() {
225 let angles = slice_angles(&[59., 292., 143.]);
226 let (first_start, _) = angles[0];
227 let (_, last_end) = angles[2];
228 assert!((first_start + std::f32::consts::FRAC_PI_2).abs() < 1e-6);
229 assert!((last_end - first_start - std::f32::consts::TAU).abs() < 1e-4);
230 assert_eq!(angles[0].1, angles[1].0);
231}
232
233#[test]
234fn slice_angles_ignore_negative_and_empty_totals() {
235 let angles = slice_angles(&[-5., 10.]);
236 assert_eq!(angles[0].0, angles[0].1);
237 assert!((angles[1].1 - angles[1].0 - std::f32::consts::TAU).abs() < 1e-4);
238 assert!(
239 slice_angles(&[0., 0.])
240 .iter()
241 .all(|(start, end)| start == end)
242 );
243}
244
245#[test]
246fn unit_fraction_clamps_gauge_values() {
247 assert_eq!(unit_fraction(50., 0., 100.), 0.5);
248 assert_eq!(unit_fraction(-20., 0., 100.), 0.);
249 assert_eq!(unit_fraction(250., 0., 100.), 1.);
250 assert_eq!(unit_fraction(60., 20., 100.), 0.5);
251 assert_eq!(unit_fraction(5., 10., 10.), 0.);
252}
253
254#[test]
255fn nice_scale_rounds_up_to_round_steps() {
256 let scale = nice_scale(292., 4);
257 assert_eq!(scale.step, 100.);
258 assert_eq!(scale.maximum, 300.);
259 assert_eq!(scale.ticks(), vec![0., 100., 200., 300.]);
260 let small = nice_scale(0.9, 4);
261 assert!(small.maximum >= 0.9);
262 assert_eq!(nice_scale(0., 4).maximum, 1.);
263 assert_eq!(nice_scale(100., 4).maximum, 100.);
264}
265
266#[test]
267fn bar_scaling_is_proportional_to_scale_maximum() {
268 let scale = nice_scale(292., 4);
269 assert!((unit_fraction(150., 0., scale.maximum) - 0.5).abs() < 1e-6);
270 assert!(unit_fraction(292., 0., scale.maximum) < 1.);
271}
272
273#[test]
274fn label_stride_skips_labels_that_do_not_fit() {
275 assert_eq!(label_stride(8, 60., 40.), 1);
276 assert_eq!(label_stride(8, 30., 62.), 3);
277 assert_eq!(label_stride(0, 30., 62.), 1);
278}
279
280#[test]
281fn series_helpers_union_categories_and_stack_totals() {
282 let chart = parse_chart(json!({"type": "Chart.VerticalBar.Grouped", "data": days_series()}));
283 let ChartKind::GroupedBar { series, .. } = &chart.kind else {
284 panic!("expected grouped bar");
285 };
286 assert_eq!(series_categories(series).len(), 3);
287 assert_eq!(series_maximum(series, false), 100.);
288 assert_eq!(series_maximum(series, true), 127.);
289}
290
291#[test]
292fn chart_values_format_without_trailing_zeros() {
293 assert_eq!(format_chart_value(292.), "292");
294 assert_eq!(format_chart_value(2.5), "2.5");
295 assert_eq!(format_chart_value(0.333333), "0.33");
296}
crates/core/tests/card_inputs.rs +1 −1
@@ -142,7 +142,7 @@ fn inputs_without_id_or_choices_and_unknown_types_fall_back() {
142 142 json!([
143 143 {"type": "Input.Text"},
144 144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
145 {"type": "Input.Rating", "id": "r", "fallbackText": "Rating is not supported"}
145 {"type": "Input.Slider", "id": "r", "fallbackText": "Slider is not supported"}
146 146 ]),
147 147 json!([]),
148 148 );
@@ -142,7 +142,7 @@ fn inputs_without_id_or_choices_and_unknown_types_fall_back() {
142 json!([
142 json!([
143 {"type": "Input.Text"},
143 {"type": "Input.Text"},
144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
144 {"type": "Input.ChoiceSet", "id": "c", "choices": []},
145 {"type": "Input.Rating", "id": "r", "fallbackText": "Rating is not supported"}
145 {"type": "Input.Slider", "id": "r", "fallbackText": "Slider is not supported"}
146 ]),
146 ]),
147 json!([]),
147 json!([]),
148 );
148 );
crates/core/tests/markdown.rs +25 −1
@@ -1,5 +1,5 @@
1 1 use serde::Deserialize;
2 use teams_core::markdown_to_html;
2 use teams_core::{card_markdown_to_html, markdown_to_html};
3 3
4 4 #[derive(Deserialize)]
5 5 struct Golden {
@@ -60,3 +60,27 @@ fn list_items_escape_html() {
60 60 fn list_lines_inside_a_fence_stay_code() {
61 61 assert_eq!(markdown_to_html("```\n- a\n```"), "<pre>- a</pre>");
62 62 }
63
64 #[test]
65 fn card_markdown_adds_italic_and_mentions_to_the_message_dialect() {
66 assert_eq!(
67 card_markdown_to_html("_soft_ and *slanted* and **bold**"),
68 "<i>soft</i> and <i>slanted</i> and <b>bold</b>"
69 );
70 assert_eq!(
71 card_markdown_to_html("hi <at>Ada & Co</at> <x>"),
72 "hi <at>Ada &amp; Co</at> &lt;x&gt;"
73 );
74 assert_eq!(
75 markdown_to_html("_soft_ <at>Ada</at>"),
76 "_soft_ &lt;at&gt;Ada&lt;/at&gt;"
77 );
78 }
79
80 #[test]
81 fn card_markdown_keeps_snake_case_and_urls() {
82 assert_eq!(
83 card_markdown_to_html("my_var_name https://a.example/_x_/ [l](https://a.example/_y_)"),
84 "my_var_name https://a.example/_x_/ <a href=\"https://a.example/_y_\">l</a>"
85 );
86 }
@@ -1,5 +1,5 @@
1use serde::Deserialize;
1use serde::Deserialize;
2use teams_core::markdown_to_html;
2use teams_core::{card_markdown_to_html, markdown_to_html};
3
3
4#[derive(Deserialize)]
4#[derive(Deserialize)]
5struct Golden {
5struct Golden {
@@ -60,3 +60,27 @@ fn list_items_escape_html() {
60fn list_lines_inside_a_fence_stay_code() {
60fn list_lines_inside_a_fence_stay_code() {
61 assert_eq!(markdown_to_html("```\n- a\n```"), "<pre>- a</pre>");
61 assert_eq!(markdown_to_html("```\n- a\n```"), "<pre>- a</pre>");
62}
62}
63
64#[test]
65fn card_markdown_adds_italic_and_mentions_to_the_message_dialect() {
66 assert_eq!(
67 card_markdown_to_html("_soft_ and *slanted* and **bold**"),
68 "<i>soft</i> and <i>slanted</i> and <b>bold</b>"
69 );
70 assert_eq!(
71 card_markdown_to_html("hi <at>Ada & Co</at> <x>"),
72 "hi <at>Ada &amp; Co</at> &lt;x&gt;"
73 );
74 assert_eq!(
75 markdown_to_html("_soft_ <at>Ada</at>"),
76 "_soft_ &lt;at&gt;Ada&lt;/at&gt;"
77 );
78}
79
80#[test]
81fn card_markdown_keeps_snake_case_and_urls() {
82 assert_eq!(
83 card_markdown_to_html("my_var_name https://a.example/_x_/ [l](https://a.example/_y_)"),
84 "my_var_name https://a.example/_x_/ <a href=\"https://a.example/_y_\">l</a>"
85 );
86}