web search done right
Bold suffix for suggestions
Mikkel Denkerc37db38eeacd
diff --git a/src/frontend/autosuggest.rs b/src/frontend/autosuggest.rsindex 6db6627e..6f7de855 100644--- a/src/frontend/autosuggest.rs+++ b/src/frontend/autosuggest.rs@@ -20,13 +20,47 @@ use axum::{extract, response::IntoResponse, Extension, Json};use super::State;+fn highlight(query: &str, suggestion: String) -> String {+ let idx = suggestion+ .chars()+ .zip(query.chars())+ .position(|(suggestion_char, query_char)| suggestion_char != query_char)+ .unwrap_or(query.len());++ let mut new_suggestion: String = suggestion.chars().take(idx).collect();+ new_suggestion += "<b>";+ new_suggestion += suggestion.chars().skip(idx).collect::<String>().as_str();+ new_suggestion += "</b>";+ new_suggestion+}+pub async fn route(extract::Query(params): extract::Query<HashMap<String, String>>,Extension(state): Extension<Arc<State>>,) -> impl IntoResponse {if let Some(query) = params.get("q") {- Json(state.autosuggest.suggestions(query).unwrap())+ let mut suggestions = Vec::new();++ for suggestion in state.autosuggest.suggestions(query).unwrap() {+ suggestions.push(highlight(query, suggestion));+ }++ Json(suggestions)} else {Json(Vec::new())}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn suffix_highlight() {+ assert_eq!(&highlight("", "test".to_string()), "<b>test</b>");+ assert_eq!(&highlight("t", "test".to_string()), "t<b>est</b>");+ assert_eq!(&highlight("te", "test".to_string()), "te<b>st</b>");+ assert_eq!(&highlight("tes", "test".to_string()), "tes<b>t</b>");+ assert_eq!(&highlight("test", "test".to_string()), "test<b></b>");+ }+}