Coder Social home page Coder Social logo

stimulus-autocomplete's Introduction

Stimulus Autocomplete controller

This is a tiny stimulus controller (1.5kB gzipped) to make a selection from a list of results fetched from the server. See it in action.

Demo

Installation

If you are using a js bundler with node_modules support (such as esbuild, rollup.js or Webpack) install the package from npm:

yarn add stimulus-autocomplete

If you're using importmap-rails, you'll need to pin stimulus-autocomplete:

./bin/importmap pin stimulus-autocomplete

Usage

Load your stimulus application as usual and the register the autocomplete controller with it:

import { Application } from '@hotwired/stimulus'
import { Autocomplete } from 'stimulus-autocomplete'

const application = Application.start()
application.register('autocomplete', Autocomplete)

To use the autocomplete, you need some markup as this:

<div data-controller="autocomplete" data-autocomplete-url-value="/birds/search" role="combobox">
  <input type="text" data-autocomplete-target="input"/>
  <input type="hidden" name="bird_id" data-autocomplete-target="hidden"/>
  <ul class="list-group" data-autocomplete-target="results"></ul>
</div>

The component makes a request to the data-autocomplete-url to fetch results for the contents of the input field. The server must answer with an html fragment:

<li class="list-group-item" role="option" data-autocomplete-value="1">Blackbird</li>
<li class="list-group-item" role="option" data-autocomplete-value="2">Bluebird</li>
<li class="list-group-item" role="option" data-autocomplete-value="3">Mockingbird</li>

Note: class list-group on <ul> and list-group-item on <li> is required to apply the same css as displayed in the gif above.

Items can be included that are not selectable, such as help text or delimiters using aria-disabled attribute:

<li role="option" aria-disabled="true">Start typing to search...</li>

If the controller has a hidden target, that field will be updated with the value of the selected option. Otherwise, the search text field will be updated.

The height of the result list can be limited with CSS, e.g.:

<ul class="list-group" data-autocomplete-target="results" style="max-height: 10rem; overflow-y: scroll;"></ul>

If you want a custom query parameter name, use the data-autocomplete-query-param-value attribute.

<div data-controller="autocomplete" data-autocomplete-url-value="/birds/search" data-autocomplete-query-param-value="name" ...>

The above will setup will fetch the results from /bird/search?name=SEARCH_TEXT.

Events

Events on the main element that registered the controller:

  • autocomplete.change fires when the users selects a new value from the autocomplete field. The event detail contains the value and textValue properties of the selected result.
  • loadstart fires before the autocomplete fetches the results from the server.
  • load fires when results have been successfully loaded.
  • error fires when there's an error fetching the results.
  • loadend fires when the request for results ends, successfully or not.
  • toggle fires when the results element is shown or hidden.

Events on the optional hidden input:

  • input and change dispatched to it when the users selects a new value from the autocomplete. This allows you to bind subsequent behavior directly to the <input type=hidden> element.

Optional parameters

  • autocomplete-min-length set the minimum number of characters required to make an autocomplete request.

    <div class="form-group" data-controller="autocomplete" data-autocomplete-min-length-value="3" data-autocomplete-url-value="/birds/search">
      ...
    </div>
  • autocomplete-submit-on-enter submit the form after the autocomplete selection via enter keypress.

     <div class="form-group" data-controller="autocomplete" data-autocomplete-submit-on-enter-value="true" data-autocomplete-url-value="/birds/search">
       ...
     </div>
  • autocomplete-selected-class Stimulus Autocomplete adds a default .active class to the currently selected result. You can use another class instead of .active with the this attribute.

     <div data-controller="autocomplete" data-autocomplete-url-value="/results-plain-text.html" data-autocomplete-selected-class="selected-result">
       ...
     </div>
  • autocomplete-label can be used to define the input label upon selection. That way your option elements can have more elaborate markup, i.e.:

    <li class="list-group-item" role="option" data-autocomplete-value="1" data-autocomplete-label="Blackbird">
      <p>Blackbird</p>
      <p class="text-muted"><small>That's also the name of an airplane</small></p>
    </li>
  • autocomplete-delay-value how long to wait since the user stops typing until the autocomplete makes a request to the server. Defaults to 300 (ms).

      <div data-controller="autocomplete" data-autocomplete-url-value="/results-plain-text.html" data-autocomplete-delay-value="500">
        ...
      </div>

Optional HTML configuration

  • If the <input> target has an autofocus attribute then the input will be given focus immediately so the user can start typing. This is useful if the <input> is dynamically added/morphed into the DOM (say by a "edit" button) and the user expects to start typing immediately.

Extension points

URL building

The autcomplete default behaviour is to add a q querystring parameter to the the base data-autocomplete-url. If you need a different format, you can override the controllers buildURL method.

import { Application } from '@hotwired/stimulus'
import { Autocomplete } from 'stimulus-autocomplete'

const application = Application.start()

class CustomAutocomplete extends Autocomplete {
  buildURL(query) {
    return `${new URL(this.urlValue, window.location.href).toString()}/${query}`
  }
}

application.register('autocomplete', CustomAutocomplete)

Examples

Credits

Heavily inspired on github's autocomplete element.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/afcapel/stimulus-autocomplete. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

Release a new version

To release a new version follow these steps:

  1. Update the version number in package.json. Try to follow semantic versioning guidelines as much as possible.

  2. Publish the package to npmjs.com with yarn run release

License

This package is available as open source under the terms of the MIT License.

stimulus-autocomplete's People

Contributors

abhinaykumar avatar afcapel avatar alexandre-t avatar dependabot[bot] avatar drnic avatar duffyjp avatar glaszig avatar intrepidd avatar jasonlor avatar miharekar avatar phylor avatar pruzicka avatar pythonandchips avatar seb-jean avatar thebluber avatar thomasvanholder avatar weaverryan avatar x4d3 avatar yourivdlans avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stimulus-autocomplete's Issues

suggestion: center selected item (scroll)

Currently, if there are more autocomplete menu items than fit in the visible area, the "down" key even will happily move to items that are not visible. Perhaps we could scroll the menu so that selected items are always visible?

demo

Clean hidden field id when input text get empty

Hi. I realize that when the input text is cleared, the input hidden doesn't have its value cleared as well. It keeps the value ID of old search selected.

Is there a way to clear hidden field after cleaning the input text?

Use keyboard navigation to navigate results

Currently, the input element captures blur and closes the results when focus leaves the element. It seems like it would be desirable in cases where someone is using a screenreader or keyboard navigation that, if focus leaves the textbox but is transferred to one of the elements in the result list, that list of results will remain open until focus has entirely transitioned out of the autocomplete results.

If my interpretation is correct here, I'm happy to do the work for a PR.

example app - Can't resolve 'stimulus'

@afcapel I thought I'd add some bonus examples; but I'm struggling to get the example app running -- and perhaps there's a gap in my nodejs setup or something you do to get the example app running?

yarn run build # fails with or without dist/ folder
cd examples
rm -rf node_modules # just to make sure
yarn
npm run start

And amongst the output is the following error:

> [email protected] start /Users/drnic/workspace/stimulus-autocomplete/examples
> webpack-dev-server --config webpack.dev.js --mode development
...

ERROR in ../src/autocomplete.mjs
Module not found: Error: Can't resolve 'stimulus' in '/Users/drnic/workspace/stimulus-autocomplete/src'
 @ ../src/autocomplete.mjs 31:0-38 338:2-12
 @ ./app.js

Any protips or things you can think of for what might be missing from my environment?

$ node -v
v14.15.3
$ npm -v
6.14.9

Is there a way to catch the hidden field change from another controller

I'm kinda new to Stimulus but I've managed to change some of my jQuery stuff over.

This is very similar to what I was using in jQuery. My problem is after the hidden field is populated with whatever was selected in the ul targets, how can I catch that change?

