Created
November 7, 2022 20:58
-
-
Save GriffinSauce/ab7d5b667a8fc7ee7020a6b26377a6ce to your computer and use it in GitHub Desktop.
Algolia Destination Autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {autocomplete, getAlgoliaResults} = window['@algolia/autocomplete-js'] | |
const ALGOLIA_APP_ID = '<APP ID>' | |
const ALGOLIA_API_KEY = '<API KEY>' | |
const ALGOLIA_INDEX_NAME = '<INDEX NAME>' | |
const SUPPORTED_LOCALES = | |
'ar da de en es fi fr he hu id it ja ko ms nl no pl pt pt-BR ru sv th tr zh zh-CN zh-HK zh-TW' | |
const DEFAULT_LOCALE = 'en' | |
const SEARCH_URL = '<SEARCH BASE URL>' | |
const searchClient = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY) | |
const getLocale = () => { | |
if (!navigator.language) return 'en' | |
const locales = SUPPORTED_LOCALES.split(' ') | |
const preferredLocale = locales.find(locale => locale === navigator.language) | |
if (preferredLocale) return preferredLocale | |
const root = navigator.language.split('-') | |
const rootLocale = locales.find(locale => locale === root) | |
return rootLocale || DEFAULT_LOCALE | |
} | |
const locale = getLocale() | |
const getName = hit => { | |
const key = { | |
place: 'placeName', | |
hotel: 'hotelName' | |
}[hit.objectType] | |
return hit[key] && hit[key][locale] | |
} | |
const getParamName = hit => | |
({ | |
place: 'placeId', | |
hotel: 'hotelId' | |
}[hit.objectType]) | |
const getId = hit => hit.objectID.split(':')[1] | |
autocomplete({ | |
container: '#autocomplete', | |
placeholder: 'Your destination', | |
defaultActiveItemId: 0, | |
getSources({query}) { | |
return [ | |
{ | |
sourceId: 'destinations', | |
getItems() { | |
return getAlgoliaResults({ | |
searchClient, | |
queries: [ | |
{ | |
indexName: ALGOLIA_INDEX_NAME, | |
query, | |
params: { | |
hitsPerPage: 5, | |
filters: 'isDeleted != 1' | |
} | |
} | |
], | |
transformResponse: ({hits}) => hits[0].filter(getName) | |
}) | |
}, | |
getItemUrl({item}) { | |
return SEARCH_URL + '?' + getParamName(item) + '=' + getId(item) | |
}, | |
templates: { | |
item: ({item}) => getName(item) | |
} | |
} | |
] | |
}, | |
navigator: { | |
navigate({itemUrl}) { | |
const windowReference = window.open(itemUrl, '_blank', 'noopener') | |
if (windowReference) windowReference.focus() | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment