This repository has been archived by the owner on May 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openwhyd-search.js
79 lines (65 loc) · 2.07 KB
/
openwhyd-search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var username = 'adrien'
var callbackFctName = 'onOpenwhydData'
var profileUrl = 'https://openwhyd.org/' + username +'?limit=99999&callback=' + callbackFctName
// DATA MODEL
var allTracks = []
function indexTracks(tracks) {
console.log('loaded', tracks.length, 'tracks')
allTracks = tracks.map((tr) => ({
...tr,
_name: [tr.name, tr.text].join(" ").toLowerCase() // pre-compute and store normalized post name & description (for faster search)
}))
}
function search(query) {
var results = []
query = query.trim().toLowerCase() // normalize search query
var terms = !query ? [] : query.split(' ')
console.log('query terms:', terms)
if (!terms.length) {
return []
}
return terms.reduce(
// exclude results which name do not contain this term
(results, term) => results.filter((res) => res._name.indexOf(term) !== -1),
allTracks
)
}
// UI INIT
var ui = (function(document, search){
var searchBox = document.getElementById('search-box')
var searchResults = document.getElementById('search-results')
function clearResults() {
searchResults.innerHTML = ''
}
function appendResult(result) {
var a = document.createElement('a')
a.href = 'https://openwhyd.org/c/' + result._id
a.appendChild(document.createTextNode(result.name))
var li = document.createElement('li')
li.appendChild(a)
searchResults.appendChild(li)
}
searchBox.onkeyup = function() {
clearResults()
var results = search(searchBox.value)
if (!results || !results.length) {
appendResult({ name: '(no results)' })
} else {
results.forEach(appendResult)
}
}
return {
clearResults: clearResults,
appendResult: appendResult,
}
})(document, search)
// LOAD PROFILE DATA FROM OPENWHYD
ui.appendResult({ name: '(loading tracks from openwhyd...)' })
window[callbackFctName] = function(json) {
indexTracks(json)
ui.clearResults()
ui.appendResult({ name: '(loaded ' + allTracks.length + ' tracks from openwhyd! ^^)' })
}
var script = document.createElement('script')
script.src = profileUrl
document.body.appendChild(script)