lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Command` and its parts: a filterable list of actions with keyboard movement.
// cspell:words Ünïcode ünï

use std::rc::Rc;

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::overlay::{focus_element, is_escape};

use super::roving::{Roving, RovingAxis, roving_move};
use super::util::element_text;

/// Whether an item's text matches a query, like the Lumen web runtime's command filter: the
/// query is trimmed and both sides compare case-insensitively; an empty query matches everything.
pub fn command_matches(text: &str, query: &str) -> bool {
    let query = query.trim().to_lowercase();

    query.is_empty() || text.to_lowercase().contains(&query)
}

#[derive(Clone, Copy)]
struct CommandContext {
    query: Signal<String>,
    roving: Roving,
    input: Signal<Option<Rc<MountedData>>>,
}

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

/// Props for [`Command`].
#[derive(Props, Clone, PartialEq)]
pub struct CommandProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// A [`CommandInput`] followed by [`CommandItem`]s, optionally grouped in a [`CommandList`],
    /// and a [`CommandEmpty`] message.
    pub children: Element,
}

/// A command palette: a search field that filters a list of actions.
///
/// Typing in the [`CommandInput`] hides [`CommandItem`]s whose text does not contain the query,
/// like Lumen's web runtime. `ArrowDown` and `ArrowUp` move from the field into the visible items
/// and between them; `Home` and `End` jump to the ends; `Escape` returns to the field.
#[component]
pub fn Command(props: CommandProps) -> Element {
    let query = use_signal(String::new);
    let input = use_signal(|| None::<Rc<MountedData>>);
    let roving = Roving::use_new();

    use_context_provider(|| CommandContext {
        query,
        roving,
        input,
    });

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

    rsx! {
        div { class, "data-ui-command": "true", ..props.attributes, {props.children} }
    }
}

/// Props for [`CommandInput`].
#[derive(Props, Clone, PartialEq)]
pub struct CommandInputProps {
    /// Called with the query on every edit.
    pub on_value_change: Option<EventHandler<String>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `placeholder` and `aria_label`.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// The search field of a [`Command`]. Renders a Lumen `Input` of type `search`.
#[component]
pub fn CommandInput(props: CommandInputProps) -> Element {
    let CommandContext {
        mut query,
        roving,
        mut input,
    } = use_command("CommandInput");
    let class = compose([Some("ui-input"), props.class.as_deref()]);
    let on_value_change = props.on_value_change;

    rsx! {
        input {
            class,
            r#type: "search",
            oninput: move |event| {
                let value = event.value();
                query.set(value.clone());

                if let Some(handler) = on_value_change {
                    handler.call(value);
                }
            },
            onkeydown: move |event| {
                let last = match event.key() {
                    Key::ArrowDown => false,
                    Key::ArrowUp => true,
                    _ => return,
                };

                event.prevent_default();
                roving.focus_edge(last);
            },
            onmounted: move |event| input.set(Some(event.data())),
            ..props.attributes,
        }
    }
}

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

/// An optional wrapper that groups the items of a [`Command`].
#[component]
pub fn CommandList(props: CommandListProps) -> Element {
    rsx! {
        div { class: props.class, "data-slot": "command-list", ..props.attributes, {props.children} }
    }
}

/// Props for [`CommandItem`].
#[derive(Props, Clone, PartialEq)]
pub struct CommandItemProps {
    /// Text the query is matched against. Defaults to the item's own text.
    #[props(into)]
    pub value: Option<String>,
    /// Disables the item and skips it during keyboard movement.
    #[props(default)]
    pub disabled: bool,
    /// Activation handler.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Item label.
    pub children: Element,
}

/// One action of a [`Command`]. Hidden while the query does not match its text.
#[component]
pub fn CommandItem(props: CommandItemProps) -> Element {
    let CommandContext {
        query,
        roving,
        input,
    } = use_command("CommandItem");
    let text = props
        .value
        .clone()
        .unwrap_or_else(|| element_text(&props.children));
    let hidden = !command_matches(&text, &query.read());
    let key = roving.use_item(props.disabled, hidden);
    let onclick = props.onclick;

    rsx! {
        button {
            class: props.class,
            "data-ui-command-item": "true",
            disabled: props.disabled,
            hidden,
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            onfocus: move |_| roving.focused(key),
            onkeydown: move |event| {
                if is_escape(&event) {
                    event.prevent_default();
                    focus_element(input());
                    return;
                }

                if let Some(movement) = roving_move(&event.key(), RovingAxis::Vertical, false) {
                    event.prevent_default();
                    roving.move_focus(Some(key), movement);
                }
            },
            onmounted: move |event| roving.mount(key, event.data()),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`CommandEmpty`].
#[derive(Props, Clone, PartialEq)]
pub struct CommandEmptyProps {
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<p>` or global attribute.
    #[props(extends = GlobalAttributes, extends = p)]
    pub attributes: Vec<Attribute>,
    /// The message, such as "No results".
    pub children: Element,
}

/// A message shown while a query matches no [`CommandItem`].
#[component]
pub fn CommandEmpty(props: CommandEmptyProps) -> Element {
    let CommandContext { query, roving, .. } = use_command("CommandEmpty");
    let searching = !query.read().trim().is_empty();
    let hidden = !(searching && roving.visible_count() == 0);

    rsx! {
        p {
            class: props.class,
            "data-slot": "command-empty",
            hidden,
            role: "status",
            ..props.attributes,
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::command_matches;

    #[test]
    fn matching_is_trimmed_and_case_insensitive() {
        assert!(command_matches("Open documentation", ""));
        assert!(command_matches("Open documentation", "  DOC "));
        assert!(!command_matches("Toggle theme", "doc"));
        assert!(command_matches("Ünïcode", "ünï"));
        assert!(!command_matches("short", &"x".repeat(10_000)));
    }
}