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';
|
2021-04-23 18:10:37 +02:00
|
|
|
import Spinner from 'component/spinner';
|
2018-02-24 01:24:00 +01:00
|
|
|
|
2018-03-26 23:32:43 +02:00
|
|
|
type Props = {
|
2021-04-23 18:10:37 +02:00
|
|
|
data: any,
|
2018-03-26 23:32:43 +02:00
|
|
|
label: string,
|
2021-04-23 18:10:37 +02:00
|
|
|
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();
|
2021-04-23 18:10:37 +02:00
|
|
|
(this: any).handleDownload = this.handleDownload.bind(this);
|
2018-02-24 01:24:00 +01:00
|
|
|
}
|
|
|
|
|
2021-04-23 18:10:37 +02:00
|
|
|
handleDownload() {
|
|
|
|
const { data, defaultFileName } = this.props;
|
2018-02-24 01:24:00 +01:00
|
|
|
|
2021-04-23 18:10:37 +02: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() {
|
2021-04-23 18:10:37 +02:00
|
|
|
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 && (
|
|
|
|
<>
|
2022-02-07 19:15:22 +01:00
|
|
|
{progressMsg}
|
2021-04-23 18:10:37 +02:00
|
|
|
<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;
|