Giter VIP home page Giter VIP logo

autocomplete's Introduction

Autocomplete

A JavaScript library that lets you quickly build autocomplete experiences

Version MIT License

All you need to get started is:

  • A container to inject the experience into
  • Data to fill the autocomplete with
  • Any Virtual DOM solution (JavaScript, Preact, React, Vue, etc.)

The data that populates the autocomplete results are called sources. You can use whatever you want in your sources: a static set of searches terms, search results from an external source like an Algolia index, recent searches, and more.

By configuring just those two required parameters (container and getSources) you can have an interactive autocomplete experience. The library creates an input and provides the interactivity and accessibility attributes, but you're in full control of the DOM elements to output.

Screenshot

Documentation โ€ข API โ€ข Playground

Installation

The recommended way to get started is with the autocomplete-js package. It includes everything you need to render a JavaScript autocomplete experience.

Otherwise, you can install the autocomplete-core package if you want to build a renderer from scratch.

All Autocomplete packages are available on the npm registry.

yarn add @algolia/autocomplete-js
# or
npm install @algolia/autocomplete-js

If you don't use a package manager, you can use the HTML script element:

<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
<script>
  const { autocomplete } = window['@algolia/autocomplete-js'];
</script>

Usage

To get started, you need a container for your autocomplete to go in. If you don't have one already, you can insert one into your markup:

<div id="autocomplete"></div>

Then, insert your autocomplete into it by calling the autocomplete function and providing the container. It can be a CSS selector or an Element.

Make sure to provide a container (e.g., a div), not an input. Autocomplete generates a fully accessible search box for you.

import { autocomplete } from '@algolia/autocomplete-js';

autocomplete({
  container: '#autocomplete',
  // ...
});

Continue reading our Getting Started guide.

Documentation

The documentation offers a few ways to learn about the Autocomplete library:

  • Read the Core Concepts to learn more about underlying principles, like Sources and State.
  • Follow the Guides to understand how to build common UX patterns.
  • Refer to API reference for a comprehensive list of parameters and options.
  • Try out the Playground where you can fork a basic implementation and play around.

You can find more on the documentation.

Support

Packages

Package Description Documentation
autocomplete-js JavaScript package for Autocomplete Documentation
autocomplete-core JavaScript core primitives to build an autocomplete experience Documentation
autocomplete-plugin-recent-searches A plugin to add recent searches to Autocomplete Documentation
autocomplete-plugin-query-suggestions A plugin to add query suggestions to Autocomplete Documentation
autocomplete-plugin-algolia-insights A plugin to add Algolia Insights to Autocomplete Documentation
autocomplete-plugin-redirect-url A plugin to enable redirect URLs Documentation
autocomplete-plugin-tags A plugin to manage and display a list of tags in Autocomplete Documentation
autocomplete-preset-algolia Presets to use Algolia features with Autocomplete Documentation
autocomplete-theme-classic Classic theme for Autocomplete Documentation

Showcase

See the awesome experiences people built with Autocomplete:

DocSearch Algolia Documentation

Find more in our Showcase.

Sandboxes

Check out sandboxes using Autocomplete.

License

MIT

autocomplete's People

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  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

autocomplete's Issues

Make css classes from layout configurable?

For projects like docsearch or places I would like to be able to generate such markup:

<span class="algolia-places">
  <input class="ap-hint" />
  <input class="ap-input" />
  <span class="ap-dropdown-menu"></span>
</span>

etc..

Mostly because:

  • when talking about styling the project, we do not want/need to have the user understand places is based on algolia autocomplete. We are already wrapping it and hiding a bit of complexity.
  • when the user will have both a docsearch and a places autocompletion menu, it will be a lot easier to style them separately. Otherwise you would have to add weird classes/override selectors weight.

What do you think?

Get rid of the `data` API

The original typeahead.js code was using the $.data API to store the underlying datum, key and value values. Zepto and jQuery don't react the same way while storing objects (see #31).

We should find another way to save those 3 values, avoiding using the data attributes.

Selenium testing clicking results in the dropdown [question]

Autocomplete version: 0.16.1
Selenium: 2.50.1

I've been writing selenium test cases (in python) for our autocomplete integration. One of the tests I would like to write consists of clicking one of the results, and then verifying that the appropriate action occurs. Unfortunately, I discovered that selenium's click even causes the menu to disappear rather than trigger the appropriate click events. The browser under test is Firefox 45. If I insert an ipdb.set_trace prior to the click and actually click the result myself in the browser, the operation succeeds. I've set break points in the autocomplete.js, and it appears the appropriate click events aren't being triggered.

