use std::time::Duration;
const SEARCH_TIMEOUT: Duration = Duration::from_millis(1000);
const MAX_SEARCH_LENGTH: usize = 256;
#[derive(Clone, Debug, Default)]
pub(super) struct TypeAhead {
pub(super) search: String,
last_character: Option<Duration>,
searching: bool,
}
impl TypeAhead {
fn has_timed_out(&self, now: Duration) -> bool {
self.last_character
.is_none_or(|last| now.saturating_sub(last) > SEARCH_TIMEOUT)
}
pub(super) fn is_searching(&mut self, now: Duration) -> bool {
if self.has_timed_out(now) {
self.searching = false;
}
self.searching
}
pub(super) fn append(&mut self, character: &str, now: Duration) -> bool {
let created = self.has_timed_out(now);
if created {
self.search.clear();
}
self.last_character = Some(now);
if self.search.encode_utf16().count() <= MAX_SEARCH_LENGTH {
self.search.push_str(character);
}
self.searching = true;
created
}
pub(super) fn reset(&mut self) {
self.search.clear();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Match {
Prefix,
Exact,
}
pub(super) fn find_item(
texts: &[Option<&str>],
search: &str,
start: usize,
rule: Match,
) -> Option<usize> {
let count = texts.len();
let mut index = start;
for _ in 0..count {
let text = texts[index].filter(|text| !text.is_empty())?;
let text = text.trim_start_matches(' ');
let found = match rule {
Match::Exact => are_strings_equal(text, search),
Match::Prefix => starts_with_ignoring_linguistics(text, search),
};
if found {
return Some(index);
}
index += 1;
if index == count {
index = 0;
}
}
None
}
pub(super) fn search_start(selected: Option<usize>, count: usize, created: bool) -> usize {
match selected {
Some(index) if created && index + 1 < count => index + 1,
Some(_) if created => 0,
None if created => 0,
Some(index) => index,
None => 0,
}
}
pub(super) fn starts_with_ignoring_linguistics(source: &str, prefix: &str) -> bool {
if prefix.encode_utf16().count() > source.encode_utf16().count() {
return false;
}
fold(source).starts_with(&fold(prefix))
}
pub(super) fn are_strings_equal(a: &str, b: &str) -> bool {
a.eq_ignore_ascii_case(b)
}
pub(super) fn is_search_string_valid(text: &str) -> bool {
!text.trim_start_matches(' ').is_empty()
}
fn fold(text: &str) -> String {
text.chars()
.map(|character| match character {
'\u{FF01}'..='\u{FF5E}' => {
char::from_u32(character as u32 - 0xFF01 + 0x21).unwrap_or(character)
}
'\u{3000}' => ' ',
'\u{3041}'..='\u{3096}' => char::from_u32(character as u32 + 0x60).unwrap_or(character),
other => other,
})
.flat_map(char::to_lowercase)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_prefix_matches_regardless_of_case_width_and_kana() {
assert!(starts_with_ignoring_linguistics("wAsHINGton", "Wa"));
assert!(starts_with_ignoring_linguistics("Blue", "bl"));
assert!(starts_with_ignoring_linguistics("カタカナ", "かた"));
assert!(!starts_with_ignoring_linguistics("Red", "Reds"));
assert!(!starts_with_ignoring_linguistics("Green", "r"));
}
#[test]
fn exact_matches_ignore_only_ascii_case() {
assert!(are_strings_equal("Arial", "ARIAL"));
assert!(!are_strings_equal("Arial", "Arial Black"));
assert!(!are_strings_equal("É", "é"));
}
#[test]
fn a_search_string_of_spaces_is_not_valid() {
assert!(!is_search_string_valid(""));
assert!(!is_search_string_valid(" "));
assert!(is_search_string_valid(" a"));
}
#[test]
fn the_walk_wraps_and_trims_leading_spaces() {
let texts = [Some("Apple"), Some(" Banana"), Some("Avocado")];
assert_eq!(find_item(&texts, "a", 1, Match::Prefix), Some(2));
assert_eq!(find_item(&texts, "b", 2, Match::Prefix), Some(1));
assert_eq!(find_item(&texts, "apple", 0, Match::Exact), Some(0));
assert_eq!(find_item(&texts, "c", 0, Match::Prefix), None);
}
#[test]
fn an_item_without_text_ends_the_walk() {
let texts = [Some("Apple"), None, Some("Cherry")];
assert_eq!(find_item(&texts, "c", 0, Match::Prefix), None);
assert_eq!(find_item(&texts, "c", 2, Match::Prefix), Some(2));
assert_eq!(find_item(&[Some("")], "a", 0, Match::Prefix), None);
}
#[test]
fn a_new_string_starts_after_the_selection() {
assert_eq!(search_start(Some(1), 3, true), 2);
assert_eq!(search_start(Some(2), 3, true), 0);
assert_eq!(search_start(Some(1), 3, false), 1);
assert_eq!(search_start(None, 3, false), 0);
assert_eq!(search_start(None, 3, true), 0);
}
#[test]
fn characters_within_a_second_extend_the_string() {
let mut type_ahead = TypeAhead::default();
assert!(type_ahead.append("a", Duration::from_millis(5000)));
assert!(!type_ahead.append("b", Duration::from_millis(5900)));
assert_eq!(type_ahead.search, "ab");
assert!(type_ahead.is_searching(Duration::from_millis(6800)));
assert!(!type_ahead.is_searching(Duration::from_millis(7000)));
assert!(type_ahead.append("c", Duration::from_millis(7000)));
assert_eq!(type_ahead.search, "c");
}
}