Is there any implementation / tutorial for text field autocomplete in Rails using Hotwire?
I don’t want a jQuery solution, want one with StimulusJS. Or if someone can recommend some js package that can be implemented with import map, that would fine too.
Sure. Could you say a little more about what you mean by autocomplete? I have seen a couple different approaches, both of which could reasonably be considered “autocomplete”.
As you type, a list of possible results appear below the input, and if you click one of them, the text box updates with your choice, and the suggestion list disappears.
As you type, the input gets light grey text to the right (in LTR input mode) with what the server thinks you’re trying to spell. As you continue typing, the suggestion updates in the field. If you click or tab, the word completes in the field and the suggestion is gone.
As you type, a list of possible results appear below the input, and if you click one of them, the text box updates with your choice, and the suggestion list disappears.
The latest DriftingRuby (YouTube) video shows how to use the HotwireCombobox gem for this kind of thing (not precisely what you are looking for, but if you squint…)
I’ve also just coded this sort of thing from scratch before, although I can’t find a modern enough example to copy and paste for you. It’s really quite a simple thing to build using either TurboStream responses (more modern) or UJS (creaky-old). The canonical result your server should respond with is a UL containing LIs with their ID set to the (prefixed) record ID and a string containing the human-readable label. In a Stimulus setting, you would probably also add a data-target to each LI to make it all automatic. As you can see in the video, the Rails controller side is just going to do a fairly liberal SQL “infix LIKE” query to find results.
This pattern has been well-solved in Rails since the version 2 days, when we all used Prototype.js and ScriptAculoUs Autocomplete, and liked it!
I just finished rewriting one in Stimulus and Turbo that had originally been hand-rolled in jQuery, but i must say things can get pretty complex, depending on how smart you need your autocompleter to be.
In ours, one of the autocompleter controllers returns a big primer that tries to match the user input with any word in the title of a record. It shows the first ten results (of maybe 1000) and then refines the ten results from the same primer as the user types more letters.
It’s a bear and i haven’t even refactored it to pass the record ids yet. It works entirely on string matching right now.
Thoughtbot has a decent walkthrough of what they call “typeahead search” using hotwire/turbo/stimulus, which I think is essentially what you’re looking for: