Skip to content

Instantly share code, notes, and snippets.

@dcooney
Last active December 10, 2021 18:04
Show Gist options
  • Save dcooney/a6c97f995bfad58ce572948b2675d3d9 to your computer and use it in GitHub Desktop.
Save dcooney/a6c97f995bfad58ce572948b2675d3d9 to your computer and use it in GitHub Desktop.
/* Setup autocomplete.js sources */
var sources = [];
var suggestion_template = wp.template( config[ 'tmpl_suggestion' ] );
var sources = [{
source: algolia.autocomplete.sources.hits( client.initIndex( config[ 'index_name' ] ), {
hitsPerPage: config[ 'max_suggestions' ],
attributesToSnippet: [
'content:10'
],
highlightPreTag: '__ais-highlight__',
highlightPostTag: '__/ais-highlight__'
} ),
templates: {
header: function () {
return wp.template( 'autocomplete-header' )( {
label: _.escape( config[ 'label' ] )
} );
},
suggestion: function ( hit ) {
if ( hit.escaped === true ) {
return suggestion_template( hit );
}
hit.escaped = true;
for ( var key in hit._highlightResult ) {
/* We do not deal with arrays. */
if ( typeof hit._highlightResult[ key ].value !== 'string' ) {
continue;
}
hit._highlightResult[ key ].value = _.escape( hit._highlightResult[ key ].value );
hit._highlightResult[ key ].value = hit._highlightResult[ key ].value.replace( /__ais-highlight__/g, '<em>' ).replace( /__\/ais-highlight__/g, '</em>' );
}
for ( var key in hit._snippetResult ) {
/* We do not deal with arrays. */
if ( typeof hit._snippetResult[ key ].value !== 'string' ) {
continue;
}
hit._snippetResult[ key ].value = _.escape( hit._snippetResult[ key ].value );
hit._snippetResult[ key ].value = hit._snippetResult[ key ].value.replace( /__ais-highlight__/g, '<em>' ).replace( /__\/ais-highlight__/g, '</em>' );
}
return suggestion_template( hit );
}
}
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment