1
use std::cell::RefCell;
2
use std::collections::HashMap;
3
use std::rc::Rc;
4
use wasm_bindgen::JsCast;
5
use wasm_bindgen::prelude::*;
6
use web_sys::{Element, HtmlElement, HtmlInputElement, KeyboardEvent};
7

            
8
use super::Suggestion;
9
use crate::data_attrs::AutocompleteAttr;
10
use crate::escape::html_escape;
11

            
12
/// Configuration for autocomplete behavior.
13
pub struct AutocompleteConfig {
14
    pub fetch_url: String,
15
    pub dependency_input: Option<HtmlInputElement>,
16
}
17

            
18
impl AutocompleteConfig {
19
    #[must_use]
20
1
    pub fn get(url: impl Into<String>) -> Self {
21
1
        Self {
22
1
            fetch_url: url.into(),
23
1
            dependency_input: None,
24
1
        }
25
1
    }
26

            
27
    #[must_use]
28
    pub fn with_dependency(mut self, input: HtmlInputElement) -> Self {
29
        self.dependency_input = Some(input);
30
        self
31
    }
32
}
33

            
34
/// Builds a cache key from URL and optional dependency value.
35
#[must_use]
36
2
pub fn build_cache_key(url: &str, dependency_value: Option<&str>) -> String {
37
2
    match dependency_value {
38
1
        Some(dep) => format!("{url}?dep={dep}"),
39
1
        None => url.to_string(),
40
    }
41
2
}
42

            
43
pub struct Autocomplete<T: Suggestion> {
44
    input: HtmlInputElement,
45
    hidden_primary: HtmlInputElement,
46
    container: Element,
47
    items: Vec<T>,
48
    filtered_indices: Vec<usize>,
49
    selected_index: Option<usize>,
50
    is_open: bool,
51
}
52

            
53
impl<T: Suggestion> Autocomplete<T> {
54
    #[must_use]
55
    pub fn new(
56
        input: HtmlInputElement,
57
        hidden_primary: HtmlInputElement,
58
        container: Element,
59
    ) -> Self {
60
        Self {
61
            input,
62
            hidden_primary,
63
            container,
64
            items: Vec::new(),
65
            filtered_indices: Vec::new(),
66
            selected_index: None,
67
            is_open: false,
68
        }
69
    }
70

            
71
    pub fn set_items(&mut self, items: Vec<T>) {
72
        self.items = items;
73
        self.filter(&self.input.value());
74
    }
75

            
76
    pub fn filter(&mut self, query: &str) {
77
        self.filtered_indices = self
78
            .items
79
            .iter()
80
            .enumerate()
81
            .filter(|(_, item)| query.is_empty() || item.matches(query))
82
            .map(|(i, _)| i)
83
            .collect();
84
        self.selected_index = if self.filtered_indices.is_empty() {
85
            None
86
        } else {
87
            Some(0)
88
        };
89
        self.render_suggestions();
90
    }
91

            
92
    pub fn select(&mut self, index: usize) {
93
        if let Some(&item_idx) = self.filtered_indices.get(index)
94
            && let Some(item) = self.items.get(item_idx)
95
        {
96
            let display_text = item.display_text().to_string();
97
            let id = item.get_id().to_string();
98

            
99
            self.input.set_value(&display_text);
100
            self.hidden_primary.set_value(&id);
101

            
102
            self.trigger_input_event(&self.input);
103
            self.trigger_change_event(&self.hidden_primary);
104
        }
105
        self.close();
106
    }
107

            
108
    pub fn open(&mut self) {
109
        self.is_open = true;
110
        self.show_container();
111
        self.filter(&self.input.value());
112
    }
113

            
114
    pub fn close(&mut self) {
115
        self.is_open = false;
116
        self.hide_container();
117
        self.container.set_inner_html("");
118
    }
119

            
120
    fn show_container(&self) {
121
        if let Ok(el) = self.container.clone().dyn_into::<HtmlElement>() {
122
            let _ = el.style().set_property("display", "block");
123
        }
124
    }
125

            
126
    fn hide_container(&self) {
127
        if let Ok(el) = self.container.clone().dyn_into::<HtmlElement>() {
128
            let _ = el.style().set_property("display", "none");
129
        }
130
    }
131

            
132
    pub fn move_selection(&mut self, delta: i32) {
133
        if self.filtered_indices.is_empty() {
134
            return;
135
        }
136

            
137
        let len = self.filtered_indices.len();
138
        let current = self.selected_index.unwrap_or(0) as i32;
139
        let new_idx = (current + delta).rem_euclid(len as i32) as usize;
140
        self.selected_index = Some(new_idx);
141
        self.render_suggestions();
142
    }
143

            
144
    pub fn select_current(&mut self) {
145
        if let Some(idx) = self.selected_index {
146
            self.select(idx);
147
        }
148
    }
149

            
150
    fn render_suggestions(&mut self) {
151
        if !self.is_open {
152
            self.container.set_inner_html("");
153
            return;
154
        }
155

            
156
        let mut html = String::new();
157
        for (display_idx, &item_idx) in self.filtered_indices.iter().enumerate() {
158
            if let Some(item) = self.items.get(item_idx) {
159
                let selected_class = if self.selected_index == Some(display_idx) {
160
                    " selected"
161
                } else {
162
                    ""
163
                };
164
                html.push_str(&format!(
165
                    r#"<div class="autocomplete-item{}" {}="{}">{}</div>"#,
166
                    selected_class,
167
                    AutocompleteAttr::Index.as_str(),
168
                    display_idx,
169
                    html_escape(item.display_text())
170
                ));
171
            }
172
        }
173

            
174
        if html.is_empty() && !self.input.value().is_empty() {
175
            html = r#"<div class="no-results">No matches found</div>"#.to_string();
176
        }
177

            
178
        self.container.set_inner_html(&html);
179
    }
180

            
181
    fn trigger_input_event(&self, element: &HtmlInputElement) {
182
        let init = web_sys::EventInit::new();
183
        init.set_bubbles(true);
184
        if let Ok(event) = web_sys::Event::new_with_event_init_dict("input", &init) {
185
            let _ = element.dispatch_event(&event);
186
        }
187
    }
188

            
189
    fn trigger_change_event(&self, element: &HtmlInputElement) {
190
        let init = web_sys::EventInit::new();
191
        init.set_bubbles(true);
192
        if let Ok(event) = web_sys::Event::new_with_event_init_dict("change", &init) {
193
            let _ = element.dispatch_event(&event);
194
        }
195
    }
196
}
197

            
198
/// The `data-index` of the `.autocomplete-item` under a pointer event,
199
/// if any. The event target may be the item itself or a descendant, so
200
/// it resolves via `closest`.
201
pub(crate) fn item_index_at(e: &web_sys::MouseEvent) -> Option<usize> {
202
    let target = e.target()?;
203
    let el = target.dyn_into::<Element>().ok()?;
204
    let item = el.closest(".autocomplete-item").ok().flatten()?;
205
    item.get_attribute(AutocompleteAttr::Index.as_str())?
206
        .parse::<usize>()
207
        .ok()
208
}
209

            
210
fn log_listener_error(what: &str, error: &JsValue) {
211
    web_sys::console::error_2(&JsValue::from_str(&format!("autocomplete {what}:")), error);
212
}
213

            
214
fn listen<E: wasm_bindgen::convert::FromWasmAbi + 'static>(
215
    target: &web_sys::EventTarget,