One of my uses was to duplicate a bank transaction based on description. You do the autocomplete search and once a transaction is selected, I'd turn on a button (show) to duplicate the transaction.

I can put a button next to the input field, but it's of no use unless the hidden field is populated. Guess I can fire off an alert saying nothing selected, but that does not feel right.

I tried with another controller to look for the ul to be clicked or the hidden field to be changed and I get no joy. Below is my html/slim f

h5 Other Players (or use Search field)
div[data-controller="autocomplete" data-autocomplete-url="/players/search"]
  input[type="text" data-target="autocomplete.input" placeholder="Player Search"]
  input[type="hidden" name="player_id" data-target="autocomplete.hidden callerActions.hidden" data-action="callerActions#showSearched"]
  .w3-right.my-btn.w3-blue[data-action="click->callerActions#addSearched" data-playerid=""] Add Searched
  ul.w3-ul.w3-border[data-target="autocomplete.results"]

As a side note, this package is almost 2 year old and I see little action on the Stimulus Discourse - how accepted is Stimulus? I'm becoming comfortable with it but is it going to be around for a while?

Error using skypack ESM module with stimulus-rails

Hi,

I've used stimulus in the past but am new using stimulus-rails with ESM modules from skypack.dev.

I'm getting the following error when adding stimulus-autocomplete to my project:

Failed to autoload controller: autocomplete Error: Unable to resolve specifier 'autocomplete_controller' from http://localhost:3000/assets/stimulus/loaders/autoloader-049…957166e3d004afc916a4c399f9e164045c348d56d6fb01db375ef8acf.js
    throwUnresolved http://localhost:3000/assets/stimulus/libraries/es-module-shims-108c9f5a06bb8dcc1fd6ffac571d699e3bf8d76ba3f09e205a96b98063d61441.js:472
    resolve http://localhost:3000/assets/stimulus/libraries/es-module-shims-108c9f5a06bb8dcc1fd6ffac571d699e3bf8d76ba3f09e205a96b98063d61441.js:468
    importShim$1 http://localhost:3000/assets/stimulus/libraries/es-module-shims-108c9f5a06bb8dcc1fd6ffac571d699e3bf8d76ba3f09e205a96b98063d61441.js:267
    loadController http://localhost:3000/assets/stimulus/loaders/autoloader-049dda1957166e3d004afc916a4c399f9e164045c348d56d6fb01db375ef8acf.js:20
    autoloadControllersWithin http://localhost:3000/assets/stimulus/loaders/autoloader-049dda1957166e3d004afc916a4c399f9e164045c348d56d6fb01db375ef8acf.js:8
    <anonymous> http://localhost:3000/assets/stimulus/loaders/autoloader-049dda1957166e3d004afc916a4c399f9e164045c348d56d6fb01db375ef8acf.js:52

My index.js:

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

import { Autocomplete } from 'https://cdn.skypack.dev/stimulus-autocomplete';

const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))

application.register('autocomplete', Autocomplete)

And my HTML view:

<div data-controller="autocomplete" data-autocomplete-url="/birds/search">
  <input type="text" data-autocomplete-target="input"/>
  <input type="hidden" name="bird_id" data-autocomplete-target="hidden"/>
  <ul class="list-group" data-autocomplete-target="results"></ul>
</div>

Could this be because the ES Module Entrypoint is missing for this package? https://www.skypack.dev/view/stimulus-autocomplete

Thank you!

Error: Missing target element "autocomplete.results"

Hi,

using this DOM:

<div data-autocomplete-url-value="tags/search" data-controller="autocomplete">
    <input class="form-control mr-sm-2" data-autocomplete-target="input" placeholder="Tags" type="text">
    <input data-autocomplete-target="hidden" name="q[tags_name_in]" type="hidden">
    <ul class="list-group" data-autocomplete-target="results"></ul>
</div>

I am getting this error on page load:

application.js:250 Error connecting controller

