BlueGit

ict rusty-teams

Files

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

adaptive_card.rs

adaptive_card.rs 33.6 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(
497 &layout_card_blocks(&text.spans),
498 id,
499 false,
500 cx,
501 ))
502 .into_any_element()
503}
504
505fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
506 v_flex()
507 .w_full()
508 .gap(px(FACT_GAP))
509 .children(facts.iter().enumerate().map(|(index, fact)| {
510 h_flex()
511 .w_full()
512 .items_start()
513 .gap(px(COLUMN_GAP))
514 .text_size(px(text_size(TextSize::Default)))
515 .line_height(relative(TEXT_LINE_HEIGHT))
516 .child(
517 div()
518 .w(px(FACT_TITLE_WIDTH))
519 .flex_none()
520 .font_weight(FontWeight::SEMIBOLD)
521 .text_color(theme::text_muted())
522 .child(fact.title.clone()),
523 )
524 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
525 &layout_card_blocks(&fact.value),
526 &format!("{id}-{index}"),
527 false,
528 cx,
529 )))
530 }))
531 .into_any_element()
532}
533
534fn columns_view(
535 columns: &[CardColumn],
536 layout: &ContainerLayout,
537 id: &str,
538 context: &CardContext,
539) -> AnyElement {
540 let tint = container_tint(layout.style);
541 div()
542 .flex()
543 .map(|row| {
544 if layout.rtl {
545 row.flex_row_reverse()
546 } else {
547 row.flex_row()
548 }
549 })
550 .items_stretch()
551 .w_full()
552 .gap(px(COLUMN_GAP))
553 .when_some(layout.min_height, |row, height| row.min_h(px(height)))
554 .when_some(tint, |row, tint| {
555 row.p(px(CONTAINER_PADDING))
556 .rounded(px(CONTAINER_RADIUS))
557 .bg(tint)
558 })
559 .children(
560 columns
561 .iter()
562 .enumerate()
563 .filter(|(_, column)| {
564 column
565 .target_width
566 .is_none_or(|target| target.matches(context.width_class))
567 })
568 .map(|(index, column)| {
569 let content = container_view(
570 &column.items,
571 &format!("{id}-{index}"),
572 context,
573 &column.layout,
574 None,
575 );
576 let content = selectable(
577 content.into_any_element(),
578 column.select_action.as_ref(),
579 &format!("{id}-{index}"),
580 false,
581 context,
582 );
583 let aligned =
584 v_flex()
585 .h_full()
586 .map(|aligned| match column.layout.vertical_alignment {
587 VerticalAlignment::Top => aligned.justify_start(),
588 VerticalAlignment::Center => aligned.justify_center(),
589 VerticalAlignment::Bottom => aligned.justify_end(),
590 });
591 sized_column(aligned, column.width).child(content)
592 }),
593 )
594 .into_any_element()
595}
596
597pub(super) fn sized_column(column: Div, width: ColumnWidth) -> Div {
598 match width {
599 ColumnWidth::Auto => column.flex_none(),
600 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
601 ColumnWidth::Weighted(weight) => column
602 .flex_basis(px(0.))
603 .flex_grow(weight.max(0.))
604 .min_w(px(0.)),
605 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
606 }
607}
608
609fn aligned_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
610 h_flex()
611 .w_full()
612 .map(|row| match image.alignment {
613 HorizontalAlignment::Left => row.justify_start(),
614 HorizontalAlignment::Center => row.justify_center(),
615 HorizontalAlignment::Right => row.justify_end(),
616 })
617 .child(selectable_image(image, id, context))
618 .into_any_element()
619}
620
621fn selectable_image(image: &CardImage, id: &str, context: &CardContext) -> AnyElement {
622 selectable(
623 image_view(image, id),
624 image.select_action.as_ref(),
625 id,
626 true,
627 context,
628 )
629}
630
631pub(super) fn selectable(
632 content: AnyElement,
633 select_action: Option<&CardAction>,
634 id: &str,
635 fit: bool,
636 context: &CardContext,
637) -> AnyElement {
638 let select_key = format!("{id}-select");
639 let Some(handler) = select_action
640 .filter(|action| action.is_clickable())
641 .and_then(|action| click_handler(action, &select_key, None, context))
642 else {
643 return content;
644 };
645 let group = SharedString::from(select_key.clone());
646 div()
647 .id(ElementId::Name(select_key.into()))
648 .group(group.clone())
649 .relative()
650 .cursor_pointer()
651 .map(|wrapper| {
652 if fit {
653 wrapper.self_start().flex_none()
654 } else {
655 wrapper.w_full()
656 }
657 })
658 .on_click(move |_, _, cx| {
659 cx.stop_propagation();
660 handler(cx)
661 })
662 .child(content)
663 .child(
664 div()
665 .absolute()
666 .inset_0()
667 .rounded(px(CONTAINER_RADIUS))
668 .group_hover(group, |tint| tint.bg(white().opacity(SELECT_TINT))),
669 )
670 .into_any_element()
671}
672
673fn image_view(image: &CardImage, id: &str) -> AnyElement {
674 let width = match (image.width, image.height, named_image_width(image.size)) {
675 (Some(width), _, _) => width,
676 (None, Some(height), _) => height,
677 (None, None, Some(width)) => width,
678 (None, None, None) => MEDIUM_IMAGE,
679 }
680 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
681 let height = image.height.unwrap_or(width);
682 let radius = px(if image.person {
683 width.min(height) / 2.
684 } else {
685 IMAGE_RADIUS
686 });
687 let frame = div()
688 .id(ElementId::Name(id.to_owned().into()))
689 .w(px(width))
690 .h(px(height))
691 .max_w(relative(1.))
692 .flex_none()
693 .overflow_hidden()
694 .rounded(radius);
695 if !EXTERNAL_IMAGE_SCHEMES
696 .iter()
697 .any(|scheme| image.url.starts_with(scheme))
698 {
699 return frame.bg(theme::surface_raised()).into_any_element();
700 }
701 let alt_text = image.alt_text.clone();
702 frame
703 .when_some(image.background_color, |frame, color| frame.bg(rgba(color)))
704 .when_some(alt_text, |frame, alt_text| {
705 frame.tooltip(move |window, cx| Tooltip::new(alt_text.clone()).build(window, cx))
706 })
707 .child(
708 img(bounded(image.url.clone()))
709 .size_full()
710 .rounded(radius)
711 .object_fit(ObjectFit::Cover)
712 .with_loading(move || image_placeholder(radius))
713 .with_fallback(move || image_placeholder(radius)),
714 )
715 .into_any_element()
716}
717
718fn image_placeholder(radius: Pixels) -> AnyElement {
719 div()
720 .size_full()
721 .rounded(radius)
722 .bg(theme::surface_raised())
723 .into_any_element()
724}
725
726fn named_image_width(size: ImageSize) -> Option<f32> {
727 match size {
728 ImageSize::Small => Some(SMALL_IMAGE),
729 ImageSize::Medium => Some(MEDIUM_IMAGE),
730 ImageSize::Large => Some(LARGE_IMAGE),
731 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
732 ImageSize::Auto => None,
733 }
734}
735
736fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {
737 let open_card = context
738 .state
739 .open_card(id)
740 .and_then(|index| actions.get(index))
741 .and_then(|action| match &action.kind {
742 CardActionKind::ShowCard(card) => Some(card),
743 _ => None,
744 });
745 let split = split_overflow(actions, |action| {
746 context.visible(action.id.as_ref(), action.visible)
747 });
748 let overflow_key = format!("{id}-overflow");
749 let overflow_open = !split.overflow.is_empty() && context.state.slot(&overflow_key, 0) == 1;
750 v_flex()
751 .w_full()
752 .gap(px(ACTION_GAP))
753 .child(
754 h_flex()
755 .w_full()
756 .flex_wrap()
757 .gap(px(ACTION_GAP))
758 .children(
759 split
760 .primary
761 .iter()
762 .map(|&index| action_button(&actions[index], index, id, context)),
763 )
764 .when(!split.overflow.is_empty(), |row| {
765 row.child(overflow_button(&overflow_key, overflow_open, context))
766 }),
767 )
768 .when(overflow_open, |column| {
769 column.child(
770 v_flex()
771 .self_start()
772 .items_start()
773 .gap(px(OVERFLOW_PANEL_PADDING))
774 .p(px(OVERFLOW_PANEL_PADDING))
775 .rounded(px(CONTAINER_RADIUS))
776 .bg(theme::surface_raised())
777 .children(
778 split
779 .overflow
780 .iter()
781 .map(|&index| action_button(&actions[index], index, id, context)),
782 ),
783 )
784 })
785 .when_some(open_card, |column, card| {
786 let nested_id = format!("{id}-show");
787 let nested_context = context.nested(card);
788 column.child(
789 v_flex()
790 .w_full()
791 .p(px(CONTAINER_PADDING))
792 .gap(px(ACTION_GAP))
793 .rounded(px(CONTAINER_RADIUS))
794 .bg(theme::surface_raised())
795 .child(items_view(&card.items, &nested_id, &nested_context, false))
796 .when(!card.actions.is_empty(), |nested| {
797 nested.child(actions_view(
798 &card.actions,
799 &format!("{nested_id}-actions"),
800 &nested_context,
801 ))
802 }),
803 )
804 })
805}
806
807fn overflow_button(overflow_key: &str, open: bool, context: &CardContext) -> Stateful<Div> {
808 let handler = slot_handler(context, overflow_key, usize::from(!open));
809 action_frame(overflow_key, theme::border_strong())
810 .text_color(theme::accent_text())
811 .cursor_pointer()
812 .hover(|button| button.bg(theme::row_hover()))
813 .when(open, |button| button.bg(theme::row_hover()))
814 .popup_trigger_tooltip_text(open, ACTION_OVERFLOW_TOOLTIP)
815 .child(ACTION_OVERFLOW_LABEL)
816 .on_click(move |_, _, cx| {
817 cx.stop_propagation();
818 handler(cx)
819 })
820}
821
822fn action_frame(button_id: &str, border: Hsla) -> Stateful<Div> {
823 div()
824 .id(ElementId::Name(button_id.to_owned().into()))
825 .px(px(12.))
826 .py(px(6.))
827 .rounded(px(ACTION_RADIUS))
828 .border_1()
829 .border_color(border)
830 .text_size(px(ACTION_TEXT_SIZE))
831 .font_weight(FontWeight::SEMIBOLD)
832}
833
834pub(super) fn slot_handler(context: &CardContext, slot_key: &str, value: usize) -> ClickHandler {
835 let scope = context.scope.clone();
836 let slot_key = slot_key.to_owned();
837 Rc::new(move |cx| {
838 let (scope, slot_key) = (scope.clone(), slot_key.clone());
839 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
840 state.set_card_slot(&scope, &slot_key, value, cx)
841 });
842 })
843}
844
845fn action_button(
846 action: &CardAction,
847 index: usize,
848 actions_id: &str,
849 context: &CardContext,
850) -> Stateful<Div> {
851 let button_id = format!("{actions_id}-{index}");
852 let phase = context.state.phase(&button_id).cloned();
853 let label = action_label(
854 action,
855 &phase,
856 context.state.open_card(actions_id) == Some(index),
857 );
858 let border = match phase {
859 Some(ActionPhase::Failed(_)) => theme::red(),
860 _ => theme::border_strong(),
861 };
862 let button = action_frame(&button_id, border).child(label);
863 if !action.is_clickable() {
864 let hint = match action.kind {
865 CardActionKind::Unavailable(reason) if action.enabled => Some(reason.to_owned()),
866 _ if action.enabled => Some(ACTION_DISABLED_TOOLTIP.to_owned()),
867 _ => action.tooltip.clone(),
868 };
869 return button
870 .text_color(theme::text_muted())
871 .opacity(ACTION_DISABLED_OPACITY)
872 .when_some(hint, |button, hint| {
873 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
874 })
875 .on_click(|_, _, cx| cx.stop_propagation());
876 }
877 let enabled = button.text_color(theme::accent_text());
878 if phase == Some(ActionPhase::Busy) {
879 return enabled
880 .opacity(ACTION_BUSY_OPACITY)
881 .on_click(|_, _, cx| cx.stop_propagation());
882 }
883 let hint = failure_reason(&phase).or_else(|| action.tooltip.clone());
884 let enabled = enabled
885 .cursor_pointer()
886 .hover(|button| button.bg(theme::row_hover()))
887 .when_some(hint, |button, hint| {
888 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
889 });
890 match click_handler(action, &button_id, Some((actions_id, index)), context) {
891 Some(handler) => enabled.on_click(move |_, _, cx| {
892 cx.stop_propagation();
893 handler(cx)
894 }),
895 None => enabled,
896 }
897}
898
899fn click_handler(
900 action: &CardAction,
901 action_key: &str,
902 show_card: Option<(&str, usize)>,
903 context: &CardContext,
904) -> Option<ClickHandler> {
905 let scope = context.scope.clone();
906 match &action.kind {
907 CardActionKind::OpenUrl(url) => {
908 let url = url.clone();
909 Some(Rc::new(move |cx| app_base::open_link::open_url(cx, &url)))
910 }
911 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
912 let action = action.clone();
913 let action_key = action_key.to_owned();
914 let inputs = context.inputs.clone();
915 Some(Rc::new(move |cx| {
916 let (scope, action, action_key, inputs) = (
917 scope.clone(),
918 action.clone(),
919 action_key.clone(),
920 inputs.clone(),
921 );
922 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
923 state.run_card_action(scope, action_key, action, inputs, cx)
924 });
925 }))
926 }
927 CardActionKind::ShowCard(_) => {
928 let (actions_id, index) = show_card?;
929 let actions_id = actions_id.to_owned();
930 Some(Rc::new(move |cx| {
931 let (scope, actions_id) = (scope.clone(), actions_id.clone());
932 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
933 state.toggle_show_card(&scope, &actions_id, index, cx)
934 });
935 }))
936 }
937 CardActionKind::ToggleVisibility(targets) => {
938 let elements: Vec<(String, bool, Option<bool>)> = targets
939 .iter()
940 .map(|target| {
941 let initial = context
942 .initial_visibility
943 .get(&target.element_id)
944 .copied()
945 .unwrap_or(true);
946 (target.element_id.clone(), initial, target.visible)
947 })
948 .collect();
949 let root_key = context.root_key.clone();
950 Some(Rc::new(move |cx| {
951 let (scope, root_key, elements) =
952 (scope.clone(), root_key.clone(), elements.clone());
953 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
954 state.toggle_card_elements(&scope, &root_key, elements, cx)
955 });
956 }))
957 }
958 CardActionKind::Unavailable(_) | CardActionKind::Unsupported => None,
959 }
960}
961
962fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {
963 match phase {
964 Some(ActionPhase::Failed(reason)) => Some(reason.clone()),
965 _ => None,
966 }
967}
968
969fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {
970 match phase {
971 Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),
972 Some(ActionPhase::Done) => h_flex()
973 .gap(px(ACTION_ICON_GAP))
974 .items_center()
975 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
976 .child(action.title.clone())
977 .into_any_element(),
978 _ if open => titled(action, format!("{} ^", action.title)),
979 _ => titled(action, action.title.clone()),
980 }
981}
982
983fn titled(action: &CardAction, text: String) -> AnyElement {
984 match action.icon.as_ref().map(action_icon_view) {
985 Some(icon) => h_flex()
986 .gap(px(ACTION_ICON_GAP))
987 .items_center()
988 .child(icon)
989 .child(text)
990 .into_any_element(),
991 None => text.into_any_element(),
992 }
993}