lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Carousel`, `CarouselViewport`, `CarouselItem`, `CarouselPrevious`, and `CarouselNext`.
//!
//! `@santi020k/lumen-react` renders only the `Carousel` section and leaves paging to Lumen's web
//! runtime, which scrolls `[data-ui-carousel-viewport]` by its width when a
//! `[data-ui-carousel-prev]` or `[data-ui-carousel-next]` button is pressed. These parts render the
//! same markup and do the paging in Rust:
//!
//! - On web and desktop, the viewport scrolls by its own width, like the runtime.
//! - On Dioxus Native, which cannot scroll an element from code yet, the carousel pages instead:
//!   items before the current page are `hidden`.

use std::rc::Rc;

use dioxus::html::geometry::PixelsVector2D;
use dioxus::prelude::*;

use super::headers::has_content;
use super::structure::use_direction;
use super::util::directional_key;
use crate::class::{Glass, compose};
use crate::{Button, ButtonSize, ButtonVariant};

#[derive(Clone, Copy)]
struct CarouselContext {
    /// First visible item while paging without scroll support.
    index: Signal<usize>,
    /// Render-order counter for items.
    next_order: CopyValue<usize>,
    /// Mounted item count.
    count: CopyValue<usize>,
    viewport: Signal<Option<Rc<MountedData>>>,
    right_to_left: Signal<bool>,
    /// Set by a [`CarouselItem`] while a carousel key bubbles out of the slide's content.
    ///
    /// Dioxus events carry no target, so the slide marks keys from its content (text fields,
    /// `contenteditable` regions, and other controls) on their way up, and the carousel leaves
    /// marked keys to that content.
    key_from_slide: CopyValue<bool>,
}

/// Where a carousel command moves.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CarouselMove {
    Previous,
    Next,
    First,
    Last,
}

/// The move a key requests, flipping the arrows in right-to-left layouts.
pub(crate) fn carousel_key_move(key: &Key, right_to_left: bool) -> Option<CarouselMove> {
    match directional_key(key, right_to_left) {
        Key::ArrowLeft => Some(CarouselMove::Previous),
        Key::ArrowRight => Some(CarouselMove::Next),
        Key::Home => Some(CarouselMove::First),
        Key::End => Some(CarouselMove::Last),
        _ => None,
    }
}

/// The page index after a move, clamped to the items (the paging fallback).
pub(crate) fn carousel_page(current: usize, count: usize, movement: CarouselMove) -> usize {
    let last = count.saturating_sub(1);

    match movement {
        CarouselMove::Previous => current.saturating_sub(1).min(last),
        CarouselMove::Next => (current + 1).min(last),
        CarouselMove::First => 0,
        CarouselMove::Last => last,
    }
}

impl CarouselContext {
    fn go(&self, movement: CarouselMove) {
        let viewport = self.viewport.peek().clone();

        let Some(viewport) = viewport else {
            let mut index = self.index;
            let next = carousel_page(*index.peek(), *self.count.peek(), movement);
            index.set(next);
            return;
        };

        // Scrolling runs right to left in RTL layouts, where scroll offsets are negative.
        let sign = if *self.right_to_left.peek() {
            -1.0
        } else {
            1.0
        };

        spawn(async move {
            let (Ok(offset), Ok(rect), Ok(size)) = (
                viewport.get_scroll_offset().await,
                viewport.get_client_rect().await,
                viewport.get_scroll_size().await,
            ) else {
                return;
            };
            let width = rect.width();
            let x = match movement {
                CarouselMove::Previous => offset.x - width * sign,
                CarouselMove::Next => offset.x + width * sign,
                CarouselMove::First => 0.0,
                CarouselMove::Last => (size.width - width).max(0.0) * sign,
            };
            let _ = viewport
                .scroll(PixelsVector2D::new(x, offset.y), ScrollBehavior::Smooth)
                .await;
        });
    }
}

fn use_carousel(component: &str) -> CarouselContext {
    try_use_context::<CarouselContext>()
        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Carousel."))
}

/// Props for [`Carousel`].
#[derive(Props, Clone, PartialEq)]
pub struct CarouselProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute. Name the carousel with `aria_label`.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// A [`CarouselViewport`] and the previous and next buttons.
    pub children: Element,
}

/// A horizontally scrolling set of slides with previous and next controls.
///
/// Inside the carousel, Left and Right arrow keys move a page (flipped in right-to-left layouts),
/// and Home and End jump to the first and last page. Keys pressed inside a [`CarouselItem`], such
/// as in a text field, stay with the slide's content.
#[component]
pub fn Carousel(props: CarouselProps) -> Element {
    let right_to_left = use_direction().is_rtl();
    let mut direction = use_signal(|| right_to_left);
    let carousel = use_context_provider(|| CarouselContext {
        index: Signal::new(0),
        next_order: CopyValue::new(0),
        count: CopyValue::new(0),
        viewport: Signal::new(None),
        right_to_left: direction,
        key_from_slide: CopyValue::new(false),
    });

    if *direction.peek() != right_to_left {
        direction.set(right_to_left);
    }

    let glass = props.glass.class("ui-carousel");
    let class = compose([
        Some("ui-carousel"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        section {
            class,
            "data-ui-carousel": "true",
            onkeydown: move |event| {
                let mut key_from_slide = carousel.key_from_slide;

                if *key_from_slide.peek() {
                    key_from_slide.set(false);
                    return;
                }

                let Some(movement) = carousel_key_move(&event.key(), right_to_left) else {
                    return;
                };
                event.prevent_default();
                carousel.go(movement);
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`CarouselViewport`].
#[derive(Props, Clone, PartialEq)]
pub struct CarouselViewportProps {
    /// Extra classes for the viewport.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// [`CarouselItem`]s.
    pub children: Element,
}

/// The scroll-snapping row of slides (`data-ui-carousel-viewport`).
#[component]
pub fn CarouselViewport(props: CarouselViewportProps) -> Element {
    let carousel = use_carousel("CarouselViewport");
    let mut viewport = carousel.viewport;

    rsx! {
        div {
            class: props.class,
            "data-ui-carousel-viewport": "true",
            onmounted: move |event| viewport.set(Some(event.data())),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`CarouselItem`].
#[derive(Props, Clone, PartialEq)]
pub struct CarouselItemProps {
    /// Extra classes for the slide.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<article>` or global attribute.
    #[props(extends = GlobalAttributes, extends = article)]
    pub attributes: Vec<Attribute>,
    /// Slide content.
    pub children: Element,
}