Error: Missing target element "autocomplete.results"
    at Controller.get (target_properties.js:15)
    at Controller.e.connect (stimulus-autocomplete.js:18)
    at Context.connect (context.js:23)
    at Module.connectContextForScope (module.js:39)
    at Router.scopeConnected (router.js:100)
    at ScopeObserver.elementMatchedValue (scope_observer.js:55)
    at ValueListObserver.tokenMatched (value_list_observer.js:54)
    at TokenListObserver.tokenMatched (token_list_observer.js:82)
    at token_list_observer.js:69
    at Array.forEach (<anonymous>)

Everything seems to be there and this is almost a copy&paste from the original example. Any idea what is going on?

Prefilled form

I’m trying to use the autocomplete to get list of items lproducts to prefill a form. For example i serach for product 1. I want to get his id name price to prefill the form.

is there a way to achieve this with the component ?

How to display 'not found' plus suggestion

Hi,
what would be the best way

  • search for entry
  • and if entry is not found display line with 'entry not found, if you want to create it click here'
  • so it could include link with suggestion
    Thanks

Petr

Can't resolve 'stimulus-autocomplete'

Upgrading to 3.0.0-rc2 gives me this error:

Module not found: Error: Can't resolve 'stimulus-autocomplete' in '/Users/jaredmoody/code/redacted'
  resolve 'stimulus-autocomplete' in '/Users/jaredmoody/code/app.jetbuilt.com/app/javascript/controllers/projects'
  Parsed request is a module

I'm not the most familiar with JS modules, but suspect 455f36a broke something here.

Stimulus 2.0.0 compatibility

Hello!

Stimulus 2.0.0 changed the default behavior of the data-target attribute, and now trigger warnings in the JS Console to surface the deprecation.

However, after updating to the 2.0.0 version, pages that use this package throw this warning:

Uncaught (in promise) TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at ValueObserver.get (value_observer.js:73)
    at ValueObserver.invokeChangedCallbacksForDefaultValues (value_observer.js:48)
    at new ValueObserver (value_observer.js:11)
    at new Context (context.js:12)
    at Module.fetchContextForScope (module.js:55)
    at Module.connectContextForScope (module.js:37)
    at Router.scopeConnected (router.js:114)
    at ScopeObserver.elementMatchedValue (scope_observer.js:54)
    at ValueListObserver.tokenMatched (value_list_observer.js:54)

I'm not sure how to resolve this yet, but wanted to log the finding in case someone else has. I've confirmed reverting to Stimulus 1.1.1 returns the app to previous behavior.

result window css is broken

Hello , when search is made, result windows is not looking like your gif, there is no active blue color when mouse moves and window is not closing it self after choosing. Could you check if i added wrong class or something.

result

<% @names.each.with_index do |name, index| %>
<li role="option" class="list-group-item"  data-autocomplete-value=<%= name.id %> > <%= name.name %> </li>
<% end %>

form field

        <input type="text" data-target="autocomplete.input"/>
    <%= f.hidden_field :company_id, value: current_user.company_id %>
    <ul data-target="autocomplete.results" class="list-group"></ul>
    <%= f.hidden_field :category_id, data: {:target => "autocomplete.hidden"} %>
  </div>


Thank you.

Error Unexpected token after import stimulus-autocomplete

Hello,

I have this error once I import stimulus-autocomplete :

