BlueGit

ict rusty-teams

Files

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

adaptive_card.rs

adaptive_card.rs 33.4 KiB Download Raw
1use std::collections::HashMap;
2use std::rc::Rc;
3
4use gpui_kit::component::{ActiveTheme as _, h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::{
8 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
9 CardInput, CardItem, CardSpacing, CardText, ColumnWidth, ContainerLayout, ContainerStyle,
10 HorizontalAlignment, ImageSize, TextColor, TextSize, VerticalAlignment, WidthClass,
11 split_overflow,
12};
13
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};
24use super::widgets::symbol;
25use crate::app_state::{AppHandle, AppState};
26use crate::card_state::{ActionPhase, CardScope, CardState};
27use crate::render::{layout_blocks, render_blocks};
28use crate::theme;
29
30const CARD_WIDTH: f32 = 480.;
31const CARD_FULL_WIDTH: f32 = 720.;
32const CARD_PADDING: f32 = 12.;
33const CARD_RADIUS: f32 = 10.;
34const CARD_BORDER_WIDTH: f32 = 1.;
35const COLUMN_GAP: f32 = 8.;
36const SEPARATOR_PADDING: f32 = 8.;
37const ACTION_GAP: f32 = 8.;
38const ACTION_RADIUS: f32 = 6.;
39const ACTION_TEXT_SIZE: f32 = 13.;
40const ACTION_DISABLED_OPACITY: f32 = 0.5;
41const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
42const ACTION_BUSY_OPACITY: f32 = 0.6;
43const ACTION_CHECK_SIZE: f32 = 14.;
44const ACTION_ICON_GAP: f32 = 4.;
45const NOTE_TEXT_SIZE: f32 = 12.;
46const FACT_TITLE_WIDTH: f32 = 96.;
47const FACT_GAP: f32 = 2.;
48const CONTAINER_PADDING: f32 = 8.;
49const CONTAINER_RADIUS: f32 = 6.;
50const CONTAINER_TINT: f32 = 0.16;
51const TEXT_LINE_HEIGHT: f32 = 1.35;
52const IMAGE_RADIUS: f32 = 4.;
53const IMAGE_SET_GAP: f32 = 6.;
54const SMALL_IMAGE: f32 = 40.;
55const MEDIUM_IMAGE: f32 = 80.;
56const LARGE_IMAGE: f32 = 160.;
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)>;
64
65pub(super) struct CardContext<'a> {
66 pub(super) cx: &'a App,
67 pub(super) scope: &'a CardScope,
68 pub(super) state: &'a CardState,
69 root_key: String,
70 initial_visibility: Rc<HashMap<String, bool>>,
71 inputs: Vec<CardInput>,
72 width_class: WidthClass,
73}
74
75impl<'a> CardContext<'a> {
76 fn new(card: &AdaptiveCard, scope: &'a CardScope, cx: &'a App) -> Self {
77 CardContext {
78 cx,
79 scope,
80 state: &cx.global::<AppHandle>().0.read(cx).cards,
81 root_key: scope.card_key(),
82 initial_visibility: Rc::new(card.element_visibility()),
83 inputs: card.own_inputs(),
84 width_class: WidthClass::from_pixels(card_width(card)),
85 }
86 }
87
88 fn nested(&self, card: &AdaptiveCard) -> CardContext<'a> {
89 let mut inputs = self.inputs.clone();
90 inputs.extend(card.own_inputs());
91 CardContext {
92 cx: self.cx,
93 scope: self.scope,
94 state: self.state,
95 root_key: self.root_key.clone(),
96 initial_visibility: self.initial_visibility.clone(),
97 inputs,
98 width_class: self.width_class,
99 }
100 }
101
102 pub(super) fn visible(&self, id: Option<&String>, initial: bool) -> bool {
103 match id {
104 Some(id) => self
105 .state
106 .is_visible(&format!("{}/{id}", self.root_key), initial),
107 None => initial,
108 }
109 }
110}
111
112pub fn cards_view(
113 cards: &[AdaptiveCard],
114 conversation_id: &str,
115 message_id: &str,
116 cx: &App,
117) -> Vec<AnyElement> {
118 cards
119 .iter()
120 .enumerate()
121 .map(|(index, card)| {
122 let scope = CardScope::message(conversation_id, message_id, index);
123 card_view(card, &scope, cx)
124 })
125 .collect()
126}
127
128pub fn ensure_cards_inputs(
129 app: &Entity<AppState>,
130 cards: &[AdaptiveCard],
131 conversation_id: &str,
132 message_id: &str,
133 window: &mut Window,
134 cx: &mut App,
135) {
136 if cards.is_empty() {
137 return;
138 }
139 app.update(cx, |state, cx| {
140 for (index, card) in cards.iter().enumerate() {
141 let scope = CardScope::message(conversation_id, message_id, index);
142 state.ensure_card_inputs(&scope, card, window, cx);
143 }
144 });
145}
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
162pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
163 let context = CardContext::new(card, scope, cx);
164 let id = scope.card_key();
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));
171 let visible_actions = card
172 .actions
173 .iter()
174 .any(|action| context.visible(action.id.as_ref(), action.visible));
175 v_flex()
176 .id(ElementId::Name(format!("{id}-root").into()))
177 .relative()
178 .w(px(card_width(card)))
179 .max_w(relative(1.))
180 .p(px(CARD_PADDING))
181 .rounded(px(CARD_RADIUS))
182 .bg(theme::surface())
183 .border(px(CARD_BORDER_WIDTH))
184 .border_color(theme::border())
185 .text_color(theme::text_strong())
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))
198 .when(visible_actions, |card_element| {
199 card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
200 actions_view(&card.actions, &format!("{id}-actions"), &context),
201 ))
202 })
203 .when_some(note, |card_element, note| {
204 card_element.child(
205 div()
206 .mt(px(spacing_pixels(CardSpacing::Default)))
207 .text_size(px(NOTE_TEXT_SIZE))
208 .text_color(theme::text_muted())
209 .child(note),
210 )
211 })
212 .into_any_element()
213}
214
215fn card_width(card: &AdaptiveCard) -> f32 {
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();
272 let mut column = v_flex().w_full();
273 for (position, (index, item)) in shown.iter().enumerate() {
274 let item_id = format!("{id}-{index}");
275 let first = position == 0;
276 let bleed = top_level
277 .then(|| bleed_edges(item, first, position + 1 == shown.len()))
278 .flatten();
279 column = column.child(
280 div()
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| {
290 wrapper.mt(px(spacing_pixels(item.spacing)))
291 })
292 .when(!first && item.separator, |wrapper| {
293 wrapper
294 .pt(px(SEPARATOR_PADDING))
295 .border_t_1()
296 .border_color(theme::border())
297 })
298 .child(element_view(&item.element, &item_id, context, bleed)),
299 );
300 }
301 column
302}
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
320fn spacing_pixels(spacing: CardSpacing) -> f32 {
321 match spacing {
322 CardSpacing::None => 0.,
323 CardSpacing::Small => 4.,
324 CardSpacing::Default => 8.,
325 CardSpacing::Medium => 12.,
326 CardSpacing::Large | CardSpacing::Padding => 16.,
327 CardSpacing::ExtraLarge => 24.,
328 }
329}
330
331fn element_view(
332 element: &CardElement,
333 id: &str,
334 context: &CardContext,
335 bleed: Option<BleedEdges>,
336) -> AnyElement {
337 match element {
338 CardElement::Text(text) => text_view(text, id, context.cx),
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 }))
347 .into_any_element()
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 ),
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),
377 CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
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),
383 }
384}
385
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> {
432 match style {
433 ContainerStyle::Default => None,
434 ContainerStyle::Emphasis => Some(theme::surface_raised()),
435 ContainerStyle::Accent => Some(theme::accent().opacity(CONTAINER_TINT)),
436 ContainerStyle::Good => Some(theme::green().opacity(CONTAINER_TINT)),
437 ContainerStyle::Warning => Some(theme::amber().opacity(CONTAINER_TINT)),
438 ContainerStyle::Attention => Some(theme::red().opacity(CONTAINER_TINT)),
439 }
440}
441
442fn text_size(size: TextSize) -> f32 {
443 match size {
444 TextSize::Small => 11.5,
445 TextSize::Default => 13.5,
446 TextSize::Medium => 15.,
447 TextSize::Large => 17.5,
448 TextSize::ExtraLarge => 21.,
449 }
450}
451
452fn text_color(text: &CardText) -> Hsla {
453 card_color(text.color, text.subtle)
454}
455
456pub(super) fn card_color(color: TextColor, subtle: bool) -> Hsla {
457 match color {
458 TextColor::Accent => theme::accent_text(),
459 TextColor::Good => theme::green(),
460 TextColor::Warning => theme::amber(),
461 TextColor::Attention => theme::red_soft(),
462 TextColor::Default | TextColor::Dark | TextColor::Light if subtle => theme::text_muted(),
463 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
464 }
465}
466
467fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
468 div()
469 .w_full()
470 .min_w(px(0.))
471 .text_size(px(text_size(text.size)))
472 .line_height(relative(TEXT_LINE_HEIGHT))
473 .text_color(text_color(text))
474 .when(text.bold, |element| {
475 element.font_weight(FontWeight::SEMIBOLD)
476 })
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 })
494 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
495 .into_any_element()
496}
497
498fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
499 v_flex()
500 .w_full()
501 .gap(px(FACT_GAP))
502 .children(facts.iter().enumerate().map(|(index, fact)| {
503 h_flex()
504 .w_full()
505 .items_start()
506 .gap(px(COLUMN_GAP))
507 .text_size(px(text_size(TextSize::Default)))
508 .line_height(relative(TEXT_LINE_HEIGHT))
509 .child(
510 div()
511 .w(px(FACT_TITLE_WIDTH))
512 .flex_none()
513 .font_weight(FontWeight::SEMIBOLD)
514 .text_color(theme::text_muted())
515 .child(fact.title.clone()),
516 )
517 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
518 &layout_blocks(&fact.value),
519 &format!("{id}-{index}"),
520 false,
521 cx,
522 )))
523 }))
524 .into_any_element()
525}
526
527fn columns_view(
528 columns: &[CardColumn],
529 layout: &ContainerLayout,
530 id: &str,
531 context: &CardContext,
532) -> AnyElement {
533 let tint = container_tint(layout.style);
534 div()
535 .flex()
536 .map(|row| {
537 if layout.rtl {
538 row.flex_row_reverse()
539 } else {
540 row.flex_row()
541 }
542 })
543 .items_stretch()
544 .w_full()
545 .gap(px(COLUMN_GAP))
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 )
587 .into_any_element()
588}
589
590pub(super) fn sized_column(column: Div, width: ColumnWidth) -> Div {
591 match width {
592 ColumnWidth::Auto => column.flex_none(),
593 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
594 ColumnWidth::Weighted(weight) => column
595 .flex_basis(px(0.))
596 .flex_grow(weight.max(0.))
597 .min_w(px(0.)),
598 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
599 }
600}
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
666fn image_view(image: &CardImage, id: &str) -> AnyElement {
667 let width = match (image.width, image.height, named_image_width(image.size)) {
668 (Some(width), _, _) => width,
669 (None, Some(height), _) => height,
670 (None, None, Some(width)) => width,
671 (None, None, None) => MEDIUM_IMAGE,
672 }
673 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
674 let height = image.height.unwrap_or(width);
675 let radius = px(if image.person {
676 width.min(height) / 2.
677 } else {
678 IMAGE_RADIUS
679 });
680 let frame = div()
681 .id(ElementId::Name(id.to_owned().into()))
682 .w(px(width))
683 .h(px(height))
684 .max_w(relative(1.))
685 .flex_none()
686 .overflow_hidden()
687 .rounded(radius);
688 if !EXTERNAL_IMAGE_SCHEMES
689 .iter()
690 .any(|scheme| image.url.starts_with(scheme))
691 {
692 return frame.bg(theme::surface_raised()).into_any_element();
693 }
694 let alt_text = image.alt_text.clone();
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 })
700 .child(
701 img(image.url.clone())
702 .size_full()
703 .rounded(radius)
704 .object_fit(ObjectFit::Cover)
705 .with_loading(move || image_placeholder(radius))
706 .with_fallback(move || image_placeholder(radius)),
707 )
708 .into_any_element()
709}
710
711fn image_placeholder(radius: Pixels) -> AnyElement {
712 div()
713 .size_full()
714 .rounded(radius)
715 .bg(theme::surface_raised())
716 .into_any_element()
717}
718
719fn named_image_width(size: ImageSize) -> Option<f32> {
720 match size {
721 ImageSize::Small => Some(SMALL_IMAGE),
722 ImageSize::Medium => Some(MEDIUM_IMAGE),
723 ImageSize::Large => Some(LARGE_IMAGE),
724 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
725 ImageSize::Auto => None,
726 }
727}
728
729fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {
730 let open_card = context
731 .state
732 .open_card(id)
733 .and_then(|index| actions.get(index))
734 .and_then(|action| match &action.kind {
735 CardActionKind::ShowCard(card) => Some(card),
736 _ => None,
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;
743 v_flex()
744 .w_full()
745 .gap(px(ACTION_GAP))
746 .child(
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 }),
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 })
778 .when_some(open_card, |column, card| {
779 let nested_id = format!("{id}-show");
780 let nested_context = context.nested(card);
781 column.child(
782 v_flex()
783 .w_full()
784 .p(px(CONTAINER_PADDING))
785 .gap(px(ACTION_GAP))
786 .rounded(px(CONTAINER_RADIUS))
787 .bg(theme::surface_raised())
788 .child(items_view(&card.items, &nested_id, &nested_context, false))
789 .when(!card.actions.is_empty(), |nested| {
790 nested.child(actions_view(
791 &card.actions,
792 &format!("{nested_id}-actions"),
793 &nested_context,
794 ))
795 }),
796 )
797 })
798}
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
838fn action_button(
839 action: &CardAction,
840 index: usize,
841 actions_id: &str,
842 context: &CardContext,
843) -> Stateful<Div> {
844 let button_id = format!("{actions_id}-{index}");
845 let phase = context.state.phase(&button_id).cloned();
846 let label = action_label(
847 action,
848 &phase,
849 context.state.open_card(actions_id) == Some(index),
850 );
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);
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 };
862 return button
863 .text_color(theme::text_muted())
864 .opacity(ACTION_DISABLED_OPACITY)
865 .when_some(hint, |button, hint| {
866 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
867 })
868 .on_click(|_, _, cx| cx.stop_propagation());
869 }
870 let enabled = button.text_color(theme::accent_text());
871 if phase == Some(ActionPhase::Busy) {
872 return enabled
873 .opacity(ACTION_BUSY_OPACITY)
874 .on_click(|_, _, cx| cx.stop_propagation());
875 }
876 let hint = failure_reason(&phase).or_else(|| action.tooltip.clone());
877 let enabled = enabled
878 .cursor_pointer()
879 .hover(|button| button.bg(theme::row_hover()))
880 .when_some(hint, |button, hint| {
881 button.tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx))
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> {
898 let scope = context.scope.clone();
899 match &action.kind {
900 CardActionKind::OpenUrl(url) => {
901 let url = url.clone();
902 Some(Rc::new(move |cx| cx.open_url(&url)))
903 }
904 CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
905 let action = action.clone();
906 let action_key = action_key.to_owned();
907 let inputs = context.inputs.clone();
908 Some(Rc::new(move |cx| {
909 let (scope, action, action_key, inputs) = (
910 scope.clone(),
911 action.clone(),
912 action_key.clone(),
913 inputs.clone(),
914 );
915 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
916 state.run_card_action(scope, action_key, action, inputs, cx)
917 });
918 }))
919 }
920 CardActionKind::ShowCard(_) => {
921 let (actions_id, index) = show_card?;
922 let actions_id = actions_id.to_owned();
923 Some(Rc::new(move |cx| {
924 let (scope, actions_id) = (scope.clone(), actions_id.clone());
925 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
926 state.toggle_show_card(&scope, &actions_id, index, cx)
927 });
928 }))
929 }
930 CardActionKind::ToggleVisibility(targets) => {
931 let elements: Vec<(String, bool, Option<bool>)> = targets
932 .iter()
933 .map(|target| {
934 let initial = context
935 .initial_visibility
936 .get(&target.element_id)
937 .copied()
938 .unwrap_or(true);
939 (target.element_id.clone(), initial, target.visible)
940 })
941 .collect();
942 let root_key = context.root_key.clone();
943 Some(Rc::new(move |cx| {
944 let (scope, root_key, elements) =
945 (scope.clone(), root_key.clone(), elements.clone());
946 cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
947 state.toggle_card_elements(&scope, &root_key, elements, cx)
948 });
949 }))
950 }
951 CardActionKind::Unavailable(_) | CardActionKind::Unsupported => None,
952 }
953}
954
955fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {
956 match phase {
957 Some(ActionPhase::Failed(reason)) => Some(reason.clone()),
958 _ => None,
959 }
960}
961
962fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {
963 match phase {
964 Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),
965 Some(ActionPhase::Done) => h_flex()
966 .gap(px(ACTION_ICON_GAP))
967 .items_center()
968 .child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
969 .child(action.title.clone())
970 .into_any_element(),
971 _ if open => titled(action, format!("{} ^", action.title)),
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(),
985 }
986}