@uppy/file-input
Version:
Simple UI of a file input button that works with Uppy right out of the box
104 lines (101 loc) • 2.98 kB
JavaScript
import { h } from 'preact';
import { UIPlugin } from '@uppy/core';
import toArray from '@uppy/utils/lib/toArray';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore We don't want TS to generate types for the package.json
const packageJson = {
"version": "4.1.2"
};
import locale from './locale.js';
const defaultOptions = {
pretty: true,
inputName: 'files[]'
};
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/files
export default class FileInput extends UIPlugin {
constructor(uppy, opts) {
super(uppy, {
...defaultOptions,
...opts
});
this.input = null;
this.id = this.opts.id || 'FileInput';
this.title = 'File Input';
this.type = 'acquirer';
this.defaultLocale = locale;
this.i18nInit();
this.render = this.render.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
addFiles(files) {
const descriptors = files.map(file => ({
source: this.id,
name: file.name,
type: file.type,
data: file
}));
try {
this.uppy.addFiles(descriptors);
} catch (err) {
this.uppy.log(err);
}
}
handleInputChange(event) {
this.uppy.log('[FileInput] Something selected through input...');
const files = toArray(event.currentTarget.files || []);
this.addFiles(files);
// Clear the input so that Chrome can detect file section when the same file is repeatedly selected
// (see https://github.com/transloadit/uppy/issues/768#issuecomment-2264902758)
// eslint-disable-next-line no-param-reassign
event.currentTarget.value = '';
}
handleClick() {
this.input.click();
}
render() {
var _restrictions$allowed;
/* http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/ */
const hiddenInputStyle = {
width: '0.1px',
height: '0.1px',
opacity: 0,
overflow: 'hidden',
position: 'absolute',
zIndex: -1
};
const {
restrictions
} = this.uppy.opts;
return h("div", {
className: "uppy-FileInput-container"
}, h("input", {
className: "uppy-FileInput-input",
style: this.opts.pretty ? hiddenInputStyle : undefined,
type: "file",
name: this.opts.inputName,
onChange: this.handleInputChange,
multiple: restrictions.maxNumberOfFiles !== 1,
accept: (_restrictions$allowed = restrictions.allowedFileTypes) == null ? void 0 : _restrictions$allowed.join(', '),
ref: input => {
this.input = input;
}
}), this.opts.pretty && h("button", {
className: "uppy-FileInput-btn",
type: "button",
onClick: this.handleClick
}, this.i18n('chooseFiles')));
}
install() {
const {
target
} = this.opts;
if (target) {
this.mount(target, this);
}
}
uninstall() {
this.unmount();
}
}
FileInput.VERSION = packageJson.version;