Skip to main content

arc_ui/data/
card.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/card/card.tsx` & `.module.css`
3//!
4//! P6 Component #1: `card`
5//!
6//! - Media / content / footer card with hover lift (`y: 0 -> -2px` on `motion.spring.snappy`),
7//!   raised shadow (`Shadows::raised`), `border_strong` border tint, and slow subtle media zoom.
8//! - Status line (`status`): when the text changes, the old line lifts out quickly while the new
9//!   words rise in staggered (`stagger.word = 40ms`) with `ease.enter`.
10//! - Optional quick-look `details`: clicking anywhere on the card (except action buttons) opens a
11//!   centered `480px` modal panel (`Radii::SURFACE`, `Shadows::floating`, `oklch(10% 0 0 / 0.46)`
12//!   backdrop) with `motion.spring.smooth` (`0.30s` open / `0.26s` close), close button (`Escape`
13//!   or click), and `120ms`-delayed details reveal.
14
15use std::{cell::RefCell, rc::Rc, time::Duration};
16
17use arc_motion::{
18    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
19    is_reduced_motion, motion_now, spring::SpringOptions,
20};
21use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
22use gpui_kit::{
23    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
24    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
25    Window, base::StyledExt as _, canvas, deferred, div, point, prelude::*, px,
26};
27
28/// Maximum quick-look modal width (`30rem = 480px`).
29pub const CARD_QUICK_LOOK_MAX_W: f32 = 480.0;
30/// Hover vertical lift (`-2px` matching `whileHover={{ y: -2 }}`).
31pub const CARD_HOVER_LIFT_PX: f32 = -2.0;
32/// Word-by-word stagger delay for status updates (`40ms`).
33pub const CARD_STATUS_WORD_STAGGER_SECS: f64 = 0.04;
34
35type OpenChangeCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
36type SlotBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
37
38/// Samples `(old_alpha, old_y_px)` for the departing status line over `duration.fast` (`160ms`).
39pub fn card_status_exit_sample(elapsed_secs: f64, reduced: bool) -> (f32, f32) {
40    if reduced || elapsed_secs >= 0.16 {
41        return (0.0, -4.0);
42    }
43    let t = (elapsed_secs / 0.16).clamp(0.0, 1.0) as f32;
44    let eased = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t);
45    let blur = BlurFallback::evaluate(px(eased * 2.0), reduced);
46    (
47        ((1.0 - eased) * blur.opacity_multiplier).clamp(0.0, 1.0),
48        -4.0 * eased,
49    )
50}
51
52/// Samples `(alpha, y_px)` for word `word_index` of an entering status line (`stagger.word = 40ms`).
53pub fn card_status_word_sample(elapsed_secs: f64, word_index: usize, reduced: bool) -> (f32, f32) {
54    if reduced {
55        return (1.0, 0.0);
56    }
57    let delay = word_index as f64 * CARD_STATUS_WORD_STAGGER_SECS;
58    let local = elapsed_secs - delay;
59    if local <= 0.0 {
60        return (0.0, 4.5);
61    }
62    if local >= 0.24 {
63        return (1.0, 0.0);
64    }
65    let t = (local / 0.24).clamp(0.0, 1.0) as f32;
66    let eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
67    let blur = BlurFallback::evaluate(px((1.0 - eased) * 4.0), reduced);
68    (
69        (eased * blur.opacity_multiplier).clamp(0.0, 1.0),
70        4.5 * (1.0 - eased),
71    )
72}
73
74/// Samples `(alpha, y_px)` for the quick-look details reveal (`120ms` delay + `240ms ease.enter`).
75pub fn card_details_reveal_sample(elapsed_secs: f64, returning: bool, reduced: bool) -> (f32, f32) {
76    if returning {
77        return (0.0, 0.0);
78    }
79    if reduced {
80        return (1.0, 0.0);
81    }
82    let local = elapsed_secs - 0.12;
83    if local <= 0.0 {
84        return (0.0, 6.0);
85    }
86    if local >= 0.24 {
87        return (1.0, 0.0);
88    }
89    let t = (local / 0.24).clamp(0.0, 1.0) as f32;
90    let eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
91    (eased.clamp(0.0, 1.0), 6.0 * (1.0 - eased))
92}
93
94fn paint_close_icon(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
95    let r = 4.2;
96    for (x1, y1, x2, y2) in [
97        (cx - r, cy - r, cx + r, cy + r),
98        (cx + r, cy - r, cx - r, cy + r),
99    ] {
100        let mut pb = PathBuilder::stroke(px(1.75));
101        pb.move_to(point(px(x1), px(y1)));
102        pb.line_to(point(px(x2), px(y2)));
103        if let Ok(path) = pb.build() {
104            window.paint_path(path, color);
105        }
106    }
107}
108
109#[derive(Clone)]
110struct CardInternal {
111    open: bool,
112    open_changed_at: f64,
113    hovered: bool,
114    prev_status: Option<SharedString>,
115    last_status: Option<SharedString>,
116    status_changed_at: f64,
117    root_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
118    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
119    focus_handle: FocusHandle,
120}
121
122impl CardInternal {
123    fn new(
124        default_open: bool,
125        status: Option<SharedString>,
126        now: f64,
127        focus_handle: FocusHandle,
128    ) -> Self {
129        Self {
130            open: default_open,
131            open_changed_at: now - 1.0,
132            hovered: false,
133            prev_status: None,
134            last_status: status,
135            status_changed_at: now - 1.0,
136            root_bounds: Rc::new(RefCell::new(None)),
137            panel_bounds: Rc::new(RefCell::new(None)),
138            focus_handle,
139        }
140    }
141}
142
143/// Content card with hover lift, animated status word-roll, and optional quick-look morph (`card`).
144#[derive(IntoElement)]
145pub struct Card {
146    id: ElementId,
147    title: SharedString,
148    description: Option<SharedString>,
149    media: Option<SlotBuilder>,
150    body: Option<SlotBuilder>,
151    action: Option<SlotBuilder>,
152    avatar: Option<SlotBuilder>,
153    meta: Option<SharedString>,
154    status: Option<SharedString>,
155    details: Option<SlotBuilder>,
156    open_override: Option<bool>,
157    default_open: bool,
158    on_open_change: Option<OpenChangeCallback>,
159}
160
161impl Card {
162    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
163        Self {
164            id: id.into(),
165            title: title.into(),
166            description: None,
167            media: None,
168            body: None,
169            action: None,
170            avatar: None,
171            meta: None,
172            status: None,
173            details: None,
174            open_override: None,
175            default_open: false,
176            on_open_change: None,
177        }
178    }
179
180    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
181        self.description = Some(description.into());
182        self
183    }
184
185    pub fn media(
186        mut self,
187        builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
188    ) -> Self {
189        self.media = Some(Rc::new(builder));
190        self
191    }
192
193    pub fn body(mut self, builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static) -> Self {
194        self.body = Some(Rc::new(builder));
195        self
196    }
197
198    pub fn action(
199        mut self,
200        builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
201    ) -> Self {
202        self.action = Some(Rc::new(builder));
203        self
204    }
205
206    pub fn avatar(
207        mut self,
208        builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
209    ) -> Self {
210        self.avatar = Some(Rc::new(builder));
211        self
212    }
213
214    pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
215        self.meta = Some(meta.into());
216        self
217    }
218
219    pub fn status(mut self, status: impl Into<SharedString>) -> Self {
220        self.status = Some(status.into());
221        self
222    }
223
224    /// Quick-look details slot; setting this makes the card clickable to expand into a modal view.
225    pub fn details(
226        mut self,
227        builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
228    ) -> Self {
229        self.details = Some(Rc::new(builder));
230        self
231    }
232
233    pub fn open(mut self, open: bool) -> Self {
234        self.open_override = Some(open);
235        self
236    }
237
238    pub fn default_open(mut self, default_open: bool) -> Self {
239        self.default_open = default_open;
240        self
241    }
242
243    pub fn on_open_change(mut self, cb: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
244        self.on_open_change = Some(Rc::new(cb));
245        self
246    }
247}
248
249fn render_status_line(
250    current: &str,
251    previous: Option<&str>,
252    elapsed_secs: f64,
253    text_muted: Hsla,
254    reduced: bool,
255) -> AnyElement {
256    let words: Vec<&str> = current.split_whitespace().collect();
257    let mut incoming_row = div()
258        .flex()
259        .flex_row()
260        .flex_wrap()
261        .items_center()
262        .gap(px(3.0))
263        .text_size(Typography::TEXT_XS)
264        .text_color(text_muted);
265
266    for (idx, word) in words.iter().enumerate() {
267        let (alpha, y_px) = card_status_word_sample(elapsed_secs, idx, reduced);
268        incoming_row = incoming_row.child(
269            div()
270                .relative()
271                .top(px(y_px))
272                .opacity(alpha)
273                .child(SharedString::from(*word)),
274        );
275    }
276
277    let outgoing_el = previous.and_then(|prev| {
278        let (old_alpha, old_y) = card_status_exit_sample(elapsed_secs, reduced);
279        if old_alpha <= 0.01 {
280            None
281        } else {
282            Some(
283                div()
284                    .absolute()
285                    .left_0()
286                    .top(px(old_y))
287                    .opacity(old_alpha)
288                    .text_size(Typography::TEXT_XS)
289                    .text_color(text_muted)
290                    .whitespace_nowrap()
291                    .child(SharedString::from(prev.to_string())),
292            )
293        }
294    });
295
296    div()
297        .relative()
298        .min_w(px(0.0))
299        .when_some(outgoing_el, |el, out| el.child(out))
300        .child(incoming_row)
301        .into_any_element()
302}
303
304impl RenderOnce for Card {
305    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
306        let theme = cx.arc_theme().clone();
307        let colors = theme.colors;
308        let motion = theme.motion;
309        let reduced = is_reduced_motion(cx);
310        let now = motion_now(cx);
311        let has_details = self.details.is_some();
312
313        let state_cell = window
314            .use_keyed_state(
315                ElementId::NamedChild(self.id.clone().into(), SharedString::from("card-state")),
316                cx,
317                |_, cx| {
318                    Rc::new(RefCell::new(CardInternal::new(
319                        self.default_open,
320                        self.status.clone(),
321                        now,
322                        cx.focus_handle(),
323                    )))
324                },
325            )
326            .read(cx)
327            .clone();
328
329        let is_controlled = self.open_override.is_some();
330        let mut request_anim = false;
331
332        let (
333            is_open,
334            open_elapsed,
335            hovered,
336            prev_status,
337            status_elapsed,
338            focus_handle,
339            root_bounds,
340            panel_bounds,
341        ) = {
342            let mut st = state_cell.borrow_mut();
343            let resolved_open = if has_details {
344                self.open_override.unwrap_or(st.open)
345            } else {
346                false
347            };
348            if resolved_open != st.open {
349                st.open = resolved_open;
350                st.open_changed_at = now;
351            }
352            if st.last_status != self.status {
353                st.prev_status = st.last_status.take();
354                st.last_status = self.status.clone();
355                st.status_changed_at = now;
356            }
357            let status_dt = (now - st.status_changed_at).max(0.0);
358            let word_count = self
359                .status
360                .as_ref()
361                .map(|s| s.split_whitespace().count())
362                .unwrap_or(0);
363            let max_status_dur = 0.26 + word_count as f64 * CARD_STATUS_WORD_STAGGER_SECS;
364            if !reduced && st.prev_status.is_some() {
365                if status_dt < max_status_dur {
366                    request_anim = true;
367                } else {
368                    st.prev_status = None;
369                }
370            }
371            let open_dt = (now - st.open_changed_at).max(0.0);
372            if !reduced && st.open && open_dt < 0.40 {
373                request_anim = true;
374            }
375            (
376                st.open,
377                open_dt,
378                st.hovered,
379                st.prev_status.clone(),
380                status_dt,
381                st.focus_handle.clone(),
382                st.root_bounds.clone(),
383                st.panel_bounds.clone(),
384            )
385        };
386
387        if request_anim {
388            window.request_animation_frame();
389        }
390
391        // Hover vertical lift (`0 -> -2px`) on `spring.snappy`
392        let lift_target = if hovered && !reduced {
393            CARD_HOVER_LIFT_PX
394        } else {
395            0.0
396        };
397        let lift_y = if reduced {
398            0.0
399        } else {
400            arc_spring(
401                ElementId::NamedChild(self.id.clone().into(), SharedString::from("card-lift")),
402                lift_target,
403                motion.spring.snappy,
404                window,
405                cx,
406            )
407        };
408
409        // Subtle media zoom inset while hovered (slow zoom in, quicker ease out)
410        let zoom_target = if hovered && !reduced {
411            1.0_f32
412        } else {
413            0.0_f32
414        };
415        let zoom_spec = if hovered {
416            SpringSpec::visual(0.68, 0.0)
417        } else {
418            SpringSpec::visual(0.42, 0.0)
419        };
420        let zoom_t = if reduced {
421            0.0
422        } else {
423            arc_spring_with_options(
424                ElementId::NamedChild(self.id.clone().into(), SharedString::from("card-zoom")),
425                zoom_target,
426                SpringOptions::new(zoom_spec).with_initial_value(0.0),
427                window,
428                cx,
429            )
430            .value
431            .clamp(0.0, 1.0)
432        };
433
434        // Presence for quick-look modal
435        let presence = ArcPresence::new((self.id.clone(), "quick-look"), is_open)
436            .config(ArcPresenceConfig {
437                enter_duration: Duration::from_millis(240),
438                exit_duration: Duration::from_millis(200),
439                ..ArcPresenceConfig::default()
440            })
441            .animate_initial(false)
442            .sample(window, cx);
443        let modal_spring_t = if reduced {
444            if is_open { 1.0 } else { 0.0 }
445        } else {
446            let spec = if is_open {
447                SpringSpec::visual(0.30, 0.0)
448            } else {
449                SpringSpec::visual(0.26, 0.0)
450            };
451            arc_spring_with_options(
452                ElementId::NamedChild(self.id.clone().into(), SharedString::from("modal-morph")),
453                if is_open { 1.0 } else { 0.0 },
454                SpringOptions::new(spec).with_initial_value(0.0),
455                window,
456                cx,
457            )
458            .value
459            .clamp(0.0, 1.0)
460        };
461
462        let render_footer = |window: &mut Window, cx: &mut App| -> Option<AnyElement> {
463            let has_footer = self.avatar.is_some()
464                || self.meta.is_some()
465                || self.status.is_some()
466                || self.action.is_some();
467            if !has_footer {
468                return None;
469            }
470            let byline = if self.avatar.is_some() || self.meta.is_some() || self.status.is_some() {
471                Some(
472                    div()
473                        .flex_1()
474                        .min_w(px(0.0))
475                        .flex()
476                        .flex_row()
477                        .items_center()
478                        .gap(Spacing::S3)
479                        .when_some(self.avatar.as_ref(), |el, av| {
480                            el.child(
481                                div()
482                                    .w(Spacing::S8)
483                                    .h(Spacing::S8)
484                                    .rounded(Radii::PILL)
485                                    .overflow_hidden()
486                                    .bg(colors.surface_muted)
487                                    .flex_shrink_0()
488                                    .flex()
489                                    .items_center()
490                                    .justify_center()
491                                    .child(av(window, cx)),
492                            )
493                        })
494                        .child(
495                            div()
496                                .flex_1()
497                                .min_w(px(0.0))
498                                .flex()
499                                .flex_col()
500                                .gap(px(2.0))
501                                .when_some(self.meta.clone(), |el, meta| {
502                                    el.child(
503                                        div()
504                                            .text_size(Typography::TEXT_XS)
505                                            .font_medium()
506                                            .text_color(colors.foreground)
507                                            .truncate()
508                                            .child(meta),
509                                    )
510                                })
511                                .when_some(self.status.as_ref(), |el, st| {
512                                    el.child(render_status_line(
513                                        st.as_ref(),
514                                        prev_status.as_deref(),
515                                        status_elapsed,
516                                        colors.text_muted,
517                                        reduced,
518                                    ))
519                                }),
520                        ),
521                )
522            } else {
523                None
524            };
525
526            let action_el = self.action.as_ref().map(|act| {
527                div()
528                    .flex_shrink_0()
529                    .flex()
530                    .flex_row()
531                    .items_center()
532                    .gap(Spacing::S2)
533                    .on_mouse_down(MouseButton::Left, |_, _, cx| {
534                        cx.stop_propagation();
535                    })
536                    .child(act(window, cx))
537            });
538
539            Some(
540                div()
541                    .w_full()
542                    .mt(Spacing::S5)
543                    .flex()
544                    .flex_row()
545                    .items_center()
546                    .justify_between()
547                    .gap(Spacing::S3)
548                    .when_some(byline, |el, b| el.child(b))
549                    .when_some(action_el, |el, a| el.child(a))
550                    .into_any_element(),
551            )
552        };
553
554        let media_card_el = self.media.as_ref().map(|m| {
555            let expand = zoom_t * 3.0;
556            div()
557                .w_full()
558                .min_h(px(112.0))
559                .overflow_hidden()
560                .bg(colors.surface_muted)
561                .rounded_tl(Radii::PANEL)
562                .rounded_tr(Radii::PANEL)
563                .flex()
564                .items_center()
565                .justify_center()
566                .child(
567                    div()
568                        .w_full()
569                        .mx(px(-expand))
570                        .my(px(-expand * 0.5))
571                        .child(m(window, cx)),
572                )
573        });
574        let body_card_el = self.body.as_ref().map(|b| b(window, cx));
575        let footer_card_el = render_footer(window, cx);
576
577        let border_col = if hovered {
578            colors.border_strong
579        } else {
580            colors.border
581        };
582
583        let hover_state = state_cell.clone();
584        let open_state = state_cell.clone();
585        let on_open_card = self.on_open_change.clone();
586
587        let mut card_box = div()
588            .id(self.id.clone())
589            .role(Role::Region)
590            .relative()
591            .top(px(lift_y))
592            .w_full()
593            .min_w(px(0.0))
594            .rounded(Radii::PANEL)
595            .border_1()
596            .border_color(border_col)
597            .bg(colors.surface)
598            .text_color(colors.foreground)
599            .overflow_hidden()
600            .when(has_details, |el| el.cursor_pointer())
601            .on_hover(move |is_hov: &bool, window, _| {
602                let changed = {
603                    let mut st = hover_state.borrow_mut();
604                    if st.hovered != *is_hov {
605                        st.hovered = *is_hov;
606                        true
607                    } else {
608                        false
609                    }
610                };
611                if changed {
612                    window.refresh();
613                }
614            })
615            .when(has_details, |el| {
616                el.on_mouse_down(MouseButton::Left, move |_, window, cx| {
617                    let t_now = motion_now(cx);
618                    if !is_controlled {
619                        let mut st = open_state.borrow_mut();
620                        st.open = true;
621                        st.open_changed_at = t_now;
622                    }
623                    if let Some(ref cb) = on_open_card {
624                        cb(&true, window, cx);
625                    }
626                    window.refresh();
627                })
628            })
629            .when_some(media_card_el, |el, m| el.child(m))
630            .child(
631                div()
632                    .w_full()
633                    .p(Spacing::S5)
634                    .flex()
635                    .flex_col()
636                    .child(
637                        div()
638                            .text_size(Typography::TEXT_LG)
639                            .font_medium()
640                            .text_color(colors.foreground)
641                            .child(self.title.clone()),
642                    )
643                    .when_some(self.description.clone(), |el, desc| {
644                        el.child(
645                            div()
646                                .mt(Spacing::S2)
647                                .text_size(Typography::TEXT_SM)
648                                .text_color(colors.text_secondary)
649                                .child(desc),
650                        )
651                    })
652                    .when_some(body_card_el, |el, b| el.child(b))
653                    .when_some(footer_card_el, |el, f| el.child(f)),
654            );
655
656        if hovered {
657            card_box = card_box.shadow(Shadows::raised(theme.mode));
658        }
659
660        // Quick-look modal portal when details are present and presence is mounted
661        let modal_layer: Option<AnyElement> = if has_details && presence.should_render() {
662            let returning = !is_open;
663            let overlay_alpha = (presence.progress * 0.46).clamp(0.0, 0.46);
664            let overlay_bg = Hsla::black().opacity(overlay_alpha);
665            let panel_y = if reduced {
666                0.0
667            } else {
668                (1.0 - modal_spring_t) * 18.0
669            };
670            let panel_alpha = presence.progress.clamp(0.0, 1.0);
671            let (details_alpha, details_y) =
672                card_details_reveal_sample(open_elapsed, returning, reduced);
673            let viewport = window.viewport_size();
674            let (rel_left, rel_top) = root_bounds
675                .borrow()
676                .map(|b| (-f32::from(b.origin.x), -f32::from(b.origin.y)))
677                .unwrap_or((0.0, 0.0));
678
679            let media_modal_el = self.media.as_ref().map(|m| {
680                div()
681                    .w_full()
682                    .min_h(px(140.0))
683                    .overflow_hidden()
684                    .bg(colors.surface_muted)
685                    .rounded_tl(Radii::SURFACE)
686                    .rounded_tr(Radii::SURFACE)
687                    .flex()
688                    .items_center()
689                    .justify_center()
690                    .child(m(window, cx))
691            });
692            let body_modal_el = self.body.as_ref().map(|b| b(window, cx));
693            let footer_modal_el = render_footer(window, cx);
694            let details_modal_el = self.details.as_ref().map(|d| d(window, cx));
695
696            let close_bg = oklab_mix(colors.surface_raised, Hsla::transparent_black(), 0.78);
697            let close_border = oklab_mix(colors.border, Hsla::transparent_black(), 0.70);
698            let close_fg = colors.foreground;
699
700            let close_state_btn = state_cell.clone();
701            let on_open_close = self.on_open_change.clone();
702            let close_state_bg = state_cell.clone();
703            let on_open_bg = self.on_open_change.clone();
704            let close_state_key = state_cell.clone();
705            let on_open_key = self.on_open_change.clone();
706            let panel_bounds_hit = panel_bounds.clone();
707            let panel_bounds_write = panel_bounds.clone();
708
709            Some(
710                deferred(
711                    div()
712                        .id(ElementId::NamedChild(
713                            self.id.clone().into(),
714                            SharedString::from("quick-look-overlay"),
715                        ))
716                        .track_focus(&focus_handle)
717                        .absolute()
718                        .left(px(rel_left))
719                        .top(px(rel_top))
720                        .w(viewport.width)
721                        .h(viewport.height)
722                        .bg(overlay_bg)
723                        .flex()
724                        .items_center()
725                        .justify_center()
726                        .p(Spacing::S4)
727                        .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
728                            if let Some(pb) = *panel_bounds_hit.borrow()
729                                && pb.contains(&ev.position)
730                            {
731                                return;
732                            }
733                            let t_now = motion_now(cx);
734                            if !is_controlled {
735                                let mut st = close_state_bg.borrow_mut();
736                                st.open = false;
737                                st.open_changed_at = t_now;
738                            }
739                            if let Some(ref cb) = on_open_bg {
740                                cb(&false, window, cx);
741                            }
742                            window.refresh();
743                        })
744                        .on_key_down(move |ev: &KeyDownEvent, window, cx| {
745                            if ev.keystroke.key.as_str() == "escape" {
746                                let t_now = motion_now(cx);
747                                if !is_controlled {
748                                    let mut st = close_state_key.borrow_mut();
749                                    st.open = false;
750                                    st.open_changed_at = t_now;
751                                }
752                                if let Some(ref cb) = on_open_key {
753                                    cb(&false, window, cx);
754                                }
755                                window.refresh();
756                            }
757                        })
758                        .child(
759                            div()
760                                .relative()
761                                .top(px(panel_y))
762                                .opacity(panel_alpha)
763                                .w(px(CARD_QUICK_LOOK_MAX_W))
764                                .max_w_full()
765                                .rounded(Radii::SURFACE)
766                                .border_1()
767                                .border_color(colors.border)
768                                .bg(colors.surface_raised)
769                                .text_color(colors.foreground)
770                                .shadow(Shadows::floating(theme.mode))
771                                .overflow_hidden()
772                                .on_mouse_down(MouseButton::Left, |_, _, cx| {
773                                    cx.stop_propagation();
774                                })
775                                .child(
776                                    canvas(
777                                        move |bounds, _, _| {
778                                            *panel_bounds_write.borrow_mut() = Some(bounds);
779                                        },
780                                        |_, _, _, _| {},
781                                    )
782                                    .size_full()
783                                    .absolute()
784                                    .inset_0(),
785                                )
786                                .when_some(media_modal_el, |el, m| el.child(m))
787                                .child(
788                                    div()
789                                        .id(ElementId::NamedChild(
790                                            self.id.clone().into(),
791                                            SharedString::from("quick-look-close"),
792                                        ))
793                                        .absolute()
794                                        .top(Spacing::S4)
795                                        .right(Spacing::S4)
796                                        .w(Spacing::S8)
797                                        .h(Spacing::S8)
798                                        .rounded(Radii::PILL)
799                                        .border_1()
800                                        .border_color(close_border)
801                                        .bg(close_bg)
802                                        .cursor_pointer()
803                                        .hover(move |s| s.bg(colors.surface_raised))
804                                        .flex()
805                                        .items_center()
806                                        .justify_center()
807                                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
808                                            cx.stop_propagation();
809                                            let t_now = motion_now(cx);
810                                            if !is_controlled {
811                                                let mut st = close_state_btn.borrow_mut();
812                                                st.open = false;
813                                                st.open_changed_at = t_now;
814                                            }
815                                            if let Some(ref cb) = on_open_close {
816                                                cb(&false, window, cx);
817                                            }
818                                            window.refresh();
819                                        })
820                                        .child(
821                                            canvas(
822                                                |_, _, _| {},
823                                                move |bounds, _, window, _| {
824                                                    let cx_p = f32::from(bounds.origin.x)
825                                                        + f32::from(bounds.size.width) * 0.5;
826                                                    let cy_p = f32::from(bounds.origin.y)
827                                                        + f32::from(bounds.size.height) * 0.5;
828                                                    paint_close_icon(cx_p, cy_p, close_fg, window);
829                                                },
830                                            )
831                                            .size_full(),
832                                        ),
833                                )
834                                .child(
835                                    div()
836                                        .w_full()
837                                        .p(Spacing::S6)
838                                        .flex()
839                                        .flex_col()
840                                        .child(
841                                            div()
842                                                .text_size(Typography::TEXT_XL)
843                                                .font_medium()
844                                                .text_color(colors.foreground)
845                                                .child(self.title),
846                                        )
847                                        .when_some(self.description, |el, desc| {
848                                            el.child(
849                                                div()
850                                                    .mt(Spacing::S2)
851                                                    .text_size(Typography::TEXT_SM)
852                                                    .text_color(colors.text_secondary)
853                                                    .child(desc),
854                                            )
855                                        })
856                                        .when_some(body_modal_el, |el, b| el.child(b))
857                                        .when_some(footer_modal_el, |el, f| el.child(f))
858                                        .when_some(details_modal_el, |el, d| {
859                                            el.child(
860                                                div()
861                                                    .relative()
862                                                    .top(px(details_y))
863                                                    .opacity(details_alpha)
864                                                    .mt(Spacing::S6)
865                                                    .pt(Spacing::S5)
866                                                    .border_t_1()
867                                                    .border_color(colors.border)
868                                                    .text_size(Typography::TEXT_SM)
869                                                    .text_color(colors.text_secondary)
870                                                    .child(d),
871                                            )
872                                        }),
873                                ),
874                        ),
875                )
876                .with_priority(10)
877                .into_any_element(),
878            )
879        } else {
880            None
881        };
882
883        let root_bounds_write = root_bounds.clone();
884        div()
885            .relative()
886            .w_full()
887            .min_w(px(0.0))
888            .child(
889                canvas(
890                    move |bounds, _, _| {
891                        *root_bounds_write.borrow_mut() = Some(bounds);
892                    },
893                    |_, _, _, _| {},
894                )
895                .absolute()
896                .inset_0(),
897            )
898            .child(card_box)
899            .when_some(modal_layer, |el, m| el.child(m))
900            .into_any_element()
901    }
902}
903
904#[cfg(test)]
905mod tests {
906    use super::*;
907
908    #[test]
909    fn card_status_word_stagger_and_details_reveal_timings() {
910        let (a0, y0) = card_status_word_sample(0.02, 0, false);
911        let (a1, y1) = card_status_word_sample(0.02, 2, false);
912        assert!(a0 > 0.0 && y0 < 4.5);
913        assert_eq!(a1, 0.0);
914        assert_eq!(y1, 4.5);
915
916        let (da_early, dy_early) = card_details_reveal_sample(0.05, false, false);
917        assert_eq!(da_early, 0.0);
918        assert_eq!(dy_early, 6.0);
919
920        let (da_done, dy_done) = card_details_reveal_sample(0.40, false, false);
921        assert_eq!(da_done, 1.0);
922        assert_eq!(dy_done, 0.0);
923
924        let (da_ret, _) = card_details_reveal_sample(0.40, true, false);
925        assert_eq!(da_ret, 0.0);
926    }
927}