lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Tour`: a guided walkthrough of anchored steps.

use std::collections::HashMap;
use std::rc::Rc;

use dioxus::prelude::*;

use super::shared::{css_pixels, focus_stored};
use crate::class::compose;
use crate::hooks::use_controllable;
use crate::overlay::is_escape;

/// One step of a [`Tour`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TourStep {
    /// CSS selector of the element the step points at, such as `#search`.
    pub target: String,
    /// Optional heading.
    pub title: Option<String>,
    /// Step text.
    pub content: String,
}

impl TourStep {
    /// A step pointing at `target` with `content`.
    pub fn new(target: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            target: target.into(),
            title: None,
            content: content.into(),
        }
    }

    /// Sets the heading.
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }
}

/// Where the tour panel sits.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TourPlacement {
    /// Not measured yet; the panel keeps its stylesheet position.
    Unknown,
    /// Under the target element (web and desktop).
    At { top: f64, left: f64 },
    /// Centered, when the target cannot be measured (Dioxus Native or a missing target).
    Centered,
}

impl TourPlacement {
    fn style(self) -> Option<String> {
        match self {
            Self::Unknown => None,
            Self::At { top, left } => {
                Some(format!("top:{};left:{}", css_pixels(top), css_pixels(left)))
            }
            Self::Centered => Some("top:50%;left:50%;transform:translate(-50%, -50%)".to_string()),
        }
    }
}

/// Web and desktop only: the target's position under its bottom edge. The selector arrives through
/// `dioxus.recv`, so it is never interpolated into the script.
const TOUR_TARGET_SCRIPT: &str = r"
const selector = await dioxus.recv();
let element = null;
try { element = document.querySelector(selector); } catch (error) { element = null; }
if (!element) return null;
const rect = element.getBoundingClientRect();
return [rect.bottom + 8, rect.left];
";

async fn measure_tour_target(selector: String) -> TourPlacement {
    let eval = document::eval(TOUR_TARGET_SCRIPT);

    if eval.send(selector).is_err() {
        return TourPlacement::Centered;
    }

    match eval.join::<Option<(f64, f64)>>().await {
        Ok(Some((top, left))) if top.is_finite() && left.is_finite() => {
            TourPlacement::At { top, left }
        }
        _ => TourPlacement::Centered,
    }
}

/// Props for [`Tour`].
#[derive(Props, Clone, PartialEq)]
pub struct TourProps {
    /// The steps, in order.
    #[props(default)]
    pub steps: Vec<TourStep>,
    /// Controlled open state.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the requested open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Called with the index of the step that becomes current.
    pub on_step_change: Option<EventHandler<usize>>,
    /// Close button label. Defaults to "Done".
    #[props(default = "Done".to_string(), into)]
    pub close_label: String,
    /// Next button label. Defaults to "Next".
    #[props(default = "Next".to_string(), into)]
    pub next_label: String,
    /// Back button label. Steps after the first show a Back button only when it is set.
    #[props(into)]
    pub prev_label: Option<String>,
    /// Accessible name of the tour panel. Defaults to "Guided tour".
    #[props(default = "Guided tour".to_string(), into)]
    pub label: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra content at the end of the panel.
    pub children: Element,
}

/// A guided tour: a backdrop and a panel that steps through anchored tips.
///
/// Opening starts at the first step and focuses its first button. Next moves to the following
/// step; Done, Escape, or a click on the backdrop closes the tour. On web and desktop the
/// panel sits under each step's target; on Dioxus Native, which cannot measure elements by
/// selector, it is centered.
#[component]
pub fn Tour(props: TourProps) -> Element {
    let state = use_controllable(props.open, || props.default_open, props.on_open_change);
    let mut step = use_signal(|| 0_usize);
    let mut placement = use_signal(|| TourPlacement::Unknown);
    let mut buttons = use_signal(HashMap::<usize, Rc<MountedData>>::new);
    let open = state.get();
    let current = *step.read();
    let count = props.steps.len();
    let target = props.steps.get(current).map(|item| item.target.clone());
    let on_step_change = props.on_step_change;
    let mut go_to = move |index: usize| {
        if *step.peek() != index {
            step.set(index);

            if let Some(handler) = on_step_change {
                handler.call(index);
            }
        }
    };

    use_effect(use_reactive(
        (&open, &current, &target),
        move |(open, current, target)| {
            // However the tour closed, including a controlled `open` turning false, the next
            // opening starts at the first step.
            if !open {
                go_to(0);
                return;
            }

            focus_stored(buttons.peek().get(&current).cloned());

            if let Some(selector) = target.filter(|selector| !selector.is_empty()) {
                spawn(async move {
                    let measured = measure_tour_target(selector).await;
                    placement.set(measured);
                });
            } else {
                placement.set(TourPlacement::Centered);
            }
        },
    ));

    let mut close = move || {
        state.set(false);
        go_to(0);
    };
    let class = compose([Some("ui-tour"), props.class.as_deref()]);
    let style = if open { placement.read().style() } else { None };

    rsx! {
        div {
            class,
            "data-ui-bound": "true",
            "data-ui-owner": "dioxus",
            "data-ui-tour": "true",
            hidden: !open,
            onkeydown: move |event: KeyboardEvent| {
                if is_escape(&event) && event.default_action_enabled() && state.get() {
                    event.prevent_default();
                    close();
                }
            },
            ..props.attributes,
            div {
                aria_hidden: "true",
                class: "ui-tour__backdrop",
                "data-ui-tour-backdrop": "true",
                onclick: move |_| close(),
            }
            div {
                aria_label: props.label.clone(),
                aria_modal: "false",
                class: "ui-tour__popover",
                "data-ui-tour-popover": "true",
                role: "dialog",
                style,
                tabindex: "-1",
                for (index, item) in props.steps.iter().enumerate() {
                    div {
                        key: "{index}",
                        class: "ui-tour__step",
                        "data-target": item.target.clone(),
                        "data-ui-tour-step": "true",
                        hidden: index != current,
                        if let Some(title) = item.title.clone().filter(|title| !title.is_empty()) {
                            p { class: "ui-tour__title", {title} }
                        }
                        p { class: "ui-tour__content", {item.content.clone()} }
                        div { class: "ui-tour__actions",
                            if let Some(prev_label) = props.prev_label.clone().filter(|_| index > 0) {
                                button {
                                    class: "ui-button ui-button--ghost ui-button--sm",
                                    "data-ui-tour-prev": "true",
                                    r#type: "button",
                                    onclick: move |_| go_to(index - 1),
                                    {prev_label}
                                }
                            }
                            button {
                                class: "ui-button ui-button--ghost ui-button--sm",
                                "data-ui-tour-close": "true",
                                r#type: "button",
                                onclick: move |_| close(),
                                onmounted: move |event| {
                                    buttons.write().insert(index, event.data());
                                },
                                {props.close_label.clone()}
                            }
                            if index + 1 < count {
                                button {
                                    class: "ui-button ui-button--default ui-button--sm",
                                    "data-ui-tour-next": "true",
                                    r#type: "button",
                                    onclick: move |_| go_to(index + 1),
                                    {props.next_label.clone()}
                                }
                            }
                        }
                    }
                }
                {props.children}
            }
        }
    }
}