I realize this may just be an issue with selenium, and not something you guys can fix. I'm hoping that someone may have had prior experience with this and know of a solution. For now, I am going to write the test cases to use arrow keys and pressing enter, but that's not optimal.

Any advice is greatly appreciated!

-Kyle

The wrapper span should inherit the display property

It uses inline-block by default but that doesn't work if the original input is depending on table-cell like in:

<div class="input-group">
  <input type="text" class="form-control" />
  <span class="input-group-addon">
    <i class="fa fa-search"></i>
  </span>
</div>

Branding

It could be cool to have a cleaner way to do branding with static content.

For now we have to simulate a hit which is not so good. Will be very helpful for integrations

What do you think ?

Popular queries (aka Amazon-like) autocomplete section

The goal of this feature is to provide an easy way to build the Amazon-like suggestions:

iPho Search
  • iPhone in All departments
  • iPhone in Electronics
  • iPhone in Cell phones & accessories
  • iPhone 6
  • iPhone 6 Cases
  • iPhone 5
  • iPhone 5s
  • iPhone 5c

We basically search in a queries index to find the top searches matching the end-user query, then for the best result we search in the products index and display the departments using the faceting results.

This logic is pretty generic and could be implemented with:

var client = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey')
var products = client.newIndex("products");
var queries = client.newIndex("queries");

var popularQueries = AutoComplete.popularIn(queries, { hitsPerPage: 6 }, {
  source: 'query' /* OR function getNestedQuery(hit) { return hit.query; } */,
  index: products,
  facets: 'categories.lvl0'.
  maxValuesPerFacet: 3
});

$('#search-input').autocomplete({ hint: false }, [
  {
    source: popularQueries,
    templates: {
      suggestion: function(suggestion) {
        return suggestion._highlightResult.query.value + (suggestion.facet ? ' in <b>' + suggestion.facet.value + '</b>' : '');
      }
    }
  }
]);

Can't bind autocomplete on more than one input

The following code should let me bind the same autocomplete dropdown to two unrelated inputs. Unfortunatly, it does not seem to work, I have an empty dropdown being displayed under both inputs.

autocomplete('#search-input,#search-input2', ...)

image

Instant search

Until recently ๐Ÿ˜„ typeahead was out default autocompletion implementation for us. I think now that we have this repo, it could be very cool that it could be our instant search default implementation. I think this is THE the place where we could unify all our integration instant implementation.

I have several points where I am not sure how we can implement that in a generic customizable way. But I sure we will manage.

I am thinking of an instant implementation that will look like this :

$("#instant_search_input").instant({
  "container": "#instant_search_container",
  "content_template": "#instant_search_content",
  [...]
});

Obviously there is a lot to discuss

Do you think this could make sense ?

_.every helper function is broken

_.every within _onRender function doesn't actually work as one would expect: _.every along with isDataEmpty it always returns truthly on multiple datasets which then hides the entire element.

    _onRendered: function onRendered() {
        this.isEmpty = _.every(this.datasets, isDatasetEmpty);
        if (this.isEmpty) {
          this._hide();
        } else if (this.isOpen) {
          this._show();
        }

        this.trigger('datasetRendered');

        function isDatasetEmpty(dataset) {
          return dataset.isEmpty();
        }
      },

as of right now we dirty fixed the issue:

      every: function(thisArg, callbackfn) {
        return false;
      },

would you consider a pr?

Create an Algolia adapter

Create an Algolia adapter wrapping the following code:

function(q, cb) {
  index.search(q, { hitsPerPage: 5 }, function(error, content) {
    if (error) {
      cb([]);
      return;
    }
    cb(content.hits, content);
  });
}

RTL

Hey,

There's a problem when my layout is html="rtl":
The input's placeholder defaults to ltr - span.algolia-autocomplete has style="direction:ltr".

I gather this bit from the source code is responsible:

getLanguageDirection: function getLanguageDirection() {
  return (this.$input.css('direction') || 'ltr').toLowerCase();
}

If I specify style="direction:rtl!important" or dir="rtl", it properly aligns the placeholder, but it also stops auto-recognizing what direction the language that's typed in, so when I type in English and expect it to auto-jump to the left, it remains on the right side, resulting in the hint being unaligned with whatever's being typed in.

