lbry-desktop/ui/component/common/file-selector.jsx

94 lines
2.3 KiB
React
Raw Normal View History

2018-03-26 14:32:43 -07:00
// @flow
2019-02-22 00:01:59 -05:00
import * as React from 'react';
2018-03-26 14:32:43 -07:00
import Button from 'component/button';
2019-02-13 12:27:20 -04:00
import { FormField } from 'component/common/form';
2018-10-13 22:49:47 +07:00
2018-03-26 14:32:43 -07:00
type Props = {
type: string,
currentPath?: ?string,
onFileChosen: WebFile => void,
label?: string,
placeholder?: string,
2018-07-18 11:46:21 -04:00
fileLabel?: string,
2018-06-08 00:05:45 -04:00
directoryLabel?: string,
accept?: string,
error?: string,
disabled?: boolean,
2018-03-26 14:32:43 -07:00
};
class FileSelector extends React.PureComponent<Props> {
componentDidUpdate(prevProps: Props) {
// If the form has just been cleared,
// clear the file input
if (prevProps.currentPath && !this.props.currentPath) {
this.fileInput.current.value = null;
}
}
2018-03-26 14:32:43 -07:00
static defaultProps = {
type: 'file',
};
2019-09-27 12:22:15 -04:00
fileInput: React.ElementRef<any>;
2019-02-22 00:01:59 -05:00
2018-03-26 14:32:43 -07:00
constructor() {
super();
2019-02-22 00:01:59 -05:00
this.fileInput = React.createRef();
this.handleFileInputSelection = this.handleFileInputSelection.bind(this);
this.fileInputButton = this.fileInputButton.bind(this);
2018-03-26 14:32:43 -07:00
}
handleFileInputSelection = () => {
2019-09-27 12:22:15 -04:00
const { files } = this.fileInput.current;
if (!files) {
return;
}
const file = files[0];
2019-09-27 12:22:15 -04:00
if (this.props.onFileChosen) {
this.props.onFileChosen(file);
2019-09-27 12:22:15 -04:00
}
};
fileInputButton = () => {
this.fileInput.current.click();
};
2019-02-22 00:01:59 -05:00
2018-03-26 14:32:43 -07:00
input: ?HTMLInputElement;
render() {
const { type, currentPath, label, fileLabel, directoryLabel, placeholder, accept, error, disabled } = this.props;
const buttonLabel = type === 'file' ? fileLabel || __('Choose File') : directoryLabel || __('Choose Directory');
const placeHolder = currentPath || placeholder;
2019-12-09 13:51:00 -05:00
2018-03-26 14:32:43 -07:00
return (
2019-02-22 00:01:59 -05:00
<React.Fragment>
<FormField
label={label}
2019-03-18 01:06:41 -04:00
webkitdirectory="true"
className="form-field--copyable"
error={error}
disabled={disabled}
2019-03-18 01:06:41 -04:00
type="text"
readOnly="readonly"
value={placeHolder || __('Choose a file')}
inputButton={
2019-11-22 16:13:00 -05:00
<Button button="secondary" disabled={disabled} onClick={this.fileInputButton} label={buttonLabel} />
}
/>
<input
type={'file'}
style={{ display: 'none' }}
accept={accept}
ref={this.fileInput}
onChange={() => this.handleFileInputSelection()}
webkitdirectory={type === 'openDirectory' ? 'True' : null}
2019-02-22 00:01:59 -05:00
/>
</React.Fragment>
2018-03-26 14:32:43 -07:00
);
}
}
export default FileSelector;