Skip to main content

bhoo/systems/material/
carousel.rs

1use crate::*;
2
3/// Supported carousel layouts. Material keyline parity remains in progress.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum CarouselLayout {
6    #[default]
7    Uncontained,
8    FullScreen,
9    CenteredHero,
10    MultiBrowse,
11}
12
13#[derive(Clone, Copy, Debug)]
14pub struct CarouselOptions {
15    pub layout: CarouselLayout,
16    pub item_width: f32,
17    pub spacing: f32,
18    pub snap: bool,
19    pub rtl: bool,
20    pub enabled: bool,
21}
22impl Default for CarouselOptions {
23    fn default() -> Self {
24        Self {
25            layout: CarouselLayout::Uncontained,
26            item_width: 220.0,
27            spacing: 8.0,
28            snap: true,
29            rtl: false,
30            enabled: true,
31        }
32    }
33}
34
35#[derive(Clone, Copy, Debug)]
36pub struct CarouselItem<'a> {
37    pub label: &'a str,
38    pub image: Option<&'a Image>,
39    pub enabled: bool,
40}
41
42#[derive(Default)]
43pub struct CarouselState {
44    offset: f32,
45    from: f32,
46    target: f32,
47    started: f64,
48    animating: bool,
49    index: usize,
50    max_index: usize,
51    pending: Option<usize>,
52    pending_focus: Option<usize>,
53    drag_origin: Option<f32>,
54    drag_initial: f32,
55    dragging: bool,
56    step: f32,
57    maximum: f32,
58}
59impl CarouselState {
60    pub fn index(&self) -> usize {
61        self.index
62    }
63    pub fn can_previous(&self) -> bool {
64        self.index > 0
65    }
66    pub fn can_next(&self) -> bool {
67        self.index < self.max_index
68    }
69    pub fn go_to(&mut self, index: usize) {
70        self.pending = Some(index);
71    }
72    pub fn next(&mut self) {
73        self.go_to(self.index.saturating_add(1).min(self.max_index));
74    }
75    pub fn previous(&mut self) {
76        self.go_to(self.index.saturating_sub(1));
77    }
78}
79
80// Approximate start-aligned multi-browse keylines. Centers and sizes are
81// linearly interpolated so adjacent masks remain separated during dragging.
82fn multi_browse_keyline(index: i32, large: f32, large_count: usize, medium: f32, small: f32, spacing: f32) -> (f32, f32) {
83    if index < 0 {
84        return (-spacing - small * 0.5 + (index + 1) as f32 * (small + spacing), small);
85    }
86    let large_count = large_count as i32;
87    if index < large_count { return (index as f32 * (large + spacing) + large * 0.5, large); }
88    let before = large_count as f32 * (large + spacing);
89    if medium > 0.0 && index == large_count { return (before + medium * 0.5, medium); }
90    let first_small = large_count + i32::from(medium > 0.0);
91    let before = before + if medium > 0.0 { medium + spacing } else { 0.0 };
92    (before + small * 0.5 + (index - first_small) as f32 * (small + spacing), small)
93}
94
95fn multi_browse_sample(relative: f32, large: f32, large_count: usize, medium: f32, small: f32, spacing: f32) -> (f32, f32) {
96    let left = relative.floor() as i32;
97    let t = relative - left as f32;
98    let a = multi_browse_keyline(left, large, large_count, medium, small, spacing);
99    let b = multi_browse_keyline(left + 1, large, large_count, medium, small, spacing);
100    (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
101}
102
103impl Frame<'_> {
104    /// A bounded, virtualized uncontained or full-screen carousel. Items are
105    /// independently actionable; a drag cancels the pressed item's activation.
106    pub fn carousel(
107        &mut self,
108        id: u64,
109        bounds: Rect,
110        items: &[CarouselItem<'_>],
111        state: &mut CarouselState,
112        options: CarouselOptions,
113    ) -> Option<usize> {
114        self.carousel_named(id, bounds, items, state, options, "Carousel")
115    }
116
117    /// A carousel with a caller-provided accessible region name.
118    pub fn carousel_named(
119        &mut self,
120        id: u64,
121        bounds: Rect,
122        items: &[CarouselItem<'_>],
123        state: &mut CarouselState,
124        options: CarouselOptions,
125        label: &str,
126    ) -> Option<usize> {
127        let count = items.len();
128        if count == 0
129            || count > 4096
130            || id > u64::MAX - count as u64
131            || !bounds.x.is_finite()
132            || !bounds.y.is_finite()
133            || !bounds.width.is_finite()
134            || !bounds.height.is_finite()
135            || bounds.width <= 0.0
136            || bounds.height <= 0.0
137            || !options.item_width.is_finite()
138            || !options.spacing.is_finite()
139        {
140            return None;
141        }
142        let visible = bounds.intersect(self.clip);
143        if visible.width <= 0.0 || visible.height <= 0.0 {
144            if state.animating {
145                state.offset = state.target;
146            }
147            state.animating = false;
148            state.drag_origin = None;
149            return None;
150        }
151        let enabled = self.enabled && options.enabled;
152        let hero = options.layout == CarouselLayout::CenteredHero;
153        let browse = options.layout == CarouselLayout::MultiBrowse;
154        let spacing = if options.layout == CarouselLayout::FullScreen {
155            0.0
156        } else {
157            let gap = options.spacing.clamp(0.0, 64.0);
158            if hero || browse { gap.min(bounds.width / 4.0) } else { gap }
159        };
160        let small = if browse && count > 1 {
161            (bounds.width / 8.0).clamp(40.0, 56.0).min(bounds.width / 3.0)
162        } else if hero && count >= 3 && bounds.width >= 168.0 {
163            (bounds.width / 6.0).clamp(40.0, 56.0)
164        } else {
165            0.0
166        };
167        let mut medium = 0.0;
168        let mut large_count = 1;
169        let width = if options.layout == CarouselLayout::FullScreen || (browse && count == 1) {
170            bounds.width
171        } else if browse {
172            let available = (bounds.width - small - spacing).max(1.0);
173            let target = options.item_width.clamp(small.max(1.0), available.max(small.max(1.0)));
174            large_count = (((bounds.width - small + spacing) / (target + spacing)).floor() as usize)
175                .clamp(1, count - 1);
176            let leftover = bounds.width - large_count as f32 * target - (large_count + 1) as f32 * spacing - small;
177            if count > large_count + 1 && leftover >= small && leftover < target {
178                medium = leftover;
179                target
180            } else {
181                ((bounds.width - small - large_count as f32 * spacing) / large_count as f32).max(1.0)
182            }
183        } else if hero {
184            let neighbor_space = if small > 0.0 {
185                2.0 * (small + spacing)
186            } else {
187                0.0
188            };
189            (bounds.width - neighbor_space).max(1.0)
190        } else {
191            options
192                .item_width
193                .clamp(48.0_f32.min(bounds.width), bounds.width)
194        };
195        let step = width + spacing;
196        let maximum = if hero || browse {
197            count.saturating_sub(1) as f32 * step
198        } else {
199            ((count as f32 * step - spacing) - bounds.width).max(0.0)
200        };
201        state.max_index = if hero || browse { count - 1 } else { (maximum / step).ceil() as usize };
202        state.index = state.index.min(state.max_index);
203        if (state.step - step).abs() > 0.001 || (state.maximum - maximum).abs() > 0.001 {
204            let relative = if state.step > 0.0 {
205                state.offset / state.step
206            } else {
207                0.0
208            };
209            state.offset = (relative * step).clamp(0.0, maximum);
210            state.target = (state.index as f32 * step).min(maximum);
211            if state.animating {
212                state.from = state.offset;
213                state.started = self.ui.time;
214                state.animating = (state.target - state.offset).abs() > 0.01;
215            }
216            state.drag_origin = None;
217            state.dragging = false;
218            state.step = step;
219            state.maximum = maximum;
220        }
221        if state
222            .pending_focus
223            .is_some_and(|index| index >= count || !items[index].enabled)
224        {
225            state.pending_focus = None;
226        }
227        state.offset = state.offset.clamp(0.0, maximum);
228        if let Some(index) = state.pending.take() {
229            state.index = index.min(state.max_index);
230            state.from = state.offset;
231            state.target = (state.index as f32 * step).min(maximum);
232            state.started = self.ui.time;
233            state.animating = !self.reduced_motion() && (state.target - state.offset).abs() > 0.01;
234            if !state.animating {
235                state.offset = state.target;
236            }
237        }
238        if state.animating {
239            let progress = ((self.ui.time - state.started) / 0.3).clamp(0.0, 1.0) as f32;
240            let eased = crate::timing::Easing::Cubic([0.2, 0.0, 0.0, 1.0]).sample(progress);
241            state.offset = (state.from + (state.target - state.from) * eased).clamp(0.0, maximum);
242            state.animating = progress < 1.0 && !self.reduced_motion();
243            if state.animating {
244                self.ui.continuous = true;
245            } else {
246                state.offset = state.target;
247            }
248        }
249        if enabled && self.input.pressed && self.pointer_in(bounds) {
250            state.drag_origin = self.input.pointer.map(|p| p[0]);
251            state.drag_initial = state.offset;
252            state.dragging = false;
253            state.animating = false;
254        }
255        if let (true, Some(origin), Some(pointer)) =
256            (enabled, state.drag_origin, self.input.pointer)
257        {
258            let distance = if options.rtl {
259                pointer[0] - origin
260            } else {
261                origin - pointer[0]
262            };
263            if distance.abs() > 4.0 {
264                state.dragging = true;
265            }
266            if state.dragging {
267                let next_offset = (state.drag_initial + distance).clamp(0.0, maximum);
268                if next_offset != state.offset {
269                    self.ui.continuous = true;
270                }
271                state.offset = next_offset;
272                state.index = ((state.offset / step).round() as usize).min(state.max_index);
273                self.ui.active = None;
274            }
275        }
276        if self.input.released || self.input.cancelled || self.input.blurred || !enabled {
277            if state.dragging {
278                self.ui.active = None;
279                if options.snap || matches!(options.layout, CarouselLayout::FullScreen | CarouselLayout::CenteredHero | CarouselLayout::MultiBrowse) {
280                    state.go_to(state.index);
281                    self.ui.continuous = true;
282                }
283            }
284            state.drag_origin = None;
285            state.dragging = false;
286        }
287        if enabled
288            && self.pointer_in(bounds)
289            && self.input.scroll[1].is_finite()
290            && self.input.scroll[1] != 0.0
291        {
292            if self.input.scroll[1] > 0.0 {
293                state.next();
294            } else {
295                state.previous();
296            }
297            self.ui.continuous = true;
298        }
299        self.semantic(
300            Response {
301                id,
302                bounds: visible,
303                enabled,
304                ..Response::default()
305            },
306            Role::Carousel,
307            label,
308            false,
309            None,
310            Some(state.index as f32 + 1.0),
311            Some([1.0, count as f32]),
312        );
313        let first = if hero || browse {
314            ((state.offset / step).floor().max(0.0) as usize).saturating_sub(large_count + 2)
315        } else {
316            ((state.offset / step).floor() as usize).min(count - 1)
317        };
318        let last = if hero || browse {
319            ((state.offset / step).ceil() as usize + large_count + 3).min(count)
320        } else {
321            (((state.offset + bounds.width) / step).ceil() as usize + 1).min(count)
322        };
323        let mut chosen = None;
324        self.within(bounds, |f| {
325            for (index, item) in items.iter().enumerate().take(last).skip(first) {
326                let shift = index as f32 * step - state.offset;
327                let item_bounds = if browse {
328                    let position = state.offset / step;
329                    let relative = index as f32 - position;
330                    let start = multi_browse_sample(relative, width, large_count, medium, small, spacing);
331                    let end = multi_browse_sample(-relative, width, large_count, medium, small, spacing);
332                    let end_mix = (position - count.saturating_sub(2) as f32).clamp(0.0, 1.0);
333                    let center = start.0 + (bounds.width - end.0 - start.0) * end_mix;
334                    let item_width = start.1 + (end.1 - start.1) * end_mix;
335                    let logical_x = center - item_width * 0.5;
336                    Rect { x: if options.rtl { bounds.x + bounds.width - logical_x - item_width } else { bounds.x + logical_x }, width: item_width, ..bounds }
337                } else if hero {
338                    let position = state.offset / step;
339                    let relative = index as f32 - position;
340                    let distance = relative.abs();
341                    let item_width = if small == 0.0 {
342                        width
343                    } else {
344                        width + (small - width) * distance.min(1.0)
345                    };
346                    let anchor = (bounds.width - width) * 0.5;
347                    let start_edge = (1.0 - position).clamp(0.0, 1.0);
348                    let end_edge =
349                        (1.0 - (count.saturating_sub(1) as f32 - position)).clamp(0.0, 1.0);
350                    let center = bounds.width * 0.5 - anchor * start_edge + anchor * end_edge;
351                    let neighbor_width = if small == 0.0 { width } else { small };
352                    let neighbor_step = (width + neighbor_width) * 0.5 + spacing;
353                    let displacement = if distance <= 1.0 {
354                        distance * neighbor_step
355                    } else {
356                        neighbor_step + (distance - 1.0) * (neighbor_width + spacing)
357                    };
358                    let logical_x = center + relative.signum() * displacement - item_width * 0.5;
359                    Rect {
360                        x: if options.rtl {
361                            bounds.x + bounds.width - logical_x - item_width
362                        } else {
363                            bounds.x + logical_x
364                        },
365                        width: item_width,
366                        ..bounds
367                    }
368                } else {
369                    Rect {
370                        x: if options.rtl {
371                            bounds.x + bounds.width - width - shift
372                        } else {
373                            bounds.x + shift
374                        },
375                        width,
376                        ..bounds
377                    }
378                };
379                let visible_item = item_bounds.intersect(f.clip);
380                if visible_item.width <= 0.0 || visible_item.height <= 0.0 {
381                    continue;
382                }
383                let r = f.target(
384                    id + index as u64 + 1,
385                    item_bounds,
386                    item.label,
387                    enabled && item.enabled,
388                    Role::CarouselItem,
389                );
390                if let Some(node) = f.ui.semantics.last_mut() {
391                    node.value = Some(index as f32 + 1.0);
392                    node.range = Some([1.0, count as f32]);
393                }
394                if r.clicked {
395                    chosen = Some(index);
396                }
397                if let Some(image) = item.image {
398                    if hero || browse {
399                        // Fit content to the large item first, then reveal the
400                        // centered portion covered by the current mask. This
401                        // preserves content scale as the mask changes.
402                        let content = Rect { width, ..item_bounds };
403                        if let Some((_, mut uv)) = crate::media::fit_image(content, image.width(), image.height(), ImageFit::Cover)
404                            && item_bounds.intersect(f.clip).width > 0.0
405                            && item_bounds.intersect(f.clip).height > 0.0
406                        {
407                            let fraction = (item_bounds.width / width).clamp(0.0, 1.0);
408                            let inset = (uv[2] - uv[0]) * (1.0 - fraction) * 0.5;
409                            uv[0] += inset;
410                            uv[2] -= inset;
411                            f.commands.push(DrawCommand::Image { bounds: item_bounds, uv, radius: 16.0, color: Color(255, 255, 255, 255), image: image.clone() });
412                        }
413                    } else {
414                        f.paint_image(item_bounds, image, ImageFit::Cover, 16.0);
415                    }
416                } else {
417                    f.paint_rect(
418                        item_bounds,
419                        16.0,
420                        if index % 2 == 0 {
421                            f.ui.theme.secondary
422                        } else {
423                            f.ui.theme.primary_container
424                        },
425                    );
426                }
427                f.state_layer(r, 16.0, f.ui.theme.text);
428                let text_width = f.text_width(item.label, TextStyle { size: 14.0, ..TextStyle::default() });
429                if !(hero || browse) || item_bounds.width >= text_width + 24.0 {
430                    let label = Rect {
431                        y: item_bounds.y + item_bounds.height - 40.0,
432                        height: 40.0,
433                        ..item_bounds
434                    };
435                    f.commands
436                        .push(DrawCommand::PushClip(label.intersect(f.clip)));
437                    f.paint_rect(item_bounds, 16.0, f.ui.theme.background.opacity(0.8));
438                    f.commands.push(DrawCommand::PopClip);
439                    f.styled_text(
440                        label,
441                        item.label,
442                        f.ui.theme.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
443                        TextStyle {
444                            size: 14.0,
445                            padding: 12.0,
446                            ..TextStyle::default()
447                        },
448                    );
449                }
450                f.focus_ring(r);
451            }
452        });
453        if enabled
454            && !self.key_consumed
455            && let Some(key) = self.input.key
456            && key.pressed
457            && matches!(key.key, Key::Left | Key::Right | Key::Home | Key::End)
458            && let Some(current) = self
459                .ui
460                .focused
461                .and_then(|focus| focus.checked_sub(id + 1))
462                .filter(|index| *index < count as u64)
463        {
464            let next = match key.key {
465                Key::Home => (0..count).find(|&index| items[index].enabled),
466                Key::End => (0..count).rev().find(|&index| items[index].enabled),
467                _ if (key.key == Key::Right) != options.rtl => {
468                    ((current as usize + 1)..count).find(|&index| items[index].enabled)
469                }
470                _ => (0..current as usize).rev().find(|&index| items[index].enabled),
471            };
472            if let Some(next) = next {
473                state.go_to(next);
474                state.pending_focus = Some(next);
475                self.key_consumed = true;
476                self.ui.continuous = true;
477            }
478        }
479        if let Some(index) = state.pending_focus
480            && !state.animating
481            && state.pending.is_none()
482            && self
483                .ui
484                .semantics
485                .iter()
486                .any(|n| n.id == id + index as u64 + 1 && n.enabled)
487        {
488            self.request_focus(id + index as u64 + 1);
489            state.pending_focus = None;
490            self.ui.continuous = true;
491        }
492        chosen
493    }
494}
495
496#[cfg(test)]
497#[path = "carousel.spec.rs"]
498mod tests;