1
//! Autocomplete of the server-rendered forms: a select cell (`data-source`)
2
//! offers the shared options, a text cell (`data-suggest`) the tag
3
//! endpoints. One delegated set of listeners per form, so rows added later
4
//! work. A select cell is a visible control showing the option label and,
5
//! beside it in the same `<label>`, the hidden input carrying its id: a pick
6
//! sets both, typing keeps the id only while the text is exactly one label.
7

            
8
mod items;
9
mod place;
10
#[cfg(test)]
11
mod tests;
12

            
13
use std::cell::{Cell, RefCell};
14
use std::collections::HashMap;
15
use std::rc::{Rc, Weak};
16

            
17
use wasm_bindgen::closure::Closure;
18
use wasm_bindgen::prelude::*;
19
use web_sys::{
20
    Element, Event, EventInit, HtmlElement, HtmlFormElement, HtmlInputElement, KeyboardEvent,
21
    MouseEvent,
22
};
23

            
24
use crate::autocomplete::item_index_at;
25
use crate::data_attrs::AutocompleteAttr;
26
use crate::escape::html_escape;
27
use crate::filled_marks::{COPIED, FILLED};
28
use crate::rows::{each_element, listen};
29
use items::{Item, labelled_id, parse_items, resolve_id};
30

            
31
const READY: &str = "data-suggest-ready";
32
const SLOP: i32 = 8;
33

            
34
thread_local! {
35
    static CACHE: RefCell<HashMap<String, Rc<Vec<Item>>>> = RefCell::new(HashMap::new());
36
    static PICKS: Cell<u32> = const { Cell::new(0) };
37
    /// Set while the widget fires its own events, which must not reopen it.
38
    static SILENT: Cell<bool> = const { Cell::new(false) };
39
}
40

            
41
fn options_url(source: &str) -> String {
42
    format!("/api/forms/options/{source}")
43
}
44

            
45
fn report(result: Result<(), JsValue>) {
46
    if let Err(error) = result {
47
        web_sys::console::error_1(&error);
48
    }
49
}
50

            
51
fn cell_input(row: &Element, cell: &str) -> Option<HtmlInputElement> {
52
    let selector = format!("input[name$=\".{cell}\"]");
53
    row.query_selector(&selector).ok()??.dyn_into().ok()
54
}
55

            
56
/// The visible control of the select cell `cell` in `row`.
57
fn select_input(row: &Element, cell: &str) -> Option<HtmlInputElement> {
58
    let selector = format!("input[data-source][name$=\".{cell}\"]");
59
    row.query_selector(&selector).ok()??.dyn_into().ok()
60
}
61

            
62
/// The hidden input carrying the id a select control shows.
63
fn reference_of(visible: &HtmlInputElement) -> Option<HtmlInputElement> {
64
    let label = visible.parent_element()?;
65
    label
66
        .query_selector("input[type=\"hidden\"]")
67
        .ok()??
68
        .dyn_into()
69
        .ok()
70
}
71

            
72
fn row_of(input: &HtmlInputElement) -> Option<Element> {
73
    input.closest("[data-row]").ok()?
74
}
75

            
76
/// Where `input` gets its suggestions; none for a value without a name.
77
fn endpoint(input: &HtmlInputElement) -> Option<String> {
78
    if let Some(source) = input.get_attribute("data-source") {
79
        return Some(options_url(&source));
80
    }
81
    let url = input.get_attribute("data-suggest")?;
82
    let Some(by) = input.get_attribute("data-suggest-by") else {
83
        return Some(url);
84
    };
85
    let name = cell_input(&row_of(input)?, &by)?.value();
86
    let encoded = String::from(js_sys::encode_uri_component(&name));
87
    (!name.is_empty()).then(|| format!("{url}?name={encoded}"))
88
}
89

            
90
async fn items_at(url: &str) -> Result<Rc<Vec<Item>>, JsValue> {
91
    if let Some(cached) = CACHE.with(|cache| cache.borrow().get(url).cloned()) {
92
        return Ok(cached);
93
    }
94
    let body = crate::http::fetch_json(url).await?;
95
    let items = Rc::new(parse_items(&body).map_err(|e| JsValue::from_str(&e.to_string()))?);
96
    // Fetches racing on one url must share a single list, or each landing
97
    // would look like new content and rebuild the open items.
98
    Ok(CACHE.with(|cache| Rc::clone(cache.borrow_mut().entry(url.into()).or_insert(items))))
99
}
100

            
101
fn fire(input: &HtmlInputElement, name: &str) -> Result<(), JsValue> {
102
    let init = EventInit::new();
103
    init.set_bubbles(true);
104
    input
105
        .dispatch_event(&Event::new_with_event_init_dict(name, &init)?)
106
        .map(drop)
107
}
108

            
109
/// Set the text and tell the form, so conversion and the like re-evaluate.
110
fn write(input: &HtmlInputElement, text: &str) -> Result<(), JsValue> {
111
    input.set_value(text);
112
    SILENT.set(true);
113
    let fired = ["input", "change"]
114
        .iter()
115
        .try_for_each(|name| fire(input, name));
116
    SILENT.set(false);
117
    fired
118
}
119

            
120
/// The text and value a select control was loaded or last picked with.
121
const PRISTINE_TEXT: &str = "data-pristine-text";
122
const PRISTINE_ID: &str = "data-pristine-id";
123

            
124
/// Record what a select control shows and carries now as its pristine pair.
125
fn remember(input: &HtmlInputElement, hidden: &HtmlInputElement) -> Result<(), JsValue> {
126
    input.set_attribute(PRISTINE_TEXT, &input.value())?;
127
    input.set_attribute(PRISTINE_ID, &hidden.value())
128
}
129

            
130
/// Point a select control at `item`: the hidden input carries its id, the
131
/// visible control its label. A cell without a hidden input takes the label.
132
fn choose(input: &HtmlInputElement, item: &Item) -> Result<(), JsValue> {
133
    match reference_of(input) {
134
        Some(hidden) => {
135
            hidden.set_value(item.id.as_deref().unwrap_or_default());
136
            write(input, &item.label)?;
137
            remember(input, &hidden)
138
        }
139
        None => write(input, &item.label),
140
    }
141
}
142

            
143
/// Give the select cell `cell` of `to` the text and id `from` shows, as a pick would.
144
pub(crate) fn copy_pick(from: &Element, to: &Element, cell: &str) -> Result<(), JsValue> {
145
    let (Some(source), Some(target)) = (select_input(from, cell), select_input(to, cell)) else {
146
        return Ok(());
147
    };
148
    let id = reference_of(&source).map(|hidden| hidden.value());
149
    let item = Item {
150
        id,
151
        label: source.value(),
152
        ..Item::default()
153
    };
154
    choose(&target, &item)?;
155
    target.set_attribute(FILLED, "")?;
156
    target.set_attribute(COPIED, "")
157
}
158

            
159
fn is_empty(input: &HtmlInputElement) -> bool {
160
    input.value().is_empty() && reference_of(input).is_none_or(|hidden| hidden.value().is_empty())
161
}
162

            
163
/// Keep the id of `hidden` only while the text of `input` is exactly the
164
/// label of one of `items`, and tell the form. The pristine text keeps the
165
/// pristine value: a loaded label is never rebound to whatever entity holds
166
/// its label now.
167
fn apply_typed(
168
    input: &HtmlInputElement,
169
    hidden: &HtmlInputElement,
170
    items: &[Item],
171
) -> Result<(), JsValue> {
172
    let text = input.value();
173
    let pristine = input.get_attribute(PRISTINE_TEXT).unwrap_or_default();
174
    let id = match text == pristine {
175
        true => input.get_attribute(PRISTINE_ID).unwrap_or_default(),
176
        false => labelled_id(items, &text).unwrap_or_default().to_string(),
177
    };
178
    if hidden.value() == id {
179
        return Ok(());
180
    }
181
    hidden.set_value(&id);
182
    fire(hidden, "change")
183
}
184

            
185
/// [`apply_typed`] to a select control, once its options are loaded.
186
fn match_typed(input: &HtmlInputElement) -> Result<(), JsValue> {
187
    let (Some(source), Some(hidden)) = (input.get_attribute("data-source"), reference_of(input))
188
    else {
189
        return Ok(());
190
    };
191
    let url = options_url(&source);
192
    match CACHE.with(|cache| cache.borrow().get(&url).cloned()) {
193
        Some(items) => apply_typed(input, &hidden, &items),
194
        None => {
195
            let input = input.clone();
196
            wasm_bindgen_futures::spawn_local(async move {
197
                match items_at(&url).await {
198
                    Ok(items) => report(apply_typed(&input, &hidden, &items)),
199
                    Err(error) => web_sys::console::error_1(&error),
200
                }
201
            });
202
            Ok(())
203
        }
204
    }
205
}
206

            
207
/// The id of the commodity options matching `text`, once they are cached.
208
pub(crate) fn commodity_id(text: &str) -> Option<String> {
209
    let items = CACHE.with(|cache| cache.borrow().get(&options_url("commodities")).cloned())?;
210
    resolve_id(&items, text).map(str::to_string)
211
}
212

            
213
/// Fetch the commodity options so that later comparisons resolve names.
214
pub(crate) async fn load_commodities() {
215
    drop(items_at(&options_url("commodities")).await);
216
}
217

            
218
/// What a pick in `source` puts into the cell it fills: a commodity pick is
219
/// the fill itself, an account pick gives its only commodity.
220
async fn fill_of(source: &HtmlInputElement, item: Option<Item>) -> Option<Item> {
221
    let item = item?;
222
    if source.get_attribute("data-source").as_deref() == Some("commodities") {
223
        return Some(item);
224
    }
225
    let commodity = item.commodity?;
226
    let items = items_at(&options_url("commodities")).await.ok()?;
227
    items
228
        .iter()
229
        .find(|o| o.id.as_deref() == Some(commodity.as_str()))
230
        .cloned()
231
}
232

            
233
const PICK: &str = "data-pick";
234

            
235
fn unmark(input: &HtmlInputElement) -> Result<(), JsValue> {
236
    input.remove_attribute(FILLED)?;
237
    input.remove_attribute(COPIED)
238
}
239

            
240
/// A fill wrote `input`: it is no longer the copy of the split above.
241
fn marked_filled(input: &HtmlInputElement) -> Result<(), JsValue> {
242
    input.remove_attribute(COPIED)?;
243
    input.set_attribute(FILLED, "")
244
}
245

            
246
fn fillable(input: &HtmlInputElement) -> bool {
247
    is_empty(input) || input.has_attribute(FILLED)
248
}
249

            
250
fn current(input: &HtmlInputElement, pick: u32) -> bool {
251
    input
252
        .get_attribute(PICK)
253
        .is_some_and(|n| n == pick.to_string())
254
}
255

            
256
/// Fill the declared cells while they are empty or filled before, each fill
257
/// filling on in turn, unless `input` was picked again meanwhile: the earlier
258
/// reply must not overwrite the later pick's fills. A pick that yields no
259
/// fill clears the filled cells, and stops at a copied one a fill has not moved.
260
async fn fill(input: HtmlInputElement, item: Item, pick: u32) {
261
    let Some(row) = row_of(&input) else {
262
        return;
263
    };
264
    let (mut source, mut item) = (input.clone(), Some(item));
265
    while let Some(cell) = source.get_attribute("data-fills") {
266
        let fill = fill_of(&source, item).await;
267
        let Some(target) = select_input(&row, &cell).filter(fillable) else {
268
            return;
269
        };
270
        if !current(&input, pick) {
271
            return;
272
        }
273
        match &fill {
274
            Some(fill) => report(choose(&target, fill).and_then(|()| marked_filled(&target))),
275
            None if target.has_attribute(COPIED) => return,
276
            None => report(clear(&target)),
277
        }
278
        (source, item) = (target, fill);
279
    }
280
}
281

            
282
/// Empty a filled select cell, as the user clearing it would.
283
fn clear(target: &HtmlInputElement) -> Result<(), JsValue> {
284
    if is_empty(target) {
285
        return Ok(());
286
    }
287
    choose(target, &Item::default())?;
288
    unmark(target)
289
}
290

            
291
struct Session {
292
    input: HtmlInputElement,
293
    url: String,
294
    items: Rc<Vec<Item>>,
295
    shown: Vec<usize>,
296
    selected: usize,
297
}
298

            
299
impl Session {
300
    fn html(&self) -> String {
301
        let mut html = String::new();
302
        for (position, &index) in self.shown.iter().enumerate() {
303
            let item = &self.items[index];
304
            let class = if position == self.selected {
305
                " selected"
306
            } else {
307
                ""
308
            };
309
            let context = item
310
                .context()
311
                .map(|path| format!(" <span class=\"optional\">{}</span>", html_escape(path)))
312
                .unwrap_or_default();
313
            html.push_str(&format!(
314
                "<div class=\"autocomplete-item{class}\" {}=\"{position}\">{}{context}</div>",
315
                AutocompleteAttr::Index.as_str(),
316
                html_escape(&item.label),
317
            ));
318
        }
319
        html
320
    }
321
}
322

            
323
/// What the popup's items were last built from.
324
struct Rendered {
325
    items: Rc<Vec<Item>>,
326
    shown: Vec<usize>,
327
}
328

            
329
impl Rendered {
330
    fn of(session: &Session) -> Self {
331
        Self {
332
            items: Rc::clone(&session.items),
333
            shown: session.shown.clone(),
334
        }
335
    }
336

            
337
    fn matches(&self, session: &Session) -> bool {
338
        Rc::ptr_eq(&self.items, &session.items) && self.shown == session.shown
339
    }
340
}
341

            
342
struct Widget {
343
    form: HtmlFormElement,
344
    popup: HtmlElement,
345
    session: RefCell<Option<Session>>,
346
    /// The pointer position and the index in the options of the pressed item.
347
    pressed: Cell<Option<(i32, i32, usize)>>,
348
    rendered: RefCell<Option<Rendered>>,
349
    /// Re-fits the open list when the visible area moves or shrinks.
350
    refit: Closure<dyn FnMut(Event)>,
351
}
352

            
353
impl Widget {
354
    fn open(self: &Rc<Self>, input: &HtmlInputElement) {
355
        let Some(url) = endpoint(input) else {
356
            self.close();
357
            return;
358
        };
359
        self.pressed.set(None);
360
        let cached = CACHE.with(|cache| cache.borrow().get(&url).cloned());
361
        let fetch = cached.is_none();
362
        *self.session.borrow_mut() = Some(Session {
363
            input: input.clone(),
364
            url: url.clone(),
365
            items: cached.unwrap_or_default(),
366
            shown: Vec::new(),
367
            selected: 0,
368
        });
369
        self.refresh();
370
        if fetch {
371
            wasm_bindgen_futures::spawn_local(Rc::clone(self).load(input.clone(), url));
372
        }
373
    }
374

            
375
    async fn load(self: Rc<Self>, input: HtmlInputElement, url: String) {
376
        match items_at(&url).await {
377
            Ok(items) => {
378
                let mut session = self.session.borrow_mut();
379
                if let Some(open) = session
380
                    .as_mut()
381
                    .filter(|s| s.url == url && s.input.is_same_node(Some(&input)))
382
                {
383
                    open.items = items;
384
                }
385
                drop(session);
386
                self.refresh();
387
            }
388
            Err(error) => web_sys::console::error_1(&error),
389
        }
390
    }
391

            
392
    fn close(&self) {
393
        *self.session.borrow_mut() = None;
394
        *self.rendered.borrow_mut() = None;
395
        self.pressed.set(None);
396
        self.popup.set_inner_html("");
397
        let refit = self.refit.as_ref().unchecked_ref();
398
        for (target, event) in place::viewport_events() {
399
            report(target.remove_event_listener_with_callback(event, refit));
400
        }
401
    }
402

            
403
    fn follow(&self) {
404
        let refit = self.refit.as_ref().unchecked_ref();
405
        for (target, event) in place::viewport_events() {
406
            report(target.add_event_listener_with_callback(event, refit));
407
        }
408
    }
409

            
410
    fn fit(&self) {
411
        let input = self.session.borrow().as_ref().map(|s| s.input.clone());
412
        if let Some(input) = input {
413
            report(place::fit(&self.popup, &input));
414
        }
415
    }
416

            
417
    fn refresh(&self) {
418
        self.render();
419
        self.fit();
420
    }
421

            
422
    fn render(&self) {
423
        let mut guard = self.session.borrow_mut();
424
        let Some(session) = guard.as_mut() else {
425
            *self.rendered.borrow_mut() = None;
426
            self.popup.set_inner_html("");
427
            return;
428
        };
429
        let query = session.input.value().to_lowercase();
430
        session.shown = (0..session.items.len())
431
            .filter(|&n| session.items[n].matches(&query))
432
            .collect();
433
        session.selected = session.selected.min(session.shown.len().saturating_sub(1));
434
        self.build(session);
435
        let parent = session.input.parent_element();
436
        let placed = |p: &Element| {
437
            self.popup
438
                .parent_element()
439
                .is_some_and(|c| c.is_same_node(Some(p)))
440
        };
441
        if let Some(parent) = parent.filter(|p| !placed(p)) {
442
            report(parent.append_child(&self.popup).map(drop));
443
        }
444
        self.follow();
445
    }
446

            
447
    /// Rebuild the items only when what they list changed; otherwise just
448
    /// move the selection, so nodes under a press stay put.
449
    fn build(&self, session: &Session) {
450
        let unchanged = self
451
            .rendered
452
            .borrow()
453
            .as_ref()
454
            .is_some_and(|rendered| rendered.matches(session));
455
        match unchanged {
456
            true => self.mark_selected(session.selected),
457
            false => {
458
                self.popup.set_inner_html(&session.html());
459
                *self.rendered.borrow_mut() = Some(Rendered::of(session));
460
            }
461
        }
462
    }
463

            
464
    fn mark_selected(&self, selected: usize) {
465
        let children = self.popup.children();
466
        for n in 0..children.length() {
467
            let Some(item) = children.item(n) else {
468
                continue;
469
            };
470
            let on = usize::try_from(n).is_ok_and(|n| n == selected);
471
            report(
472
                item.class_list()
473
                    .toggle_with_force("selected", on)
474
                    .map(drop),
475
            );
476
        }
477
    }
478

            
479
    fn step(&self, forward: bool) {
480
        if let Some(session) = self.session.borrow_mut().as_mut() {
481
            let len = session.shown.len().max(1);
482
            session.selected = if forward {
483
                (session.selected + 1) % len
484
            } else {
485
                (session.selected + len - 1) % len
486
            };
487
        }
488
        self.refresh();
489
    }
490

            
491
    fn pick(self: &Rc<Self>, position: usize) {
492
        let index = self
493
            .session
494
            .borrow()
495
            .as_ref()
496
            .and_then(|s| s.shown.get(position).copied());
497
        if let Some(index) = index {
498
            self.pick_option(index);
499
        }
500
    }
501

            
502
    fn pick_option(self: &Rc<Self>, index: usize) {
503
        let chosen = self.session.borrow().as_ref().and_then(|s| {
504
            let item = s
505
                .shown
506
                .contains(&index)
507
                .then(|| s.items.get(index))??
508
                .clone();
509
            Some((s.input.clone(), item))
510
        });
511
        let Some((input, item)) = chosen else {
512
            return;
513
        };
514
        let pick = PICKS.get().wrapping_add(1);
515
        PICKS.set(pick);
516
        report(input.set_attribute(PICK, &pick.to_string()));
517
        self.close();
518
        report(choose(&input, &item).and_then(|()| unmark(&input)));
519
        if input.has_attribute("data-fills") {
520
            wasm_bindgen_futures::spawn_local(fill(input, item, pick));
521
        }
522
    }
523

            
524
    fn on_key(self: &Rc<Self>, event: &Event, input: &HtmlInputElement) {
525
        let Some(key) = event.dyn_ref::<KeyboardEvent>().map(KeyboardEvent::key) else {
526
            return;
527
        };
528
        let choice = self
529
            .session
530
            .borrow()
531
            .as_ref()
532
            .filter(|s| !s.shown.is_empty())
533
            .map(|s| s.selected);
534
        match (key.as_str(), choice) {
535
            ("ArrowDown", Some(_)) => self.step(true),
536
            ("ArrowDown", None) => self.open(input),
537
            ("ArrowUp", Some(_)) => self.step(false),
538
            ("Enter", Some(selected)) => self.pick(selected),
539
            ("Escape", _) => self.close(),
540
            _ => return,
541
        }
542
        event.prevent_default();
543
    }
544

            
545
    fn on_pointer(&self, kind: &str, event: &Event) {
546
        let Some(mouse) = event.dyn_ref::<MouseEvent>() else {
547
            return;
548
        };
549
        match kind {
550
            "pointerdown" if mouse.button() == 0 => {
551
                let option = item_index_at(mouse).and_then(|position| {
552
                    self.session
553
                        .borrow()
554
                        .as_ref()
555
                        .and_then(|s| s.shown.get(position).copied())
556
                });
557
                if let Some(index) = option {
558
                    event.prevent_default();
559
                    self.pressed
560
                        .set(Some((mouse.client_x(), mouse.client_y(), index)));
561
                }
562
            }
563
            "pointermove" => {
564
                let moved = self.pressed.get().is_some_and(|(x, y, _)| {
565
                    (mouse.client_x() - x).abs() + (mouse.client_y() - y).abs() > SLOP
566
                });
567
                if moved {
568
                    self.pressed.set(None);
569
                }
570
            }
571
            _ => {}
572
        }
573
    }
574
}
575

            
576
fn suggest_input(event: &Event) -> Option<HtmlInputElement> {
577
    let input: HtmlInputElement = event.target()?.dyn_into().ok()?;
578
    (input.has_attribute("data-source") || input.has_attribute("data-suggest")).then_some(input)
579
}
580

            
581
type InputHandler = fn(&Rc<Widget>, &Event, &HtmlInputElement);
582

            
583
fn wire_form(widget: &Rc<Widget>) -> Result<(), JsValue> {
584
    let on = |name: &str, handler: InputHandler| {
585
        let widget = Rc::clone(widget);
586
        listen(&widget.form.clone(), name, move |event| {
587
            if let Some(input) = suggest_input(&event) {
588
                handler(&widget, &event, &input);
589
            }
590
        })
591
    };
592
    on("focusin", |w, _, input| w.open(input))?;
593
    on("input", |w, _, input| {
594
        if !SILENT.get() {
595
            report(unmark(input));
596
            report(match_typed(input));
597
            w.open(input);
598
        }
599
    })?;
600
    on("focusout", |w, _, input| {
601
        w.close();
602
        if reference_of(input).is_some_and(|hidden| hidden.value().is_empty()) {
603
            report(match_typed(input));
604
        }
605
    })?;
606
    on("keydown", |w, event, input| w.on_key(event, input))
607
}
608

            
609
fn wire_popup(widget: &Rc<Widget>) -> Result<(), JsValue> {
610
    for kind in ["pointerdown", "pointermove"] {
611
        let widget = Rc::clone(widget);
612
        let popup = widget.popup.clone();
613
        listen(&popup, kind, move |event| widget.on_pointer(kind, &event))?;
614
    }
615
    let up = Rc::clone(widget);
616
    listen(&widget.popup, "pointerup", move |_| {
617
        if let Some((_, _, index)) = up.pressed.take() {
618
            up.pick_option(index);
619
        }
620
    })?;
621
    let cancel = Rc::clone(widget);
622
    listen(&widget.popup, "pointercancel", move |_| {
623
        cancel.pressed.set(None)
624
    })
625
}
626

            
627
/// Offer suggestions in the select and tag cells of a rendered form.
628
///
629
/// # Errors
630
/// Returns the DOM error if the popup or a listener cannot be set up.
631
pub fn init_suggest(form: &HtmlFormElement) -> Result<(), JsValue> {
632
    if form.has_attribute(READY) {
633
        return Ok(());
634
    }
635
    form.set_attribute(READY, "")?;
636
    for input in each_element(form, "input[data-source]")? {
637
        let input: HtmlInputElement = input.dyn_into()?;
638
        if let Some(hidden) = reference_of(&input) {
639
            remember(&input, &hidden)?;
640
        }
641
    }
642
    let document = form.owner_document().ok_or("no document")?;
643
    let popup: HtmlElement = document.create_element("div")?.dyn_into()?;
644
    popup.set_class_name("autocomplete-results");
645
    let widget = Rc::new_cyclic(|widget: &Weak<Widget>| {
646
        let widget = widget.clone();
647
        Widget {
648
            form: form.clone(),
649
            popup,
650
            session: RefCell::new(None),
651
            pressed: Cell::new(None),
652
            rendered: RefCell::new(None),
653
            refit: Closure::new(move |_: Event| {
654
                if let Some(widget) = widget.upgrade() {
655
                    widget.fit();
656
                }
657
            }),
658
        }
659
    });
660
    wire_form(&widget)?;
661
    wire_popup(&widget)
662
}