Skip to content

Instantly share code, notes, and snippets.

@georgejipa
Forked from owenconti/5ec339ed59c37.html
Created November 13, 2023 15:07
Show Gist options
  • Save georgejipa/c3fa5b2769528cf8f4ee8215ff33551d to your computer and use it in GitHub Desktop.
Save georgejipa/c3fa5b2769528cf8f4ee8215ff33551d to your computer and use it in GitHub Desktop.
Moving our search drop down from Algolia to Alpine.js
<div class="relative">
<div id="#search-box"></div>
<div id="#hits"></div>
</div>
// search.js
import algoliasearch from 'algoliasearch/lite';
import instantsearch from 'instantsearch.js';
import { searchBox, hits } from 'instantsearch.js/es/widgets';
import 'instantsearch.css/themes/reset.css';
const searchClient = algoliasearch(window.algoliaAppId, window.algoliaApiKey);
export default function () {
const search = instantsearch({
searchClient,
indexName: 'default',
searchFunction(helper) {
const container = document.querySelector('#hits');
container.style.display = helper.state.query === '' ? 'none' : '';
if (helper.state.query) {
helper.search();
}
}
});
search.addWidgets([
searchBox({
container: '#search-box',
placeholder: 'Search...',
}),
hits({
container: '#hits',
templates: {
empty: '<p class="p-2 m-0">No results</p>',
item: `<a href="{{ url }}" class="block px-2 py-3 bg-white text-sm text-left border-b border-gray-300 hover:bg-gray-200 hover:no-underline">
{{ title }}
</a>`
}
})
]);
search.start();
}
<div class="relative w-64" x-data="initSearch()">
<input
type="search"
x-model="query"
x-on:keyup="search()"
class="bg-white border border-gray-300 p-2 rounded w-full"
placeholder="Search..."
/>
<div x-show="query" class="absolute bg-white shadow rounded w-full max-w-full" style="display: none;">
<p x-show="loading" class="py-2 m-0">Loading</p>
<p x-show="!loading && !resultsHtml" class="py-2 m-0">No results.</p>
<div x-show="!loading && resultsHtml" x-html="resultsHtml"></div>
</div>
</div>
function initSearch() {
return {
query: '',
loading: true,
resultsHtml: null,
search: debounce(function() {
if (!this.query) {
return;
}
this.loading = true;
const host = `https://${window.algoliaAppId}-dsn.algolia.net`;
const url = `${host}/1/indexes/default?query=${encodeURIComponent(this.query)}`;
fetch(url, {
headers: {
'X-Algolia-Application-Id': window.algoliaAppId,
'X-Algolia-API-Key': window.algoliaApiKey,
}
})
.then((response) => response.json())
.then((data) => {
this.resultsHtml = null;
if (data.hits.length) {
this.resultsHtml = data.hits.map(({ url, title }) => {
return `<a
href="${url}"
class="block px-2 py-3 bg-white text-sm text-left border-b border-gray-300 hover:bg-gray-200 hover:no-underline"
>${title}</a>`;
}).join('');
}
this.loading = false;
});
}, 250)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment