Files: efc84dd991368b380bd934c8c83d25abdcb866cc / index.js
1673 bytesRaw
1 | var h = require('hyperscript') |
2 | var pull = require('pull-stream') |
3 | |
4 | module.exports = function combobox(opt) { |
5 | var otherSelectOption = h('option', {value: ''}, 'other…') |
6 | var input = h('input', { |
7 | onkeyup: function () { |
8 | otherSelectOption.value = this.value |
9 | if (opt.onchange) opt.onchange.call(select) |
10 | }, |
11 | onblur: function () { |
12 | if (!this.value) { |
13 | select.selectedIndex = 0 |
14 | this.parentNode.replaceChild(select, this) |
15 | } |
16 | } |
17 | }) |
18 | var select = h('select', { |
19 | style: opt.style, |
20 | onchange: function () { |
21 | if (!this.value) { |
22 | input.style.width = this.offsetWidth + 'px' |
23 | this.parentNode.replaceChild(input, this) |
24 | input.focus() |
25 | } |
26 | if (opt.onchange) opt.onchange.call(this) |
27 | } |
28 | }, |
29 | opt.placeholder ? h('option', |
30 | {disabled: true, selected: true, hidden: true, value: ''}, |
31 | opt.placeholder) : null |
32 | ) |
33 | var readOptions = opt.options || opt.read |
34 | if (readOptions) pull( |
35 | readOptions, |
36 | pull.filter(), |
37 | pull.drain(function (option) { |
38 | select.appendChild(option) |
39 | if (option.value === opt.default) { |
40 | select.value = option.value |
41 | } |
42 | if (select.value === option.value) { |
43 | if (opt.onchange) opt.onchange.call(select) |
44 | } |
45 | }, function (err) { |
46 | if (err) return cb ? cb(err) : console.error(err) |
47 | select.appendChild(otherSelectOption) |
48 | }) |
49 | ) |
50 | else select.appendChild(otherSelectOption) |
51 | select.swap = function (newEl) { |
52 | if (select.parentNode) select.parentNode.replaceChild(newEl, select) |
53 | else if (input.parentNode) input.parentNode.replaceChild(newEl, input) |
54 | return newEl |
55 | } |
56 | return select |
57 | } |
58 | |
59 | |
60 |
Built with git-ssb-web