Lines
3.73 %
Functions
1.63 %
Branches
100 %
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use web_sys::{Element, HtmlElement, HtmlInputElement, KeyboardEvent};
use super::Suggestion;
use crate::data_attrs::AutocompleteAttr;
use crate::escape::html_escape;
/// Configuration for autocomplete behavior.
pub struct AutocompleteConfig {
pub fetch_url: String,
pub dependency_input: Option<HtmlInputElement>,
}
impl AutocompleteConfig {
#[must_use]
pub fn get(url: impl Into<String>) -> Self {
Self {
fetch_url: url.into(),
dependency_input: None,
pub fn with_dependency(mut self, input: HtmlInputElement) -> Self {
self.dependency_input = Some(input);
self
/// Builds a cache key from URL and optional dependency value.
pub fn build_cache_key(url: &str, dependency_value: Option<&str>) -> String {
match dependency_value {
Some(dep) => format!("{url}?dep={dep}"),
None => url.to_string(),
pub struct Autocomplete<T: Suggestion> {
input: HtmlInputElement,
hidden_primary: HtmlInputElement,
container: Element,
items: Vec<T>,
filtered_indices: Vec<usize>,
selected_index: Option<usize>,
is_open: bool,
impl<T: Suggestion> Autocomplete<T> {
pub fn new(
) -> Self {
input,
hidden_primary,
container,
items: Vec::new(),
filtered_indices: Vec::new(),
selected_index: None,
is_open: false,
pub fn set_items(&mut self, items: Vec<T>) {
self.items = items;
self.filter(&self.input.value());
pub fn filter(&mut self, query: &str) {
self.filtered_indices = self
.items
.iter()
.enumerate()
.filter(|(_, item)| query.is_empty() || item.matches(query))
.map(|(i, _)| i)
.collect();
self.selected_index = if self.filtered_indices.is_empty() {
None
} else {
Some(0)
};
self.render_suggestions();
pub fn select(&mut self, index: usize) {
if let Some(&item_idx) = self.filtered_indices.get(index)
&& let Some(item) = self.items.get(item_idx)
{
let display_text = item.display_text().to_string();
let id = item.get_id().to_string();
self.input.set_value(&display_text);
self.hidden_primary.set_value(&id);
self.trigger_input_event(&self.input);
self.trigger_change_event(&self.hidden_primary);
self.close();
pub fn open(&mut self) {
self.is_open = true;
self.show_container();
pub fn close(&mut self) {
self.is_open = false;
self.hide_container();
self.container.set_inner_html("");
fn show_container(&self) {
if let Ok(el) = self.container.clone().dyn_into::<HtmlElement>() {
let _ = el.style().set_property("display", "block");
fn hide_container(&self) {
let _ = el.style().set_property("display", "none");
pub fn move_selection(&mut self, delta: i32) {
if self.filtered_indices.is_empty() {
return;
let len = self.filtered_indices.len();
let current = self.selected_index.unwrap_or(0) as i32;
let new_idx = (current + delta).rem_euclid(len as i32) as usize;
self.selected_index = Some(new_idx);
pub fn select_current(&mut self) {
if let Some(idx) = self.selected_index {
self.select(idx);
fn render_suggestions(&mut self) {
if !self.is_open {
let mut html = String::new();
for (display_idx, &item_idx) in self.filtered_indices.iter().enumerate() {
if let Some(item) = self.items.get(item_idx) {
let selected_class = if self.selected_index == Some(display_idx) {
" selected"
""
html.push_str(&format!(
r#"<div class="autocomplete-item{}" {}="{}">{}</div>"#,
selected_class,
AutocompleteAttr::Index.as_str(),
display_idx,
html_escape(item.display_text())
));
if html.is_empty() && !self.input.value().is_empty() {
html = r#"<div class="no-results">No matches found</div>"#.to_string();
self.container.set_inner_html(&html);
fn trigger_input_event(&self, element: &HtmlInputElement) {
let init = web_sys::EventInit::new();
init.set_bubbles(true);
if let Ok(event) = web_sys::Event::new_with_event_init_dict("input", &init) {
let _ = element.dispatch_event(&event);
fn trigger_change_event(&self, element: &HtmlInputElement) {
if let Ok(event) = web_sys::Event::new_with_event_init_dict("change", &init) {
/// The `data-index` of the `.autocomplete-item` under a pointer event,
/// if any. The event target may be the item itself or a descendant, so
/// it resolves via `closest`.
pub(crate) fn item_index_at(e: &web_sys::MouseEvent) -> Option<usize> {
let target = e.target()?;
let el = target.dyn_into::<Element>().ok()?;
let item = el.closest(".autocomplete-item").ok().flatten()?;
item.get_attribute(AutocompleteAttr::Index.as_str())?
.parse::<usize>()
.ok()
fn log_listener_error(what: &str, error: &JsValue) {
web_sys::console::error_2(&JsValue::from_str(&format!("autocomplete {what}:")), error);
fn listen<E: wasm_bindgen::convert::FromWasmAbi + 'static>(
target: &web_sys::EventTarget,
event: &str,
handler: impl FnMut(E) + 'static,
) {
let callback = Closure::wrap(Box::new(handler) as Box<dyn FnMut(E)>);
if let Err(error) =
target.add_event_listener_with_callback(event, callback.as_ref().unchecked_ref())
log_listener_error(event, &error);
callback.forget();
pub fn attach_autocomplete<T: Suggestion>(
ac: Rc<RefCell<Autocomplete<T>>>,
config: AutocompleteConfig,
let input = ac.borrow().input.clone();
let container = ac.borrow().container.clone();
let config = Rc::new(config);
let cache: Rc<RefCell<HashMap<String, Vec<T>>>> = Rc::new(RefCell::new(HashMap::new()));
let ac_input = Rc::clone(&ac);
listen(&input, "input", move |_: web_sys::InputEvent| {
// Use try_borrow_mut to skip if already borrowed (e.g., during programmatic selection)
let Ok(mut ac) = ac_input.try_borrow_mut() else {
let query = ac.input.value();
ac.open();
ac.filter(&query);
});
let ac_focus = Rc::clone(&ac);
let config_focus = Rc::clone(&config);
let cache_focus = Rc::clone(&cache);
let input_focus = input.clone();
listen(&input, "focus", move |_: web_sys::FocusEvent| {
ac_focus.borrow_mut().open();
if let Some(ref dep_input) = config_focus.dependency_input {
let dep_value = dep_input.value();
if dep_value.is_empty() {
let ac_fetch = Rc::clone(&ac_focus);
let config_fetch = Rc::clone(&config_focus);
let cache_fetch = Rc::clone(&cache_focus);
let dep_value_clone = dep_value.clone();
let input_fetch = input_focus.clone();
wasm_bindgen_futures::spawn_local(async move {
let name = String::from(js_sys::encode_uri_component(&dep_value_clone));
let url = format!("{}?name={name}", config_fetch.fetch_url);
let cache_key = build_cache_key(&config_fetch.fetch_url, Some(&dep_value_clone));
if let Some(cached) = cache_fetch.borrow().get(&cache_key) {
ac_fetch.borrow_mut().set_items(cached.clone());
match fetch_items(&url).await {
Ok(items) => {
clear_fetch_error(&input_fetch);
cache_fetch.borrow_mut().insert(cache_key, items.clone());
ac_fetch.borrow_mut().set_items(items);
Err(error) => show_fetch_error(&input_fetch, &error),
let ac_blur = Rc::clone(&ac);
listen(&input, "blur", move |_: web_sys::FocusEvent| {
let Some(window) = web_sys::window() else {
let ac_delayed = Rc::clone(&ac_blur);
let delayed_close = Closure::once(Box::new(move || {
ac_delayed.borrow_mut().close();
}) as Box<dyn FnOnce()>);
if let Err(error) = window.set_timeout_with_callback_and_timeout_and_arguments_0(
delayed_close.as_ref().unchecked_ref(),
150,
log_listener_error("blur timer", &error);
delayed_close.forget();
let ac_keydown = Rc::clone(&ac);
listen(&input, "keydown", move |e: KeyboardEvent| {
let mut ac = ac_keydown.borrow_mut();
match e.key().as_str() {
"ArrowDown" => {
e.prevent_default();
ac.move_selection(1);
"ArrowUp" => {
ac.move_selection(-1);
"Enter" if ac.is_open && ac.selected_index.is_some() => {
ac.select_current();
"Escape" => {
ac.close();
_ => {}
// Pointer-event tap-to-select that still lets the (max-height,
// overflow-y) results list be touch-scrolled. The old
// `mousedown`(prevent-default) + `click`(select) pair worked on
// desktop but never selected on touch: the synthesized `mousedown`
// couldn't cancel the input blur, so the 150ms delayed close fired
// before the `click` landed.
//
// `pointerdown` (primary button only) records the pressed item and
// `prevent_default`s to keep the input focused — suppressing the
// blur and its delayed close. A `pointermove` past a small slop is a
// scroll drag and cancels the pending pick; `pointerup` commits it;
// `pointercancel` (fired when the browser takes over for scrolling)
// discards it. Selecting on `pointerdown` instead would close the
// list on the first contact of a scroll gesture.
let pending: Rc<RefCell<Option<(i32, i32, usize)>>> = Rc::new(RefCell::new(None));
let down_pending = Rc::clone(&pending);
listen(&container, "pointerdown", move |e: web_sys::MouseEvent| {
if e.button() != 0 {
let Some(idx) = item_index_at(&e) else {
*down_pending.borrow_mut() = Some((e.client_x(), e.client_y(), idx));
let move_pending = Rc::clone(&pending);
listen(&container, "pointermove", move |e: web_sys::MouseEvent| {
let moved = move_pending
.borrow()
.is_some_and(|(sx, sy, _)| (e.client_x() - sx).abs() + (e.client_y() - sy).abs() > 8);
if moved {
*move_pending.borrow_mut() = None;
let ac_select = Rc::clone(&ac);
let up_pending = Rc::clone(&pending);
listen(&container, "pointerup", move |_: web_sys::MouseEvent| {
if let Some((_, _, idx)) = up_pending.borrow_mut().take() {
ac_select.borrow_mut().select(idx);
let cancel_pending = Rc::clone(&pending);
listen(&container, "pointercancel", move |_: web_sys::Event| {
*cancel_pending.borrow_mut() = None;
// Skip initial fetch if there's a dependency - fetch on focus instead
if config.dependency_input.is_none() {
let ac_fetch = Rc::clone(&ac);
let config_fetch = Rc::clone(&config);
let cache_fetch = Rc::clone(&cache);
let input_fetch = input.clone();
let cache_key = build_cache_key(&config_fetch.fetch_url, None);
match fetch_items::<T>(&config_fetch.fetch_url).await {
async fn fetch_items<T: Suggestion>(url: &str) -> Result<Vec<T>, JsValue> {
let body = crate::http::fetch_json(url).await?;
serde_json::from_str(&body).map_err(|e| JsValue::from_str(&e.to_string()))
fn show_fetch_error(input: &HtmlInputElement, error: &JsValue) {
let message = error.as_string().unwrap_or_else(|| "Request failed".into());
web_sys::console::error_1(&JsValue::from_str(&format!(
"autocomplete fetch failed: {message}"
)));
input.set_title(&message);
let _ = input.class_list().add_1("autocomplete-error");
fn clear_fetch_error(input: &HtmlInputElement) {
input.set_title("");
let _ = input.class_list().remove_1("autocomplete-error");
#[cfg(test)]
#[path = "component_tests.rs"]
mod tests;