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

90 lines
2.1 KiB
React
Raw Normal View History

2018-03-26 23:32:43 +02:00
// @flow
2018-11-26 02:21:25 +01:00
import * as ICONS from 'constants/icons';
2019-03-05 05:46:57 +01:00
2018-02-24 01:24:00 +01:00
import React from 'react';
2018-03-26 23:32:43 +02:00
import Button from 'component/button';
import Spinner from 'component/spinner';
2018-02-24 01:24:00 +01:00
2018-03-26 23:32:43 +02:00
type Props = {
data: any,
2018-03-26 23:32:43 +02:00
label: string,
tooltip?: string,
defaultFileName?: string,
filters?: Array<string>,
onFetch?: () => void,
progressMsg?: string,
disabled?: boolean,
2018-03-26 23:32:43 +02:00
};
2018-02-24 01:24:00 +01:00
2018-03-26 23:32:43 +02:00
class FileExporter extends React.PureComponent<Props> {
constructor() {
super();
(this: any).handleDownload = this.handleDownload.bind(this);
2018-02-24 01:24:00 +01:00
}
handleDownload() {
const { data, defaultFileName } = this.props;
2018-02-24 01:24:00 +01:00
const element = document.createElement('a');
const file = new Blob([data], { type: 'text/plain' });
element.href = URL.createObjectURL(file);
element.download = defaultFileName || 'file.txt';
// $FlowFixMe
document.body.appendChild(element);
element.click();
// $FlowFixMe
document.body.removeChild(element);
2018-02-24 01:24:00 +01:00
}
render() {
const { data, label, tooltip, disabled, onFetch, progressMsg } = this.props;
if (onFetch) {
return (
<>
{!progressMsg && (
<div className="button-group">
<Button
button="alt"
disabled={disabled}
icon={ICONS.FETCH}
label={label}
aria-label={tooltip}
onClick={() => onFetch()}
/>
{data && (
<Button
button="alt"
disabled={disabled}
icon={ICONS.DOWNLOAD}
aria-label={__('Download fetched file')}
onClick={this.handleDownload}
/>
)}
</div>
)}
{progressMsg && (
<>
{__(progressMsg)}
<Spinner type="small" />
</>
)}
</>
);
} else {
return (
<Button
button="primary"
disabled={disabled}
icon={ICONS.DOWNLOAD}
label={label || __('Export')}
aria-label={tooltip}
onClick={this.handleDownload}
/>
);
}
2018-02-24 01:24:00 +01:00
}
}
export default FileExporter;