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

102 lines
2.1 KiB
JavaScript
Raw Normal View History

import ngModule from '../../module';
2019-10-28 20:40:24 +00:00
import Field from '../field';
import './style.scss';
2019-10-28 20:40:24 +00:00
/**
* Input file selector.
*
* @property {String} accept List of valid file types
*/
export default class InputFile extends Field {
constructor($element, $) {
super($element, $);
this._multiple = false;
2019-10-18 19:36:30 +00:00
this.input = this.element.querySelector('input');
this.registerEvents();
}
2019-10-28 20:40:24 +00:00
/*
* Registers all event emitters
*/
registerEvents() {
2019-10-28 20:40:24 +00:00
this.input.addEventListener('change', () => {
const files = this.input.files;
const fileList = Array
.from(files)
.map(file => file.name)
.join(', ');
const label = this.element.querySelector('.value');
2019-10-28 20:40:24 +00:00
label.innerHTML = fileList;
2019-10-28 20:40:24 +00:00
this.field = files.length ? files : null;
});
}
2019-10-28 20:40:24 +00:00
get field() {
return super.field;
}
2019-10-28 20:40:24 +00:00
set field(value) {
if (!value) this.input.value = '';
super.field = value;
}
/**
2019-10-28 20:40:24 +00:00
* @property {FileList} files Selected files list
*/
get files() {
2019-10-28 20:40:24 +00:00
return this.input.files;
}
set files(value) {
2019-10-28 20:40:24 +00:00
this.input.files = value;
}
/**
2019-10-28 20:40:24 +00:00
* @property {Boolean} multiple Whether to allow multiple file selection
*/
get multiple() {
2019-10-28 20:40:24 +00:00
return this.input.multiple;
}
set multiple(value) {
2019-10-28 20:40:24 +00:00
this.input.multiple = value;
}
2019-10-28 20:40:24 +00:00
/*
* Fires file selection explorer event
*/
openFileSelector() {
this.input.click();
}
2019-10-28 20:40:24 +00:00
2021-01-26 06:21:05 +00:00
onChange($event) {
2019-10-28 20:40:24 +00:00
this.emit('change', {
value: this.field,
2021-01-26 06:21:05 +00:00
$files: this.files,
$event: $event
2019-10-28 20:40:24 +00:00
});
}
2021-03-10 08:01:32 +00:00
get accept() {
return this._accept;
}
set accept(value) {
this._accept = value;
this.$.$applyAsync(() =>
this.input.setAttribute('accept', value));
}
}
2019-10-18 19:36:30 +00:00
ngModule.vnComponent('vnInputFile', {
template: require('./index.html'),
controller: InputFile,
bindings: {
multiple: '<?',
accept: '@?',
2019-10-28 20:40:24 +00:00
files: '=?'
}
});