BlueGit

ict rusty-teams

Files

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

adaptive_card.rs

adaptive_card.rs 33.5 KiB Download Raw
1use crate::views::image_memory::bounded;
2use std::collections::HashMap;
3use std::rc::Rc;
4
5use gpui_kit::component::tooltip::{PopupTriggerTooltip as _, Tooltip};
6use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{
10 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
11 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerLayout, ContainerStyle,
12 HorizontalAlignment, ImageSize, TextColor, TextSize, VerticalAlignment, WidthClass,
13 split_overflow,
14};
15
16use super::card_carousel::carousel_view;
17use super::card_chart::chart_view;
18use super::card_code_block::code_block_view;
19use super::card_icon::{action_icon_view, icon_view};
20use super::card_input::{input_view, rating_display_view};
21use super::card_media::media_view;
22use super::card_table::table_view;
23use super::card_widgets::{
24 badge_view, compound_button_view, leading, progress_bar_view, progress_ring_view,
25};
26use super::widgets::symbol;
27use crate::app_state::{AppHandle, AppState};
28use crate::card_state::{ActionPhase, CardScope, CardState};
29use crate::render::{layout_card_blocks, render_blocks};
30use crate::theme;
31
32const CARD_WIDTH: f32 = 480.;
33const CARD_FULL_WIDTH: f32 = 720.;
34const CARD_PADDING: f32 = 12.;
35const CARD_RADIUS: f32 = 10.;
36const CARD_BORDER_WIDTH: f32 = 1.;
37const COLUMN_GAP: f32 = 8.;
38const SEPARATOR_PADDING: f32 = 8.;
39const ACTION_GAP: f32 = 8.;
40const ACTION_RADIUS: f32 = 6.;
41const ACTION_TEXT_SIZE: f32 = 13.;
42const ACTION_DISABLED_OPACITY: f32 = 0.5;
43const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
44const ACTION_BUSY_OPACITY: f32 = 0.6;
45const ACTION_CHECK_SIZE: f32 = 14.;
46const ACTION_ICON_GAP: f32 = 4.;
47const NOTE_TEXT_SIZE: f32 = 12.;
48const FACT_TITLE_WIDTH: f32 = 96.;
49const FACT_GAP: f32 = 2.;
50const CONTAINER_PADDING: f32 = 8.;
51const CONTAINER_RADIUS: f32 = 6.;
52const CONTAINER_TINT: f32 = 0.16;
53const TEXT_LINE_HEIGHT: f32 = 1.35;
54const IMAGE_RADIUS: f32 = 4.;
55const IMAGE_SET_GAP: f32 = 6.;
56const SMALL_IMAGE: f32 = 40.;
57const MEDIUM_IMAGE: f32 = 80.;
58const LARGE_IMAGE: f32 = 160.;
59const EXTERNAL_IMAGE_SCHEMES: [&str; 2] = ["https://", "http://"];
60const ACTION_OVERFLOW_LABEL: &str = "...";
61const ACTION_OVERFLOW_TOOLTIP: &str = "More actions";
62const OVERFLOW_PANEL_PADDING: f32 = 4.;
63const SELECT_TINT: f32 = 0.07;
64
65pub(super) type ClickHandler = Rc<dyn Fn(&mut App)>;
66
67pub(super) struct CardContext<'a> {
68 pub(super) cx: &'a App,
69 pub(super) scope: &'a CardScope,
70 pub(super) state: &'a CardState,
71 root_key: String,
72 initial_visibility: Rc<HashMap<String, bool>>,
73 inputs: Vec<CardInput>,
74 width_class: WidthClass,
75}
76
77impl<'a> CardContext<'a> {
78 fn new(card: &AdaptiveCard, scope: &'a CardScope, cx: &'a App) -> Self {
79 CardContext {
80 cx,
81 scope,
82 state: &cx.global::<AppHandle>().0.read(cx).cards,
83 root_key: scope.card_key(),
84 initial_visibility: Rc::new(card.element_visibility()),
85 inputs: card.own_inputs(),
86 width_class: WidthClass::from_pixels(card_width(card)),
87 }
88 }
89
90 fn nested(&self, card: &AdaptiveCard) -> CardContext<'a> {
91 let mut inputs = self.inputs.clone();
92 inputs.extend(card.own_inputs());
93 CardContext {
94 cx: self.cx,
95 scope: self.scope,
96 state: self.state,
97 root_key: self.root_key.clone(),
98 initial_visibility: self.initial_visibility.clone(),
99 inputs,
100 width_class: self.width_class,
101 }
102 }
103
104 pub(super) fn visible(&self, id: Option<&String>, initial: bool) -> bool {
105 match id {
106 Some(id) => self
107 .state
108 .is_visible(&format!("{}/{id}", self.root_key), initial),
109 None => initial,
110 }
111 }
112}
113
114pub fn cards_view(
115 cards: &[AdaptiveCard],
116 conversation_id: &str,
117 message_id: &str,
118 cx: &App,
119) -> Vec<AnyElement> {
120 cards
121 .iter()
122 .enumerate()
123 .map(|(index, card)| {
124 let scope = CardScope::message(conversation_id, message_id, index);
125 card_view(card, &scope, cx)
126 })
127 .collect()
128}
129
130pub fn ensure_cards_inputs(
131 app: &Entity<AppState>,
132 cards: &[AdaptiveCard],
133 conversation_id: &str,
134 message_id: &str,
135 window: &mut Window,
136 cx: &mut App,
137) {
138 if cards.is_empty() {
139 return;
140 }
141 app.update(cx, |state, cx| {
142 for (index, card) in cards.iter().enumerate() {
143 let scope = CardScope::message(conversation_id, message_id, index);
144 state.ensure_card_inputs(&scope, card, window, cx);
145 }
146 });
147}
148
149pub fn request_card_refreshes(
150 app: &Entity<AppState>,
151 cards: &[AdaptiveCard],
152 conversation_id: &str,
153 message_id: &str,
154 cx: &mut App,
155) {
156 if cards.iter().all(|card| card.refresh.is_none()) {
157 return;
158 }
159 app.update(cx, |state, cx| {
160 state.request_card_refreshes(conversation_id, message_id, cards, cx)
161 });
162}
163
164pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
165 let context = CardContext::new(card, scope, cx);
166 let id = scope.card_key();
167 let note = context.state.note(&id).map(str::to_owned);
168 let select_handler = card
169 .select_action
170 .as_ref()
171 .filter(|action| action.is_clickable())
172 .and_then(|action| click_handler(action, &format!("{id}-select"), None, &context));
173 let visible_actions = card
174 .actions
175 .iter()
176 .any(|action| context.visible(action.id.as_ref(), action.visible));
177 v_flex()
178 .id(ElementId::Name(format!("{id}-root").into()))
179 .relative()
180 .w(px(card_width(card)))
181 .max_w(relative(1.))
182 .p(px(CARD_PADDING))
183 .rounded(px(CARD_RADIUS))
184 .bg(theme::surface())
185 .border(px(CARD_BORDER_WIDTH))
186 .border_color(theme::border())
187 .text_color(theme::text_strong())
188 .when_some(select_handler, |root, handler| {
189 root.cursor_pointer()
190 .hover(|root| root.bg(theme::row_hover()))
191 .on_click(move |_, _, cx| {
192 cx.stop_propagation();
193 handler(cx)
194 })
195 })
196 .when_some(card.layout.background_image.clone(), |root, url| {
197 root.child(background_layer(&url, CARD_RADIUS))
198 })
199 .child(aligned_body(&card.items, &id, &context, &card.layout, true))
200 .when(visible_actions, |card_element| {
201 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
202 actions_view(&card.actions, &format!("{id}-actions"), &context),
203 ))
204 })
205 .when_some(note, |card_element, note| {
206 card_element.child(
207 div()
208 .mt(px(spacing_pixels(CardSpacing::Default)))
209 .text_size(px(NOTE_TEXT_SIZE))
210 .text_color(theme::text_muted())
211 .child(note),
212 )
213 })
214 .into_any_element()
215}
216
217fn card_width(card: &AdaptiveCard) -> f32 {
218 if card.full_width {
219 CARD_FULL_WIDTH
220 } else {
221 CARD_WIDTH
222 }
223}
224
225fn background_layer(url: &str, radius: f32) -> AnyElement {
226 div()
227 .absolute()
228 .inset_0()
229 .rounded(px(radius))
230 .overflow_hidden()
231 .child(
232 img(bounded(url.to_owned()))
233 .size_full()
234 .object_fit(ObjectFit::Cover)
235 .with_loading(|| div().into_any_element())
236 .with_fallback(|| div().into_any_element()),
237 )
238 .into_any_element()
239}
240
241fn aligned_body(
242 items: &[CardItem],
243 id: &str,
244 context: &CardContext,
245 layout: &ContainerLayout,
246 top_level: bool,
247) -> Div {
248 items_view(items, id, context, top_level)
249 .when_some(layout.min_height, |body, height| body.min_h(px(height)))
250 .map(|body| match layout.vertical_alignment {
251 VerticalAlignment::Top => body.justify_start(),
252 VerticalAlignment::Center => body.justify_center(),
253 VerticalAlignment::Bottom => body.justify_end(),
254 })
255 .when(layout.rtl, |body| body.text_right())
256}
257
258pub(super) fn items_view(
259 items: &[CardItem],
260 id: &str,
261 context: &CardContext,
262 top_level: bool,
263) -> Div {
264 let shown: Vec<(usize, &CardItem)> = items
265 .iter()
266 .enumerate()
267 .filter(|(_, item)| {
268 context.visible(item.id.as_ref(), item.visible)
269 && item
270 .target_width
271 .is_none_or(|target| target.matches(context.width_class))
272 })
273 .collect();
274 let mut column = v_flex().w_full();
275 for (position, (index, item)) in shown.iter().enumerate() {
276 let item_id = format!("{id}-{index}");
277 let first = position == 0;
278 let bleed = top_level
279 .then(|| bleed_edges(item, first, position + 1 == shown.len()))
280 .flatten();
281 column = column.child(
282 div()
283 .map(|wrapper| match bleed {
284 Some(edges) => wrapper
285 .mx(px(-CARD_PADDING))
286 .when(edges.top, |wrapper| wrapper.mt(px(-CARD_PADDING)))
287 .when(edges.bottom, |wrapper| wrapper.mb(px(-CARD_PADDING))),
288 None => wrapper.w_full(),
289 })
290 .when(item.stretch, |wrapper| wrapper.flex_grow(1.))
291 .when(!first && bleed.is_none_or(|edges| !edges.top), |wrapper| {
292 wrapper.mt(px(spacing_pixels(item.spacing)))
293 })
294 .when(!first && item.separator, |wrapper| {
295 wrapper
296 .pt(px(SEPARATOR_PADDING))
297 .border_t_1()
298 .border_color(theme::border())
299 })
300 .child(element_view(&item.element, &item_id, context, bleed)),
301 );
302 }
303 column
304}
305
306#[derive(Clone, Copy)]
307pub(super) struct BleedEdges {
308 top: bool,
309 bottom: bool,
310}
311
312fn bleed_edges(item: &CardItem, first: bool, last: bool) -> Option<BleedEdges> {
313 match &item.element {
314 CardElement::Container { layout, .. } if layout.bleed => Some(BleedEdges {
315 top: first,
316 bottom: last,
317 }),
318 _ => None,
319 }
320}
321
322fn spacing_pixels(spacing: CardSpacing) -> f32 {
323 match spacing {
324 CardSpacing::None => 0.,
325 CardSpacing::Small => 4.,
326 CardSpacing::Default => 8.,
327 CardSpacing::Medium => 12.,
328 CardSpacing::Large | CardSpacing::Padding => 16.,
329 CardSpacing::ExtraLarge => 24.,
330 }
331}
332
333fn element_view(
334 element: &CardElement,
335 id: &str,
336 context: &CardContext,
337 bleed: Option<BleedEdges>,
338) -> AnyElement {
339 match element {
340 CardElement::Text(text) => text_view(text, id, context.cx),
341 CardElement::Image(image) => aligned_image(image, id, context),
342 CardElement::ImageSet(images) => {
343 h_flex()
344 .flex_wrap()
345 .gap(px(IMAGE_SET_GAP))
346 .children(images.iter().enumerate().map(|(index, image)| {
347 selectable_image(image, &format!("{id}-{index}"), context)
348 }))
349 .into_any_element()
350 }
351 CardElement::Columns { columns, layout } => columns_view(columns, layout, id, context),
352 CardElement::Container {
353 layout,
354 items,
355 select_action,
356 } => selectable(
357 container_view(items, id, context, layout, bleed).into_any_element(),
358 select_action.as_ref(),
359 id,
360 false,
361 context,
362 ),
363 CardElement::Facts(facts) => facts_view(facts, id, context.cx),
364 CardElement::Media(media) => media_view(media, id),
365 CardElement::Icon(icon) => selectable(
366 icon_view(icon),
367 icon.select_action.as_ref(),
368 id,
369 true,
370 context,
371 ),
372 CardElement::Table(table) => table_view(table, id, context),
373 CardElement::CodeBlock(block) => code_block_view(block, id, context),
374 CardElement::Badge(badge) => leading(badge_view(badge, id)),
375 CardElement::ProgressBar(bar) => progress_bar_view(bar, id),
376 CardElement::ProgressRing(ring) => leading(progress_ring_view(ring, id)),
377 CardElement::CompoundButton(button) => compound_button_view(button, id, context),
378 CardElement::Carousel(carousel) => carousel_view(carousel, id, context),
379 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
380 CardElement::Input(input) => {
381 input_view(input, context.scope, context.state, &context.inputs)
382 }
383 CardElement::Rating(display) => rating_display_view(display),
384 CardElement::Chart(chart) => chart_view(chart),
385 }
386}
387
388pub(super) fn container_view(
389 items: &[CardItem],
390 id: &str,
391 context: &CardContext,
392 layout: &ContainerLayout,
393 bleed: Option<BleedEdges>,
394) -> Div {
395 let tint = container_tint(layout.style);
396 let padded = tint.is_some() || layout.background_image.is_some();
397 let inset = |edge: bool| {
398 if edge {
399 CARD_PADDING
400 } else if padded {
401 CONTAINER_PADDING
402 } else {
403 0.
404 }
405 };
406 v_flex()
407 .w_full()
408 .relative()
409 .map(|container| match bleed {
410 Some(edges) => container
411 .px(px(CARD_PADDING))
412 .pt(px(inset(edges.top)))
413 .pb(px(inset(edges.bottom)))
414 .when(edges.top, |container| {
415 container.rounded_t(px(CARD_RADIUS - CARD_BORDER_WIDTH))
416 })
417 .when(edges.bottom, |container| {
418 container.rounded_b(px(CARD_RADIUS - CARD_BORDER_WIDTH))
419 }),
420 None => container.when(padded, |container| {
421 container
422 .p(px(CONTAINER_PADDING))
423 .rounded(px(CONTAINER_RADIUS))
424 }),
425 })
426 .when_some(tint, |container, tint| container.bg(tint))
427 .when_some(layout.background_image.clone(), |container, url| {
428 container.child(background_layer(&url, CONTAINER_RADIUS))
429 })
430 .child(aligned_body(items, id, context, layout, false))
431}
432
433pub(super) fn container_tint(style: ContainerStyle) -> Option<Hsla> {
434 match style {
435 ContainerStyle::Default => None,
436 ContainerStyle::Emphasis => Some(theme::surface_raised()),
437 ContainerStyle::Accent => Some(theme::accent().opacity(CONTAINER_TINT)),
438 ContainerStyle::Good => Some(theme::green().opacity(CONTAINER_TINT)),
439 ContainerStyle::Warning => Some(theme::amber().opacity(CONTAINER_TINT)),
440 ContainerStyle::Attention => Some(theme::red().opacity(CONTAINER_TINT)),
441 }
442}
443
444fn text_size(size: TextSize) -> f32 {
445 match size {
446 TextSize::Small => 11.5,
447 TextSize::Default => 13.5,
448 TextSize::Medium => 15.,
449 TextSize::Large => 17.5,
450 TextSize::ExtraLarge => 21.,
451 }
452}
453
454fn text_color(text: &CardText) -> Hsla {
455 card_color(text.color, text.subtle)
456}
457
458pub(super) fn card_color(color: TextColor, subtle: bool) -> Hsla {
459 match color {
460 TextColor::Accent => theme::accent_text(),
461 TextColor::Good => theme::green(),
462 TextColor::Warning => theme::amber(),
463 TextColor::Attention => theme::red_soft(),
464 TextColor::Default | TextColor::Dark | TextColor::Light if subtle => theme::text_muted(),
465 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
466 }
467}
468
469fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
470 div()
471 .w_full()
472 .min_w(px(0.))
473 .text_size(px(text_size(text.size)))
474 .line_height(relative(TEXT_LINE_HEIGHT))
475 .text_color(text_color(text))
476 .when(text.bold, |element| {
477 element.font_weight(FontWeight::SEMIBOLD)
478 })
479 .when(text.monospace, |element| {
480 element.font_family(cx.theme().mono_font_family.clone())
481 })
482 .map(|element| match text.alignment {
483 Some(HorizontalAlignment::Left) => element.text_left(),
484 Some(HorizontalAlignment::Center) => element.text_center(),
485 Some(HorizontalAlignment::Right) => element.text_right(),
486 None => element,
487 })
488 .map(|element| match (text.wrap, text.max_lines) {
489 (false, _) => element
490 .whitespace_nowrap()
491 .overflow_hidden()
492 .text_ellipsis(),
493 (true, Some(lines)) => element.text_ellipsis().line_clamp(lines),
494 (true, None) => element,
495 })
496 .child(render_blocks(&layout_card_blocks(&text.spans), id, false, cx))
497 .into_any_element()
498}
499
500fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
501 v_flex()
502 .w_full()
503 .gap(px(FACT_GAP))
504 .children(facts.iter().enumerate().map(|(index, fact)| {
505 h_flex()
506 .w_full()
507 .items_start()
508 .gap(px(COLUMN_GAP))
509 .text_size(px(text_size(TextSize::Default)))
510 .line_height(relative(TEXT_LINE_HEIGHT))
511 .child(
512 div()
513 .w(px(FACT_TITLE_WIDTH))
514 .flex_none()
515 .font_weight(FontWeight::SEMIBOLD)
516 .text_color(theme::text_muted())
517 .child(fact.title.clone()),
518 )
519 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
520 &layout_card_blocks(&fact.value),
521 &format!("{id}-{index}"),
522 false,
523 cx,
524 )))
525 }))
526 .into_any_element()
527}
528
529fn columns_view(
530 columns: &[CardColumn],
531 layout: &ContainerLayout,
532 id: &str,
533 context: &CardContext,
534) -> AnyElement {
535 let tint = container_tint(layout.style);
536 div()
537 .flex()
538 .map(|row| {
539 if layout.rtl {
540 row.flex_row_reverse()
541 } else {
542 row.flex_row()
543 }
544 })
545 .items_stretch()
546 .w_full()
547 .gap(px(COLUMN_GAP))
548 .when_some(layout.min_height, |row, height| row.min_h(px(height)))
549 .when_some(tint, |row, tint| {
550 row.p(px(CONTAINER_PADDING))
551 .rounded(px(CONTAINER_RADIUS))
552 .bg(tint)
553 })
554 .children(
555 columns
556 .iter()
557 .enumerate()
558 .filter(|(_, column)| {
559 column
560 .target_width
561 .is_none_or(|target| target.matches(context.width_class))
562 })
563 .map(|(index, column)| {
564 let content = container_view(
565 &column.items,
566 &format!("{id}-{index}"),
567 context,
568 &column.layout,
569 None,
570 );
571 let content = selectable(
572 content.into_any_element(),
573 column.select_action.as_ref(),
574 &format!("{id}-{index}"),
575 false,
576 context,
577 );
578 let aligned =
579 v_flex()
580 .h_full()
581 .map(|aligned| match column.layout.vertical_alignment {
582 VerticalAlignment::Top => aligned.justify_start(),
583 VerticalAlignment::Center => aligned.justify_center(),
584 VerticalAlignment::Bottom => aligned.justify_end(),
585 });
586 sized_column(aligned, column.width).child(content)
587 }),
588 )
589 .into_any_element()
590}
591
592pub(super) fn sized_column(column: Div, width: ColumnWidth) -> Div {
593 match width {
594 ColumnWidth::Auto => column.flex_none(),
595 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
596 ColumnWidth::Weighted(weight) => column
597 .flex_basis(px(0.))
598 .flex_grow(weight.max(0.))
599 .min_w(px(0.)),
600 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
601 }
602}
603
604fn aligned_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
605 h_flex()
606 .w_full()
607 .map(|row| match image.alignment {
608 HorizontalAlignment::Left => row.justify_start(),
609 HorizontalAlignment::Center => row.justify_center(),
610 HorizontalAlignment::Right => row.justify_end(),
611 })
612 .child(selectable_image(image, id, context))
613 .into_any_element()
614}
615
616fn selectable_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
617 selectable(
618 image_view(image, id),
619 image.select_action.as_ref(),
620 id,
621 true,
622 context,
623 )
624}
625
626pub(super) fn selectable(
627 content: AnyElement,
628 select_action: Option<&CardAction>,
629 id: &str,
630 fit: bool,
631 context: &CardContext,
632) -> AnyElement {
633 let select_key = format!("{id}-select");
634 let Some(handler) = select_action
635 .filter(|action| action.is_clickable())
636 .and_then(|action| click_handler(action, &select_key, None, context))
637 else {
638 return content;
639 };
640 let group = SharedString::from(select_key.clone());
641 div()
642 .id(ElementId::Name(select_key.into()))
643 .group(group.clone())
644 .relative()
645 .cursor_pointer()
646 .map(|wrapper| {
647 if fit {
648 wrapper.self_start().flex_none()
649 } else {
650 wrapper.w_full()
651 }
652 })
653 .on_click(move |_, _, cx| {
654 cx.stop_propagation();
655 handler(cx)
656 })
657 .child(content)
658 .child(
659 div()
660 .absolute()
661 .inset_0()
662 .rounded(px(CONTAINER_RADIUS))
663 .group_hover(group, |tint| tint.bg(white().opacity(SELECT_TINT))),
664 )
665 .into_any_element()
666}
667
668fn image_view(image: &CardImage, id: &str) -> AnyElement {
669 let width = match (image.width, image.height, named_image_width(image.size)) {
670 (Some(width), _, _) => width,
671 (None, Some(height), _) => height,
672 (None, None, Some(width)) => width,
673 (None, None, None) => MEDIUM_IMAGE,
674 }
675 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
676 let height = image.height.unwrap_or(width);
677 let radius = px(if image.person {
678 width.min(height) / 2.
679 } else {
680 IMAGE_RADIUS
681 });
682 let frame = div()
683 .id(ElementId::Name(id.to_owned().into()))
684 .w(px(width))
685 .h(px(height))
686 .max_w(relative(1.))
687 .flex_none()
688 .overflow_hidden()
689 .rounded(radius);
690 if !EXTERNAL_IMAGE_SCHEMES
691 .iter()
692 .any(|scheme| image.url.starts_with(scheme))
693 {
694 return frame.bg(theme::surface_raised()).into_any_element();
695 }
696 let alt_text = image.alt_text.clone();
697 frame
698 .when_some(image.background_color, |frame, color| frame.bg(rgba(color)))
699 .when_some(alt_text, |frame, alt_text| {
700 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
701 })
702 .child(
703 img(bounded(image.url.clone()))
704 .size_full()
705 .rounded(radius)
706 .object_fit(ObjectFit::Cover)
707 .with_loading(move || image_placeholder(radius))
708 .with_fallback(move || image_placeholder(radius)),
709 )
710 .into_any_element()
711}
712
713fn image_placeholder(radius: Pixels) -> AnyElement {
714 div()
715 .size_full()
716 .rounded(radius)
717 .bg(theme::surface_raised())
718 .into_any_element()
719}
720
721fn named_image_width(size: ImageSize) -> Option<f32> {
722 match size {
723 ImageSize::Small => Some(SMALL_IMAGE),
724 ImageSize::Medium => Some(MEDIUM_IMAGE),
725 ImageSize::Large => Some(LARGE_IMAGE),
726 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
727 ImageSize::Auto => None,
728 }
729}
730
731fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {
732 let open_card = context
733 .state
734 .open_card(id)
735 .and_then(|index| actions.get(index))
736 .and_then(|action| match &action.kind {
737 CardActionKind::ShowCard(card) => Some(card),
738 _ => None,
739 });
740 let split = split_overflow(actions, |action| {
741 context.visible(action.id.as_ref(), action.visible)
742 });
743 let overflow_key = format!("{id}-overflow");
744 let overflow_open = !split.overflow.is_empty() && context.state.slot(&overflow_key, 0) == 1;
745 v_flex()
746 .w_full()
747 .gap(px(ACTION_GAP))
748 .child(
749 h_flex()
750 .w_full()
751 .flex_wrap()
752 .gap(px(ACTION_GAP))
753 .children(
754 split
755 .primary
756 .iter()
757 .map(|&index| action_button(&actions[index], index, id, context)),
758 )
759 .when(!split.overflow.is_empty(), |row| {
760 row.child(overflow_button(&overflow_key, overflow_open, context))
761 }),
762 )
763 .when(overflow_open, |column| {
764 column.child(
765 v_flex()
766 .self_start()
767 .items_start()
768 .gap(px(OVERFLOW_PANEL_PADDING))
769 .p(px(OVERFLOW_PANEL_PADDING))
770 .rounded(px(CONTAINER_RADIUS))
771 .bg(theme::surface_raised())
772 .children(
773 split
774 .overflow
775 .iter()
776 .map(|&index| action_button(&actions[index], index, id, context)),
777 ),
778 )
779 })
780 .when_some(open_card, |column, card| {
781 let nested_id = format!("{id}-show");
782 let nested_context = context.nested(card);
783 column.child(
784 v_flex()
785 .w_full()
786 .p(px(CONTAINER_PADDING))
787 .gap(px(ACTION_GAP))
788 .rounded(px(CONTAINER_RADIUS))
789 .bg(theme::surface_raised())
790 .child(items_view(&card.items, &nested_id, &nested_context, false))
791 .when(!card.actions.is_empty(), |nested| {
792 nested.child(actions_view(
793 &card.actions,
794 &format!("{nested_id}-actions"),
795 &nested_context,
796 ))
797 }),
798 )
799 })
800}
801
802fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Stateful<Div> {
803 let handler = slot_handler(context, overflow_key, usize::from(!open));
804 action_frame(overflow_key, theme::border_strong())
805 .text_color(theme::accent_text())
806 .cursor_pointer()
807 .hover(|button| button.bg(theme::row_hover()))
808 .when(open, |button| button.bg(theme::row_hover()))
809 .popup_trigger_tooltip_text(open, ACTION_OVERFLOW_TOOLTIP)
810 .child(ACTION_OVERFLOW_LABEL)
811 .on_click(move |_, _, cx| {
812 cx.stop_propagation();
813 handler(cx)
814 })
815}
816
817fn action_frame(button_id: &str, border: Hsla) -> Stateful<Div> {
818 div()
819 .id(ElementId::Name(button_id.to_owned().into()))
820 .px(px(12.))
821 .py(px(6.))
822 .rounded(px(ACTION_RADIUS))
823 .border_1()
824 .border_color(border)
825 .text_size(px(ACTION_TEXT_SIZE))
826 .font_weight(FontWeight::SEMIBOLD)
827}
828
829pub(super) fn slot_handler(context: &CardContext, slot_key: &str, value: usize) -> ClickHandler {
830 let scope = context.scope.clone();
831 let slot_key = slot_key.to_owned();
832 Rc::new(move |cx| {
833 let (scope, slot_key) = (scope.clone(), slot_key.clone());
834 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
835 state.set_card_slot(&scope, &slot_key, value, cx)
836 });
837 })
838}
839
840fn action_button(
841 action: &CardAction,
842 index: usize,
843 actions_id: &str,
844 context: &CardContext,
845) -> Stateful<Div> {
846 let button_id = format!("{actions_id}-{index}");
847 let phase = context.state.phase(&button_id).cloned();
848 let label = action_label(
849 action,
850 &phase,
851 context.state.open_card(actions_id) == Some(index),
852 );
853 let border = match phase {
854 Some(ActionPhase::Failed(_)) => theme::red(),
855 _ => theme::border_strong(),
856 };
857 let button = action_frame(&button_id, border).child(label);
858 if !action.is_clickable() {
859 let hint = match action.kind {
860 CardActionKind::Unavailable(reason) if action.enabled => Some(reason.to_owned()),
861 _ if action.enabled => Some(ACTION_DISABLED_TOOLTIP.to_owned()),
862 _ => action.tooltip.clone(),
863 };
864 return button
865 .text_color(theme::text_muted())
866 .opacity(ACTION_DISABLED_OPACITY)
867 .when_some(hint, |button, hint| {
868 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
869 })
870 .on_click(|_, _, cx| cx.stop_propagation());
871 }
872 let enabled = button.text_color(theme::accent_text());
873 if phase == Some(ActionPhase::Busy) {
874 return enabled
875 .opacity(ACTION_BUSY_OPACITY)
876 .on_click(|_, _, cx| cx.stop_propagation());
877 }
878 let hint = failure_reason(&phase).or_else(|| action.tooltip.clone());
879 let enabled = enabled
880 .cursor_pointer()
881 .hover(|button| button.bg(theme::row_hover()))
882 .when_some(hint, |button, hint| {
883 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
884 });
885 match click_handler(action, &button_id, Some((actions_id, index)), context) {
886 Some(handler) => enabled.on_click(move |_, _, cx| {
887 cx.stop_propagation();
888 handler(cx)
889 }),
890 None => enabled,
891 }
892}
893
894fn click_handler(
895 action: &CardAction,
896 action_key: &str,
897 show_card: Option<(&str, usize)>,
898 context: &CardContext,
899) -> Option<ClickHandler> {
900 let scope = context.scope.clone();
901 match &action.kind {
902 CardActionKind::OpenUrl(url) => {
903 let url = url.clone();
904 Some(Rc::new(move |cx| cx.open_url(&url)))
905 }
906 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
907 let action = action.clone();
908 let action_key = action_key.to_owned();
909 let inputs = context.inputs.clone();
910 Some(Rc::new(move |cx| {
911 let (scope, action, action_key, inputs) = (
912 scope.clone(),
913 action.clone(),
914 action_key.clone(),
915 inputs.clone(),
916 );
917 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
918 state.run_card_action(scope, action_key, action, inputs, cx)
919 });
920 }))
921 }
922 CardActionKind::ShowCard(_) => {
923 let (actions_id, index) = show_card?;
924 let actions_id = actions_id.to_owned();
925 Some(Rc::new(move |cx| {
926 let (scope, actions_id) = (scope.clone(), actions_id.clone());
927 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
928 state.toggle_show_card(&scope, &actions_id, index, cx)
929 });
930 }))
931 }
932 CardActionKind::ToggleVisibility(targets) => {
933 let elements: Vec<(String, bool, Option<bool>)> = targets
934 .iter()
935 .map(|target| {
936 let initial = context
937 .initial_visibility
938 .get(&target.element_id)
939 .copied()
940 .unwrap_or(true);
941 (target.element_id.clone(), initial, target.visible)
942 })
943 .collect();
944 let root_key = context.root_key.clone();
945 Some(Rc::new(move |cx| {
946 let (scope, root_key, elements) =
947 (scope.clone(), root_key.clone(), elements.clone());
948 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
949 state.toggle_card_elements(&scope, &root_key, elements, cx)
950 });
951 }))
952 }
953 CardActionKind::Unavailable(_) | CardActionKind::Unsupported => None,
954 }
955}
956
957fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {
958 match phase {
959 Some(ActionPhase::Failed(reason)) => Some(reason.clone()),
960 _ => None,
961 }
962}
963
964fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {
965 match phase {
966 Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),
967 Some(ActionPhase::Done) => h_flex()
968 .gap(px(ACTION_ICON_GAP))
969 .items_center()
970 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
971 .child(action.title.clone())
972 .into_any_element(),
973 _ if open => titled(action, format!("{} ^", action.title)),
974 _ => titled(action, action.title.clone()),
975 }
976}
977
978fn titled(action: &CardAction, text: String) -> AnyElement {
979 match action.icon.as_ref().map(action_icon_view) {
980 Some(icon) => h_flex()
981 .gap(px(ACTION_ICON_GAP))
982 .items_center()
983 .child(icon)
984 .child(text)
985 .into_any_element(),
986 None => text.into_any_element(),
987 }
988}