Module parse failed: Unexpected token (7:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| export default class Autocomplete extends Controller {
>   static targets = ["input", "hidden", "results"]
|   static classes = ["selected"]
|   static values = {

thank you for your help

[docs] Mention that selected item will have "active" class set

Perhaps because the example app uses bootstrap css, it wasn't obvious that my own CSS needed to explicitly provide an li.active class to visualise the currently selected item via keys up/down. Might be worth adding to readme.

If you're ever inspired, might also be worth replacing the implicit magic of bootstrap with some explicit CSS to demonstrate which classes are important for non-bootstrap users.

How to fetch data on focus?

Hey! Nice lib, thanks for the great work!
I am struggling to open prompt with results as soon, as user focused input field.
I tried to add

autocomplete-min-length-value="0"

but this does not help.

How can I fetch data as soon, as user sets focus into input?

Make the query paramater name `q` customizable

It'd be nice if the query paramater name q was customizable via the stimulus paramater/value HTML attribute like

<div data-controller="autocomplete"
    data-autocomplete-url-value="/birds/search"
    data-autocomplete-query-param="name_or_desc_cont"
    .... />

This will make it really easy to integrate with Rails search gems like Ransack.

[RFC] Support for useTransition with consistent "toggle" event (or new open/close events)

Hi!

FYI - I would be fully open to submitting a PR for this feature :).

I'd like to integrate the useTransition() mixin from stimulus-use - https://stimulus-use.github.io/stimulus-use/#/use-transition - to get a nice fade in/fade out effect. To do that, I need an event from stimulus-autocomplete that allows me to know when the results target is being shown/hidden.

stimulus-autocomplete does have a toggle event, but it's only used in the open() and close() methods: no toggle event is triggered as a result of the AJAX call or if the results close due to a "blur" in the input.

I believe we can support this fairly easily:

  1. Dispatch a new open event in ALL cases when the results target changes from "closed" to "opened"
  2. Similarly, dispatch a close event in ALL cases when the results target changes from "opened" to "closed"
  3. A new option/value - useHiddenAttribute - that defaults to true. If this is set to false, then the library will not add/remove the this.element.hidden. This will allow users to apply their own logic.

With this setup (and I would verify this) I believe you could use the built-in controller from stimulus-autocomplete and the built-in transition controller from stimulus-use entirely in HTML to add fading out to this library, without custom JavaScript.

Any issues with this proposal?

Cheers and thanks for the wonderful library!

Replace .bind with ES6 => operator

I believe we can remove lines like:

    this.onResultsClick = this.onResultsClick.bind(this)

By re-defining the functions with ES6 syntax => operator:

onResultsClick = event => {
...
}

Relates to #20

Setting X-Requested-With header in V3

I upgraded to Symfony 6, and in the process had to upgrade to stimulus-autocomplete:^3.0.0-rc.6.

The behavior I'm observing is that stimulus-autocomplete is doing an Ajax call, but it is not setting the X-Requested-With header to XMLHttpRequest.

In stimulus-autocomplete:^2.0 this worked perfectly.

Multiselection

Hi,

Would you consider a multi-selection PR where a user selects multiple values from the dropdown;

Release Tags on GitHub?

Hi!

I noticed that new releases are being published to npm, but not on GitHub. That is, of course, totally possible and allowed :). But it's a little less traditional, and I got confused at first when checking for new releases (as I check GitHub first). Would you be willing to publish tags to GitHub as well? It's minor - but would be appreciated.

Cheers!

Failed to resolve module specifier "stimulus-autocomplete"

Ruby 3.0.3
Rails 7.0.0.alpha2

Hello

After following the instructions to install and usage, I launch the server and I received this error: Uncaught TypeError: Failed to resolve module specifier "stimulus-autocomplete". Relative references must start with either "/", "./", or "../".

# app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"
import { Autocomplete } from "stimulus-autocomplete"
# and tried import { Autocomplete } from 'stimulus-autocomplete/src/autocomplete'

const application = Application.start()
application.register('autocomplete', Autocomplete)

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

Example doesn't work

Hi there! I'm trying to use your library, and am having trouble adapting it to a Rails stack (without bootstrap).

The example page refers to a file that isn't found in the repo:

<script src="../assets/app.js"></script>

which results in a 404.

Is there another example I can refer to? Looking forward to using this more!

Getting stimulus error on pages using stimulus autocomplete

I took the bait and upgraded to stimulus 2.0 everything seems to be working except for any autocomplete pages,

I think I initially had 2 errors. Upgraded to version 1.4.2 from 1.4.0 and down to 1

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'Object.keys(valueDescriptorMap)')

I saw some of the updates for version 2 didn't see anything where it worked or didn't work with stimulus 2.0

On another page where I have not updated the targets I got a different error

TypeError: undefined is not an object (evaluating 'Object.keys(valueDescriptorMap)')