216
    event: &str,
217
    handler: impl FnMut(E) + 'static,
218
) {
219
    let callback = Closure::wrap(Box::new(handler) as Box<dyn FnMut(E)>);
220
    if let Err(error) =
221
        target.add_event_listener_with_callback(event, callback.as_ref().unchecked_ref())
222
    {
223
        log_listener_error(event, &error);
224
    }
225
    callback.forget();
226
}
227

            
228
pub fn attach_autocomplete<T: Suggestion>(
229
    ac: Rc<RefCell<Autocomplete<T>>>,
230
    config: AutocompleteConfig,
231
) {
232
    let input = ac.borrow().input.clone();
233
    let container = ac.borrow().container.clone();
234

            
235
    let config = Rc::new(config);
236
    let cache: Rc<RefCell<HashMap<String, Vec<T>>>> = Rc::new(RefCell::new(HashMap::new()));
237

            
238
    let ac_input = Rc::clone(&ac);
239
    listen(&input, "input", move |_: web_sys::InputEvent| {
240
        // Use try_borrow_mut to skip if already borrowed (e.g., during programmatic selection)
241
        let Ok(mut ac) = ac_input.try_borrow_mut() else {
242
            return;
243
        };
244
        let query = ac.input.value();
245
        ac.open();
246
        ac.filter(&query);
247
    });
248

            
249
    let ac_focus = Rc::clone(&ac);
250
    let config_focus = Rc::clone(&config);
251
    let cache_focus = Rc::clone(&cache);
252
    let input_focus = input.clone();
253
    listen(&input, "focus", move |_: web_sys::FocusEvent| {
254
        ac_focus.borrow_mut().open();
255

            
256
        if let Some(ref dep_input) = config_focus.dependency_input {
257
            let dep_value = dep_input.value();
258
            if dep_value.is_empty() {
259
                return;
260
            }
261

            
262
            let ac_fetch = Rc::clone(&ac_focus);
263
            let config_fetch = Rc::clone(&config_focus);
264
            let cache_fetch = Rc::clone(&cache_focus);
265
            let dep_value_clone = dep_value.clone();
266
            let input_fetch = input_focus.clone();
267

            
268
            wasm_bindgen_futures::spawn_local(async move {
269
                let name = String::from(js_sys::encode_uri_component(&dep_value_clone));
270
                let url = format!("{}?name={name}", config_fetch.fetch_url);
271
                let cache_key = build_cache_key(&config_fetch.fetch_url, Some(&dep_value_clone));
272

            
273
                if let Some(cached) = cache_fetch.borrow().get(&cache_key) {
274
                    ac_fetch.borrow_mut().set_items(cached.clone());
275
                    return;
276
                }
277

            
278
                match fetch_items(&url).await {
279
                    Ok(items) => {
280
                        clear_fetch_error(&input_fetch);
281
                        cache_fetch.borrow_mut().insert(cache_key, items.clone());
282
                        ac_fetch.borrow_mut().set_items(items);
283
                    }
284
                    Err(error) => show_fetch_error(&input_fetch, &error),
285
                }
286
            });
287
        }
288
    });
289

            
290
    let ac_blur = Rc::clone(&ac);
291
    listen(&input, "blur", move |_: web_sys::FocusEvent| {
292
        let Some(window) = web_sys::window() else {
293
            return;
294
        };
295
        let ac_delayed = Rc::clone(&ac_blur);
296
        let delayed_close = Closure::once(Box::new(move || {
297
            ac_delayed.borrow_mut().close();
298
        }) as Box<dyn FnOnce()>);
299
        if let Err(error) = window.set_timeout_with_callback_and_timeout_and_arguments_0(
300
            delayed_close.as_ref().unchecked_ref(),
301
            150,
302
        ) {
303
            log_listener_error("blur timer", &error);
304
        }
305
        delayed_close.forget();
306
    });
307

            
308
    let ac_keydown = Rc::clone(&ac);
309
    listen(&input, "keydown", move |e: KeyboardEvent| {
310
        let mut ac = ac_keydown.borrow_mut();
311
        match e.key().as_str() {
312
            "ArrowDown" => {
313
                e.prevent_default();
314
                ac.move_selection(1);
315
            }
316
            "ArrowUp" => {
317
                e.prevent_default();
318
                ac.move_selection(-1);
319
            }
320
            "Enter" if ac.is_open && ac.selected_index.is_some() => {
321
                e.prevent_default();
322
                ac.select_current();
323
            }
324
            "Escape" => {
325
                ac.close();
326
            }
327
            _ => {}
328
        }
329
    });
330

            
331
    // Pointer-event tap-to-select that still lets the (max-height,
332
    // overflow-y) results list be touch-scrolled. The old
333
    // `mousedown`(prevent-default) + `click`(select) pair worked on
334
    // desktop but never selected on touch: the synthesized `mousedown`
335
    // couldn't cancel the input blur, so the 150ms delayed close fired
336
    // before the `click` landed.
337
    //
338
    // `pointerdown` (primary button only) records the pressed item and
339
    // `prevent_default`s to keep the input focused — suppressing the
340
    // blur and its delayed close. A `pointermove` past a small slop is a
341
    // scroll drag and cancels the pending pick; `pointerup` commits it;
342
    // `pointercancel` (fired when the browser takes over for scrolling)
343
    // discards it. Selecting on `pointerdown` instead would close the
344
    // list on the first contact of a scroll gesture.
345
    let pending: Rc<RefCell<Option<(i32, i32, usize)>>> = Rc::new(RefCell::new(None));
346

            
347
    let down_pending = Rc::clone(&pending);
348
    listen(&container, "pointerdown", move |e: web_sys::MouseEvent| {
349
        if e.button() != 0 {
350
            return;
351
        }
352
        let Some(idx) = item_index_at(&e) else {
353
            return;
354
        };
355
        e.prevent_default();
356
        *down_pending.borrow_mut() = Some((e.client_x(), e.client_y(), idx));
357
    });
358

            
359
    let move_pending = Rc::clone(&pending);
360
    listen(&container, "pointermove", move |e: web_sys::MouseEvent| {
361
        let moved = move_pending
362
            .borrow()
363
            .is_some_and(|(sx, sy, _)| (e.client_x() - sx).abs() + (e.client_y() - sy).abs() > 8);
364
        if moved {
365
            *move_pending.borrow_mut() = None;
366
        }
367
    });
368

            
369
    let ac_select = Rc::clone(&ac);
370
    let up_pending = Rc::clone(&pending);
371
    listen(&container, "pointerup", move |_: web_sys::MouseEvent| {
372
        if let Some((_, _, idx)) = up_pending.borrow_mut().take() {
373
            ac_select.borrow_mut().select(idx);
374
        }
375
    });
376

            
377
    let cancel_pending = Rc::clone(&pending);
378
    listen(&container, "pointercancel", move |_: web_sys::Event| {
379
        *cancel_pending.borrow_mut() = None;
380
    });
381

            
382
    // Skip initial fetch if there's a dependency - fetch on focus instead
383
    if config.dependency_input.is_none() {
384
        let ac_fetch = Rc::clone(&ac);
385
        let config_fetch = Rc::clone(&config);
386
        let cache_fetch = Rc::clone(&cache);
387
        let input_fetch = input.clone();
388
        wasm_bindgen_futures::spawn_local(async move {
389
            let cache_key = build_cache_key(&config_fetch.fetch_url, None);
390

            
391
            if let Some(cached) = cache_fetch.borrow().get(&cache_key) {
392
                ac_fetch.borrow_mut().set_items(cached.clone());
393
                return;
394
            }
395

            
396
            match fetch_items::<T>(&config_fetch.fetch_url).await {
397
                Ok(items) => {
398
                    clear_fetch_error(&input_fetch);
399
                    cache_fetch.borrow_mut().insert(cache_key, items.clone());
400
                    ac_fetch.borrow_mut().set_items(items);
401
                }
402
                Err(error) => show_fetch_error(&input_fetch, &error),
403
            }
404
        });
405
    }
406
}
407

            
408
async fn fetch_items<T: Suggestion>(url: &str) -> Result<Vec<T>, JsValue> {
409
    let body = crate::http::fetch_json(url).await?;
410
    serde_json::from_str(&body).map_err(|e| JsValue::from_str(&e.to_string()))
411
}
412

            
413
fn show_fetch_error(input: &HtmlInputElement, error: &JsValue) {
414
    let message = error.as_string().unwrap_or_else(|| "Request failed".into());
415
    web_sys::console::error_1(&JsValue::from_str(&format!(
416
        "autocomplete fetch failed: {message}"
417
    )));
418
    input.set_title(&message);
419
    let _ = input.class_list().add_1("autocomplete-error");
420
}
421

            
422
fn clear_fetch_error(input: &HtmlInputElement) {
423
    input.set_title("");
424
    let _ = input.class_list().remove_1("autocomplete-error");
425
}
426

            
427
#[cfg(test)]
428
#[path = "component_tests.rs"]
429
mod tests;