lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Private helpers shared by the overlay components.

use std::rc::Rc;

use dioxus::core::{DynamicNode, TemplateNode, VNode};
use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::hooks::{Controllable, use_controllable};
use crate::{ButtonSize, ButtonVariant};

/// Controlled or uncontrolled open state that compound parts can read reactively.
///
/// `Controllable` reads a controlled prop without subscribing, so parts that read it through
/// context would miss prop changes. The memo re-renders every reader when either the prop or the
/// internal value changes.
#[derive(Clone, Copy)]
pub(crate) struct OpenState {
    state: Controllable<bool>,
    view: Memo<bool>,
}

impl OpenState {
    /// The current value. Reading it subscribes the component.
    pub(crate) fn get(self) -> bool {
        *self.view.read()
    }

    /// Requests a new value, like [`Controllable::set`].
    pub(crate) fn set(self, open: bool) {
        self.state.set(open);
    }
}

/// Keeps an open state that an `open` prop may control.
pub(crate) fn use_open_state(
    open: Option<bool>,
    default_open: bool,
    on_open_change: Option<EventHandler<bool>>,
) -> OpenState {
    let state = use_controllable(open, || default_open, on_open_change);
    let view = use_memo(use_reactive((&open,), move |(open,)| {
        open.unwrap_or_else(|| state.get())
    }));

    OpenState { state, view }
}

/// The `data-surface` value for a glass setting, like `resolveSurface` in lumen-react.
pub(crate) fn surface(glass: Glass) -> &'static str {
    if glass == Glass::Off {
        "default"
    } else {
        "glass"
    }
}

fn button_size_class(size: ButtonSize) -> &'static str {
    match size {
        ButtonSize::Default => "ui-button--default-size",
        ButtonSize::Sm => "ui-button--sm",
        ButtonSize::Lg => "ui-button--lg",
        ButtonSize::Icon => "ui-button--icon",
    }
}

/// The classes of a Lumen `Button`, for triggers that need handlers `Button` does not forward.
///
/// Disabled styling comes from the native `disabled` attribute, as it does for `Button`.
pub(crate) fn button_class(
    variant: ButtonVariant,
    size: ButtonSize,
    extra: Option<&str>,
) -> String {
    let variant = format!("ui-button--{}", variant.as_str());

    compose([
        Some("ui-button"),
        Some(variant.as_str()),
        Some(button_size_class(size)),
        extra,
    ])
}

/// Whether an `Element` renders anything, so optional children can skip their wrapper like React's
/// `{children && …}`.
pub(crate) fn has_content(element: &Element) -> bool {
    let Ok(node) = element else {
        return false;
    };

    node.template
        .roots
        .iter()
        .any(|root| !is_placeholder_root(node, root))
}

fn is_placeholder_root(node: &VNode, root: &TemplateNode) -> bool {
    match root {
        TemplateNode::Dynamic { id } => match node.dynamic_nodes.get(*id) {
            Some(DynamicNode::Placeholder(_)) | None => true,
            Some(DynamicNode::Fragment(children)) => children.iter().all(|child| {
                child
                    .template
                    .roots
                    .iter()
                    .all(|root| is_placeholder_root(child, root))
            }),
            Some(DynamicNode::Text(text)) => text.value.is_empty(),
            Some(DynamicNode::Component(_)) => false,
        },
        TemplateNode::Text { text } => text.is_empty(),
        TemplateNode::Element { .. } => false,
    }
}

/// The plain text of an `Element`, for typeahead. Text rendered by child components is not
/// visible here; give those items an explicit text value.
pub(crate) fn element_text(element: &Element) -> String {
    let mut text = String::new();

    if let Ok(node) = element {
        collect_node_text(node, &mut text);
    }

    text
}

fn collect_node_text(node: &VNode, out: &mut String) {
    for root in node.template.roots {
        collect_template_text(node, root, out);
    }
}

fn collect_template_text(node: &VNode, template: &TemplateNode, out: &mut String) {
    match template {
        TemplateNode::Text { text } => out.push_str(text),
        TemplateNode::Element { children, .. } => {
            for child in *children {
                collect_template_text(node, child, out);
            }
        }
        TemplateNode::Dynamic { id } => match node.dynamic_nodes.get(*id) {
            Some(DynamicNode::Text(text)) => out.push_str(&text.value),
            Some(DynamicNode::Fragment(children)) => {
                for child in children {
                    collect_node_text(child, out);
                }
            }
            _ => {}
        },
    }
}

/// Formats a CSS pixel length the way React serializes numeric style values (`0`, `12px`).
pub(crate) fn css_pixels(value: f64) -> String {
    if value == 0.0 {
        "0".to_string()
    } else {
        format!("{value}px")
    }
}

/// Focuses a stored node, if any.
pub(crate) fn focus_stored(node: Option<Rc<MountedData>>) {
    crate::overlay::focus_element(node);
}

