Skip to main content

lumen_dioxus/navigation/
command.rs

1//! `Command` and its parts: a filterable list of actions with keyboard movement.
2// cspell:words Ünïcode ünï
3
4use std::rc::Rc;
5
6use dioxus::prelude::*;
7
8use crate::class::{Glass, compose};
9use crate::overlay::{focus_element, is_escape};
10
11use super::roving::{Roving, RovingAxis, roving_move};
12use super::util::element_text;
13
14/// Whether an item's text matches a query, like the Lumen web runtime's command filter: the
15/// query is trimmed and both sides compare case-insensitively; an empty query matches everything.
16pub fn command_matches(text: &str, query: &str) -> bool {
17    let query = query.trim().to_lowercase();
18
19    query.is_empty() || text.to_lowercase().contains(&query)
20}
21
22#[derive(Clone, Copy)]
23struct CommandContext {
24    query: Signal<String>,
25    roving: Roving,
26    input: Signal<Option<Rc<MountedData>>>,
27}
28
29fn use_command(component: &str) -> CommandContext {
30    try_use_context::<CommandContext>()
31        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Command."))
32}
33
34/// Props for [`Command`].
35#[derive(Props, Clone, PartialEq)]
36pub struct CommandProps {
37    /// Glass intensity.
38    #[props(default, into)]
39    pub glass: Glass,
40    /// Extra classes appended after the Lumen classes.
41    #[props(into)]
42    pub class: Option<String>,
43    /// Any other `<div>` or global attribute.
44    #[props(extends = GlobalAttributes, extends = div)]
45    pub attributes: Vec<Attribute>,
46    /// A [`CommandInput`] followed by [`CommandItem`]s, optionally grouped in a [`CommandList`],
47    /// and a [`CommandEmpty`] message.
48    pub children: Element,
49}
50
51/// A command palette: a search field that filters a list of actions.
52///
53/// Typing in the [`CommandInput`] hides [`CommandItem`]s whose text does not contain the query,
54/// like Lumen's web runtime. `ArrowDown` and `ArrowUp` move from the field into the visible items
55/// and between them; `Home` and `End` jump to the ends; `Escape` returns to the field.
56#[component]
57pub fn Command(props: CommandProps) -> Element {
58    let query = use_signal(String::new);
59    let input = use_signal(|| None::<Rc<MountedData>>);
60    let roving = Roving::use_new();
61
62    use_context_provider(|| CommandContext {
63        query,
64        roving,
65        input,
66    });
67
68    let glass = props.glass.class("ui-command");
69    let class = compose([Some("ui-command"), glass.as_deref(), props.class.as_deref()]);
70
71    rsx! {
72        div { class, "data-ui-command": "true", ..props.attributes, {props.children} }
73    }
74}
75
76/// Props for [`CommandInput`].
77#[derive(Props, Clone, PartialEq)]
78pub struct CommandInputProps {
79    /// Called with the query on every edit.
80    pub on_value_change: Option<EventHandler<String>>,
81    /// Extra classes appended after the Lumen class.
82    #[props(into)]
83    pub class: Option<String>,
84    /// Any other `<input>` or global attribute, such as `placeholder` and `aria_label`.
85    #[props(extends = GlobalAttributes, extends = input)]
86    pub attributes: Vec<Attribute>,
87}
88
89/// The search field of a [`Command`]. Renders a Lumen `Input` of type `search`.
90#[component]
91pub fn CommandInput(props: CommandInputProps) -> Element {
92    let CommandContext {
93        mut query,
94        roving,
95        mut input,
96    } = use_command("CommandInput");
97    let class = compose([Some("ui-input"), props.class.as_deref()]);
98    let on_value_change = props.on_value_change;
99
100    rsx! {
101        input {
102            class,
103            r#type: "search",
104            oninput: move |event| {
105                let value = event.value();
106                query.set(value.clone());
107
108                if let Some(handler) = on_value_change {
109                    handler.call(value);
110                }
111            },
112            onkeydown: move |event| {
113                let last = match event.key() {
114                    Key::ArrowDown => false,
115                    Key::ArrowUp => true,
116                    _ => return,
117                };
118
119                event.prevent_default();
120                roving.focus_edge(last);
121            },
122            onmounted: move |event| input.set(Some(event.data())),
123            ..props.attributes,
124        }
125    }
126}
127
128/// Props for [`CommandList`].
129#[derive(Props, Clone, PartialEq)]
130pub struct CommandListProps {
131    /// Extra classes.
132    #[props(into)]
133    pub class: Option<String>,
134    /// Any other `<div>` or global attribute.
135    #[props(extends = GlobalAttributes, extends = div)]
136    pub attributes: Vec<Attribute>,
137    /// The [`CommandItem`]s.
138    pub children: Element,
139}
140
141/// An optional wrapper that groups the items of a [`Command`].
142#[component]
143pub fn CommandList(props: CommandListProps) -> Element {
144    rsx! {
145        div { class: props.class, "data-slot": "command-list", ..props.attributes, {props.children} }
146    }
147}
148
149/// Props for [`CommandItem`].
150#[derive(Props, Clone, PartialEq)]
151pub struct CommandItemProps {
152    /// Text the query is matched against. Defaults to the item's own text.
153    #[props(into)]
154    pub value: Option<String>,
155    /// Disables the item and skips it during keyboard movement.
156    #[props(default)]
157    pub disabled: bool,
158    /// Activation handler.
159    pub onclick: Option<EventHandler<MouseEvent>>,
160    /// Extra classes.
161    #[props(into)]
162    pub class: Option<String>,
163    /// Any other `<button>` or global attribute.
164    #[props(extends = GlobalAttributes, extends = button)]
165    pub attributes: Vec<Attribute>,
166    /// Item label.
167    pub children: Element,
168}
169
170/// One action of a [`Command`]. Hidden while the query does not match its text.
171#[component]
172pub fn CommandItem(props: CommandItemProps) -> Element {
173    let CommandContext {
174        query,
175        roving,
176        input,
177    } = use_command("CommandItem");
178    let text = props
179        .value
180        .clone()
181        .unwrap_or_else(|| element_text(&props.children));
182    let hidden = !command_matches(&text, &query.read());
183    let key = roving.use_item(props.disabled, hidden);
184    let onclick = props.onclick;
185
186    rsx! {
187        button {
188            class: props.class,
189            "data-ui-command-item": "true",
190            disabled: props.disabled,
191            hidden,
192            r#type: "button",
193            onclick: move |event| {
194                if let Some(handler) = onclick {
195                    handler.call(event);
196                }
197            },
198            onfocus: move |_| roving.focused(key),
199            onkeydown: move |event| {
200                if is_escape(&event) {
201                    event.prevent_default();
202                    focus_element(input());
203                    return;
204                }
205
206                if let Some(movement) = roving_move(&event.key(), RovingAxis::Vertical, false) {
207                    event.prevent_default();
208                    roving.move_focus(Some(key), movement);
209                }
210            },
211            onmounted: move |event| roving.mount(key, event.data()),
212            ..props.attributes,
213            {props.children}
214        }
215    }
216}
217
218/// Props for [`CommandEmpty`].
219#[derive(Props, Clone, PartialEq)]
220pub struct CommandEmptyProps {
221    /// Extra classes.
222    #[props(into)]
223    pub class: Option<String>,
224    /// Any other `<p>` or global attribute.
225    #[props(extends = GlobalAttributes, extends = p)]
226    pub attributes: Vec<Attribute>,
227    /// The message, such as "No results".
228    pub children: Element,
229}
230
231/// A message shown while a query matches no [`CommandItem`].
232#[component]
233pub fn CommandEmpty(props: CommandEmptyProps) -> Element {
234    let CommandContext { query, roving, .. } = use_command("CommandEmpty");
235    let searching = !query.read().trim().is_empty();
236    let hidden = !(searching && roving.visible_count() == 0);
237
238    rsx! {
239        p {
240            class: props.class,
241            "data-slot": "command-empty",
242            hidden,
243            role: "status",
244            ..props.attributes,
245            {props.children}
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::command_matches;
253
254    #[test]
255    fn matching_is_trimmed_and_case_insensitive() {
256        assert!(command_matches("Open documentation", ""));
257        assert!(command_matches("Open documentation", "  DOC "));
258        assert!(!command_matches("Toggle theme", "doc"));
259        assert!(command_matches("Ünïcode", "ünï"));
260        assert!(!command_matches("short", &"x".repeat(10_000)));
261    }
262}