Okay, maybe this is a duplicate that was supposedly fixed, but it still not working for me,

The node module is still showing a dependency for stimulus 1.1.0 after a yarn upgrade. Opps missed the >= 1.1.0 <3

I guess my question, is this version (1.4,2) supposed to work with stimulus 2.0??

A more detailed error from console. I get this error on any page with an autocomplete controller

[Error] TypeError: undefined is not an object (evaluating 'Object.keys(valueDescriptorMap)')
  keys (application-9994f39afd28c71b29c6.js:7241)
  get (application-9994f39afd28c71b29c6.js:7241)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7216)
  ValueObserver (application-9994f39afd28c71b29c6.js:7179)
  Context (application-9994f39afd28c71b29c6.js:5851:92)
  (anonymous function) (application-9994f39afd28c71b29c6.js:6539)
  (anonymous function) (application-9994f39afd28c71b29c6.js:6521)
  (anonymous function) (application-9994f39afd28c71b29c6.js:6680)
  (anonymous function) (application-9994f39afd28c71b29c6.js:6882)
  (anonymous function) (application-9994f39afd28c71b29c6.js:8351)
  (anonymous function) (application-9994f39afd28c71b29c6.js:8223)
  forEach
  (anonymous function) (application-9994f39afd28c71b29c6.js:8209)
  (anonymous function) (application-9994f39afd28c71b29c6.js:8190)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7750)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7933)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7908)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7887)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7852)
  (anonymous function) (application-9994f39afd28c71b29c6.js:7842)

which points to file import { StringMapObserver } from "@stimulus/mutation-observers";

Document how to cut npm releases

@afcapel if you can recall, could you document how you would build + cut an npm release?

I know I had some issues #22 with some of the commands last year when I gave them a try; so perhaps I was doing something wrong/using some unused commands.

No license provided

Hello!

There is no license in the repo, so this library should be treated as a proprietary code. Could you specify the license in repository, please?

Send additional parameter to search relation

I have two autocomplete fields. One selects a client, the other selects a client's products. Therefore the second autocomplete field depends on the value of the first autocomplete field. I need to send an additional parameter to the backend so I can run a query based off the id of the first autocomplete.

