Skip to main content

pax_std/layout/
carousel.rs

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