use std::time::Duration;
use dioxus::prelude::*;
pub(crate) const TYPEAHEAD_RESET: Duration = Duration::from_millis(700);
const TYPEAHEAD_MAX_CHARS: usize = 256;
pub(crate) fn is_single_key(text: &str) -> bool {
text.encode_utf16().nth(1).is_none() && !text.is_empty()
}
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)
}
pub(crate) fn is_space(key: &Key) -> bool {
matches!(key, Key::Character(text) if text == " ")
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Typeahead {
query: String,
chars: usize,
generation: u64,
}
impl Typeahead {
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
}
pub(crate) fn query(&self) -> &str {
&self.query
}
pub(crate) fn is_empty(&self) -> bool {
self.query.is_empty()
}
pub(crate) fn reset(&mut self) {
self.query.clear();
self.chars = 0;
self.generation = self.generation.wrapping_add(1);
}
pub(crate) fn expire(&mut self, generation: u64) {
if self.generation == generation {
self.query.clear();
self.chars = 0;
}
}
}
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"));
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");
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());
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);
}
}