-
Notifications
You must be signed in to change notification settings - Fork 0
/
widgets_script.html
82 lines (74 loc) · 2.46 KB
/
widgets_script.html
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
<!-- Make InstantSearch put widgets in the DOM -->
<script>
// --- Prep InstantSearch ---
const searchClient = algoliasearch(
"{{ site_env.algolia_app_id }}",
"{{ site_env.algolia_api_key }}"
);
const indexName = "{{ site_env.algolia_index_name }}";
const singleIndexStateMapping = instantsearch.stateMappings.singleIndex(indexName);
const withoutPageStateMapping = {
stateToRoute(uiState) {
const { page, ...state } = singleIndexStateMapping.stateToRoute(uiState);
return state;
},
routeToState(routeState) {
const { [indexName]: indexUiState } =
singleIndexStateMapping.routeToState(routeState);
const { page, ...state } = indexUiState;
return { [indexName]: state };
},
};
const search = instantsearch({
indexName,
searchClient,
routing: { stateMapping: withoutPageStateMapping },
});
// --- Define some custom helpers ---
const hitTemplate = function (hit) {
let date = "";
if (hit.date) {
date = moment.unix(hit.date).format("MMM D, YYYY");
}
let url = `{{ site.baseurl }}${hit.url}#${hit.anchor}`;
const title = hit._highlightResult.title.value;
let breadcrumbs = "";
if (hit._highlightResult.headings) {
breadcrumbs = hit._highlightResult.headings
.map((match) => {
return `<span class="post-breadcrumb">${match.value}</span>`;
})
.join(" > ");
}
const result_content = hit._highlightResult.html.value; // Used to work, v2
return `
<div class="post-item">
<h2><a class="post-link" href="${url}">${title}</a></h2>
<p>${date}</p>
{{#breadcrumbs}}<a href="${url}" class="post-breadcrumbs">${breadcrumbs}</a>{{/breadcrumbs}}
<div class="post-snippet">${result_content}</div>
</div>
`;
};
// --- Add all widgets ---
search.addWidgets([
// --- Define the "searchbar" as using the "searchBox" widget
instantsearch.widgets.searchBox({
container: "#search-searchbar",
placeholder: "Search this site...",
autofocus: false,
}),
instantsearch.widgets.poweredBy({
container: "#search-poweredby", // This is required if you're on the free Community plan
}),
instantsearch.widgets.hits({
container: "#search-hits",
escapeHTML: false,
templates: {
item: hitTemplate,
},
}),
]);
// --- Throw InstantSearch into the DOM ---
search.start();
</script>