/// Next position in a list for menu-style arrow, Home, and End keys. Returns `None` for other keys.
pub(crate) fn menu_key_index(key: &Key, current: Option<usize>, len: usize) -> Option<usize> {
    if len == 0 {
        return None;
    }

    match key {
        Key::ArrowDown => crate::overlay::wrap_index(current, 1, len),
        Key::ArrowUp => crate::overlay::wrap_index(current, -1, len),
        Key::Home => Some(0),
        Key::End => Some(len - 1),
        _ => None,
    }
}

/// Typeahead for menus: the index of the next label that starts with `query`.
///
/// A query made of one repeated character cycles through the labels that start with it, starting
/// after `current`; a longer query keeps the current item while it still matches.
pub(crate) fn typeahead_index(
    labels: &[String],
    current: Option<usize>,
    query: &str,
) -> Option<usize> {
    if labels.is_empty() {
        return None;
    }

    let query = query.to_lowercase();
    let mut chars = query.chars();
    let first = chars.next()?;
    let repeated = chars.all(|character| character == first);
    let needle = if repeated { first.to_string() } else { query };
    let len = labels.len();
    let start = match current {
        Some(index) if !repeated => index % len,
        Some(index) => (index + 1) % len,
        None => 0,
    };

    (0..len)
        .map(|offset| (start + offset) % len)
        .find(|index| labels[*index].trim().to_lowercase().starts_with(&needle))
}

/// Whether a key event is a single printable character without command modifiers.
pub(crate) fn typeahead_character(event: &KeyboardEvent) -> Option<String> {
    let modifiers = event.modifiers();

    if modifiers.ctrl() || modifiers.meta() || modifiers.alt() {
        return None;
    }

    match event.key() {
        Key::Character(text) if text.chars().count() == 1 && !text.trim().is_empty() => Some(text),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use dioxus::prelude::*;

    use super::{Key, css_pixels, element_text, has_content, menu_key_index, typeahead_index};

    #[test]
    fn element_text_reads_static_and_dynamic_text() {
        let name = "Archive";
        assert_eq!(element_text(&rsx! { "Edit" }), "Edit");
        assert_eq!(element_text(&rsx! { "{name} all" }), "Archive all");
        assert_eq!(
            element_text(&rsx! { span { "Du" } strong { "plicate" } }),
            "Duplicate"
        );
        assert_eq!(element_text(&rsx! {}), "");
    }

    #[test]
    fn has_content_skips_placeholders() {
        let empty = false;
        assert!(!has_content(&rsx! {}));
        assert!(!has_content(&VNode::empty()));
        assert!(!has_content(&rsx! { if empty { "x" } }));
        assert!(has_content(&rsx! { "x" }));
        assert!(has_content(&rsx! { p {} }));
    }

    fn labels(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| (*value).to_string()).collect()
    }

    #[test]
    fn menu_keys_wrap_and_jump() {
        assert_eq!(menu_key_index(&Key::ArrowDown, None, 3), Some(0));
        assert_eq!(menu_key_index(&Key::ArrowUp, None, 3), Some(2));
        assert_eq!(menu_key_index(&Key::ArrowDown, Some(2), 3), Some(0));
        assert_eq!(menu_key_index(&Key::Home, Some(2), 3), Some(0));
        assert_eq!(menu_key_index(&Key::End, Some(0), 3), Some(2));
        assert_eq!(menu_key_index(&Key::Enter, Some(0), 3), None);
        assert_eq!(menu_key_index(&Key::ArrowDown, None, 0), None);
    }

    #[test]
    fn typeahead_cycles_and_matches_prefixes() {
        let items = labels(&["Archive", "Delete", "Duplicate", "Edit"]);
        assert_eq!(typeahead_index(&items, None, "d"), Some(1));
        assert_eq!(typeahead_index(&items, Some(1), "d"), Some(2));
        assert_eq!(typeahead_index(&items, Some(2), "d"), Some(1));
        assert_eq!(typeahead_index(&items, Some(2), "dd"), Some(1));
        assert_eq!(typeahead_index(&items, Some(1), "du"), Some(2));
        assert_eq!(typeahead_index(&items, Some(1), "DE"), Some(1));
        assert_eq!(typeahead_index(&items, None, "z"), None);
        assert_eq!(typeahead_index(&items, None, ""), None);
        assert_eq!(typeahead_index(&[], None, "a"), None);
    }

    #[test]
    fn typeahead_handles_long_queries() {
        let items = labels(&["a".repeat(10_000).as_str(), "b"]);
        let query = "a".repeat(20_000);
        assert_eq!(typeahead_index(&items, None, &query), Some(0));
    }

    #[test]
    fn pixels_follow_react_number_styles() {
        assert_eq!(css_pixels(0.0), "0");
        assert_eq!(css_pixels(12.0), "12px");
        assert_eq!(css_pixels(12.5), "12.5px");
    }
}