-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
69 lines (58 loc) · 2.62 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
69
import {enhanceSelectElement} from 'accessible-autocomplete'
import openregisterPickerEngine from 'openregister-picker-engine'
function inputValueTemplate (result) {
if (typeof result === 'string') {
return result
}
return result && result.name
}
function suggestionTemplate (result) {
if (typeof result === 'string') {
return '<strong>' + result + '</strong>'
}
const path = result && result.path
? ' (' + result.path + ')'
: ''
return result && '<strong>' + result.name + '</strong>' + path
}
function openregisterLocationPicker (opts) {
// Set defaults.
opts.fallback = opts.fallback || ((query, syncResults) => {
const availableOptions = Array.prototype.map.call(opts.selectElement.options, o => o.innerText)
const filteredResults = query
? availableOptions.filter(r => r.toLowerCase().indexOf(query.toLowerCase()) !== -1)
: []
const templatedResults = filteredResults.map(r => ({ name: r }))
syncResults(templatedResults)
})
opts.minLength = opts.minLength || 2
opts.onConfirm = opts.onConfirm || ((result) => {
var requestedOption = Array.prototype.filter.call(opts.selectElement.options, o => o.innerText === (result && result.name))[0]
if (requestedOption) { requestedOption.selected = true }
})
const optionsWithAdditionalSynonyms = Array.prototype
.filter.call(opts.selectElement.options, option => option.dataset && option.dataset.additionalSynonyms)
const htmlAdditionalSynonyms = optionsWithAdditionalSynonyms
// => [<HtmlOption value="country:GB" data-additional-synonyms="['Albion', 'Blighty']">, ...]
.map(option => ({ code: option.value, synonyms: option.dataset.additionalSynonyms }))
// => [{ code: 'country:GB', synonyms: "['Albion', 'Blighty']" }, ...]
.reduce((additionalSynonymsArray, additionalSynonymsSet) => {
const additionalSynonymsSeparated = JSON.parse(additionalSynonymsSet.synonyms)
.map(synonymName => ({ name: synonymName, code: additionalSynonymsSet.code }))
return additionalSynonymsArray.concat(additionalSynonymsSeparated)
}, [])
// => [{ code: 'country:GB', name: 'Albion' }, { code: 'country:GB', name: 'Blighty' }, ...]
opts.additionalSynonyms = (opts.additionalSynonyms || []).concat(htmlAdditionalSynonyms)
opts.source = opts.source || openregisterPickerEngine({
additionalEntries: opts.additionalEntries,
additionalSynonyms: opts.additionalSynonyms,
url: opts.url,
fallback: opts.fallback
})
opts.templates = opts.templates || {
inputValue: inputValueTemplate,
suggestion: suggestionTemplate
}
enhanceSelectElement(opts)
}
export default openregisterLocationPicker