Last active
February 15, 2019 18:26
-
-
Save schicks/05598894dd32f8f29f9a30b452224e3d to your computer and use it in GitHub Desktop.
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
import axios from 'axios' | |
import config from '../../config' | |
const searchUrl = '/library/search?q=' | |
const libraryCoursesUrl = '/library/courses/' | |
const debounce = (func, wait, immediate) => { | |
let timeout | |
return (...args) => { | |
const later = () => { | |
timeout = null | |
if (!immediate) { | |
func(...args) | |
} | |
} | |
const callNow = immediate && !timeout | |
timeout && clearTimeout(timeout) | |
timeout = setTimeout(later, wait) | |
if (callNow) { | |
func(...args) | |
} | |
} | |
} | |
const updateAutoComplete = async (queryText) => { | |
if (!queryText) { | |
return | |
} | |
const response = await axios.get(`/search/api/v2/suggest?searchTerm=${encodeURIComponent(queryText)}`, {headers: {'X-Client-ID': config.searchClientId}}) | |
const suggestions = response.data.collection.map( | |
(suggestion) => { | |
if (suggestion.type === 'Course') { | |
return { | |
url: libraryCoursesUrl + suggestion.id, | |
id: suggestion.id, | |
text: suggestion.displayText | |
} | |
} else { | |
return { | |
url: searchUrl + suggestion.displayText, | |
id: suggestion.id, | |
text: suggestion.displayText | |
} | |
} | |
} | |
) | |
prism.updateSearchList(suggestions) | |
setSearchTypeAhead(queryText, suggestions) | |
// Update the typeahead | |
} | |
const debouncedUpdateAutoComplete = debounce(updateAutoComplete, 200) | |
const suggestionStartsWith = (suggestion, text) => { | |
return suggestion && suggestion.text.toLowerCase().indexOf(text.toLowerCase()) === 0 | |
} | |
const setSearchTypeAhead = (queryText, suggestions) => { | |
const typeAheadText = | |
queryText && suggestionStartsWith(suggestions[0], queryText) | |
? suggestions[0].text.toLowerCase() | |
: '' | |
prism.updateSearchTypeAhead(typeAheadText) | |
} | |
prism.on('searchKeyUp', (event, queryText) => { | |
debouncedUpdateAutoComplete(queryText) | |
} |
Hey there! Just wanted to give you the heads up that it looks like
debouncedUpdateAutoComplete
doesn't get called. It would be nice to see the whole workflow all the way toprism.on('searchKeyUp, someFunctionThatCallsMyDebouncedFunc)
:)
Good point, that call is not local to this function in our codebase so that had not occurred to me. I'll get an update for that in here soon.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there! Just wanted to give you the heads up that it looks like
debouncedUpdateAutoComplete
doesn't get called. It would be nice to see the whole workflow all the way toprism.on('searchKeyUp, someFunctionThatCallsMyDebouncedFunc)
:)