forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

find.rs214 lines, 7.4 KiBHistoryRawDownload
1//! Search in a list: one field, live as you type, with two options beside it. By default a search
2//! forgives typos and case: every word typed must be in the text, or close to one of its words
3//! (one slip in words of four to seven letters, two in longer ones), or the start of one. "Exact" asks for the typed
4//! text as it is, as one piece; "Match case" keeps upper and lower case apart and looks for each
5//! word as typed.
6
7use topcoat::Result;
8use topcoat::context::Cx;
9use topcoat::view::{View, component, view};
10
11use crate::i18n::Lang;
12use crate::i18n::s;
13
14/// The longest search kept, in characters.
15pub const MAX_QUERY_CHARS: usize = 100;
16
17/// A search as typed, with its options.
18#[derive(Clone, Debug, Default)]
19pub struct Finder {
20 /// The search as typed, trimmed.
21 pub q: String,
22 pub exact: bool,
23 pub case: bool,
24 /// The search folded for matching: lower case unless Match case is on.
25 needle: String,
26 words: Vec<Vec<char>>,
27}
28
29impl Finder {
30 /// A search from the query's `q`, `exact` and `case` values. An option is on when its value is
31 /// present and not empty.
32 pub fn new(q: Option<&str>, exact: Option<&str>, case: Option<&str>) -> Finder {
33 let q: String = q
34 .unwrap_or("")
35 .trim()
36 .chars()
37 .take(MAX_QUERY_CHARS)
38 .collect();
39 let exact = exact.is_some_and(|v| !v.is_empty());
40 let case = case.is_some_and(|v| !v.is_empty());
41 let needle = if case { q.clone() } else { q.to_lowercase() };
42 let words = needle
43 .split(|c: char| !c.is_alphanumeric())
44 .filter(|w| !w.is_empty())
45 .map(|w| w.chars().collect())
46 .collect();
47 Finder {
48 q,
49 exact,
50 case,
51 needle,
52 words,
53 }
54 }
55
56 /// True when nothing was typed: everything matches.
57 pub fn is_empty(&self) -> bool {
58 self.needle.is_empty()
59 }
60
61 /// True when `text` matches the search.
62 pub fn matches(&self, text: &str) -> bool {
63 if self.is_empty() {
64 return true;
65 }
66 let hay = if self.case {
67 text.to_owned()
68 } else {
69 text.to_lowercase()
70 };
71 if hay.contains(&self.needle) {
72 return true;
73 }
74 if self.exact {
75 return false;
76 }
77 // Word by word, each typed word must start one of the text's words, so a short word such
78 // as "1" does not match every text with a 1 somewhere in it. Match case asks for the words
79 // as typed, so a slip of case is not forgiven as a typo.
80 let tokens: Vec<Vec<char>> = hay
81 .split(|c: char| !c.is_alphanumeric())
82 .filter(|t| !t.is_empty())
83 .map(|t| t.chars().collect())
84 .collect();
85 !self.words.is_empty()
86 && self.words.iter().all(|word| {
87 tokens
88 .iter()
89 .any(|token| token.starts_with(word) || (!self.case && near(word, token)))
90 })
91 }
92
93 /// True when any of `fields` matches, read as one text.
94 pub fn matches_any(&self, fields: &[&str]) -> bool {
95 self.is_empty() || self.matches(&fields.join(" \u{1f} "))
96 }
97
98 /// The query pairs that keep this search in a link: `q`, and each option that is on.
99 pub fn params(&self) -> Vec<(&'static str, &str)> {
100 let mut out = vec![("q", self.q.as_str())];
101 if self.exact {
102 out.push(("exact", "1"));
103 }
104 if self.case {
105 out.push(("case", "1"));
106 }
107 out
108 }
109}
110
111/// How many slips a typed word of `len` letters may have.
112fn slips_for(len: usize) -> usize {
113 match len {
114 0..=3 => 0,
115 4..=7 => 1,
116 _ => 2,
117 }
118}
119
120/// True when the typed `word` is close to `token`, or to the start of it as long as the word.
121fn near(word: &[char], token: &[char]) -> bool {
122 let slips = slips_for(word.len());
123 if slips == 0 {
124 return false;
125 }
126 if distance(word, token) <= slips {
127 return true;
128 }
129 token.len() > word.len() && distance(word, &token[..word.len()]) <= slips
130}
131
132/// Edits (insert, delete, change, swap two neighbours) between two words.
133fn distance(a: &[char], b: &[char]) -> usize {
134 if a.len().abs_diff(b.len()) > 2 {
135 return usize::MAX;
136 }
137 let (n, m) = (a.len(), b.len());
138 let mut d = vec![vec![0usize; m + 1]; n + 1];
139 for (i, row) in d.iter_mut().enumerate() {
140 row[0] = i;
141 }
142 for j in 0..=m {
143 d[0][j] = j;
144 }
145 for i in 1..=n {
146 for j in 1..=m {
147 let cost = usize::from(a[i - 1] != b[j - 1]);
148 let mut best = (d[i - 1][j] + 1)
149 .min(d[i][j - 1] + 1)
150 .min(d[i - 1][j - 1] + cost);
151 if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
152 best = best.min(d[i - 2][j - 2] + 1);
153 }
154 d[i][j] = best;
155 }
156 }
157 d[n][m]
158}
159
160/// The search field of a list, with its two options beside it, for inside a GET form. The field
161/// searches as you type; an option applies the moment it is ticked.
162#[component]
163pub async fn finder_field(
164 cx: &Cx,
165 lang: Lang,
166 finder: Finder,
167 placeholder: &str,
168 #[default] id: Option<&str>,
169) -> Result<impl View> {
170 let id = id.unwrap_or("find-q");
171 Ok(view! {
172 <div class="list-find">
173 <div class="plain-search">
174 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
175 <label class="sr-only" for=(id)>(placeholder)</label>
176 <input id=(id) type="search" name="q" value=(finder.q.as_str()) placeholder=(placeholder) data-live-search="" autocomplete="off">
177 <label class="find-opt" title=(s(lang, "Exact", "Tam"))>
178 <input type="checkbox" name="exact" value="1" checked=(finder.exact) data-autosubmit="true">
179 <span>(s(lang, "Exact", "Tam"))</span>
180 </label>
181 <label class="find-opt" title=(s(lang, "Match case", "Büyük/küçük harf"))>
182 <input type="checkbox" name="case" value="1" checked=(finder.case) data-autosubmit="true">
183 <span>"Aa"</span>
184 </label>
185 </div>
186 <button type="submit" class="sr-only">(s(lang, "Search", "Ara"))</button>
187 </div>
188 })
189}
190
191#[cfg(test)]
192mod tests {
193 use super::Finder;
194
195 fn find(q: &str, exact: bool, case: bool) -> Finder {
196 Finder::new(Some(q), exact.then_some("1"), case.then_some("1"))
197 }
198
199 #[test]
200 fn forgives_typos_and_case_unless_asked() {
201 let text = "Repository created · Hezarfen/hezarfen_landing";
202 assert!(find("", false, false).matches(text));
203 assert!(find("reposotory", false, false).matches(text));
204 assert!(find("landnig hezarfen", false, false).matches(text));
205 assert!(find("crea", false, false).matches(text));
206 assert!(!find("deleted", false, false).matches(text));
207 assert!(!find("reposotory", true, false).matches(text));
208 assert!(find("repository CREATED", true, false).matches(text));
209 assert!(!find("repository", false, true).matches(text));
210 assert!(find("Repository", false, true).matches(text));
211 assert!(!find("bulk 1", false, false).matches("tahinli/bulk-21"));
212 assert!(find("bulk 1", false, false).matches("tahinli/bulk-12"));
213 }
214}