BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / adaptive_card.rs

adaptive_card.rs

adaptive_card.rs 18.1 KiB Download Raw
1use std::collections::HashMap;
2
3use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use teams_core::{
7 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
8 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
9 VerticalAlignment,
10};
11
12use super::widgets::symbol;
13use crate::app_state::AppHandle;
14use crate::card_state::{ActionPhase, CardScope, CardState};
15use crate::render::{layout_blocks, render_blocks};
16use crate::theme;
17
18const CARD_WIDTH: f32 = 480.;
19const CARD_FULL_WIDTH: f32 = 720.;
20const CARD_PADDING: f32 = 12.;
21const CARD_RADIUS: f32 = 10.;
22const CARD_BORDER_WIDTH: f32 = 1.;
23const COLUMN_GAP: f32 = 8.;
24const SEPARATOR_PADDING: f32 = 8.;
25const ACTION_GAP: f32 = 8.;
26const ACTION_RADIUS: f32 = 6.;
27const ACTION_TEXT_SIZE: f32 = 13.;
28const ACTION_DISABLED_OPACITY: f32 = 0.5;
29const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
30const ACTION_BUSY_OPACITY: f32 = 0.6;
31const ACTION_CHECK_SIZE: f32 = 14.;
32const ACTION_ICON_GAP: f32 = 4.;
33const NOTE_TEXT_SIZE: f32 = 12.;
34const FACT_TITLE_WIDTH: f32 = 96.;
35const FACT_GAP: f32 = 2.;
36const CONTAINER_PADDING: f32 = 8.;
37const CONTAINER_RADIUS: f32 = 6.;
38const CONTAINER_TINT: f32 = 0.16;
39const TEXT_LINE_HEIGHT: f32 = 1.35;
40const IMAGE_RADIUS: f32 = 4.;
41const IMAGE_SET_GAP: f32 = 6.;
42const SMALL_IMAGE: f32 = 40.;
43const MEDIUM_IMAGE: f32 = 80.;
44const LARGE_IMAGE: f32 = 160.;
45const EXTERNAL_IMAGE_SCHEME: &str = "https://";
46
47struct CardContext<'a> {
48 cx: &'a App,
49 scope: &'a CardScope,
50 state: &'a CardState,
51 root_key: String,
52 initial_visibility: HashMap<String, bool>,
53}
54
55impl<'a> CardContext<'a> {
56 fn new(card: &AdaptiveCard, scope: &'a CardScope, cx: &'a App) -> Self {
57 CardContext {
58 cx,
59 scope,
60 state: &cx.global::<AppHandle>().0.read(cx).cards,
61 root_key: scope.card_key(),
62 initial_visibility: card.element_visibility(),
63 }
64 }
65
66 fn visible(&self, id: Option<&String>, initial: bool) -> bool {
67 match id {
68 Some(id) => self
69 .state
70 .is_visible(&format!("{}/{id}", self.root_key), initial),
71 None => initial,
72 }
73 }
74}
75
76pub fn cards_view(
77 cards: &[AdaptiveCard],
78 conversation_id: &str,
79 message_id: &str,
80 cx: &App,
81) -> Vec<AnyElement> {
82 cards
83 .iter()
84 .enumerate()
85 .map(|(index, card)| {
86 let scope = CardScope::message(conversation_id, message_id, index);
87 card_view(card, &scope, cx)
88 })
89 .collect()
90}
91
92pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
93 let context = CardContext::new(card, scope, cx);
94 let id = scope.card_key();
95 let width = if card.full_width {
96 CARD_FULL_WIDTH
97 } else {
98 CARD_WIDTH
99 };
100 let note = context.state.note(&id).map(str::to_owned);
101 let visible_actions = card
102 .actions
103 .iter()
104 .any(|action| context.visible(action.id.as_ref(), action.visible));
105 v_flex()
106 .w(px(width))
107 .max_w(relative(1.))
108 .p(px(CARD_PADDING))
109 .rounded(px(CARD_RADIUS))
110 .bg(theme::surface())
111 .border(px(CARD_BORDER_WIDTH))
112 .border_color(theme::border())
113 .text_color(theme::text_strong())
114 .child(items_view(&card.items, &id, &context))
115 .when(visible_actions, |card_element| {
116 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
117 actions_view(&card.actions, &format!("{id}-actions"), &context),
118 ))
119 })
120 .when_some(note, |card_element, note| {
121 card_element.child(
122 div()
123 .mt(px(spacing_pixels(CardSpacing::Default)))
124 .text_size(px(NOTE_TEXT_SIZE))
125 .text_color(theme::text_muted())
126 .child(note),
127 )
128 })
129 .into_any_element()
130}
131
132fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
133 let mut shown = 0;
134 let mut column = v_flex().w_full();
135 for (index, item) in items.iter().enumerate() {
136 if !context.visible(item.id.as_ref(), item.visible) {
137 continue;
138 }
139 let item_id = format!("{id}-{index}");
140 let first = shown == 0;
141 shown += 1;
142 column = column.child(
143 div()
144 .w_full()
145 .when(!first, |wrapper| {
146 wrapper.mt(px(spacing_pixels(item.spacing)))
147 })
148 .when(!first && item.separator, |wrapper| {
149 wrapper
150 .pt(px(SEPARATOR_PADDING))
151 .border_t_1()
152 .border_color(theme::border())
153 })
154 .child(element_view(&item.element, &item_id, context)),
155 );
156 }
157 column
158}
159
160fn spacing_pixels(spacing: CardSpacing) -> f32 {
161 match spacing {
162 CardSpacing::None => 0.,
163 CardSpacing::Small => 4.,
164 CardSpacing::Default => 8.,
165 CardSpacing::Medium => 12.,
166 CardSpacing::Large | CardSpacing::Padding => 16.,
167 CardSpacing::ExtraLarge => 24.,
168 }
169}
170
171fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyElement {
172 match element {
173 CardElement::Text(text) => text_view(text, id, context.cx),
174 CardElement::Image(image) => image_view(image, id),
175 CardElement::ImageSet(images) => h_flex()
176 .flex_wrap()
177 .gap(px(IMAGE_SET_GAP))
178 .children(
179 images
180 .iter()
181 .enumerate()
182 .map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
183 )
184 .into_any_element(),
185 CardElement::Columns(columns) => columns_view(columns, id, context),
186 CardElement::Container { style, items } => {
187 let tint = container_tint(*style);
188 items_view(items, id, context)
189 .when_some(tint, |container, tint| {
190 container
191 .p(px(CONTAINER_PADDING))
192 .rounded(px(CONTAINER_RADIUS))
193 .bg(tint)
194 })
195 .into_any_element()
196 }
197 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
198 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
199 }
200}
201
202fn container_tint(style: ContainerStyle) -> Option<Hsla> {
203 match style {
204 ContainerStyle::Default => None,
205 ContainerStyle::Emphasis => Some(theme::surface_raised()),
206 ContainerStyle::Accent => Some(theme::accent().opacity(CONTAINER_TINT)),
207 ContainerStyle::Good => Some(theme::green().opacity(CONTAINER_TINT)),
208 ContainerStyle::Warning => Some(theme::amber().opacity(CONTAINER_TINT)),
209 ContainerStyle::Attention => Some(theme::red().opacity(CONTAINER_TINT)),
210 }
211}
212
213fn text_size(size: TextSize) -> f32 {
214 match size {
215 TextSize::Small => 11.5,
216 TextSize::Default => 13.5,
217 TextSize::Medium => 15.,
218 TextSize::Large => 17.5,
219 TextSize::ExtraLarge => 21.,
220 }
221}
222
223fn text_color(text: &CardText) -> Hsla {
224 match text.color {
225 TextColor::Accent => theme::accent_text(),
226 TextColor::Good => theme::green(),
227 TextColor::Warning => theme::amber(),
228 TextColor::Attention => theme::red_soft(),
229 TextColor::Default | TextColor::Dark | TextColor::Light if text.subtle => {
230 theme::text_muted()
231 }
232 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
233 }
234}
235
236fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
237 div()
238 .w_full()
239 .text_size(px(text_size(text.size)))
240 .line_height(relative(TEXT_LINE_HEIGHT))
241 .text_color(text_color(text))
242 .when(text.bold, |element| {
243 element.font_weight(FontWeight::SEMIBOLD)
244 })
245 .when(!text.wrap, |element| element.whitespace_nowrap())
246 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
247 .into_any_element()
248}
249
250fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
251 v_flex()
252 .w_full()
253 .gap(px(FACT_GAP))
254 .children(facts.iter().enumerate().map(|(index, fact)| {
255 h_flex()
256 .w_full()
257 .items_start()
258 .gap(px(COLUMN_GAP))
259 .text_size(px(text_size(TextSize::Default)))
260 .line_height(relative(TEXT_LINE_HEIGHT))
261 .child(
262 div()
263 .w(px(FACT_TITLE_WIDTH))
264 .flex_none()
265 .font_weight(FontWeight::SEMIBOLD)
266 .text_color(theme::text_muted())
267 .child(fact.title.clone()),
268 )
269 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
270 &layout_blocks(&fact.value),
271 &format!("{id}-{index}"),
272 false,
273 cx,
274 )))
275 }))
276 .into_any_element()
277}
278
279fn columns_view(columns: &[CardColumn], id: &str, context: &CardContext) -> AnyElement {
280 div()
281 .flex()
282 .flex_row()
283 .items_stretch()
284 .w_full()
285 .gap(px(COLUMN_GAP))
286 .children(columns.iter().enumerate().map(|(index, column)| {
287 let content = items_view(&column.items, &format!("{id}-{index}"), context);
288 let aligned = v_flex()
289 .h_full()
290 .map(|aligned| match column.vertical_alignment {
291 VerticalAlignment::Top => aligned.justify_start(),
292 VerticalAlignment::Center => aligned.justify_center(),
293 VerticalAlignment::Bottom => aligned.justify_end(),
294 });
295 sized_column(aligned, column.width).child(content)
296 }))
297 .into_any_element()
298}
299
300fn sized_column(column: Div, width: ColumnWidth) -> Div {
301 match width {
302 ColumnWidth::Auto => column.flex_none(),
303 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
304 ColumnWidth::Weighted(weight) => column
305 .flex_basis(px(0.))
306 .flex_grow(weight.max(0.))
307 .min_w(px(0.)),
308 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
309 }
310}
311
312fn image_view(image: &CardImage, id: &str) -> AnyElement {
313 let width = match (image.width, image.height, named_image_width(image.size)) {
314 (Some(width), _, _) => width,
315 (None, Some(height), _) => height,
316 (None, None, Some(width)) => width,
317 (None, None, None) => MEDIUM_IMAGE,
318 }
319 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
320 let height = image.height.unwrap_or(width);
321 let radius = px(if image.person {
322 width.min(height) / 2.
323 } else {
324 IMAGE_RADIUS
325 });
326 let frame = div()
327 .id(ElementId::Name(id.to_owned().into()))
328 .w(px(width))
329 .h(px(height))
330 .max_w(relative(1.))
331 .flex_none()
332 .overflow_hidden()
333 .rounded(radius);
334 if !image.url.starts_with(EXTERNAL_IMAGE_SCHEME) {
335 return frame.bg(theme::surface_raised()).into_any_element();
336 }
337 frame
338 .child(
339 img(image.url.clone())
340 .size_full()
341 .rounded(radius)
342 .object_fit(ObjectFit::Cover)
343 .with_loading(move || image_placeholder(radius))
344 .with_fallback(move || image_placeholder(radius)),
345 )
346 .into_any_element()
347}
348
349fn image_placeholder(radius: Pixels) -> AnyElement {
350 div()
351 .size_full()
352 .rounded(radius)
353 .bg(theme::surface_raised())
354 .into_any_element()
355}
356
357fn named_image_width(size: ImageSize) -> Option<f32> {
358 match size {
359 ImageSize::Small => Some(SMALL_IMAGE),
360 ImageSize::Medium => Some(MEDIUM_IMAGE),
361 ImageSize::Large => Some(LARGE_IMAGE),
362 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
363 ImageSize::Auto => None,
364 }
365}
366
367fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {
368 let open_card = context
369 .state
370 .open_card(id)
371 .and_then(|index| actions.get(index))
372 .and_then(|action| match &action.kind {
373 CardActionKind::ShowCard(card) => Some(card),
374 _ => None,
375 });
376 v_flex()
377 .w_full()
378 .gap(px(ACTION_GAP))
379 .child(
380 h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
381 actions
382 .iter()
383 .enumerate()
384 .filter(|(_, action)| context.visible(action.id.as_ref(), action.visible))
385 .map(|(index, action)| action_button(action, index, id, context)),
386 ),
387 )
388 .when_some(open_card, |column, card| {
389 let nested_id = format!("{id}-show");
390 column.child(
391 v_flex()
392 .w_full()
393 .p(px(CONTAINER_PADDING))
394 .gap(px(ACTION_GAP))
395 .rounded(px(CONTAINER_RADIUS))
396 .bg(theme::surface_raised())
397 .child(items_view(&card.items, &nested_id, context))
398 .when(!card.actions.is_empty(), |nested| {
399 nested.child(actions_view(
400 &card.actions,
401 &format!("{nested_id}-actions"),
402 context,
403 ))
404 }),
405 )
406 })
407}
408
409fn action_button(
410 action: &CardAction,
411 index: usize,
412 actions_id: &str,
413 context: &CardContext,
414) -> Stateful<Div> {
415 let button_id = format!("{actions_id}-{index}");
416 let phase = context.state.phase(&button_id).cloned();
417 let label = action_label(
418 action,
419 &phase,
420 context.state.open_card(actions_id) == Some(index),
421 );
422 let button = div()
423 .id(ElementId::Name(button_id.clone().into()))
424 .px(px(12.))
425 .py(px(6.))
426 .rounded(px(ACTION_RADIUS))
427 .border_1()
428 .border_color(match phase {
429 Some(ActionPhase::Failed(_)) => theme::red(),
430 _ => theme::border_strong(),
431 })
432 .text_size(px(ACTION_TEXT_SIZE))
433 .font_weight(FontWeight::SEMIBOLD)
434 .child(label);
435 if !action.is_clickable() {
436 return button
437 .text_color(theme::text_muted())
438 .opacity(ACTION_DISABLED_OPACITY)
439 .when(action.enabled, |button| {
440 button.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
441 })
442 .on_click(|_, _, cx| cx.stop_propagation());
443 }
444 let enabled = button.text_color(theme::accent_text());
445 if phase == Some(ActionPhase::Busy) {
446 return enabled
447 .opacity(ACTION_BUSY_OPACITY)
448 .on_click(|_, _, cx| cx.stop_propagation());
449 }
450 let enabled = enabled
451 .cursor_pointer()
452 .hover(|button| button.bg(theme::row_hover()))
453 .when_some(failure_reason(&phase), |button, reason| {
454 button.tooltip(move |window, cx| Tooltip::new(reason.clone()).build(window, cx))
455 });
456 let scope = context.scope.clone();
457 match &action.kind {
458 CardActionKind::OpenUrl(url) => {
459 let url = url.clone();
460 enabled.on_click(move |_, _, cx| {
461 cx.stop_propagation();
462 cx.open_url(&url);
463 })
464 }
465 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
466 let action = action.clone();
467 enabled.on_click(move |_, _, cx| {
468 cx.stop_propagation();
469 let (scope, action, button_id) = (scope.clone(), action.clone(), button_id.clone());
470 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
471 state.run_card_action(scope, button_id, action, cx)
472 });
473 })
474 }
475 CardActionKind::ShowCard(_) => {
476 let actions_id = actions_id.to_owned();
477 enabled.on_click(move |_, _, cx| {
478 cx.stop_propagation();
479 let (scope, actions_id) = (scope.clone(), actions_id.clone());
480 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
481 state.toggle_show_card(&scope, &actions_id, index, cx)
482 });
483 })
484 }
485 CardActionKind::ToggleVisibility(targets) => {
486 let elements: Vec<(String, bool, Option<bool>)> = targets
487 .iter()
488 .map(|target| {
489 let initial = context
490 .initial_visibility
491 .get(&target.element_id)
492 .copied()
493 .unwrap_or(true);
494 (target.element_id.clone(), initial, target.visible)
495 })
496 .collect();
497 let root_key = context.root_key.clone();
498 enabled.on_click(move |_, _, cx| {
499 cx.stop_propagation();
500 let (scope, root_key, elements) =
501 (scope.clone(), root_key.clone(), elements.clone());
502 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
503 state.toggle_card_elements(&scope, &root_key, elements, cx)
504 });
505 })
506 }
507 CardActionKind::Unsupported => enabled,
508 }
509}
510
511fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {
512 match phase {
513 Some(ActionPhase::Failed(reason)) => Some(reason.clone()),
514 _ => None,
515 }
516}
517
518fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {
519 match phase {
520 Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),
521 Some(ActionPhase::Done) => h_flex()
522 .gap(px(ACTION_ICON_GAP))
523 .items_center()
524 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
525 .child(action.title.clone())
526 .into_any_element(),
527 _ if open => format!("{} ^", action.title).into_any_element(),
528 _ => action.title.clone().into_any_element(),
529 }
530}