@products = Product.where('product_code like ?', "%#{params[:q]}%").where('client_id = ?,params[:client_id]

Is this possible?

Additional attribute

Hi,
would it be somehow possible to gather additional attribute from autocompleted model? Now with
<input type="hidden" name="bird_id" data-autocomplete-target="hidden"/> I could add bird_id to the form. I could use another attribute that would be pulled from Birds model, let's say I would have "color: 'blue'" or "night_bird:true" in the model. I would use it in the form to style/disable another fields.
Thank you

Petr R.

Additional event on select

Hey!

That would be nice to have an event when select occurs, so one can dynamically update input value. That would allow to follow the same logic as Google and others use when suggestions are works as query prefix rather than final query.

example failed to build/run

$ git clone https://github.com/afcapel/stimulus-autocomplete
$ cd stimulus-autocomplete/examples
$ yarn
yarn install v1.22.10
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "@babel/preset-env > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
...
warning " > [email protected]" has unmet peer dependency "@babel/core@^7.0.0".
[4/4] 🔨  Building fresh packages...
✨  Done in 17.89s.

$ yarn run start
yarn run v1.22.10
$ webpack-dev-server --config webpack.dev.js --mode development
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /Users/drnic/workspace/prior-study-credit/stimulus-autocomplete/examples
✖ 「wdm」: Hash: 762091d8c8249b426097
Version: webpack 4.39.1
Time: 525ms
Built at: 13/11/2020 8:45:17 am
       Asset      Size  Chunks             Chunk Names
  index.html  6.09 KiB          [emitted]
    index.js  8.81 KiB   index  [emitted]  index
results.html  6.04 KiB          [emitted]
Entrypoint index = index.js
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./app.js 40 bytes {index} [built]
[./app.js] 1.96 KiB {index} [not cacheable] [built] [failed] [1 error]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 1.96 KiB {index} [not cacheable] [built] [failed] [1 error]

ERROR in ./app.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
...
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
...

Running yarn upgrade didn't resolve this issue.

How do you catch the autocomplete.change event?

I'm trying to catch the autocomplete.change custom event, but I don't know how to do it.

autocomplete.change fires when the users selects a new value from the autocomplete field. The event detail contains the value and textValue properties of the selected result.

new CustomEvent("autocomplete.change", {

Nothing happen when I tried:

export default class extends Controller {
    change(event) {
        console.log(event);
    }
}

During compilation, I have a syntax error on the dot, when I tried:

export default class extends Controller {
    autocomplete.change(event) {
        console.log(event);
    }
}

Nothing happen when I tried:

export default class extends Controller {
    'autocomplete.change'(event) {
        console.log(event); 
    }
}

Request for additional maintainer

I'm excited for the activity in this project. I'm not currently using autocomplete in my latest projects nor am I ready to upgrade to stimulus 3 just yet.

Is there someone who would like to merge branches, cut releases, and perhaps as a bonus can maintain releases for Stimulus v2 + Stimulus v3 for a while until the community has long migrated to Stimulus 3?

error event doesn't fire on 400+ response

Hello and thank you for your work,

Can you tell me when the "error" event is supposed to fire ?

For me, a 400 or 500 http response doesn't fire the error event. Maybe it is due to the use of fetch...

Thx

Module parse failed: Unexpected token error

Unfortunately I do get the following error message from webpacker with the latest rc5 version:

Uncaught Error: Module parse failed: Unexpected token (7:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
|
| export default class Autocomplete extends Controller {

static targets = ["input", "hidden", "results"]
| static classes = ["selected"]
| static values = {

Does anyone know how to solve this? Thx in advance!

Any thought about creating a branch to support rails 7, stimulus 3.0?

Looks like there hasn't been much activity on autocomplete.

I tried a demo app with rails 7.0.0.alpha2 with both stimulus-flatpickr and stimulus-autocomplete. I did find a branch on flatpickr that supports stimulus 3.0 and rails 7. Think all they had to do is get stimulus from @hotwired/stimulus instead of stimulus.

I couldn't get the current version to work in the demo.

If not, I'm toying with a stimulus controller that does about 90% of what stimulus-autocomple does in about 40 line of code.

Auto-select/highlight the first result on "data load ended"

Hey, many thanks for this "simple" and effective stimulus controller.

I've been replacing ReactSelect throughout my apps with it.

However, there's still some UX that's bugging me. I'd like to have the first result automatically highlighted so that the user can press enter and select it. A good example is GitHub's search box in the navbar here.

Any ideas what's the easiest way to achieve that?

Thanks,
Stan

understanding the binding

Hi there

Thank you for your code. I have a question re: the following lines (reproduced below):

    // autocomplete.mjs
    this.onInputChange = debounce(this.onInputChange.bind(this), 300)
    this.onResultsClick = this.onResultsClick.bind(this)
    this.onResultsMouseDown = this.onResultsMouseDown.bind(this)
    this.onInputBlur = this.onInputBlur.bind(this)
    this.onKeydown = this.onKeydown.bind(this)

The onResultsClick methods etc. all refer to this within the method - which will refer to the current controller anyway, won't it? If that's the case then won't the above code be superfluous? Was seeking a pointer.

chrs

Ben

publish latest version?

Hi we'd like to use the features that expose the toggle event - but the latest version on npm 2.0.1-phylor-6095f2a9 does not call #open or #close in #fetchResults so we're unable to piggyback off that logic.

Happy to help publish if you can explain what I need to do?

Provide default styles

All the examples use css from bootstrap v4 to style the results box. While there's little to it, it'd be nicer if we provided a minimal css so the autocomplete is easier to use for folks that don't use bootstrap.

An example using Tailwind would be nice too.

If we implement multi selection (as per #53 (comment)), the styling would be more involved and having a foundation in place would be useful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.