1 | import BaseComponent from 'bootstrap/js/src/base-component.js'
|
2 |
|
3 | import EventHandler from 'bootstrap/js/src/dom/event-handler'
|
4 | import SelectorEngine from 'bootstrap/js/src/dom/selector-engine'
|
5 |
|
6 | import InputLabel from './input-label'
|
7 |
|
8 | const NAME = 'input'
|
9 | const DATA_KEY = 'bs.input'
|
10 | const EVENT_KEY = `.${DATA_KEY}`
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | const EVENT_CHANGE = `change${EVENT_KEY}`
|
16 |
|
17 | class Input extends BaseComponent {
|
18 | constructor(element) {
|
19 | super(element)
|
20 |
|
21 | this._label = new InputLabel(element)
|
22 | this._bindEvents()
|
23 | }
|
24 |
|
25 |
|
26 |
|
27 | static get NAME() {
|
28 | return NAME
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | _bindEvents() {
|
35 | if (this._element.getAttribute('type') === 'file') {
|
36 | EventHandler.on(this._element, EVENT_CHANGE, () => {
|
37 | this._handleFileDescription()
|
38 | })
|
39 | }
|
40 | }
|
41 |
|
42 | _handleFileDescription() {
|
43 | const fileNames = []
|
44 | let labelPrefix = ''
|
45 |
|
46 | Array.from(this._element.files).forEach((file) => {
|
47 | const fileSize = Math.round(parseInt(file.size, 10) / 1024)
|
48 | fileNames.push(file.name + ' (' + fileSize + 'kb)')
|
49 | })
|
50 |
|
51 | if (this._element.files.length > 1) {
|
52 | labelPrefix = this._element.files.length + ' file da caricare: '
|
53 | }
|
54 |
|
55 | const label = SelectorEngine.findOne('label[for="' + this._element.getAttribute('id') + '"] label.form-file-name', this._element)
|
56 | if (label) {
|
57 | label.innerText = labelPrefix + fileNames.join('; ')
|
58 | }
|
59 | }
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | const excludes = [
|
68 | 'select',
|
69 | 'input[data-bs-input][type="number"]',
|
70 | 'input[data-bs-input][type="password"]',
|
71 | 'input[data-bs-autocomplete][type="search"]',
|
72 | 'input[type="time"]',
|
73 | ]
|
74 |
|
75 | const inputs = SelectorEngine.find('input, textarea').filter((input) => {
|
76 | let result = true
|
77 | excludes.forEach((selector) => {
|
78 | if (input.matches(selector)) {
|
79 | result = false
|
80 | }
|
81 | })
|
82 | return result
|
83 | })
|
84 | inputs.forEach((input) => {
|
85 | Input.getOrCreateInstance(input)
|
86 | })
|
87 |
|
88 | export default Input
|