Skip to content

Instantly share code, notes, and snippets.

@schicks
Last active February 15, 2019 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schicks/05598894dd32f8f29f9a30b452224e3d to your computer and use it in GitHub Desktop.
Save schicks/05598894dd32f8f29f9a30b452224e3d to your computer and use it in GitHub Desktop.
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)
}
@jamesandersonwalsh
Copy link

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 to prism.on('searchKeyUp, someFunctionThatCallsMyDebouncedFunc) :)

@schicks
Copy link
Author

schicks commented Feb 13, 2019

@jimbo

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 to prism.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