UNPKG

2.16 kBJavaScriptView Raw
1import BaseComponent from 'bootstrap/js/src/base-component.js'
2
3import EventHandler from 'bootstrap/js/src/dom/event-handler'
4import SelectorEngine from 'bootstrap/js/src/dom/selector-engine'
5
6import InputLabel from './input-label'
7
8const NAME = 'input'
9const DATA_KEY = 'bs.input'
10const EVENT_KEY = `.${DATA_KEY}`
11//const DATA_API_KEY = '.data-api'
12
13//const SELECTOR_INPUT = 'input[data-bs-input]'
14
15const EVENT_CHANGE = `change${EVENT_KEY}`
16
17class Input extends BaseComponent {
18 constructor(element) {
19 super(element)
20
21 this._label = new InputLabel(element)
22 this._bindEvents()
23 }
24
25 // Getters
26
27 static get NAME() {
28 return NAME
29 }
30
31 // Public
32
33 // Private
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 * Data Api implementation
65 * ------------------------------------------------------------------------
66 */
67const 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
75const 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})
84inputs.forEach((input) => {
85 Input.getOrCreateInstance(input)
86})
87
88export default Input