Skip to main content

pax_std/layout/
carousel.rs

1#![allow(unused_imports)]
2use crate::*;
3use pax_engine::api::{Axis, Event, KeyDown, Numeric, Property, Size};
4use pax_engine::*;
5use pax_runtime::api::NodeContext;
6
7const DOT_DIAMETER: f64 = 10.0;
8const DOT_GAP: f64 = 10.0;
9const DOT_PILL_PADDING_X: f64 = 14.0;
10const DOT_PILL_THICKNESS: f64 = 26.0;
11
12/// A paged scrolling container with native scroll snapping and optional page dots.
13///
14/// Each slotted child becomes one page. The carousel lays pages out along `axis`,
15/// sizes each page with `page_size`, and binds its scroll position through an
16/// internal `Scroller`.
17#[pax]
18#[engine_import_path("pax_engine")]
19#[file("layout/carousel.pax")]
20#[custom(Default)]
21pub struct Carousel {
22    /// Axis along which pages are laid out and snapped.
23    pub axis: Property<CarouselAxis>,
24    /// Size of each page along the scroll axis (defaults to 100%).
25    pub page_size: Property<Size>,
26    /// Whether to show page-position dots when there is more than one page.
27    pub show_dots: Property<bool>,
28    /// Horizontal scroll position, in pixels.
29    pub scroll_pos_x: Property<f64>,
30    /// Vertical scroll position, in pixels.
31    pub scroll_pos_y: Property<f64>,
32
33    // Computed page layouts for the inline template.
34    pub _pages: Property<Vec<CarouselCell>>,
35    // Computed page width in pixels.
36    pub _page_width_px: Property<f64>,
37    // Computed page height in pixels.
38    pub _page_height_px: Property<f64>,
39    // Computed scrollable content width.
40    pub _scroll_width: Property<Size>,
41    // Computed scrollable content height.
42    pub _scroll_height: Property<Size>,
43    // Computed horizontal scroll snap anchors.
44    pub _snap_positions_x: Property<Vec<Size>>,
45    // Computed vertical scroll snap anchors.
46    pub _snap_positions_y: Property<Vec<Size>>,
47    // Computed number of pages.
48    pub _page_count: Property<usize>,
49    // Computed active page index.
50    pub _active_page: Property<usize>,
51    // Computed visibility for dots after accounting for page count.
52    pub _show_dots: Property<bool>,
53    // Computed dot positions and active states.
54    pub _dots: Property<Vec<CarouselDot>>,
55    // Computed total dot row/column length.
56    pub _dots_width: Property<f64>,
57    // Computed dot-pill width.
58    pub _dots_pill_width: Property<f64>,
59    // Computed dot-pill height.
60    pub _dots_pill_height: Property<f64>,
61    // Computed dot-pill x position.
62    pub _dots_pos_x: Property<Size>,
63    // Computed dot-pill y position.
64    pub _dots_pos_y: Property<Size>,
65}
66
67impl Default for Carousel {
68    fn default() -> Self {
69        Self {
70            axis: Property::new(CarouselAxis::Horizontal),
71            page_size: Property::new(Size::Percent(Numeric::F64(100.0))),
72            show_dots: Property::new(false),
73            scroll_pos_x: Property::new(0.0),
74            scroll_pos_y: Property::new(0.0),
75            _pages: Property::new(vec![]),
76            _page_width_px: Property::new(0.0),
77            _page_height_px: Property::new(0.0),
78            _scroll_width: Property::new(Size::Pixels(Numeric::F64(0.0))),
79            _scroll_height: Property::new(Size::Pixels(Numeric::F64(0.0))),
80            _snap_positions_x: Property::new(vec![]),
81            _snap_positions_y: Property::new(vec![]),
82            _page_count: Property::new(0),
83            _active_page: Property::new(0),
84            _show_dots: Property::new(false),
85            _dots: Property::new(vec![]),
86            _dots_width: Property::new(0.0),
87            _dots_pill_width: Property::new(0.0),
88            _dots_pill_height: Property::new(0.0),
89            _dots_pos_x: Property::new(Size::Percent(Numeric::F64(50.0))),
90            _dots_pos_y: Property::new(Size::Percent(Numeric::F64(92.0))),
91        }
92    }
93}
94
95/// Direction for carousel paging and scroll snapping.
96#[pax]
97#[engine_import_path("pax_engine")]
98pub enum CarouselAxis {
99    /// Pages flow left-to-right.
100    #[default]
101    Horizontal,
102    /// Pages flow top-to-bottom.
103    Vertical,
104}
105
106// Internal page layout emitted into the inline template.
107#[pax]
108#[engine_import_path("pax_engine")]
109pub struct CarouselCell {
110    // Page x offset in pixels.
111    pub x_px: f64,
112    // Page y offset in pixels.
113    pub y_px: f64,
114}
115
116// Internal page-dot layout emitted into the inline template.
117#[pax]
118#[engine_import_path("pax_engine")]
119pub struct CarouselDot {
120    // Dot x position in pixels.
121    pub x_px: f64,
122    // Dot y position in pixels.
123    pub y_px: f64,
124    // Whether this dot represents the active page.
125    pub is_active: bool,
126}
127
128struct CarouselLayout {
129    pages: Vec<CarouselCell>,
130    page_width_px: f64,
131    page_height_px: f64,
132    scroll_width: Size,
133    scroll_height: Size,
134    snap_positions_x: Vec<Size>,
135    snap_positions_y: Vec<Size>,
136}
137
138impl Carousel {
139    // Wires derived layout properties used by the inline template.
140    pub fn on_mount(&mut self, ctx: &NodeContext) {
141        let axis = self.axis.clone();
142        let page_size = self.page_size.clone();
143        let bounds = ctx.bounds_self.clone();
144        let projected_children_count = ctx.projected_children_count.clone();
145        let show_dots = self.show_dots.clone();
146        let scroll_pos_x = self.scroll_pos_x.clone();
147        let scroll_pos_y = self.scroll_pos_y.clone();
148
149        let deps = [
150            axis.untyped(),
151            page_size.untyped(),
152            bounds.untyped(),
153            projected_children_count.untyped(),
154        ];
155
156        let axis_pages = axis.clone();
157        let page_size_pages = page_size.clone();
158        let bounds_pages = bounds.clone();
159        let projected_children_count_pages = projected_children_count.clone();
160        self._pages.replace_with(Property::computed(
161            move || {
162                compute_layout(
163                    axis_pages.get(),
164                    page_size_pages.get(),
165                    bounds_pages.get(),
166                    projected_children_count_pages.get(),
167                )
168                .pages
169            },
170            &deps,
171        ));
172
173        let axis_width = axis.clone();
174        let page_size_width = page_size.clone();
175        let bounds_width = bounds.clone();
176        let projected_children_count_width = projected_children_count.clone();
177        self._page_width_px.replace_with(Property::computed(
178            move || {
179                compute_layout(
180                    axis_width.get(),
181                    page_size_width.get(),
182                    bounds_width.get(),
183                    projected_children_count_width.get(),
184                )
185                .page_width_px
186            },
187            &deps,
188        ));
189
190        let axis_height = axis.clone();
191        let page_size_height = page_size.clone();
192        let bounds_height = bounds.clone();
193        let projected_children_count_height = projected_children_count.clone();
194        self._page_height_px.replace_with(Property::computed(
195            move || {
196                compute_layout(
197                    axis_height.get(),
198                    page_size_height.get(),
199                    bounds_height.get(),
200                    projected_children_count_height.get(),
201                )
202                .page_height_px
203            },
204            &deps,
205        ));
206
207        let axis_scroll_width = axis.clone();
208        let page_size_scroll_width = page_size.clone();
209        let bounds_scroll_width = bounds.clone();
210        let projected_children_count_scroll_width = projected_children_count.clone();
211        self._scroll_width.replace_with(Property::computed(
212            move || {
213                compute_layout(
214                    axis_scroll_width.get(),
215                    page_size_scroll_width.get(),
216                    bounds_scroll_width.get(),
217                    projected_children_count_scroll_width.get(),
218                )
219                .scroll_width
220            },
221            &deps,
222        ));
223
224        let axis_scroll_height = axis.clone();
225        let page_size_scroll_height = page_size.clone();
226        let bounds_scroll_height = bounds.clone();
227        let projected_children_count_scroll_height = projected_children_count.clone();
228        self._scroll_height.replace_with(Property::computed(
229            move || {
230                compute_layout(
231                    axis_scroll_height.get(),
232                    page_size_scroll_height.get(),
233                    bounds_scroll_height.get(),
234                    projected_children_count_scroll_height.get(),
235                )
236                .scroll_height
237            },
238            &deps,
239        ));
240
241        let axis_snap_x = axis.clone();
242        let page_size_snap_x = page_size.clone();
243        let bounds_snap_x = bounds.clone();
244        let projected_children_count_snap_x = projected_children_count.clone();
245        self._snap_positions_x.replace_with(Property::computed(
246            move || {
247                compute_layout(
248                    axis_snap_x.get(),
249                    page_size_snap_x.get(),
250                    bounds_snap_x.get(),
251                    projected_children_count_snap_x.get(),
252                )
253                .snap_positions_x
254            },
255            &deps,
256        ));
257
258        let axis_snap_y = axis.clone();
259        let page_size_snap_y = page_size.clone();
260        let bounds_snap_y = bounds.clone();
261        let projected_children_count_snap_y = projected_children_count.clone();
262        self._snap_positions_y.replace_with(Property::computed(
263            move || {
264                compute_layout(
265                    axis_snap_y.get(),
266                    page_size_snap_y.get(),
267                    bounds_snap_y.get(),
268                    projected_children_count_snap_y.get(),
269                )
270                .snap_positions_y
271            },
272            &deps,
273        ));
274
275        let projected_children_count_count = projected_children_count.clone();
276        self._page_count.replace_with(Property::computed(
277            move || projected_children_count_count.get(),
278            &[projected_children_count.untyped()],
279        ));
280
281        let axis_active = axis.clone();
282        let page_size_active = page_size.clone();
283        let bounds_active = bounds.clone();
284        let projected_children_count_active = projected_children_count.clone();
285        let scroll_pos_x_active = scroll_pos_x.clone();
286        let scroll_pos_y_active = scroll_pos_y.clone();
287        self._active_page.replace_with(Property::computed(
288            move || {
289                active_page_index(
290                    axis_active.get(),
291                    page_size_active.get(),
292                    bounds_active.get(),
293                    projected_children_count_active.get(),
294                    scroll_pos_x_active.get(),
295                    scroll_pos_y_active.get(),
296                )
297            },
298            &[
299                axis.untyped(),
300                page_size.untyped(),
301                bounds.untyped(),
302                projected_children_count.untyped(),
303                scroll_pos_x.untyped(),
304                scroll_pos_y.untyped(),
305            ],
306        ));
307
308        let show_dots_prop = show_dots.clone();
309        let projected_children_count_dots = projected_children_count.clone();
310        self._show_dots.replace_with(Property::computed(
311            move || show_dots_prop.get() && projected_children_count_dots.get() > 1,
312            &[show_dots.untyped(), projected_children_count.untyped()],
313        ));
314
315        let axis_dots = axis.clone();
316        let show_dots_specs = self._show_dots.clone();
317        let active_page_specs = self._active_page.clone();
318        let projected_children_count_specs = projected_children_count.clone();
319        self._dots.replace_with(Property::computed(
320            move || {
321                let count = projected_children_count_specs.get();
322                if !show_dots_specs.get() || count <= 1 {
323                    return vec![];
324                }
325                let active_index = active_page_specs.get();
326                let spacing = DOT_DIAMETER + DOT_GAP;
327                let total_width = (count as f64 - 1.0) * spacing + DOT_DIAMETER;
328                let start_x = -total_width * 0.5 + DOT_DIAMETER * 0.5;
329                let is_vertical = matches!(axis_dots.get(), CarouselAxis::Vertical);
330                let mut dots = Vec::with_capacity(count);
331                for i in 0..count {
332                    let offset = start_x + i as f64 * spacing;
333                    dots.push(CarouselDot {
334                        x_px: if is_vertical { 0.0 } else { offset },
335                        y_px: if is_vertical { offset } else { 0.0 },
336                        is_active: i == active_index,
337                    });
338                }
339                dots
340            },
341            &[
342                self._show_dots.untyped(),
343                self._active_page.untyped(),
344                axis.untyped(),
345                projected_children_count.untyped(),
346            ],
347        ));
348
349        let show_dots_width = self._show_dots.clone();
350        let projected_children_count_width = projected_children_count.clone();
351        self._dots_width.replace_with(Property::computed(
352            move || {
353                let count = projected_children_count_width.get();
354                if !show_dots_width.get() || count <= 1 {
355                    return 0.0;
356                }
357                (count as f64 - 1.0) * (DOT_DIAMETER + DOT_GAP) + DOT_DIAMETER
358            },
359            &[
360                self._show_dots.untyped(),
361                projected_children_count.untyped(),
362            ],
363        ));
364
365        let axis_pill_width = axis.clone();
366        let dots_width_prop = self._dots_width.clone();
367        self._dots_pill_width.replace_with(Property::computed(
368            move || {
369                if matches!(axis_pill_width.get(), CarouselAxis::Vertical) {
370                    DOT_PILL_THICKNESS
371                } else {
372                    dots_width_prop.get() + DOT_PILL_PADDING_X * 2.0
373                }
374            },
375            &[axis.untyped(), self._dots_width.untyped()],
376        ));
377
378        let axis_pill_height = axis.clone();
379        let dots_height_prop = self._dots_width.clone();
380        self._dots_pill_height.replace_with(Property::computed(
381            move || {
382                if matches!(axis_pill_height.get(), CarouselAxis::Vertical) {
383                    dots_height_prop.get() + DOT_PILL_PADDING_X * 2.0
384                } else {
385                    DOT_PILL_THICKNESS
386                }
387            },
388            &[axis.untyped(), self._dots_width.untyped()],
389        ));
390
391        let axis_pos = axis.clone();
392        let axis_pos_dep = axis.clone();
393        self._dots_pos_x.replace_with(Property::computed(
394            move || {
395                if matches!(axis_pos.get(), CarouselAxis::Vertical) {
396                    Size::Percent(Numeric::F64(6.0))
397                } else {
398                    Size::Percent(Numeric::F64(50.0))
399                }
400            },
401            &[axis_pos_dep.untyped()],
402        ));
403
404        let axis_pos_y = axis.clone();
405        let axis_pos_y_dep = axis.clone();
406        self._dots_pos_y.replace_with(Property::computed(
407            move || {
408                if matches!(axis_pos_y.get(), CarouselAxis::Vertical) {
409                    Size::Percent(Numeric::F64(50.0))
410                } else {
411                    Size::Percent(Numeric::F64(92.0))
412                }
413            },
414            &[axis_pos_y_dep.untyped()],
415        ));
416    }
417
418    // Keyboard paging for arrow-key navigation.
419    pub fn key_down(&mut self, ctx: &NodeContext, args: Event<KeyDown>) {
420        let key = args.keyboard.key.as_str();
421        let axis = self.axis.get();
422        let delta = match axis {
423            CarouselAxis::Horizontal => match key {
424                "ArrowLeft" => -1,
425                "ArrowRight" => 1,
426                _ => 0,
427            },
428            CarouselAxis::Vertical => match key {
429                "ArrowUp" => -1,
430                "ArrowDown" => 1,
431                _ => 0,
432            },
433        };
434        if delta == 0 {
435            return;
436        }
437        let page_count = ctx.projected_children_count.get();
438        if page_count <= 1 {
439            return;
440        }
441        let bounds = ctx.bounds_self.get();
442        let page_extent_px = page_extent_px(axis.clone(), self.page_size.get(), bounds, page_count);
443        if page_extent_px <= 0.0 {
444            return;
445        }
446        let current_scroll = match axis {
447            CarouselAxis::Horizontal => self.scroll_pos_x.get(),
448            CarouselAxis::Vertical => self.scroll_pos_y.get(),
449        };
450        let current_index = (current_scroll / page_extent_px).round() as isize;
451        let mut next_index = current_index + delta as isize;
452        if next_index < 0 {
453            next_index = 0;
454        }
455        let last_index = page_count.saturating_sub(1) as isize;
456        if next_index > last_index {
457            next_index = last_index;
458        }
459        let target_scroll = page_extent_px * next_index as f64;
460        match axis {
461            CarouselAxis::Horizontal => self.scroll_pos_x.set(target_scroll),
462            CarouselAxis::Vertical => self.scroll_pos_y.set(target_scroll),
463        }
464    }
465}
466
467fn page_extent_px(
468    axis: CarouselAxis,
469    page_size: Size,
470    bounds: (f64, f64),
471    page_count: usize,
472) -> f64 {
473    let axis_extent = match axis {
474        CarouselAxis::Horizontal => bounds.0,
475        CarouselAxis::Vertical => bounds.1,
476    };
477    if page_count <= 1 {
478        return axis_extent;
479    }
480    match axis {
481        CarouselAxis::Horizontal => page_size.evaluate(bounds, Axis::X),
482        CarouselAxis::Vertical => page_size.evaluate(bounds, Axis::Y),
483    }
484}
485
486fn active_page_index(
487    axis: CarouselAxis,
488    page_size: Size,
489    bounds: (f64, f64),
490    page_count: usize,
491    scroll_pos_x: f64,
492    scroll_pos_y: f64,
493) -> usize {
494    if page_count <= 1 {
495        return 0;
496    }
497    let page_extent = page_extent_px(axis.clone(), page_size, bounds, page_count);
498    if page_extent <= 0.0 {
499        return 0;
500    }
501    let scroll_pos = match axis {
502        CarouselAxis::Horizontal => scroll_pos_x,
503        CarouselAxis::Vertical => scroll_pos_y,
504    };
505    let mut idx = (scroll_pos / page_extent).round() as isize;
506    if idx < 0 {
507        idx = 0;
508    }
509    let max_idx = page_count.saturating_sub(1) as isize;
510    if idx > max_idx {
511        idx = max_idx;
512    }
513    idx as usize
514}
515
516fn compute_layout(
517    axis: CarouselAxis,
518    page_size: Size,
519    bounds: (f64, f64),
520    page_count: usize,
521) -> CarouselLayout {
522    let axis_extent_px = match axis {
523        CarouselAxis::Horizontal => bounds.0,
524        CarouselAxis::Vertical => bounds.1,
525    };
526    let cross_extent_px = match axis {
527        CarouselAxis::Horizontal => bounds.1,
528        CarouselAxis::Vertical => bounds.0,
529    };
530    let page_extent_px = if page_count <= 1 {
531        axis_extent_px
532    } else {
533        match axis {
534            CarouselAxis::Horizontal => page_size.evaluate(bounds, Axis::X),
535            CarouselAxis::Vertical => page_size.evaluate(bounds, Axis::Y),
536        }
537    };
538    let scroll_pages = page_count.max(1) as f64;
539    let total_extent_px = page_extent_px * scroll_pages;
540
541    let (scroll_width_px, scroll_height_px) = match axis {
542        CarouselAxis::Horizontal => (total_extent_px, cross_extent_px),
543        CarouselAxis::Vertical => (cross_extent_px, total_extent_px),
544    };
545    let (page_width_px, page_height_px) = match axis {
546        CarouselAxis::Horizontal => (page_extent_px, cross_extent_px),
547        CarouselAxis::Vertical => (cross_extent_px, page_extent_px),
548    };
549
550    let mut pages = Vec::with_capacity(page_count);
551    let mut snap_positions_x = vec![];
552    let mut snap_positions_y = vec![];
553
554    if page_count > 1 {
555        for i in 0..page_count {
556            let offset_px = page_extent_px * (i as f64);
557            match axis {
558                CarouselAxis::Horizontal => {
559                    pages.push(CarouselCell {
560                        x_px: offset_px,
561                        y_px: 0.0,
562                    });
563                    snap_positions_x.push(Size::Pixels(Numeric::F64(offset_px)));
564                }
565                CarouselAxis::Vertical => {
566                    pages.push(CarouselCell {
567                        x_px: 0.0,
568                        y_px: offset_px,
569                    });
570                    snap_positions_y.push(Size::Pixels(Numeric::F64(offset_px)));
571                }
572            }
573        }
574    } else if page_count == 1 {
575        pages.push(CarouselCell {
576            x_px: 0.0,
577            y_px: 0.0,
578        });
579    }
580
581    CarouselLayout {
582        pages,
583        page_width_px,
584        page_height_px,
585        scroll_width: Size::Pixels(Numeric::F64(scroll_width_px)),
586        scroll_height: Size::Pixels(Numeric::F64(scroll_height_px)),
587        snap_positions_x,
588        snap_positions_y,
589    }
590}