pub use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher as _};
use super::{normalize_string, Filter};
struct FuzzyMatcher {
matcher: SkimMatcherV2,
pattern: Option<String>,
}
impl FuzzyMatcher {
fn new() -> Self {
Self { matcher: SkimMatcherV2::default().smart_case().use_cache(true), pattern: None }
}
fn with_pattern(mut self, pattern: &str) -> Self {
self.pattern = Some(normalize_string(pattern));
self
}
fn matches(&self, subject: &str) -> bool {
let Some(pattern) = self.pattern.as_ref() else { return true };
self.matcher.fuzzy_match(&normalize_string(subject), pattern).is_some()
}
}
pub fn new_filter(pattern: &str) -> impl Filter {
let searcher = FuzzyMatcher::new().with_pattern(pattern);
move |room| -> bool {
let Some(room_name) = room.cached_display_name() else { return false };
searcher.matches(&room_name)
}
}
#[cfg(test)]
mod tests {
use std::ops::Not;
use super::*;
#[test]
fn test_no_pattern() {
let matcher = FuzzyMatcher::new();
assert!(matcher.matches("hello"));
}
#[test]
fn test_empty_pattern() {
let matcher = FuzzyMatcher::new();
assert!(matcher.matches("hello"));
}
#[test]
fn test_literal() {
let matcher = FuzzyMatcher::new();
let matcher = matcher.with_pattern("mtx");
assert!(matcher.matches("matrix"));
let matcher = matcher.with_pattern("mxt");
assert!(matcher.matches("matrix").not());
}
#[test]
fn test_ignore_case() {
let matcher = FuzzyMatcher::new();
let matcher = matcher.with_pattern("mtx");
assert!(matcher.matches("MaTrIX"));
let matcher = matcher.with_pattern("mxt");
assert!(matcher.matches("MaTrIX").not());
}
#[test]
fn test_smart_case() {
let matcher = FuzzyMatcher::new();
let matcher = matcher.with_pattern("mtx");
assert!(matcher.matches("matrix"));
assert!(matcher.matches("Matrix"));
let matcher = matcher.with_pattern("Mtx");
assert!(matcher.matches("matrix").not());
assert!(matcher.matches("Matrix"));
}
#[test]
fn test_normalization() {
let matcher = FuzzyMatcher::new();
let matcher = matcher.with_pattern("ubété");
assert_eq!(matcher.pattern, Some("ubete".to_owned()));
assert!(matcher.matches("un bel été"));
let matcher = matcher.with_pattern("stf");
assert!(matcher.matches("Ștefan"));
}
}