salix/front/core/components/input-file/index.js

116 lines
2.5 KiB
JavaScript

import ngModule from '../../module';
import FormInput from '../form-input';
import './style.scss';
export default class InputFile extends FormInput {
constructor($element, $scope) {
super($element, $scope);
this._multiple = false;
this._value = 'Select a file';
this.input = this.element.querySelector('input');
this.registerEvents();
}
/**
* Registers all event emitters
*/
registerEvents() {
this.input.addEventListener('change', event => {
const target = event.target;
const fileNames = Array.from(target.files).map(file => {
return file.name;
});
const names = fileNames.join(', ');
const label = this.element.querySelector('.value');
label.innerHTML = names;
this.files = target.files;
this.emit('change', {files: target.files, event});
});
}
get value() {
return this._value;
}
set value(value) {
this._value = value;
}
/**
* Gets current value
*/
get files() {
return this._files;
}
/**
* Sets input value
*
* @param {Number} value - Value
*/
set files(value) {
this._files = value;
this.hasValue = !(value === null || value === undefined || value === '');
if (this.hasValue)
this.element.classList.add('not-empty');
else
this.element.classList.remove('not-empty');
}
/**
* Gets if multiple file selection
*/
get multiple() {
return this._multiple;
}
/**
* Sets multiple file selection
*
* @param {Boolean} value - True if is multiple
*/
set multiple(value) {
this._multiple = value;
if (value)
this.input.multiple = true;
else
this.input.multiple = false;
}
/**
* Returns a list of valid file types
*/
get accept() {
return this._accept;
}
/**
* Sets a list of valid file types
*
* @param {String} value - Valid file types
*/
set accept(value) {
this._accept = value;
}
/**
* Fires file selection explorer event
*/
openFileSelector() {
this.input.click();
}
}
ngModule.vnComponent('vnInputFile', {
template: require('./index.html'),
controller: InputFile,
bindings: {
multiple: '<?',
accept: '@?',
files: '=model'
}
});