Developers

Typeahead Autocomplete

Overview

The typeahead autocomplete component (formerly known as "autocompleter") predicts a list of title results based on the characters typed by the user on a search box.

This component must be linked to a search Store, since it is able to use the filters defined in the store to filter the suggestions.

Usage

This is how you create this component:

sdk.component('autocompleter', target: HTMLElement|String, options: Object);

Sample

By default, this component looks like this:

Options

The following options can be set in this component:

Name Type Default Description
baseUrl String "" URL to add to all of the result links
behaveAsPopover Boolean false If set to true, the typeahead autocomplete behaves as a popover. This means that the results container floats over the other page elements. This feature uses the popper library. Inbenta recommends that you set this option to true.
filters Boolean false Whether to filter the results using the store refinements
maxResults Number 5 Set the number of results you want to display.
modifiers Object bottom-start The popup modifiers. See popper.js placements docs for valid values. This option only works if behaveAsPopover parameter is set to true
placement String bottom-start The popup placement. See popper.js placements docs for valid values. This option only works if behaveAsPopover parameter is set to true
preload Boolean true Whether to preload the typeahead autocomplete data. If false is provided, the data is retrieved when the user starts typing.
settingsToShow Array [] Lets you add the attributes that appear in each typeahead autocomplete results (for example, if you add the URL, the URL appears in the typeahead autocomplete results).
Important: You must check the "Use for autocompleter" option in the content attribute configuration.
showViewAllButton Boolean true Defines whether the button view all appears.
Use this button to show all the results from the query within the Search box.
source String The URL to fetch the typeahead autocomplete data. Will default to endpoint autocompleter/data, if not provided.
target String "_blank" Use this to specify a target for the typeahead autocomplete content.
templates Object The templates to override the default render behavior. Caution: Be aware that using the templates option modifies any display behaviour of the typeahead autocomplete, such as different styles on the selected item, hovering styling, etc. See further information about templates here.
templates.footer String | () => String Footer template
templates.header String | () => String Header template
templates.item String | (Object) => String Template to use for each result. This template will receive an object containing the result. See Item Template below for additional details.
transformData Function (object) => object Function to transform the object passed to the view
viewAllButtonHref String # URL of the main results page. The query is set in the URL as a query parameter in order to load the results.

Properties

Property Description
suggestion Get the current active content
cursor Get the current suggestion position

Methods

The following methods can be used in this component:

Method Description
setQuery(query: String) Set the current query
setInputElement(input: HTMLElement) Listen to the given input element to automate certain actions:
- Listen to input changes and update the query.
- Show the typeahead autocomplete results when focused.
- Navigate the typeahead autocomplete results with the vertical arrow keys.
- Open a new tab when a result is selected and enter is pressed.
trackClick(content: Object, openURL: bool = true, target: String = "_blank") Track a click to the given content and open the URL
blur() Hides the typeahead autocomplete results, if they are showing
focus() Opens the typeahead autocomplete results, if it has results and they are hidden

Templates

See further information about templates here.

Item Template

The item template receives a typeahead autocomplete result, enhanced with additional parameters. It uses this format:

{
  id: 1,
  repr: "Example content",
  highlighted_repr: "<b>Example</b> content",
  URL: ["/contents/1"],
  PARAGRAPHS: ["Paragraph 1"],
  // Any other attributes marked with ‘Use for autocompleter’
  // Use this to render the absolute content URL.
  __url: "https://test.io/contents/1",
  // Render this into an HTML element to track click events.
  __clickable: "..."
}

Tracking

This component calls the API to trigger the autocompleter_click event when a user clicks (left or right-click) on a content. This is logged in atomic logs with the log type AUTOCOMPLETER, and in session logs with a CLICK_AUTOCOMPLETER data key.

Events

Events to listen on this component.

Name (data key) Description
autocompleter_click When a user clicks on a suggestion from the typeahead autocomplete, it triggers a autocompleter_click event.

Labels

This component uses the following labels:

Name Default Description
AUTOCOMPLETER_VIEW_ALL_BUTTON View all contents The text for the view all button

Examples

Basic usage

<div style="position: relative">
    <input type="text" id="query">
    <div id="autocompleter"></div>
</div>

<script>
    var autocompleter = sdk.component('autocompleter', '#autocompleter', {
        settingsToShow: ['description'],
        viewAllButtonHref: 'https://cars-ecommerce.com',
    });

    var input = document.querySelector('#query');
    autocompleter.setInputElement(input);
    input.addEventListener('keypress', function (event) {
      // Track clicks and open URLs.
      if (autocompleter.suggestion && event.keyCode === 13) {
        autocompleter.trackClick(autocompleter.suggestion);
      }
    });

    // This step is necessary to allow the typeahead autocomplete to fetch the data.
    var results = sdk.component('results', document.createElement('div'));
    results.linkTo(autocompleter);
</script>

Enable filtering

<div style="position: relative">
    <input type="text" id="query">
    <div id="autocompleter"></div>
</div>

<script>
    var autocompleter = sdk.component('autocompleter', '#autocompleter', {
        settingsToShow: ['description']
        viewAllButtonHref: 'https://cars-ecommerce.com',
        // Tell the autocompleter to filter the results
        // using the rules defined in the search store.
        filters: true,
    });

    var input = document.querySelector('#query');
    autocompleter.setInputElement(input);

    // This step is necessary to allow the typeahead autocomplete to fetch the data.
    var results = sdk.component('results', document.createElement('div'));
    results.linkTo(autocompleter);

    // Define some filters: display results with red or blue colors only.
    results.searchStore.addFacet('color', 'or');
    results.searchStore.addFacetRefinement('color', 'red');
    results.searchStore.addFacetRefinement('color', 'blue');
</script>
Item Template Example
<div style="position: relative">
  <input type="text" id="query">
  <div id="autocompleter"></div>
</div>

<script>
  var autocompleter = sdk.component('autocompleter', '#autocompleter', {
            templates: {
                item: '<a class="inbenta-search-autocompleter__link" href="{{ __url }}" {{{ __clickable }}}>'
                    + '<div class="inbenta-search-autocompleter__link__setting inbenta-search-autocompleter__link__setting-title">'
                    + '{{ repr }} ({{ id }})'
                    + '</div>'
                    + '</a>'
            }
        });
  var input = document.querySelector('#query');
  autocompleter.setInputElement(input);

  //Adding hovering effect to the template item
  input.addEventListener('keyup', function (e) {
      if(e.keyCode == 38 || e.keyCode == 40) {
          var items = document.getElementsByClassName("inbenta-search-autocompleter__link");
          [].forEach.call(items, function(el, i) {
              if (i == autocompleter.cursor) {
                  el.classList.add("inbenta-search-autocompleter__link--active");
              } else {
                  el.classList.remove("inbenta-search-autocompleter__link--active");
              }
          });
      }
  });
  // This step is necessary to allow the typeahead autocomplete to fetch the data.
  var results = sdk.component('results', document.createElement('div'));
  results.linkTo(autocompleter);
</script>
Using transformData
<div style="position: relative">
  <input type="text" id="query">
  <div id="autocompleter"></div>
</div>

<script>
    var autocompleter = sdk.component('autocompleter', '#autocompleter', {
        transformData: function (result) {
            result.highlighted_repr = result.highlighted_repr.toUpperCase();
            return result;
        },
    });
    var input = document.querySelector('#query');
    autocompleter.setInputElement(input);
    input.addEventListener('keypress', function (event) {
      // Track clicks and open URLs.
      if (autocompleter.suggestion && event.keyCode === 13) {
        autocompleter.trackClick(autocompleter.suggestion);
      }
    });

    // This step is necessary to allow the typeahead autocomplete to fetch the data.
    var results = sdk.component('results', document.createElement('div'));
    results.linkTo(autocompleter);
</script>