Skip to main content

lumen_dioxus/overlays/
tour.rs

1//! `Tour`: a guided walkthrough of anchored steps.
2
3use std::collections::HashMap;
4use std::rc::Rc;
5
6use dioxus::prelude::*;
7
8use super::shared::{css_pixels, focus_stored};
9use crate::class::compose;
10use crate::hooks::use_controllable;
11use crate::overlay::is_escape;
12
13/// One step of a [`Tour`].
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct TourStep {
16    /// CSS selector of the element the step points at, such as `#search`.
17    pub target: String,
18    /// Optional heading.
19    pub title: Option<String>,
20    /// Step text.
21    pub content: String,
22}
23
24impl TourStep {
25    /// A step pointing at `target` with `content`.
26    pub fn new(target: impl Into<String>, content: impl Into<String>) -> Self {
27        Self {
28            target: target.into(),
29            title: None,
30            content: content.into(),
31        }
32    }
33
34    /// Sets the heading.
35    #[must_use]
36    pub fn with_title(mut self, title: impl Into<String>) -> Self {
37        self.title = Some(title.into());
38        self
39    }
40}
41
42/// Where the tour panel sits.
43#[derive(Clone, Copy, Debug, PartialEq)]
44enum TourPlacement {
45    /// Not measured yet; the panel keeps its stylesheet position.
46    Unknown,
47    /// Under the target element (web and desktop).
48    At { top: f64, left: f64 },
49    /// Centered, when the target cannot be measured (Dioxus Native or a missing target).
50    Centered,
51}
52
53impl TourPlacement {
54    fn style(self) -> Option<String> {
55        match self {
56            Self::Unknown => None,
57            Self::At { top, left } => {
58                Some(format!("top:{};left:{}", css_pixels(top), css_pixels(left)))
59            }
60            Self::Centered => Some("top:50%;left:50%;transform:translate(-50%, -50%)".to_string()),
61        }
62    }
63}
64
65/// Web and desktop only: the target's position under its bottom edge. The selector arrives through
66/// `dioxus.recv`, so it is never interpolated into the script.
67const TOUR_TARGET_SCRIPT: &str = r"
68const selector = await dioxus.recv();
69let element = null;
70try { element = document.querySelector(selector); } catch (error) { element = null; }
71if (!element) return null;
72const rect = element.getBoundingClientRect();
73return [rect.bottom + 8, rect.left];
74";
75
76async fn measure_tour_target(selector: String) -> TourPlacement {
77    let eval = document::eval(TOUR_TARGET_SCRIPT);
78
79    if eval.send(selector).is_err() {
80        return TourPlacement::Centered;
81    }
82
83    match eval.join::<Option<(f64, f64)>>().await {
84        Ok(Some((top, left))) if top.is_finite() && left.is_finite() => {
85            TourPlacement::At { top, left }
86        }
87        _ => TourPlacement::Centered,
88    }
89}
90
91/// Props for [`Tour`].
92#[derive(Props, Clone, PartialEq)]
93pub struct TourProps {
94    /// The steps, in order.
95    #[props(default)]
96    pub steps: Vec<TourStep>,
97    /// Controlled open state.
98    pub open: Option<bool>,
99    /// Initial open state when uncontrolled.
100    #[props(default)]
101    pub default_open: bool,
102    /// Called with the requested open state.
103    pub on_open_change: Option<EventHandler<bool>>,
104    /// Called with the index of the step that becomes current.
105    pub on_step_change: Option<EventHandler<usize>>,
106    /// Close button label. Defaults to "Done".
107    #[props(default = "Done".to_string(), into)]
108    pub close_label: String,
109    /// Next button label. Defaults to "Next".
110    #[props(default = "Next".to_string(), into)]
111    pub next_label: String,
112    /// Back button label. Steps after the first show a Back button only when it is set.
113    #[props(into)]
114    pub prev_label: Option<String>,
115    /// Accessible name of the tour panel. Defaults to "Guided tour".
116    #[props(default = "Guided tour".to_string(), into)]
117    pub label: String,
118    /// Extra classes appended after the Lumen class.
119    #[props(into)]
120    pub class: Option<String>,
121    /// Any other `<div>` or global attribute.
122    #[props(extends = GlobalAttributes, extends = div)]
123    pub attributes: Vec<Attribute>,
124    /// Extra content at the end of the panel.
125    pub children: Element,
126}
127
128/// A guided tour: a backdrop and a panel that steps through anchored tips.
129///
130/// Opening starts at the first step and focuses its first button. Next moves to the following
131/// step; Done, Escape, or a click on the backdrop closes the tour. On web and desktop the
132/// panel sits under each step's target; on Dioxus Native, which cannot measure elements by
133/// selector, it is centered.
134#[component]
135pub fn Tour(props: TourProps) -> Element {
136    let state = use_controllable(props.open, || props.default_open, props.on_open_change);
137    let mut step = use_signal(|| 0_usize);
138    let mut placement = use_signal(|| TourPlacement::Unknown);
139    let mut buttons = use_signal(HashMap::<usize, Rc<MountedData>>::new);
140    let open = state.get();
141    let current = *step.read();
142    let count = props.steps.len();
143    let target = props.steps.get(current).map(|item| item.target.clone());
144    let on_step_change = props.on_step_change;
145    let mut go_to = move |index: usize| {
146        if *step.peek() != index {
147            step.set(index);
148
149            if let Some(handler) = on_step_change {
150                handler.call(index);
151            }
152        }
153    };
154
155    use_effect(use_reactive(
156        (&open, &current, &target),
157        move |(open, current, target)| {
158            // However the tour closed, including a controlled `open` turning false, the next
159            // opening starts at the first step.
160            if !open {
161                go_to(0);
162                return;
163            }
164
165            focus_stored(buttons.peek().get(&current).cloned());
166
167            if let Some(selector) = target.filter(|selector| !selector.is_empty()) {
168                spawn(async move {
169                    let measured = measure_tour_target(selector).await;
170                    placement.set(measured);
171                });
172            } else {
173                placement.set(TourPlacement::Centered);
174            }
175        },
176    ));
177
178    let mut close = move || {
179        state.set(false);
180        go_to(0);
181    };
182    let class = compose([Some("ui-tour"), props.class.as_deref()]);
183    let style = if open { placement.read().style() } else { None };
184
185    rsx! {
186        div {
187            class,
188            "data-ui-bound": "true",
189            "data-ui-owner": "dioxus",
190            "data-ui-tour": "true",
191            hidden: !open,
192            onkeydown: move |event: KeyboardEvent| {
193                if is_escape(&event) && event.default_action_enabled() && state.get() {
194                    event.prevent_default();
195                    close();
196                }
197            },
198            ..props.attributes,
199            div {
200                aria_hidden: "true",
201                class: "ui-tour__backdrop",
202                "data-ui-tour-backdrop": "true",
203                onclick: move |_| close(),
204            }
205            div {
206                aria_label: props.label.clone(),
207                aria_modal: "false",
208                class: "ui-tour__popover",
209                "data-ui-tour-popover": "true",
210                role: "dialog",
211                style,
212                tabindex: "-1",
213                for (index, item) in props.steps.iter().enumerate() {
214                    div {
215                        key: "{index}",
216                        class: "ui-tour__step",
217                        "data-target": item.target.clone(),
218                        "data-ui-tour-step": "true",
219                        hidden: index != current,
220                        if let Some(title) = item.title.clone().filter(|title| !title.is_empty()) {
221                            p { class: "ui-tour__title", {title} }
222                        }
223                        p { class: "ui-tour__content", {item.content.clone()} }
224                        div { class: "ui-tour__actions",
225                            if let Some(prev_label) = props.prev_label.clone().filter(|_| index > 0) {
226                                button {
227                                    class: "ui-button ui-button--ghost ui-button--sm",
228                                    "data-ui-tour-prev": "true",
229                                    r#type: "button",
230                                    onclick: move |_| go_to(index - 1),
231                                    {prev_label}
232                                }
233                            }
234                            button {
235                                class: "ui-button ui-button--ghost ui-button--sm",
236                                "data-ui-tour-close": "true",
237                                r#type: "button",
238                                onclick: move |_| close(),
239                                onmounted: move |event| {
240                                    buttons.write().insert(index, event.data());
241                                },
242                                {props.close_label.clone()}
243                            }
244                            if index + 1 < count {
245                                button {
246                                    class: "ui-button ui-button--default ui-button--sm",
247                                    "data-ui-tour-next": "true",
248                                    r#type: "button",
249                                    onclick: move |_| go_to(index + 1),
250                                    {props.next_label.clone()}
251                                }
252                            }
253                        }
254                    }
255                }
256                {props.children}
257            }
258        }
259    }
260}