Skip to main content

prime_steps/
lib.rs

1//! Steps — port of PrimeNG 21.1.10 `p-steps`.
2//!
3//! Numbered wizard steps in a row: `nav.p-steps` > `ul.p-steps-list` > `li.p-steps-item` with a link, a number and a label. By
4//! default the component only displays the current step (`readonly`); in interactive mode a click and the keys ←/→/`Home`/`End`/`Enter`/
5//! `Space` switch steps. The current step is driven by the owner via `active_index` (a value or a signal).
6//!
7//! ```
8//! use leptos::prelude::*;
9//! use prime_steps::{Steps, StepsItem};
10//!
11//! let model = vec![StepsItem::new().label("Personal"), StepsItem::new().label("Seat"), StepsItem::new().label("Payment")];
12//! let html = Owner::new().with(|| view! { <Steps model=model active_index=1usize /> }.to_html());
13//! assert!(html.contains("p-steps-item-active") && html.contains("aria-current=\"step\"") && html.contains(">3<"));
14//! ```
15
16mod state;
17
18use leptos::attr::any_attribute::{AnyAttribute, IntoAnyAttribute};
19use leptos::attr::custom::custom_attribute;
20use leptos::prelude::*;
21use prime_rs_core::{OptProp, Prop, Pt};
22use std::sync::Arc;
23
24pub use state::{
25    Click, aria_disabled, click_outcome, is_activation_key, is_item_disabled, item_classes, key_target, link_tabindex, root_classes,
26};
27
28#[cfg(target_arch = "wasm32")]
29use wasm_bindgen::JsCast;
30
31/// Item command event.
32#[derive(Clone)]
33pub struct StepsCommand {
34    /// Original event (click or key).
35    pub event: web_sys::Event,
36    /// Item.
37    pub item: StepsItem,
38    /// Item index.
39    pub index: usize,
40}
41
42/// Steps item (instead of PrimeNG's `MenuItem`, without router fields).
43#[derive(Clone, Default)]
44pub struct StepsItem {
45    /// `id` attribute of the item.
46    pub id: Option<String>,
47    /// Label.
48    pub label: Option<String>,
49    /// Link address; without it the link navigation is cancelled.
50    pub url: Option<String>,
51    /// `target` of the link.
52    pub target: Option<String>,
53    /// Disabled.
54    pub disabled: bool,
55    /// Custom `tabindex` of the link.
56    pub tabindex: Option<i32>,
57    /// Inline style of `li`.
58    pub style: Option<String>,
59    /// Command on item selection.
60    pub command: Option<Callback<StepsCommand>>,
61}
62
63impl StepsItem {
64    /// Empty item.
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    /// `id` attribute.
70    pub fn id(mut self, id: impl Into<String>) -> Self {
71        self.id = Some(id.into());
72        self
73    }
74
75    /// Label.
76    pub fn label(mut self, label: impl Into<String>) -> Self {
77        self.label = Some(label.into());
78        self
79    }
80
81    /// Link address.
82    pub fn url(mut self, url: impl Into<String>) -> Self {
83        self.url = Some(url.into());
84        self
85    }
86
87    /// `target` of the link.
88    pub fn target(mut self, target: impl Into<String>) -> Self {
89        self.target = Some(target.into());
90        self
91    }
92
93    /// Whether the item is disabled.
94    pub fn disabled(mut self, disabled: bool) -> Self {
95        self.disabled = disabled;
96        self
97    }
98
99    /// `tabindex` of the link.
100    pub fn tabindex(mut self, tabindex: i32) -> Self {
101        self.tabindex = Some(tabindex);
102        self
103    }
104
105    /// Inline style of `li`.
106    pub fn style(mut self, style: impl Into<String>) -> Self {
107        self.style = Some(style.into());
108        self
109    }
110
111    /// Command.
112    pub fn command(mut self, command: impl Into<Callback<StepsCommand>>) -> Self {
113        self.command = Some(command.into());
114        self
115    }
116}
117
118/// Pass-through parts of [`Steps`].
119#[derive(Clone, Debug, Default, PartialEq, Eq)]
120pub struct StepsPt {
121    /// `nav` root.
122    pub root: Pt,
123    /// List.
124    pub list: Pt,
125    /// Item `li`.
126    pub item: Pt,
127    /// Item link.
128    pub item_link: Pt,
129    /// Number.
130    pub item_number: Pt,
131    /// Label.
132    pub item_label: Pt,
133}
134
135/// State shared by the handlers.
136struct Core {
137    model: Prop<Vec<StepsItem>>,
138    readonly: Prop<bool>,
139    active: Signal<usize>,
140    active_signal: Option<RwSignal<usize>>,
141    /// The link with keyboard focus (roving `tabindex`); `None` — the active item by default.
142    focus_index: RwSignal<Option<usize>>,
143    list: NodeRef<leptos::html::Ul>,
144    on_change: Option<Callback<usize>>,
145}
146
147impl Core {
148    fn item(&self, index: usize) -> Option<StepsItem> {
149        self.model.get_untracked().get(index).cloned()
150    }
151
152    /// Click or `Enter`/`Space` on an item.
153    fn activate(&self, event: web_sys::Event, index: usize) {
154        let Some(item) = self.item(index) else { return };
155        match click_outcome(item.disabled, self.readonly.get_untracked(), item.url.is_some()) {
156            Click::Ignore => event.prevent_default(),
157            Click::Activate { prevent_default } => {
158                if let Some(sig) = self.active_signal {
159                    sig.set(index);
160                }
161                if let Some(cb) = self.on_change {
162                    cb.run(index);
163                }
164                if prevent_default {
165                    event.prevent_default();
166                }
167                if let Some(cb) = item.command {
168                    cb.run(StepsCommand { event, item, index });
169                }
170            }
171        }
172    }
173
174    fn focus_link(&self, index: usize) {
175        self.focus_index.set(Some(index));
176        #[cfg(target_arch = "wasm32")]
177        if let Some(list) = self.list.get_untracked()
178            && let Some(link) = list
179                .children()
180                .item(index as u32)
181                .and_then(|li| li.first_element_child())
182                .and_then(|a| a.dyn_into::<web_sys::HtmlElement>().ok())
183        {
184            let _ = link.focus();
185        }
186    }
187
188    fn key_down(&self, e: &web_sys::KeyboardEvent, index: usize) {
189        let code = e.code();
190        if let Some(target) = key_target(&code, index, self.model.get_untracked().len()) {
191            self.focus_link(target);
192            e.prevent_default();
193        } else if code == "Tab" {
194            self.focus_index.set(None);
195        } else if is_activation_key(&code) {
196            self.activate(e.clone().into(), index);
197            e.prevent_default();
198        }
199    }
200}
201
202/// Wizard step indicator.
203///
204/// Properties accept a value or a signal. `active_index` is driven by the owner: a click in interactive mode reports the new index
205/// via `on_active_index_change` and updates `active_index_signal` if it is set.
206#[component]
207pub fn Steps(
208    /// Items.
209    #[prop(optional, into)]
210    model: Prop<Vec<StepsItem>>,
211    /// Current step (zero-based).
212    #[prop(optional, into)]
213    active_index: Prop<usize>,
214    /// Two-way signal of the current step: a click writes the index to it (instead of `active_index`, if set).
215    #[prop(optional)]
216    active_index_signal: Option<RwSignal<usize>>,
217    /// Display only: a click on the steps does nothing.
218    #[prop(optional, default = Prop::Static(true), into)]
219    readonly: Prop<bool>,
220    /// PrimeNG compatibility property (there it affects only router links).
221    #[prop(optional, default = Prop::Static(true), into)]
222    exact: Prop<bool>,
223    /// Inline style of the root.
224    #[prop(optional, into)]
225    style: OptProp<String>,
226    /// Extra class of the root.
227    #[prop(optional, into)]
228    style_class: OptProp<String>,
229    /// Pass-through parts.
230    #[prop(optional)]
231    pt: Option<StepsPt>,
232    /// The current step was chosen by the user.
233    #[prop(optional)]
234    on_active_index_change: Option<Callback<usize>>,
235) -> impl IntoView {
236    let _ = exact;
237    let pt = Arc::new(pt.unwrap_or_default());
238    let active: Signal<usize> = match active_index_signal {
239        Some(sig) => sig.into(),
240        None => Signal::derive({
241            let active_index = active_index.clone();
242            move || active_index.get()
243        }),
244    };
245    let core = Arc::new(Core {
246        model: model.clone(),
247        readonly: readonly.clone(),
248        active,
249        active_signal: active_index_signal,
250        focus_index: RwSignal::new(None),
251        list: NodeRef::new(),
252        on_change: on_active_index_change,
253    });
254    // A change of the current step returns the roving tabindex to it.
255    #[cfg(target_arch = "wasm32")]
256    {
257        let core = core.clone();
258        Effect::new(move |_| {
259            core.active.track();
260            core.focus_index.set(None);
261        });
262    }
263
264    let root_class = {
265        let (pt, readonly) = (pt.clone(), readonly.clone());
266        move || {
267            let extra = style_class.with(|c| c.clone());
268            let merged = root_classes(readonly.get(), extra.as_deref());
269            pt.root.merge_class(&merged).into_owned()
270        }
271    };
272    let root_style = {
273        let pt = pt.clone();
274        move || {
275            let merged = style.with(|s| pt.root.merge_style(s.as_deref().unwrap_or_default()));
276            (!merged.is_empty()).then_some(merged)
277        }
278    };
279    let items = {
280        let (core, pt) = (core.clone(), pt.clone());
281        move || core.model.get().into_iter().enumerate().map(|(index, item)| item_view(&core, &pt, index, item)).collect_view()
282    };
283    let (root_attrs, list_attrs) = (pt.root.attrs(), pt.list.attrs());
284    let list_class = pt.list.merge_class("p-steps-list").into_owned();
285    view! {
286        <nav class={root_class} style={root_style} data-pc-name="steps" {..root_attrs}>
287            <ul node_ref=core.list class={list_class} data-pc-section="menu" {..list_attrs}>
288                {items}
289            </ul>
290        </nav>
291    }
292}
293
294fn item_view(core: &Arc<Core>, pt: &Arc<StepsPt>, index: usize, item: StepsItem) -> AnyView {
295    let (active, readonly, focus_index) = (core.active, core.readonly.clone(), core.focus_index);
296    let is_active = move || active.get() == index;
297    let disabled = {
298        let (item_disabled, readonly) = (item.disabled, readonly.clone());
299        move || is_item_disabled(item_disabled, index, active.get(), readonly.get())
300    };
301    let class = {
302        let (pt, disabled, is_active) = (pt.clone(), disabled.clone(), is_active);
303        move || pt.item.merge_class(&item_classes(is_active(), disabled())).into_owned()
304    };
305    let tabindex = {
306        let (item_disabled, item_tab) = (item.disabled, item.tabindex);
307        move || {
308            match focus_index.get() {
309                Some(f) => {
310                    if f == index {
311                        0
312                    } else {
313                        -1
314                    }
315                }
316                None => link_tabindex(item_disabled, item_tab, index, active.get()),
317            }
318            .to_string()
319        }
320    };
321    let aria_dis = {
322        let (item_disabled, readonly) = (item.disabled, readonly.clone());
323        move || aria_disabled(item_disabled, index, active.get(), readonly.get()).to_string()
324    };
325    let (click_core, key_core) = (core.clone(), core.clone());
326    let attrs: Vec<AnyAttribute> = vec![custom_attribute("aria-current", move || is_active().then_some("step")).into_any_attr()];
327    let (item_attrs, link_attrs) = (pt.item.attrs(), pt.item_link.attrs());
328    let (link_class, number_class, label_class) = (
329        pt.item_link.merge_class("p-steps-item-link").into_owned(),
330        pt.item_number.merge_class("p-steps-item-number").into_owned(),
331        pt.item_label.merge_class("p-steps-item-label").into_owned(),
332    );
333    let (number_attrs, label_attrs) = (pt.item_number.attrs(), pt.item_label.attrs());
334    view! {
335        <li class={class} style={item.style.clone()} id={item.id.clone()} data-pc-section="menuitem" {..attrs} {..item_attrs}>
336            <a
337                role="link"
338                class={link_class}
339                href={item.url.clone()}
340                target={item.target.clone()}
341                tabindex={tabindex}
342                aria-expanded={move || is_active().to_string()}
343                aria-disabled={aria_dis}
344                on:click={move |e: web_sys::MouseEvent| click_core.activate(e.into(), index)}
345                on:keydown={move |e: web_sys::KeyboardEvent| key_core.key_down(&e, index)}
346                {..link_attrs}
347            >
348                <span class={number_class} {..number_attrs}>{index + 1}</span>
349                <span class={label_class} {..label_attrs}>{item.label.clone()}</span>
350            </a>
351        </li>
352    }
353    .into_any()
354}