// @flow import * as React from 'react'; import * as remote from '@electron/remote'; import Button from 'component/button'; import { FormField } from 'component/common/form'; type Props = { type: string, currentPath?: ?string, onFileChosen: (WebFile) => void, label?: string, placeholder?: string, accept?: string, error?: string, disabled?: boolean, autoFocus?: boolean, }; class FileSelector extends React.PureComponent { static defaultProps = { autoFocus: false, type: 'file', }; fileInput: React.ElementRef; constructor() { super(); this.fileInput = React.createRef(); this.handleFileInputSelection = this.handleFileInputSelection.bind(this); this.handleDirectoryInputSelection = this.handleDirectoryInputSelection.bind(this); this.fileInputButton = this.fileInputButton.bind(this); } handleFileInputSelection = () => { const { files } = this.fileInput.current; if (!files) { return; } const file = files[0]; if (this.props.onFileChosen) { this.props.onFileChosen(file); } this.fileInput.current.value = null; // clear the file input }; handleDirectoryInputSelection = () => { let defaultPath; let properties; let isWin = process.platform === 'win32'; let type = this.props.type; if (isWin === true) { defaultPath = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; } if (type === 'openFile') { properties = ['openFile']; } if (type === 'openDirectory') { properties = ['openDirectory']; } remote.dialog.showOpenDialog({ properties, defaultPath }).then((result) => { const path = result && result.filePaths[0]; if (path) { // $FlowFixMe this.props.onFileChosen({ path }); } }); }; fileInputButton = () => { this.fileInput.current.click(); }; input: ?HTMLInputElement; render() { const { type, currentPath, label, placeholder, accept, error, disabled, autoFocus = false } = this.props; const placeHolder = currentPath || placeholder; return ( } /> (type === 'openDirectory' ? () => {} : this.handleFileInputSelection())} webkitdirectory={type === 'openDirectory' ? 'True' : null} /> ); } } export default FileSelector;