-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
114 lines (100 loc) · 2.69 KB
/
app.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const searchClient = algoliasearch(
'6B29BTPQED',
'49ae085a83962db19658af549b3bac7e' // search only API key, no ADMIN key
)
const search = instantsearch({
searchClient,
indexName: 'prod_dynamic-faceting',
routing: false,
})
// initialize SearchBox
search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-box',
placeholder: 'Search products...',
})
)
search.addWidget(
instantsearch.widgets.hits({
container: '#hits',
templates: {
item: `
<div class="hit">
<div class="image"><img src="{{image}}" alt="Product image"></div>
<div class="name">{{{_highlightResult.name.value}}}</div>
</div>
`,
}
})
)
const rangeSliderWithPanel = instantsearch.widgets.panel({
templates: {
header: 'Price',
},
})(instantsearch.widgets.rangeSlider)
search.addWidget(
rangeSliderWithPanel({
container: '#price',
attribute: 'price',
tooltips: {
format: rawValue => '$' + Math.round(rawValue).toLocaleString()
},
})
)
search.addWidget(
instantsearch.widgets.pagination({
container: '#pagination',
maxPages: 10,
scrollTo: false,
})
)
// handle dynamic facets
let widgets = {}
search.on('render', () => {
const results = search.helper.lastResults
if (results.userData && results.userData[0].type === 'dynamic_facets') {
// retrieve facet list
const facets = results.userData[0].facets
// remove old attributes
const toDeleteAttrs = Object.keys(widgets).filter(attr => !facets.includes(attr))
if (toDeleteAttrs.length > 0) {
const toDeleteRefs = toDeleteAttrs.map(attr => widgets[attr])
search.removeWidgets(toDeleteRefs)
toDeleteAttrs.forEach(attr => delete widgets[attr])
}
// add new attributes
const toAdd = facets.filter(attr => !widgets.hasOwnProperty(attr)).map(attr => { widgets[attr] = createWidget(attr); return widgets[attr]; })
if (toAdd.length > 0) {
search.addWidgets(toAdd)
}
}
else {
// delete all
const toDeleteRefs = Object.keys(widgets).map(attr => widgets[attr])
if (toDeleteRefs.length > 0) {
search.removeWidgets(toDeleteRefs)
widgets = {}
}
}
})
const createWidget = attr => {
const refinementListWithPanel = instantsearch.widgets.panel({
templates: {
header: attr,
},
})(instantsearch.widgets.refinementList)
let container = document.getElementById(attr)
if (!container) {
container = document.createElement('div')
container.id = attr
document.getElementById('refinement-lists').appendChild(container)
}
return refinementListWithPanel({
container: container,
attribute: attr,
operator: 'or',
limit: 10,
})
}
// start
search.start()