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(Debug, 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; 2]>,
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(
83    index: i32,
84    large: f32,
85    large_count: usize,
86    medium: f32,
87    small: f32,
88    spacing: f32,
89) -> (f32, f32) {
90    if index < 0 {
91        return (
92            -spacing - small * 0.5 + (index + 1) as f32 * (small + spacing),
93            small,
94        );
95    }
96    let large_count = large_count as i32;
97    if index < large_count {
98        return (index as f32 * (large + spacing) + large * 0.5, large);
99    }
100    let before = large_count as f32 * (large + spacing);
101    if medium > 0.0 && index == large_count {
102        return (before + medium * 0.5, medium);
103    }
104    let first_small = large_count + i32::from(medium > 0.0);
105    let before = before + if medium > 0.0 { medium + spacing } else { 0.0 };
106    (
107        before + small * 0.5 + (index - first_small) as f32 * (small + spacing),
108        small,
109    )
110}
111
112fn multi_browse_sample(
113    relative: f32,
114    large: f32,
115    large_count: usize,
116    medium: f32,
117    small: f32,
118    spacing: f32,
119) -> (f32, f32) {
120    let left = relative.floor() as i32;
121    let t = relative - left as f32;
122    let a = multi_browse_keyline(left, large, large_count, medium, small, spacing);
123    let b = multi_browse_keyline(left + 1, large, large_count, medium, small, spacing);
124    (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
125}
126
127impl Frame<'_> {
128    /// Render interactive, viewport-wide custom pages with a shared drag and snap controller.
129    /// A horizontal drag cancels child activation. A vertical drag stays available
130    /// to the containing scroll view. The caller renders page contents and indicators.
131    pub fn carousel_pages(
132        &mut self,
133        bounds: Rect,
134        count: usize,
135        state: &mut CarouselState,
136        mut render: impl FnMut(&mut Self, usize, Rect),
137    ) {
138        let visible = bounds.intersect(self.clip);
139        if count == 0
140            || !bounds.width.is_finite()
141            || bounds.width <= 0.0
142            || visible.width <= 0.0
143            || visible.height <= 0.0
144        {
145            state.drag_origin = None;
146            state.dragging = false;
147            if state.animating {
148                state.offset = state.target;
149                state.animating = false;
150            }
151            return;
152        }
153
154        let step = bounds.width;
155        let maximum = (count - 1) as f32 * step;
156        state.max_index = count - 1;
157        state.index = state.index.min(state.max_index);
158        if state.step != step || state.maximum != maximum {
159            state.step = step;
160            state.maximum = maximum;
161            state.offset = state.index as f32 * step;
162            state.animating = false;
163            state.drag_origin = None;
164            state.dragging = false;
165        }
166        self.update_carousel_motion(bounds, state, self.enabled, false, true, true);
167
168        let first = (state.offset / step).floor() as usize;
169        self.within(bounds, |f| {
170            for index in first..(first + 2).min(count) {
171                let page = Rect {
172                    x: bounds.x + index as f32 * step - state.offset,
173                    ..bounds
174                };
175                if page.intersect(f.clip).width > 0.0 {
176                    f.within(page, |f| render(f, index, page));
177                }
178            }
179        });
180    }
181
182    fn update_carousel_motion(
183        &mut self,
184        bounds: Rect,
185        state: &mut CarouselState,
186        enabled: bool,
187        rtl: bool,
188        snap: bool,
189        pages: bool,
190    ) {
191        let step = state.step;
192        let maximum = state.maximum;
193        state.offset = state.offset.clamp(0.0, maximum);
194        if let Some(index) = state.pending.take() {
195            state.index = index.min(state.max_index);
196            state.from = state.offset;
197            state.target = (state.index as f32 * step).min(maximum);
198            state.started = self.ui.time;
199            state.animating = !self.reduced_motion() && (state.target - state.offset).abs() > 0.01;
200            if !state.animating {
201                state.offset = state.target;
202            }
203        }
204        if state.animating {
205            let progress = ((self.ui.time - state.started) / 0.3).clamp(0.0, 1.0) as f32;
206            let eased = crate::timing::Easing::Cubic([0.2, 0.0, 0.0, 1.0]).sample(progress);
207            state.offset = (state.from + (state.target - state.from) * eased).clamp(0.0, maximum);
208            state.animating = progress < 1.0 && !self.reduced_motion();
209            if state.animating {
210                self.ui.continuous = true;
211            } else {
212                state.offset = state.target;
213            }
214        }
215        if enabled && self.input.pressed && self.pointer_in(bounds) {
216            state.drag_origin = self.input.pointer;
217            state.drag_initial = state.offset;
218            state.dragging = false;
219            state.animating = false;
220        }
221        if let (true, Some(origin), Some(pointer)) = (
222            enabled && !self.input.cancelled && !self.input.blurred,
223            state.drag_origin,
224            self.input.pointer,
225        ) {
226            let distance = if rtl {
227                pointer[0] - origin[0]
228            } else {
229                origin[0] - pointer[0]
230            };
231            if pages
232                && !state.dragging
233                && (pointer[1] - origin[1]).abs() > 8.0
234                && (pointer[1] - origin[1]).abs() >= distance.abs()
235            {
236                state.drag_origin = None;
237            } else if distance.abs() > if pages { 8.0 } else { 4.0 } {
238                state.dragging = true;
239            }
240            if state.dragging {
241                let next_offset = (state.drag_initial + distance).clamp(0.0, maximum);
242                if next_offset != state.offset {
243                    self.ui.continuous = true;
244                }
245                state.offset = next_offset;
246                if !pages {
247                    state.index = ((state.offset / step).round() as usize).min(state.max_index);
248                }
249                self.ui.active = None;
250            }
251        }
252        if self.input.released || self.input.cancelled || self.input.blurred || !enabled {
253            if state.dragging {
254                self.ui.active = None;
255                if snap {
256                    let mut index = state.index;
257                    if pages && self.input.released && !self.input.cancelled && !self.input.blurred
258                    {
259                        let movement = state.offset - state.drag_initial;
260                        if movement.abs() >= (step * 0.20).min(56.0) {
261                            index = if movement > 0.0 {
262                                index + 1
263                            } else {
264                                index.saturating_sub(1)
265                            };
266                        }
267                    }
268                    state.go_to(index);
269                    self.ui.continuous = true;
270                }
271            }
272            state.drag_origin = None;
273            state.dragging = false;
274        }
275    }
276
277    /// A bounded, virtualized uncontained or full-screen carousel. Items are
278    /// independently actionable; a drag cancels the pressed item's activation.
279    pub fn carousel(
280        &mut self,
281        id: u64,
282        bounds: Rect,
283        items: &[CarouselItem<'_>],
284        state: &mut CarouselState,
285        options: CarouselOptions,
286    ) -> Option<usize> {
287        self.carousel_named(id, bounds, items, state, options, "Carousel")
288    }
289
290    /// A carousel with a caller-provided accessible region name.
291    pub fn carousel_named(
292        &mut self,
293        id: u64,
294        bounds: Rect,
295        items: &[CarouselItem<'_>],
296        state: &mut CarouselState,
297        options: CarouselOptions,
298        label: &str,
299    ) -> Option<usize> {
300        let count = items.len();
301        if count == 0
302            || count > 4096
303            || id > u64::MAX - count as u64
304            || !bounds.x.is_finite()
305            || !bounds.y.is_finite()
306            || !bounds.width.is_finite()
307            || !bounds.height.is_finite()
308            || bounds.width <= 0.0
309            || bounds.height <= 0.0
310            || !options.item_width.is_finite()
311            || !options.spacing.is_finite()
312        {
313            return None;
314        }
315        let visible = bounds.intersect(self.clip);
316        if visible.width <= 0.0 || visible.height <= 0.0 {
317            if state.animating {
318                state.offset = state.target;
319            }
320            state.animating = false;
321            state.drag_origin = None;
322            return None;
323        }
324        let enabled = self.enabled && options.enabled;
325        let hero = options.layout == CarouselLayout::CenteredHero;
326        let browse = options.layout == CarouselLayout::MultiBrowse;
327        let spacing = if options.layout == CarouselLayout::FullScreen {
328            0.0
329        } else {
330            let gap = options.spacing.clamp(0.0, 64.0);
331            if hero || browse {
332                gap.min(bounds.width / 4.0)
333            } else {
334                gap
335            }
336        };
337        let small = if browse && count > 1 {
338            (bounds.width / 8.0)
339                .clamp(40.0, 56.0)
340                .min(bounds.width / 3.0)
341        } else if hero && count >= 3 && bounds.width >= 168.0 {
342            (bounds.width / 6.0).clamp(40.0, 56.0)
343        } else {
344            0.0
345        };
346        let mut medium = 0.0;
347        let mut large_count = 1;
348        let width = if options.layout == CarouselLayout::FullScreen || (browse && count == 1) {
349            bounds.width
350        } else if browse {
351            let available = (bounds.width - small - spacing).max(1.0);
352            let target = options
353                .item_width
354                .clamp(small.max(1.0), available.max(small.max(1.0)));
355            large_count = (((bounds.width - small + spacing) / (target + spacing)).floor()
356                as usize)
357                .clamp(1, count - 1);
358            let leftover = bounds.width
359                - large_count as f32 * target
360                - (large_count + 1) as f32 * spacing
361                - small;
362            if count > large_count + 1 && leftover >= small && leftover < target {
363                medium = leftover;
364                target
365            } else {
366                ((bounds.width - small - large_count as f32 * spacing) / large_count as f32)
367                    .max(1.0)
368            }
369        } else if hero {
370            let neighbor_space = if small > 0.0 {
371                2.0 * (small + spacing)
372            } else {
373                0.0
374            };
375            (bounds.width - neighbor_space).max(1.0)
376        } else {
377            options
378                .item_width
379                .clamp(48.0_f32.min(bounds.width), bounds.width)
380        };
381        let step = width + spacing;
382        let maximum = if hero || browse {
383            count.saturating_sub(1) as f32 * step
384        } else {
385            ((count as f32 * step - spacing) - bounds.width).max(0.0)
386        };
387        state.max_index = if hero || browse {
388            count - 1
389        } else {
390            (maximum / step).ceil() as usize
391        };
392        state.index = state.index.min(state.max_index);
393        if (state.step - step).abs() > 0.001 || (state.maximum - maximum).abs() > 0.001 {
394            let relative = if state.step > 0.0 {
395                state.offset / state.step
396            } else {
397                0.0
398            };
399            state.offset = (relative * step).clamp(0.0, maximum);
400            state.target = (state.index as f32 * step).min(maximum);
401            if state.animating {
402                state.from = state.offset;
403                state.started = self.ui.time;
404                state.animating = (state.target - state.offset).abs() > 0.01;
405            }
406            state.drag_origin = None;
407            state.dragging = false;
408            state.step = step;
409            state.maximum = maximum;
410        }
411        if state
412            .pending_focus
413            .is_some_and(|index| index >= count || !items[index].enabled)
414        {
415            state.pending_focus = None;
416        }
417        let snap = options.snap || options.layout != CarouselLayout::Uncontained;
418        self.update_carousel_motion(bounds, state, enabled, options.rtl, snap, false);
419        if enabled
420            && self.pointer_in(bounds)
421            && self.input.scroll[1].is_finite()
422            && self.input.scroll[1] != 0.0
423        {
424            if self.input.scroll[1] > 0.0 {
425                state.next();
426            } else {
427                state.previous();
428            }
429            self.ui.continuous = true;
430        }
431        self.semantic(
432            Response {
433                id,
434                bounds: visible,
435                enabled,
436                ..Response::default()
437            },
438            Role::Carousel,
439            label,
440            false,
441            None,
442            Some(state.index as f32 + 1.0),
443            Some([1.0, count as f32]),
444        );
445        let first = if hero || browse {
446            ((state.offset / step).floor().max(0.0) as usize).saturating_sub(large_count + 2)
447        } else {
448            ((state.offset / step).floor() as usize).min(count - 1)
449        };
450        let last = if hero || browse {
451            ((state.offset / step).ceil() as usize + large_count + 3).min(count)
452        } else {
453            (((state.offset + bounds.width) / step).ceil() as usize + 1).min(count)
454        };
455        let mut chosen = None;
456        self.within(bounds, |f| {
457            for (index, item) in items.iter().enumerate().take(last).skip(first) {
458                let shift = index as f32 * step - state.offset;
459                let item_bounds = if browse {
460                    let position = state.offset / step;
461                    let relative = index as f32 - position;
462                    let start =
463                        multi_browse_sample(relative, width, large_count, medium, small, spacing);
464                    let end =
465                        multi_browse_sample(-relative, width, large_count, medium, small, spacing);
466                    let end_mix = (position - count.saturating_sub(2) as f32).clamp(0.0, 1.0);
467                    let center = start.0 + (bounds.width - end.0 - start.0) * end_mix;
468                    let item_width = start.1 + (end.1 - start.1) * end_mix;
469                    let logical_x = center - item_width * 0.5;
470                    Rect {
471                        x: if options.rtl {
472                            bounds.x + bounds.width - logical_x - item_width
473                        } else {
474                            bounds.x + logical_x
475                        },
476                        width: item_width,
477                        ..bounds
478                    }
479                } else if hero {
480                    let position = state.offset / step;
481                    let relative = index as f32 - position;
482                    let distance = relative.abs();
483                    let item_width = if small == 0.0 {
484                        width
485                    } else {
486                        width + (small - width) * distance.min(1.0)
487                    };
488                    let anchor = (bounds.width - width) * 0.5;
489                    let start_edge = (1.0 - position).clamp(0.0, 1.0);
490                    let end_edge =
491                        (1.0 - (count.saturating_sub(1) as f32 - position)).clamp(0.0, 1.0);
492                    let center = bounds.width * 0.5 - anchor * start_edge + anchor * end_edge;
493                    let neighbor_width = if small == 0.0 { width } else { small };
494                    let neighbor_step = (width + neighbor_width) * 0.5 + spacing;
495                    let displacement = if distance <= 1.0 {
496                        distance * neighbor_step
497                    } else {
498                        neighbor_step + (distance - 1.0) * (neighbor_width + spacing)
499                    };
500                    let logical_x = center + relative.signum() * displacement - item_width * 0.5;
501                    Rect {
502                        x: if options.rtl {
503                            bounds.x + bounds.width - logical_x - item_width
504                        } else {
505                            bounds.x + logical_x
506                        },
507                        width: item_width,
508                        ..bounds
509                    }
510                } else {
511                    Rect {
512                        x: if options.rtl {
513                            bounds.x + bounds.width - width - shift
514                        } else {
515                            bounds.x + shift
516                        },
517                        width,
518                        ..bounds
519                    }
520                };
521                let visible_item = item_bounds.intersect(f.clip);
522                if visible_item.width <= 0.0 || visible_item.height <= 0.0 {
523                    continue;
524                }
525                let r = f.target(
526                    id + index as u64 + 1,
527                    item_bounds,
528                    item.label,
529                    enabled && item.enabled,
530                    Role::CarouselItem,
531                );
532                if let Some(node) = f.ui.semantics.last_mut() {
533                    node.value = Some(index as f32 + 1.0);
534                    node.range = Some([1.0, count as f32]);
535                }
536                if r.clicked {
537                    chosen = Some(index);
538                }
539                if let Some(image) = item.image {
540                    if hero || browse {
541                        // Fit content to the large item first, then reveal the
542                        // centered portion covered by the current mask. This
543                        // preserves content scale as the mask changes.
544                        let content = Rect {
545                            width,
546                            ..item_bounds
547                        };
548                        if let Some((_, mut uv)) = crate::media::fit_image(
549                            content,
550                            image.width(),
551                            image.height(),
552                            ImageFit::Cover,
553                        ) && item_bounds.intersect(f.clip).width > 0.0
554                            && item_bounds.intersect(f.clip).height > 0.0
555                        {
556                            let fraction = (item_bounds.width / width).clamp(0.0, 1.0);
557                            let inset = (uv[2] - uv[0]) * (1.0 - fraction) * 0.5;
558                            uv[0] += inset;
559                            uv[2] -= inset;
560                            f.commands.push(DrawCommand::Image {
561                                bounds: item_bounds,
562                                uv,
563                                radius: 16.0,
564                                color: Color(255, 255, 255, 255),
565                                image: image.clone(),
566                            });
567                        }
568                    } else {
569                        f.paint_image(item_bounds, image, ImageFit::Cover, 16.0);
570                    }
571                } else {
572                    f.paint_rect(
573                        item_bounds,
574                        16.0,
575                        if index % 2 == 0 {
576                            f.ui.theme.secondary
577                        } else {
578                            f.ui.theme.primary_container
579                        },
580                    );
581                }
582                f.state_layer(r, 16.0, f.ui.theme.text);
583                let text_width = f.text_width(
584                    item.label,
585                    TextStyle {
586                        size: 14.0,
587                        ..TextStyle::default()
588                    },
589                );
590                if !(hero || browse) || item_bounds.width >= text_width + 24.0 {
591                    let label = Rect {
592                        y: item_bounds.y + item_bounds.height - 40.0,
593                        height: 40.0,
594                        ..item_bounds
595                    };
596                    f.commands
597                        .push(DrawCommand::PushClip(label.intersect(f.clip)));
598                    f.paint_rect(item_bounds, 16.0, f.ui.theme.background.opacity(0.8));
599                    f.commands.push(DrawCommand::PopClip);
600                    f.styled_text(
601                        label,
602                        item.label,
603                        f.ui.theme.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
604                        TextStyle {
605                            size: 14.0,
606                            padding: 12.0,
607                            ..TextStyle::default()
608                        },
609                    );
610                }
611                f.focus_ring(r);
612            }
613        });
614        if enabled
615            && !self.key_consumed
616            && let Some(key) = self.input.key
617            && key.pressed
618            && matches!(key.key, Key::Left | Key::Right | Key::Home | Key::End)
619            && let Some(current) = self
620                .ui
621                .focused
622                .and_then(|focus| focus.checked_sub(id + 1))
623                .filter(|index| *index < count as u64)
624        {
625            let next = match key.key {
626                Key::Home => (0..count).find(|&index| items[index].enabled),
627                Key::End => (0..count).rev().find(|&index| items[index].enabled),
628                _ if (key.key == Key::Right) != options.rtl => {
629                    ((current as usize + 1)..count).find(|&index| items[index].enabled)
630                }
631                _ => (0..current as usize)
632                    .rev()
633                    .find(|&index| items[index].enabled),
634            };
635            if let Some(next) = next {
636                state.go_to(next);
637                state.pending_focus = Some(next);
638                self.key_consumed = true;
639                self.ui.continuous = true;
640            }
641        }
642        if let Some(index) = state.pending_focus
643            && !state.animating
644            && state.pending.is_none()
645            && self
646                .ui
647                .semantics
648                .iter()
649                .any(|n| n.id == id + index as u64 + 1 && n.enabled)
650        {
651            self.request_focus(id + index as u64 + 1);
652            state.pending_focus = None;
653            self.ui.continuous = true;
654        }
655        chosen
656    }
657}
658
659#[cfg(test)]
660#[path = "carousel.spec.rs"]
661mod tests;