image

Any ideas how I can have the placeholder to be RTL to begin with, and keep the plugin auto-recognizing the typed in language direction?

(I need to support both LTR and RTL input, both when html dir="ltr" and html dir="rtl")

Align popup better so that it is not trimmed at the right edge of the screen

Sometimes the search box is located at the right edge of the screen, and the auto-completion popup, being aligned to the left edge of the input field, is displayed partially behind the right edge of the screen.

I'd suggest adjusting its horizontal position automatically when possible so that it is fully visible within the page boundaries.

The logic can be something like this: if page width is bigger than popup width + small extra margin, and with initially calculated horizontal position popup would not be entirely visible, calculate its left coordinate as "page width - small extra margin - popup width". The margin (about ~20px) is needed for aesthetic reasons, so that the popup doesn't touch the edge of the screen.

Highlighting

Hey guys,

In the original twitter typeahead there was the highlight option, with algolia's implementation we have to access suggestion._highlightResult..., but what if I'm using the plugin with my own ajax calls like I used to do with twitter typahead, instead of the Algolia service? Is there a highlighting solution I'm not aware of?

Custom template doesn't seem to work

I'm trying to use a custom template. In my source, I have

<script type="text/html" id="dropdown-test">
    <span class="aa-dropdown-menu{{#datasets}} aa-{{'with' or 'without'}}-{{name}}{{/datasets}}">
      {{#datasets}}
        <div class="aa-dataset-{{name}}">
          heyya
          <span class="aa-suggestions">
            {{#suggestions}}
              <div class="aa-suggestion">{{{suggestion}}}</div>
            {{/suggestions}}
            {{^suggestions}}
              {{{empty}}}
            {{/suggestions}}
          </span>
          {{{footer}}}
        </div>
      {{/datasets}}
    </span>
  </script>

and in my code I have

autocomplete('#seach-top-input', {
      hint: false,
      debug: true,
      templates: {
        dropdownMenu: '#dropdown-test'
      }

however my dropdown renders like this:

screen shot 2016-04-14 at 13 55 20

Seems to me like the template is found, but not rendered. Is that the case or am I mistaken?

autocomplete:opened โ€“ Triggered even if there is no result

Hi,

In my case the event autocomplete:opened is triggered even if I have no result. It's triggered when I write something in my input.

I need to triggered an event only when the dropdown autocomplete is visible.
There is something to do this or maybe there is a problem ?

Thx

No DOM change event triggered when the input changes

When we select a suggestion or autocomplete the input (tab key, right key), there's no change event triggered on the underlying DOM input nor on the container form if available.

I wonder if this is by design or a bug. Not having a change event makes it hard to use classical form/input on change and you must only rely on the autocomplete.js events.

What do you think?

Option to not close the dropdown when an item is selected

When an item is selected, the dropdown is automatically closed. I thought I could return false or event.preventDefault to stop this behavior, but it still happens.

My use case is as follows:

When a suggestion is clicked, window.location is updated to load the new resource. For some users on slower connections, the drop down disappears and there's potentially several seconds of delay before the new page opens. Meanwhile, users aren't certain anything is happening on the page. I'd like to customize the UI to indicate that the resource is loading. I feel one way to do this consists of keeping the dropdown visible, and updating the suggestion to include a spinner icon.

Thanks for the help

How to get the index of the selected item?

When a result is selected in the standalone autocomplete, I would like to know the index of the item that was selected. Does the standalone autocomplete provide an obvious way to get this information? If it's not obvious, any suggestions on how I might be able to get it?

Thanks!

openOnFocus

I saw the "openOnFocus" and expected the full suggestion list to be used, unfiltered, when openOnFocus is set to true. That's not the case.

In the Dropdown#open() function:

  open: function open() {
    if (!this.isOpen) {
      this.isOpen = true;

      if (!this.isEmpty) {
        this._show();
      }

      this.trigger('opened');
    }
  },

When the property this.isEmpty is true (empty query string) the _show() doesn't get called and the popup is in fact not opened but still closed. However, 'opened' is fired anyway and the property this.isOpen is set to true. Seems like this is not what you want because now this.isOpen is backwards and listeners have been notified that the popup is in fact open. Doh!

Be that as it may, we have a scenario where we show the customer some data, for example a list of recent searches, when the input is empty but focused. In other words, we show a default dataset to render when the query string is empty. How would you go about that scenario without hacking the library :)

Unable to use in production

Having autocomplete.js as a dependency fails when running npm install --production. The issue is appears to be caused by the npm-zepto package and its reliance on the coffee-script package as a devDependency.

โžœ  npm install --production

> [email protected] install /Users/Jon/test/node_modules/npm-zepto
> script/build

npm WARN [email protected] license should be a valid SPDX license expression

> [email protected] dist /Users/Jon/test/node_modules/npm-zepto/zepto
> coffee make dist

sh: coffee: command not found

npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/Cellar/node/5.3.0/bin/node" "/usr/local/bin/npm" "run-script" "dist"
npm ERR! node v5.3.0
npm ERR! npm  v3.5.2
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] dist: `coffee make dist`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] dist script 'coffee make dist'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the zepto package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     coffee make dist
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs zepto
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls zepto
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Jon/test/node_modules/npm-zepto/zepto/npm-debug.log
cat: zepto/dist/zepto.js: No such file or directory
npm WARN [email protected] requires a peer of angular@~1.4.2 but none was installed.
npm WARN [email protected] requires a peer of jquery@>= 1.7 but none was installed.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/Cellar/node/5.3.0/bin/node" "/usr/local/bin/npm" "install" "--production"
npm ERR! node v5.3.0
npm ERR! npm  v3.5.2
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `script/build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'script/build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the npm-zepto package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     script/build
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs npm-zepto
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls npm-zepto
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Jon/test/npm-debug.log

hinting seems busted, empty

$('#search_input').autocomplete({
hint: true
},
[
{
source: projects.ttAdapter({ hitsPerPage: 5 }),
name: 'contacts1',
...

Empty template in multi-indices queries.

I am building an autocomplete over multiple indices. What I would like is to display a message when there are no results in any datasets.

Actually we can set an empty template on each individual dataset, but not on the global level.

Is this possible? What would be the easiest way to achieve this?

Does this allow prefetch and remote search while working with mentions?

I am here because:

  1. I have implemented my own backend endpoint and used angular mentions plugin called mentio.js
  2. The suggestions was not fast enough for me.
  3. I found twitter typeahead which allows prefetch and remote dataset but it looks like it's no longer maintained.

My questions are:

  1. does this plugin allow both prefetch and remote?
  2. is there a way I can make this work with mentions in a textarea using delimiters such as @?

Ability to change the layout based on the matching datasets

Putting some CSS classes on the dropdown menu depending on if a dataset has some results would allow us to change the layout of the dropdown menu in some situations.

If we have 3 datasets:

  • products
  • categories
  • brands

and only the products dataset has results, it would set:

<span class="aa-dropdown-menu aa-with-products aa-without-categories aa-without-brands">
[...]
</span>

Built-in column layout

Maybe it could be cool to have an api to do the horizontal search.

So when you declare your typeahead you tell how many column you want. And then you have a parameter to say in which collumn you to push your dataset. It will be a lot easier to read an avoid to repeat the template every time. So that could handle 1 to n collumn (1 being the same as default typeahead layout).

If we push horizontal layout to client I think this does make even more sense.

What do you think ?

Switch between datasets

I'm working on tabbed search functionality that is very similar to this found on Discogs. My temporary solution is to destroy autocomplete after tab switch and then create another with new parameters, but this causes unattractive flash when it reappears.

Is there any way to switch between whole datasets without destroying auto-completion menu?

angular build broken?

I cannot make the angular playground or the angular build work.

And I am unsure but I think our Angular build still need jquery to be included to really work.

Attach the dropdown to the document

Very often, there are websites which are wrapping search inputs into containers containing the overflow: hidden rule, resulting in the following.
image

I think we should try to attach the dropdown to the document and position it with javascript.

This would also resolve the case where the input width is to small to provide a good user experience.
image

What will be tricky though is to detect if the dropdown has to align left/right and be displayed underneath or above the input.

To finish, this will also allow us to not suffer from the css of the search input container. Often in the header or the side menu, CSS rules are very intrusive...
image

Aria Roles - Screen Reader support

Adding aria roles where necessary would make search suggestions readable by screen readers.

I am not an expert in this field but @ova2 put a Pull Request together a long time ago at twitter/typeahead.js#995 that added some pretty good screen reader support, in case that can be of help.

I've tested with VoiceOver on MacOS: using up/down keys to navigate through suggestions doesn't read anything out, making search on our site virtually unusable for screen reader users.

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.