lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Keyboard helpers shared by [`Select`](crate::Select) and [`ListBox`](crate::ListBox): printable
//! keys and the typeahead query, which lumen-react clears 700 ms after the last key.

use std::time::Duration;

use dioxus::prelude::*;

/// How long a typeahead query lives after its last key, like lumen-react.
pub(crate) const TYPEAHEAD_RESET: Duration = Duration::from_millis(700);

/// Upper bound on the query length. A held key repeats for as long as it is pressed; once the
/// query is longer than every label nothing can match, so the bound only caps memory and the cost
/// of each comparison.
const TYPEAHEAD_MAX_CHARS: usize = 256;

/// Whether `text` is one UTF-16 code unit, like `event.key.length === 1` in the browser.
pub(crate) fn is_single_key(text: &str) -> bool {
    text.encode_utf16().nth(1).is_none() && !text.is_empty()
}

/// The text of a printable key press without Alt, Control, or Meta, as lumen-react's typeahead
/// accepts it. Shift is allowed.
pub(crate) fn printable_key(event: &KeyboardEvent) -> Option<String> {
    let Key::Character(text) = event.key() else {
        return None;
    };

    let blocked = Modifiers::ALT | Modifiers::CONTROL | Modifiers::META | Modifiers::SUPER;

    (!event.modifiers().intersects(blocked) && is_single_key(&text)).then_some(text)
}

/// Whether the key is the space bar.
pub(crate) fn is_space(key: &Key) -> bool {
    matches!(key, Key::Character(text) if text == " ")
}

/// The typeahead query. Each key restarts the reset timer by bumping the generation; a timer only
/// clears the query when its generation is still current.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Typeahead {
    query: String,
    chars: usize,
    generation: u64,
}

impl Typeahead {
    /// Appends a key in lowercase and returns the generation its reset timer must match.
    pub(crate) fn push(&mut self, key: &str) -> u64 {
        if self.chars < TYPEAHEAD_MAX_CHARS {
            let lower = key.to_lowercase();
            self.chars += lower.chars().count();
            self.query.push_str(&lower);
        }

        self.generation = self.generation.wrapping_add(1);
        self.generation
    }

    /// The current lowercase query.
    pub(crate) fn query(&self) -> &str {
        &self.query
    }

    /// Whether no query is active.
    pub(crate) fn is_empty(&self) -> bool {
        self.query.is_empty()
    }

    /// Clears the query now and cancels the pending reset.
    pub(crate) fn reset(&mut self) {
        self.query.clear();
        self.chars = 0;
        self.generation = self.generation.wrapping_add(1);
    }

    /// Clears the query when no key arrived since `generation`.
    pub(crate) fn expire(&mut self, generation: u64) {
        if self.generation == generation {
            self.query.clear();
            self.chars = 0;
        }
    }
}

/// Appends a printable key to `typeahead`, schedules its reset, and returns the new query.
pub(crate) fn extend_typeahead(mut typeahead: CopyValue<Typeahead>, key: &str) -> String {
    let generation = typeahead.write().push(key);

    spawn(async move {
        crate::time::sleep(TYPEAHEAD_RESET).await;
        typeahead.write().expire(generation);
    });

    typeahead.peek().query().to_string()
}

#[cfg(test)]
mod tests {
    use super::{TYPEAHEAD_MAX_CHARS, Typeahead, is_single_key, is_space};
    use dioxus::prelude::Key;

    #[test]
    fn single_keys_follow_utf16_length_like_the_browser() {
        assert!(is_single_key("a"));
        assert!(is_single_key(" "));
        assert!(is_single_key("é"));
        assert!(!is_single_key(""));
        assert!(!is_single_key("ab"));
        // An astral character is two UTF-16 code units, so `event.key.length` is 2.
        assert!(!is_single_key("😀"));
    }

    #[test]
    fn space_is_a_character_key() {
        assert!(is_space(&Key::Character(" ".into())));
        assert!(!is_space(&Key::Character("a".into())));
        assert!(!is_space(&Key::Enter));
    }

    #[test]
    fn typeahead_accumulates_lowercase_keys_and_expires_by_generation() {
        let mut typeahead = Typeahead::default();
        let first = typeahead.push("N");
        let second = typeahead.push("e");

        assert_eq!(typeahead.query(), "ne");

        // A timer started before the latest key does not clear the query.
        typeahead.expire(first);
        assert_eq!(typeahead.query(), "ne");

        typeahead.expire(second);
        assert!(typeahead.is_empty());

        let third = typeahead.push("w");
        typeahead.reset();
        assert!(typeahead.is_empty());

        // Reset cancels the pending timer, and a later key starts a new query.
        typeahead.push("x");
        typeahead.expire(third);
        assert_eq!(typeahead.query(), "x");
    }

    #[test]
    fn typeahead_query_is_bounded_for_held_keys() {
        let mut typeahead = Typeahead::default();

        for _ in 0..10_000 {
            typeahead.push("a");
        }

        assert_eq!(typeahead.query().chars().count(), TYPEAHEAD_MAX_CHARS);
    }
}