-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
68 lines (64 loc) · 1.94 KB
/
index.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
const { autocomplete } = window['@algolia/autocomplete-js'];
let typesenseClient = new Typesense.Client({
apiKey: 'xyz',
nodes: [
{
url: 'http://localhost:8108',
},
],
connectionTimeoutSeconds: 2,
});
autocomplete({
container: '#autocomplete',
placeholder: 'Type in an address in Boston city. Eg: 1 North Square',
detachedMediaQuery: 'none',
async getSources({ query }) {
const results = await typesenseClient
.collections('addresses_boston')
.documents()
.search({
q: query,
query_by: 'address,postcode',
highlight_full_fields: 'address,postcode',
highlight_start_tag: '<b>',
highlight_end_tag: '</b>',
per_page: 5,
});
return [
{
sourceId: 'predictions',
getItems() {
return results.hits;
},
getItemInputValue({
item: {
document: { address, postcode },
},
}) {
return `${address} ${postcode}`;
},
templates: {
item({ item, html }) {
// html is from the `htm` package. Docs: https://github.com/developit/htm
const address =
item.highlights.find((h) => h.field === 'address')?.value ||
item.document['address'];
const postcode =
item.highlights.find((h) => h.field === 'postcode')?.value ||
item.document['postcode'];
// Get the highlighted HTML fragment from Typesense results
const html_fragment = html`${address + ' ' + postcode}`;
// Send the html_fragment to `html` tagged template
// Reference: https://github.com/developit/htm/issues/226#issuecomment-1205526098
return html`<div
dangerouslySetInnerHTML=${{ __html: html_fragment }}
></div>`;
},
noResults() {
return 'No results found.';
},
},
},
];
},
});