searchbase is a lightweight and platform agnostic library that provides scaffolding to create search experiences powered by Elasticsearch.

Initialization

Copy
const searchBase = new SearchBase({
	index,
	url,
	credentials,
});

const searchComponent = searchBase.register('search-component', {
  dataField: ['name', 'description', 'name.raw', 'fullname', 'owner', 'topics'],
})

HTML

Copy
document.body.innerHTML = `
<div id="autocomplete" class="autocomplete">
	<input class="autocomplete-input" id="input" />
	<ul class="autocomplete-result-list"></ul>
</div>
<div id="selected"></div>
`;

Subscribe to state changes

Copy
searchComponent.subscribeToStateChanges(() => {
	// If we press enter key than autocomplete box is closed.
	// Handling a edge case.

	if (input.value) {
		input.blur();
		input.focus();
	}
});

Event listener

Copy
const input = document.getElementById('input');
input.addEventListener('change', searchComponent.onChange);

Using with autocomplete-js library

Copy
new Autocomplete('#autocomplete', {
	search: () => {
		return searchComponent.results.data;
	},
	getResultValue: result => result.name,
	renderResult: (result, props) => `
    <li ${props}>
      <div class="suggestion">
        <div>
          <img src=${result.avatar} alt=${result.name} />
        </div>
        <div>
        <h4>${result.name}</h4>
        <p>${result.description}</p>
        </div>
      </div>
    </li>
  `,
	onSubmit: result => {
		selectedSuggestion.innerHTML = `
    <h4>Suggestion Selected</h4>
    <div class="suggestion selected">
        <div>
          <img src=${result.avatar} alt=${result.name} />
        </div>
        <div>
          <h4>${result.name}</h4>
          <p>${result.stars} Stars</p>
        </div>
      </div>`;
	},
});

Demo