Skip to main content

bhoo/systems/material/
card.rs

1use crate::*;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub enum CardVariant {
5    #[default]
6    Filled,
7    Outlined,
8    Elevated,
9}
10
11#[derive(Clone, Copy, Debug)]
12pub struct CardOptions {
13    pub variant: CardVariant,
14    pub interactive: bool,
15    pub enabled: bool,
16}
17impl Default for CardOptions {
18    fn default() -> Self {
19        Self {
20            variant: CardVariant::Filled,
21            interactive: false,
22            enabled: true,
23        }
24    }
25}
26
27/// Caller-owned visual states of a Material card.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum CardIconGravity { TopStart, #[default] TopEnd, BottomStart, BottomEnd }
30#[derive(Clone, Copy, Debug)]
31pub struct CardVisualState {
32    pub dragged: bool,
33    pub checked: bool,
34    pub checkable: bool,
35    pub rtl: bool,
36    pub checked_icon_size: f32,
37    pub checked_icon_margin: f32,
38    pub checked_icon_gravity: CardIconGravity,
39    pub checked_icon_tint: Option<Color>,
40}
41#[derive(Clone, Copy, Debug, Default)]
42pub(crate) struct CardAppearance {
43    pub background:Option<Color>,
44    pub foreground:Option<Color>,
45    pub stroke_color:Option<Color>,
46    pub stroke_width:Option<f32>,
47    pub corner_radius:Option<f32>,
48    pub elevation:Option<f32>,
49    pub ripple_color:Option<Color>,
50}
51impl Default for CardVisualState {
52    fn default()->Self { Self {dragged:false,checked:false,checkable:false,rtl:false,checked_icon_size:24.0,checked_icon_margin:8.0,checked_icon_gravity:CardIconGravity::TopEnd,checked_icon_tint:None} }
53}
54
55impl Frame<'_> {
56    /// Paint a passive or actionable card around caller-provided content.
57    /// Child targets are processed first, so nested action clicks do not
58    /// also activate an enclosing actionable card.
59    pub fn card(
60        &mut self,
61        id: u64,
62        bounds: Rect,
63        label: &str,
64        options: CardOptions,
65        build: impl FnOnce(&mut Self),
66    ) -> Option<Response> {
67        self.card_with_dragged(id,bounds,label,options,false,build)
68    }
69    /// Paint a card with the caller-owned Material dragged state.
70    pub fn card_with_dragged(
71        &mut self,
72        id: u64,
73        bounds: Rect,
74        label: &str,
75        options: CardOptions,
76        dragged: bool,
77        build: impl FnOnce(&mut Self),
78    ) -> Option<Response> {
79        self.card_with_state(id,bounds,label,options,CardVisualState {dragged,..CardVisualState::default()},build)
80    }
81    /// Paint caller-controlled checked and dragged card states.
82    pub fn card_with_state(
83        &mut self,
84        id: u64,
85        bounds: Rect,
86        label: &str,
87        options: CardOptions,
88        state: CardVisualState,
89        build: impl FnOnce(&mut Self),
90    ) -> Option<Response> {
91        self.card_with_state_inset(id,bounds,label,options,state,16.0,CardAppearance::default(),build)
92    }
93    pub(crate) fn card_with_state_inset(
94        &mut self,
95        id:u64,
96        bounds:Rect,
97        label:&str,
98        options:CardOptions,
99        state:CardVisualState,
100        inset:f32,
101        appearance:CardAppearance,
102        build:impl FnOnce(&mut Self),
103    ) -> Option<Response> {
104        if !bounds.x.is_finite()
105            || !bounds.y.is_finite()
106            || !bounds.width.is_finite()
107            || !bounds.height.is_finite()
108            || bounds.width <= 0.0
109            || bounds.height <= 0.0
110        {
111            return None;
112        }
113        let t = self.ui.theme;
114        let radius=appearance.corner_radius.filter(|v|v.is_finite()).unwrap_or(12.0).clamp(0.0,bounds.width.min(bounds.height)*0.5);
115        let enabled = options.enabled && self.enabled;
116        let hovered = options.interactive
117            && enabled
118            && self.input.pointer_kind != PointerKind::Touch
119            && self
120                .input
121                .pointer
122                .is_some_and(|p| bounds.intersect(self.clip).contains(p));
123        let pressed = self.ui.active == Some(id);
124        let drag_target=if state.dragged && enabled {1.0} else {0.0};
125        let drag_progress=self.animate(id, 200, drag_target, drag_target).clamp(0.0,1.0);
126        let checked_target=if state.checked {1.0} else {0.0};
127        // Material Android fades the checked icon linearly using motion short2
128        // (100 ms) on entry and short1 (50 ms) on exit; reversals shorten.
129        let checked_progress=self.ui.motion.css_tween(id,201,checked_target,checked_target,
130            crate::timing::TweenSpec::new(0.100,crate::timing::Easing::Linear),
131            crate::timing::TweenSpec::new(0.050,crate::timing::Easing::Linear)).clamp(0.0,1.0);
132        let elevation = match options.variant {
133            CardVariant::Elevated => {
134                if hovered && !pressed {
135                    2
136                } else {
137                    1
138                }
139            }
140            _ if hovered && !pressed => 1,
141            _ => 0,
142        };
143        if let Some(dp)=appearance.elevation {
144            self.elevation_dp(bounds,radius,dp);
145        } else if elevation > 0 && (enabled || options.variant == CardVariant::Elevated) {
146            self.elevation(bounds, radius, elevation);
147        }
148        if drag_progress>0.001 {
149            self.shadow(bounds,radius,[0.0,3.0],5.0,-1.0,Color(0,0,0,255).opacity(0.2*drag_progress));
150            self.shadow(bounds,radius,[0.0,6.0],10.0,0.0,Color(0,0,0,255).opacity(0.14*drag_progress));
151            self.shadow(bounds,radius,[0.0,1.0],18.0,0.0,Color(0,0,0,255).opacity(0.12*drag_progress));
152        }
153        let surface = appearance.background.unwrap_or(match (options.variant, enabled) {
154            (CardVariant::Filled, true) => t.surface_highest,
155            (CardVariant::Filled, false) => t.surface_highest.mix(t.surface_variant,0.38),
156            (CardVariant::Elevated, true) => t.surface_low,
157            (CardVariant::Elevated, false) => t.background,
158            (CardVariant::Outlined, _) => t.background,
159        });
160        let default_stroke=if !enabled {t.surface_low.mix(t.outline,0.12)} else if state.checked {t.secondary} else {t.outline_variant};
161        let custom_stroke=appearance.stroke_width.is_some() || appearance.stroke_color.is_some();
162        if custom_stroke {
163            self.paint_rect(bounds,radius,surface);
164            let width=appearance.stroke_width.unwrap_or(if options.variant==CardVariant::Outlined {1.0} else {0.0}).max(0.0).min(bounds.width.min(bounds.height)*0.5);
165            let color=appearance.stroke_color.unwrap_or(default_stroke);
166            if width>0.0 {self.commands.push(DrawCommand::Outline {bounds,radius,width,color});}
167        } else if options.variant == CardVariant::Outlined {
168            self.paint_rect(
169                bounds,
170                radius,
171                default_stroke,
172            );
173            self.paint_rect(bounds.inset(1.0), (radius-1.0).max(0.0), surface);
174        } else {
175            self.paint_rect(bounds, radius, surface);
176        }
177        self.within(bounds.inset(inset), |f| {
178            let previous=f.content_color;
179            if !enabled {f.content_color=Some(previous.unwrap_or(t.text).opacity(if previous.is_some() {1.0} else {0.38}));}
180            f.with_enabled(enabled, build);
181            f.content_color=previous;
182        });
183        if let Some(color)=appearance.foreground {self.paint_rect(bounds,radius,color);}
184        else if state.checked {self.paint_rect(bounds,radius,t.secondary.opacity(0.16));}
185        else if state.dragged {self.paint_rect(bounds,radius,t.text.opacity(0.08));}
186        if checked_progress>0.001 {
187            let alpha=checked_progress;
188            let size=if state.checked_icon_size.is_finite() {state.checked_icon_size.max(0.0)} else {0.0};
189            let margin=if state.checked_icon_margin.is_finite() {state.checked_icon_margin.max(0.0)} else {0.0};
190            if size>0.0 && bounds.width>=size+2.0*margin && bounds.height>=size+2.0*margin {
191                let at_end=matches!(state.checked_icon_gravity,CardIconGravity::TopEnd|CardIconGravity::BottomEnd);
192                let at_bottom=matches!(state.checked_icon_gravity,CardIconGravity::BottomStart|CardIconGravity::BottomEnd);
193                let icon=Rect {x:if at_end != state.rtl {bounds.x+bounds.width-margin-size} else {bounds.x+margin},y:if at_bottom {bounds.y+bounds.height-margin-size} else {bounds.y+margin},width:size,height:size};
194                let index=crate::beercss_shapes::SHAPES.len()+crate::icons::material_navigation::ICONS.len()+crate::icons::material_symbols::ICONS.len()+1+crate::shapes::android_clock_shapes::SHAPES.len();
195                let tint=state.checked_icon_tint.unwrap_or(if enabled {t.secondary} else {t.outline.opacity(0.12)});
196                self.commands.push(DrawCommand::Shape {bounds:icon,index:index as u8,color:tint.opacity(alpha),rotation:0.0});
197            }
198        }
199        if options.interactive {
200            let response = self.target(id, bounds, label, enabled, Role::Button);
201            let default_ink=if state.checked && !response.pressed || state.checkable && !state.checked && response.pressed {t.secondary} else {t.on_surface_variant};
202            self.state_layer(response, radius, appearance.ripple_color.unwrap_or(default_ink));
203            self.focus_ring(response);
204            Some(response)
205        } else {
206            None
207        }
208    }
209
210    /// Horizontal swipe-to-dismiss card container with asymmetric top/bottom corner radii,
211    /// opacity fade during drag, threshold commit, and smooth spring return when released early.
212    /// Returns `true` on the frame the item is dismissed.
213    #[allow(clippy::too_many_arguments)]
214    pub fn swipe_dismiss_box(
215        &mut self,
216        id: u64,
217        bounds: Rect,
218        state: &mut SwipeDismissState,
219        top_radius: f32,
220        bottom_radius: f32,
221        build: impl FnOnce(&mut Self, Rect),
222    ) -> bool {
223        if state.dismissed {
224            return false;
225        }
226        let mut just_dismissed = false;
227        let threshold = (bounds.width * 0.42).max(72.0);
228        if let Some(p) = self.input.pointer {
229            if self.input.pressed && bounds.contains(p) {
230                state.dragging = true;
231                state.start_x = p[0] - state.offset;
232            }
233            if state.dragging {
234                state.offset = p[0] - state.start_x;
235            }
236        }
237        if state.dragging && (self.input.released || self.input.cancelled || self.input.blurred) {
238            state.dragging = false;
239            if state.offset.abs() >= threshold {
240                state.dismissed = true;
241                just_dismissed = true;
242            }
243        }
244        let display_offset = if state.dragging || state.dismissed {
245            state.offset
246        } else {
247            let anim = self.spatial(id, 77, 0.0, state.offset);
248            if anim.abs() < 0.25 {
249                state.offset = 0.0;
250                0.0
251            } else {
252                state.offset = anim;
253                anim
254            }
255        };
256        let alpha = (1.0 - (display_offset.abs() / (bounds.width.max(1.0) * 0.85))).clamp(0.15, 1.0);
257        let shifted = Rect { x: bounds.x + display_offset, ..bounds };
258        let t = self.theme();
259        self.with_opacity(alpha, |f| {
260            f.paint_asym_rect(shifted, top_radius, bottom_radius, t.surface_low);
261            f.within(shifted, |f| build(f, shifted));
262        });
263        just_dismissed
264    }
265}
266
267/// Caller-owned horizontal swipe-to-dismiss state for `Frame::swipe_dismiss_box`.
268#[derive(Clone, Copy, Debug, Default)]
269pub struct SwipeDismissState {
270    pub offset: f32,
271    pub dragging: bool,
272    pub dismissed: bool,
273    start_x: f32,
274}
275
276impl SwipeDismissState {
277    /// Normalized detach progress in `0.0..=1.0` for morphing adjacent segmented card corners.
278    pub fn detach_progress(&self) -> f32 {
279        if self.dismissed {
280            1.0
281        } else {
282            (self.offset.abs() / 24.0).clamp(0.0, 1.0)
283        }
284    }
285}
286
287/// Compute `(top_radius, bottom_radius)` for an item at `index` inside a segmented stacked card group
288/// (M3 Expressive pattern: `outer` at group ends, `inner` between touching cards, dynamically
289/// rounding to `outer` as a card or its neighbor detaches).
290pub fn segmented_card_radii(
291    index: usize,
292    count: usize,
293    outer: f32,
294    inner: f32,
295    prev_detach: f32,
296    self_detach: f32,
297    next_detach: f32,
298) -> (f32, f32) {
299    let base_top = if index == 0 { outer } else { inner };
300    let base_bot = if index + 1 >= count { outer } else { inner };
301    let t_top = prev_detach.max(self_detach).clamp(0.0, 1.0);
302    let t_bot = next_detach.max(self_detach).clamp(0.0, 1.0);
303    (base_top + (outer - base_top) * t_top, base_bot + (outer - base_bot) * t_bot)
304}
305
306#[cfg(test)]
307#[path = "card.spec.rs"]
308mod tests;