Lines
0 %
Functions
Branches
100 %
//! Autocomplete of the server-rendered forms: a select cell (`data-source`)
//! offers the shared options, a text cell (`data-suggest`) the tag
//! endpoints. One delegated set of listeners per form, so rows added later
//! work. A select cell is a visible control showing the option label and,
//! beside it in the same `<label>`, the hidden input carrying its id: a pick
//! sets both, typing keeps the id only while the text is exactly one label.
mod items;
mod place;
#[cfg(test)]
mod tests;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::{Rc, Weak};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use web_sys::{
Element, Event, EventInit, HtmlElement, HtmlFormElement, HtmlInputElement, KeyboardEvent,
MouseEvent,
};
use crate::autocomplete::item_index_at;
use crate::data_attrs::AutocompleteAttr;
use crate::escape::html_escape;
use crate::filled_marks::{COPIED, FILLED};
use crate::rows::{each_element, listen};
use items::{Item, labelled_id, parse_items, resolve_id};
const READY: &str = "data-suggest-ready";
const SLOP: i32 = 8;
thread_local! {
static CACHE: RefCell<HashMap<String, Rc<Vec<Item>>>> = RefCell::new(HashMap::new());
static PICKS: Cell<u32> = const { Cell::new(0) };
/// Set while the widget fires its own events, which must not reopen it.
static SILENT: Cell<bool> = const { Cell::new(false) };
}
fn options_url(source: &str) -> String {
format!("/api/forms/options/{source}")
fn report(result: Result<(), JsValue>) {
if let Err(error) = result {
web_sys::console::error_1(&error);
fn cell_input(row: &Element, cell: &str) -> Option<HtmlInputElement> {
let selector = format!("input[name$=\".{cell}\"]");
row.query_selector(&selector).ok()??.dyn_into().ok()
/// The visible control of the select cell `cell` in `row`.
fn select_input(row: &Element, cell: &str) -> Option<HtmlInputElement> {
let selector = format!("input[data-source][name$=\".{cell}\"]");
/// The hidden input carrying the id a select control shows.
fn reference_of(visible: &HtmlInputElement) -> Option<HtmlInputElement> {
let label = visible.parent_element()?;
label
.query_selector("input[type=\"hidden\"]")
.ok()??
.dyn_into()
.ok()
fn row_of(input: &HtmlInputElement) -> Option<Element> {
input.closest("[data-row]").ok()?
/// Where `input` gets its suggestions; none for a value without a name.
fn endpoint(input: &HtmlInputElement) -> Option<String> {
if let Some(source) = input.get_attribute("data-source") {
return Some(options_url(&source));
let url = input.get_attribute("data-suggest")?;
let Some(by) = input.get_attribute("data-suggest-by") else {
return Some(url);
let name = cell_input(&row_of(input)?, &by)?.value();
let encoded = String::from(js_sys::encode_uri_component(&name));
(!name.is_empty()).then(|| format!("{url}?name={encoded}"))
async fn items_at(url: &str) -> Result<Rc<Vec<Item>>, JsValue> {
if let Some(cached) = CACHE.with(|cache| cache.borrow().get(url).cloned()) {
return Ok(cached);
let body = crate::http::fetch_json(url).await?;
let items = Rc::new(parse_items(&body).map_err(|e| JsValue::from_str(&e.to_string()))?);
// Fetches racing on one url must share a single list, or each landing
// would look like new content and rebuild the open items.
Ok(CACHE.with(|cache| Rc::clone(cache.borrow_mut().entry(url.into()).or_insert(items))))
fn fire(input: &HtmlInputElement, name: &str) -> Result<(), JsValue> {
let init = EventInit::new();
init.set_bubbles(true);
input
.dispatch_event(&Event::new_with_event_init_dict(name, &init)?)
.map(drop)
/// Set the text and tell the form, so conversion and the like re-evaluate.
fn write(input: &HtmlInputElement, text: &str) -> Result<(), JsValue> {
input.set_value(text);
SILENT.set(true);
let fired = ["input", "change"]
.iter()
.try_for_each(|name| fire(input, name));
SILENT.set(false);
fired
/// The text and value a select control was loaded or last picked with.
const PRISTINE_TEXT: &str = "data-pristine-text";
const PRISTINE_ID: &str = "data-pristine-id";
/// Record what a select control shows and carries now as its pristine pair.
fn remember(input: &HtmlInputElement, hidden: &HtmlInputElement) -> Result<(), JsValue> {
input.set_attribute(PRISTINE_TEXT, &input.value())?;
input.set_attribute(PRISTINE_ID, &hidden.value())
/// Point a select control at `item`: the hidden input carries its id, the
/// visible control its label. A cell without a hidden input takes the label.
fn choose(input: &HtmlInputElement, item: &Item) -> Result<(), JsValue> {
match reference_of(input) {
Some(hidden) => {
hidden.set_value(item.id.as_deref().unwrap_or_default());
write(input, &item.label)?;
remember(input, &hidden)
None => write(input, &item.label),
/// Give the select cell `cell` of `to` the text and id `from` shows, as a pick would.
pub(crate) fn copy_pick(from: &Element, to: &Element, cell: &str) -> Result<(), JsValue> {
let (Some(source), Some(target)) = (select_input(from, cell), select_input(to, cell)) else {
return Ok(());
let id = reference_of(&source).map(|hidden| hidden.value());
let item = Item {
id,
label: source.value(),
..Item::default()
choose(&target, &item)?;
target.set_attribute(FILLED, "")?;
target.set_attribute(COPIED, "")
fn is_empty(input: &HtmlInputElement) -> bool {
input.value().is_empty() && reference_of(input).is_none_or(|hidden| hidden.value().is_empty())
/// Keep the id of `hidden` only while the text of `input` is exactly the
/// label of one of `items`, and tell the form. The pristine text keeps the
/// pristine value: a loaded label is never rebound to whatever entity holds
/// its label now.
fn apply_typed(
input: &HtmlInputElement,
hidden: &HtmlInputElement,
items: &[Item],
) -> Result<(), JsValue> {
let text = input.value();
let pristine = input.get_attribute(PRISTINE_TEXT).unwrap_or_default();
let id = match text == pristine {
true => input.get_attribute(PRISTINE_ID).unwrap_or_default(),
false => labelled_id(items, &text).unwrap_or_default().to_string(),
if hidden.value() == id {
hidden.set_value(&id);
fire(hidden, "change")
/// [`apply_typed`] to a select control, once its options are loaded.
fn match_typed(input: &HtmlInputElement) -> Result<(), JsValue> {
let (Some(source), Some(hidden)) = (input.get_attribute("data-source"), reference_of(input))
else {
let url = options_url(&source);
match CACHE.with(|cache| cache.borrow().get(&url).cloned()) {
Some(items) => apply_typed(input, &hidden, &items),
None => {
let input = input.clone();
wasm_bindgen_futures::spawn_local(async move {
match items_at(&url).await {
Ok(items) => report(apply_typed(&input, &hidden, &items)),
Err(error) => web_sys::console::error_1(&error),
});
Ok(())
/// The id of the commodity options matching `text`, once they are cached.
pub(crate) fn commodity_id(text: &str) -> Option<String> {
let items = CACHE.with(|cache| cache.borrow().get(&options_url("commodities")).cloned())?;
resolve_id(&items, text).map(str::to_string)
/// Fetch the commodity options so that later comparisons resolve names.
pub(crate) async fn load_commodities() {
drop(items_at(&options_url("commodities")).await);
/// What a pick in `source` puts into the cell it fills: a commodity pick is
/// the fill itself, an account pick gives its only commodity.
async fn fill_of(source: &HtmlInputElement, item: Option<Item>) -> Option<Item> {
let item = item?;
if source.get_attribute("data-source").as_deref() == Some("commodities") {
return Some(item);
let commodity = item.commodity?;
let items = items_at(&options_url("commodities")).await.ok()?;
items
.find(|o| o.id.as_deref() == Some(commodity.as_str()))
.cloned()
const PICK: &str = "data-pick";
fn unmark(input: &HtmlInputElement) -> Result<(), JsValue> {
input.remove_attribute(FILLED)?;
input.remove_attribute(COPIED)
/// A fill wrote `input`: it is no longer the copy of the split above.
fn marked_filled(input: &HtmlInputElement) -> Result<(), JsValue> {
input.remove_attribute(COPIED)?;
input.set_attribute(FILLED, "")
fn fillable(input: &HtmlInputElement) -> bool {
is_empty(input) || input.has_attribute(FILLED)
fn current(input: &HtmlInputElement, pick: u32) -> bool {
.get_attribute(PICK)
.is_some_and(|n| n == pick.to_string())
/// Fill the declared cells while they are empty or filled before, each fill
/// filling on in turn, unless `input` was picked again meanwhile: the earlier
/// reply must not overwrite the later pick's fills. A pick that yields no
/// fill clears the filled cells, and stops at a copied one a fill has not moved.
async fn fill(input: HtmlInputElement, item: Item, pick: u32) {
let Some(row) = row_of(&input) else {
return;
let (mut source, mut item) = (input.clone(), Some(item));
while let Some(cell) = source.get_attribute("data-fills") {
let fill = fill_of(&source, item).await;
let Some(target) = select_input(&row, &cell).filter(fillable) else {
if !current(&input, pick) {
match &fill {
Some(fill) => report(choose(&target, fill).and_then(|()| marked_filled(&target))),
None if target.has_attribute(COPIED) => return,
None => report(clear(&target)),
(source, item) = (target, fill);
/// Empty a filled select cell, as the user clearing it would.
fn clear(target: &HtmlInputElement) -> Result<(), JsValue> {
if is_empty(target) {
choose(target, &Item::default())?;
unmark(target)
struct Session {
input: HtmlInputElement,
url: String,
items: Rc<Vec<Item>>,
shown: Vec<usize>,
selected: usize,
impl Session {
fn html(&self) -> String {
let mut html = String::new();
for (position, &index) in self.shown.iter().enumerate() {
let item = &self.items[index];
let class = if position == self.selected {
" selected"
} else {
""
let context = item
.context()
.map(|path| format!(" <span class=\"optional\">{}</span>", html_escape(path)))
.unwrap_or_default();
html.push_str(&format!(
"<div class=\"autocomplete-item{class}\" {}=\"{position}\">{}{context}</div>",
AutocompleteAttr::Index.as_str(),
html_escape(&item.label),
));
html
/// What the popup's items were last built from.
struct Rendered {
impl Rendered {
fn of(session: &Session) -> Self {
Self {
items: Rc::clone(&session.items),
shown: session.shown.clone(),
fn matches(&self, session: &Session) -> bool {
Rc::ptr_eq(&self.items, &session.items) && self.shown == session.shown
struct Widget {
form: HtmlFormElement,
popup: HtmlElement,
session: RefCell<Option<Session>>,
/// The pointer position and the index in the options of the pressed item.
pressed: Cell<Option<(i32, i32, usize)>>,
rendered: RefCell<Option<Rendered>>,
/// Re-fits the open list when the visible area moves or shrinks.
refit: Closure<dyn FnMut(Event)>,
impl Widget {
fn open(self: &Rc<Self>, input: &HtmlInputElement) {
let Some(url) = endpoint(input) else {
self.close();
self.pressed.set(None);
let cached = CACHE.with(|cache| cache.borrow().get(&url).cloned());
let fetch = cached.is_none();
*self.session.borrow_mut() = Some(Session {
input: input.clone(),
url: url.clone(),
items: cached.unwrap_or_default(),
shown: Vec::new(),
selected: 0,
self.refresh();
if fetch {
wasm_bindgen_futures::spawn_local(Rc::clone(self).load(input.clone(), url));
async fn load(self: Rc<Self>, input: HtmlInputElement, url: String) {
Ok(items) => {
let mut session = self.session.borrow_mut();
if let Some(open) = session
.as_mut()
.filter(|s| s.url == url && s.input.is_same_node(Some(&input)))
{
open.items = items;
drop(session);
fn close(&self) {
*self.session.borrow_mut() = None;
*self.rendered.borrow_mut() = None;
self.popup.set_inner_html("");
let refit = self.refit.as_ref().unchecked_ref();
for (target, event) in place::viewport_events() {
report(target.remove_event_listener_with_callback(event, refit));
fn follow(&self) {
report(target.add_event_listener_with_callback(event, refit));
fn fit(&self) {
let input = self.session.borrow().as_ref().map(|s| s.input.clone());
if let Some(input) = input {
report(place::fit(&self.popup, &input));
fn refresh(&self) {
self.render();
self.fit();
fn render(&self) {
let mut guard = self.session.borrow_mut();
let Some(session) = guard.as_mut() else {
let query = session.input.value().to_lowercase();
session.shown = (0..session.items.len())
.filter(|&n| session.items[n].matches(&query))
.collect();
session.selected = session.selected.min(session.shown.len().saturating_sub(1));
self.build(session);
let parent = session.input.parent_element();
let placed = |p: &Element| {
self.popup
.parent_element()
.is_some_and(|c| c.is_same_node(Some(p)))
if let Some(parent) = parent.filter(|p| !placed(p)) {
report(parent.append_child(&self.popup).map(drop));
self.follow();
/// Rebuild the items only when what they list changed; otherwise just
/// move the selection, so nodes under a press stay put.
fn build(&self, session: &Session) {
let unchanged = self
.rendered
.borrow()
.as_ref()
.is_some_and(|rendered| rendered.matches(session));
match unchanged {
true => self.mark_selected(session.selected),
false => {
self.popup.set_inner_html(&session.html());
*self.rendered.borrow_mut() = Some(Rendered::of(session));
fn mark_selected(&self, selected: usize) {
let children = self.popup.children();
for n in 0..children.length() {
let Some(item) = children.item(n) else {
continue;
let on = usize::try_from(n).is_ok_and(|n| n == selected);
report(
item.class_list()
.toggle_with_force("selected", on)
.map(drop),
);
fn step(&self, forward: bool) {
if let Some(session) = self.session.borrow_mut().as_mut() {
let len = session.shown.len().max(1);
session.selected = if forward {
(session.selected + 1) % len
(session.selected + len - 1) % len
fn pick(self: &Rc<Self>, position: usize) {
let index = self
.session
.and_then(|s| s.shown.get(position).copied());
if let Some(index) = index {
self.pick_option(index);
fn pick_option(self: &Rc<Self>, index: usize) {
let chosen = self.session.borrow().as_ref().and_then(|s| {
let item = s
.shown
.contains(&index)
.then(|| s.items.get(index))??
.clone();
Some((s.input.clone(), item))
let Some((input, item)) = chosen else {
let pick = PICKS.get().wrapping_add(1);
PICKS.set(pick);
report(input.set_attribute(PICK, &pick.to_string()));
report(choose(&input, &item).and_then(|()| unmark(&input)));
if input.has_attribute("data-fills") {
wasm_bindgen_futures::spawn_local(fill(input, item, pick));
fn on_key(self: &Rc<Self>, event: &Event, input: &HtmlInputElement) {
let Some(key) = event.dyn_ref::<KeyboardEvent>().map(KeyboardEvent::key) else {
let choice = self
.filter(|s| !s.shown.is_empty())
.map(|s| s.selected);
match (key.as_str(), choice) {
("ArrowDown", Some(_)) => self.step(true),
("ArrowDown", None) => self.open(input),
("ArrowUp", Some(_)) => self.step(false),
("Enter", Some(selected)) => self.pick(selected),
("Escape", _) => self.close(),
_ => return,
event.prevent_default();
fn on_pointer(&self, kind: &str, event: &Event) {
let Some(mouse) = event.dyn_ref::<MouseEvent>() else {
match kind {
"pointerdown" if mouse.button() == 0 => {
let option = item_index_at(mouse).and_then(|position| {
self.session
.and_then(|s| s.shown.get(position).copied())
if let Some(index) = option {
self.pressed
.set(Some((mouse.client_x(), mouse.client_y(), index)));
"pointermove" => {
let moved = self.pressed.get().is_some_and(|(x, y, _)| {
(mouse.client_x() - x).abs() + (mouse.client_y() - y).abs() > SLOP
if moved {
_ => {}
fn suggest_input(event: &Event) -> Option<HtmlInputElement> {
let input: HtmlInputElement = event.target()?.dyn_into().ok()?;
(input.has_attribute("data-source") || input.has_attribute("data-suggest")).then_some(input)
type InputHandler = fn(&Rc<Widget>, &Event, &HtmlInputElement);
fn wire_form(widget: &Rc<Widget>) -> Result<(), JsValue> {
let on = |name: &str, handler: InputHandler| {
let widget = Rc::clone(widget);
listen(&widget.form.clone(), name, move |event| {
if let Some(input) = suggest_input(&event) {
handler(&widget, &event, &input);
})
on("focusin", |w, _, input| w.open(input))?;
on("input", |w, _, input| {
if !SILENT.get() {
report(unmark(input));
report(match_typed(input));
w.open(input);
})?;
on("focusout", |w, _, input| {
w.close();
if reference_of(input).is_some_and(|hidden| hidden.value().is_empty()) {
on("keydown", |w, event, input| w.on_key(event, input))
fn wire_popup(widget: &Rc<Widget>) -> Result<(), JsValue> {
for kind in ["pointerdown", "pointermove"] {
let popup = widget.popup.clone();
listen(&popup, kind, move |event| widget.on_pointer(kind, &event))?;
let up = Rc::clone(widget);
listen(&widget.popup, "pointerup", move |_| {
if let Some((_, _, index)) = up.pressed.take() {
up.pick_option(index);
let cancel = Rc::clone(widget);
listen(&widget.popup, "pointercancel", move |_| {
cancel.pressed.set(None)
/// Offer suggestions in the select and tag cells of a rendered form.
///
/// # Errors
/// Returns the DOM error if the popup or a listener cannot be set up.
pub fn init_suggest(form: &HtmlFormElement) -> Result<(), JsValue> {
if form.has_attribute(READY) {
form.set_attribute(READY, "")?;
for input in each_element(form, "input[data-source]")? {
let input: HtmlInputElement = input.dyn_into()?;
if let Some(hidden) = reference_of(&input) {
remember(&input, &hidden)?;
let document = form.owner_document().ok_or("no document")?;
let popup: HtmlElement = document.create_element("div")?.dyn_into()?;
popup.set_class_name("autocomplete-results");
let widget = Rc::new_cyclic(|widget: &Weak<Widget>| {
let widget = widget.clone();
Widget {
form: form.clone(),
popup,
session: RefCell::new(None),
pressed: Cell::new(None),
rendered: RefCell::new(None),
refit: Closure::new(move |_: Event| {
if let Some(widget) = widget.upgrade() {
widget.fit();
}),
wire_form(&widget)?;
wire_popup(&widget)