/// One slide, rendered as an `<article>` like the Lumen carousel examples.
///
/// Carousel keys pressed inside the slide stay with its content, so arrow, Home, and End keys
/// move the caret in a text field instead of the carousel.
#[component]
pub fn CarouselItem(props: CarouselItemProps) -> Element {
    let carousel = use_carousel("CarouselItem");
    let order = use_hook(|| {
        let mut next_order = carousel.next_order;
        let mut count = carousel.count;
        let order = *next_order.peek();
        let mounted = *count.peek();
        next_order.set(order + 1);
        count.set(mounted + 1);
        order
    });
    use_drop(move || {
        let mut count = carousel.count;
        let next = count.peek().saturating_sub(1);
        count.set(next);
    });

    let hidden = order < (carousel.index)();

    rsx! {
        article {
            class: props.class,
            hidden,
            onkeydown: move |event| {
                if carousel_key_move(&event.key(), false).is_none() {
                    return;
                }

                let mut key_from_slide = carousel.key_from_slide;
                key_from_slide.set(true);
                // The carousel clears the mark when the key reaches it. A handler in between may
                // stop the key first, so also clear it once this event is done, or the next key
                // pressed on the carousel itself would be ignored.
                spawn(async move { key_from_slide.set(false) });
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`CarouselPrevious`] and [`CarouselNext`].
#[derive(Props, Clone, PartialEq)]
pub struct CarouselButtonProps {
    /// Button variant. Defaults to outline.
    #[props(default = ButtonVariant::Outline)]
    pub variant: ButtonVariant,
    /// Button size. Defaults to small.
    #[props(default = ButtonSize::Sm)]
    pub size: ButtonSize,
    /// Extra classes appended after the button classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button label. Defaults to "Previous" or "Next".
    pub children: Element,
}

fn carousel_button(props: CarouselButtonProps, movement: CarouselMove) -> Element {
    let carousel = use_carousel(if movement == CarouselMove::Previous {
        "CarouselPrevious"
    } else {
        "CarouselNext"
    });
    let (marker, fallback) = if movement == CarouselMove::Previous {
        ("data-ui-carousel-prev", "Previous")
    } else {
        ("data-ui-carousel-next", "Next")
    };
    let mut attributes = vec![Attribute::new(marker, "true", None, false)];
    attributes.extend(props.attributes);
    let label = if has_content(&props.children) {
        props.children
    } else {
        rsx! { "{fallback}" }
    };

    rsx! {
        Button {
            class: props.class,
            onclick: move |_| carousel.go(movement),
            size: props.size,
            variant: props.variant,
            attributes,
            {label}
        }
    }
}

/// Scrolls the carousel back by one page.
#[component]
pub fn CarouselPrevious(props: CarouselButtonProps) -> Element {
    carousel_button(props, CarouselMove::Previous)
}

/// Scrolls the carousel forward by one page.
#[component]
pub fn CarouselNext(props: CarouselButtonProps) -> Element {
    carousel_button(props, CarouselMove::Next)
}

#[cfg(test)]
mod tests {
    use dioxus::prelude::Key;

    use super::{CarouselMove, carousel_key_move, carousel_page};

    #[test]
    fn keys_map_to_moves_and_flip_in_right_to_left_layouts() {
        assert_eq!(
            carousel_key_move(&Key::ArrowRight, false),
            Some(CarouselMove::Next)
        );
        assert_eq!(
            carousel_key_move(&Key::ArrowRight, true),
            Some(CarouselMove::Previous)
        );
        assert_eq!(
            carousel_key_move(&Key::Home, true),
            Some(CarouselMove::First)
        );
        assert_eq!(
            carousel_key_move(&Key::End, false),
            Some(CarouselMove::Last)
        );
        assert_eq!(carousel_key_move(&Key::ArrowDown, false), None);
        assert_eq!(carousel_key_move(&Key::Enter, false), None);
    }

    #[test]
    fn pages_clamp_to_the_items() {
        assert_eq!(carousel_page(0, 3, CarouselMove::Previous), 0);
        assert_eq!(carousel_page(0, 3, CarouselMove::Next), 1);
        assert_eq!(carousel_page(2, 3, CarouselMove::Next), 2);
        assert_eq!(carousel_page(1, 3, CarouselMove::First), 0);
        assert_eq!(carousel_page(0, 3, CarouselMove::Last), 2);
        assert_eq!(carousel_page(0, 0, CarouselMove::Next), 0);
        assert_eq!(carousel_page(5, 2, CarouselMove::Previous), 1);
    }
}