/* global instantsearch, algoliasearch, CONFIG, pjax */
document.addEventListener('DOMContentLoaded', () => {
const { indexName, appID, apiKey, hits } = CONFIG.algolia;
const search = instantsearch({
indexName,
searchClient : algoliasearch(appID, apiKey),
searchFunction: helper => {
if (document.querySelector('.search-input').value) {
helper.search();
}
}
});
if (typeof pjax === 'object') {
search.on('render', () => {
pjax.refresh(document.querySelector('.algolia-hits'));
});
}
// Registering Widgets
search.addWidgets([
instantsearch.widgets.configure({
hitsPerPage: hits.per_page || 10
}),
instantsearch.widgets.searchBox({
container : '.search-input-container',
placeholder : CONFIG.i18n.placeholder,
// Hide default icons of algolia search
showReset : false,
showSubmit : false,
showLoadingIndicator: false,
cssClasses : {
input: 'search-input'
}
}),
instantsearch.widgets.stats({
container: '.algolia-stats',
templates: {
text: data => {
const stats = CONFIG.i18n.hits_time
.replace('${hits}', data.nbHits)
.replace('${time}', data.processingTimeMS);
return `${stats}
`;
}
},
cssClasses: {
text: 'search-stats'
}
}),
instantsearch.widgets.hits({
container : '.algolia-hits',
escapeHTML: false,
templates : {
item: data => {
const { title, excerpt, excerptStrip, contentStripTruncate } = data._highlightResult;
let result = `${title.value}`;
const content = excerpt || excerptStrip || contentStripTruncate;
if (content && content.value) {
const div = document.createElement('div');
div.innerHTML = content.value;
result += ` ${div.textContent.substring(0, 100)}...