|
1 | 1 | ;(function () { |
2 | 2 | 'use strict' |
3 | 3 |
|
4 | | - var docsearch = require('docsearch.js/dist/cdn/docsearch.js') |
5 | | - window.addEventListener('load', function () { |
6 | | - var config = document.getElementById('search-script').dataset |
7 | | - var link = document.createElement('link') |
8 | | - link.rel = 'stylesheet' |
9 | | - link.href = config.stylesheet |
10 | | - document.head.appendChild(link) |
11 | | - var ds = docsearch({ |
| 4 | + activateSearch(require('docsearch.js/dist/cdn/docsearch.js'), document.getElementById('search-script').dataset) |
| 5 | + |
| 6 | + function activateSearch (docsearch, config) { |
| 7 | + appendStylesheet(config.stylesheet) |
| 8 | + var algoliaOptions = { |
| 9 | + hitsPerPage: parseInt(config.maxResults) || 25, |
| 10 | + } |
| 11 | + var searchForm = document.querySelector('form.search') |
| 12 | + var controller = docsearch({ |
12 | 13 | appId: config.appId, |
13 | 14 | apiKey: config.apiKey, |
14 | 15 | indexName: config.indexName, |
15 | 16 | inputSelector: '#search-query', |
16 | | - algoliaOptions: { hitsPerPage: 25 }, |
17 | | - debug: false, |
| 17 | + autocompleteOptions: { autoselect: true, debug: true, hint: false, keyboardShortcuts: ['s'], minLength: 2 }, |
| 18 | + algoliaOptions: algoliaOptions, |
18 | 19 | }) |
19 | | - ds.input.focus() |
20 | | - // document.querySelector('button.search').addEventListener('click', function (e) { |
21 | | - // if (document.querySelector('.navbar-start').classList.toggle('reveal-search-input')) { |
22 | | - // ds.autocomplete.autocomplete.setVal('') |
23 | | - // ds.input.focus() |
24 | | - // } |
25 | | - // }) |
26 | | - }) |
| 20 | + var eventEmitter = controller.autocomplete |
| 21 | + var autocomplete = eventEmitter.autocomplete |
| 22 | + autocomplete.setVal() |
| 23 | + eventEmitter.on('autocomplete:selected', disableClose) |
| 24 | + searchForm.addEventListener('click', confineEvent) |
| 25 | + document.documentElement.addEventListener('click', resetSearch.bind(autocomplete)) |
| 26 | + if (controller.input.attr('autofocus') != null) controller.input.focus() |
| 27 | + } |
| 28 | + |
| 29 | + function appendStylesheet (href) { |
| 30 | + document.head.appendChild(Object.assign(document.createElement('link'), { rel: 'stylesheet', href: href })) |
| 31 | + } |
| 32 | + |
| 33 | + function confineEvent (e) { |
| 34 | + e.stopPropagation() |
| 35 | + } |
| 36 | + |
| 37 | + function disableClose (e) { |
| 38 | + e.isDefaultPrevented = function () { |
| 39 | + return true |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + function resetSearch () { |
| 44 | + this.close() |
| 45 | + this.setVal() |
| 46 | + } |
27 | 47 | })() |
0 commit comments