lbry-desktop/src/renderer/component/common/file-exporter.jsx

84 lines
1.9 KiB
React
Raw Normal View History

2018-03-26 23:32:43 +02:00
// @flow
2018-02-24 01:24:00 +01:00
import fs from 'fs';
import path from 'path';
import React from 'react';
2018-03-26 23:32:43 +02:00
import Button from 'component/button';
2018-02-24 01:24:00 +01:00
import parseData from 'util/parseData';
import * as icons from 'constants/icons';
2018-03-26 23:32:43 +02:00
import { remote } from 'electron';
2018-02-24 01:24:00 +01:00
2018-03-26 23:32:43 +02:00
type Props = {
data: Array<any>,
title: string,
label: string,
defaultPath?: string,
filters: Array<string>,
onFileCreated?: string => void,
};
2018-02-24 01:24:00 +01:00
2018-03-26 23:32:43 +02:00
class FileExporter extends React.PureComponent<Props> {
2018-03-22 16:43:35 +01:00
static defaultProps = {
filters: [],
};
2018-03-26 23:32:43 +02:00
constructor() {
super();
this.handleButtonClick = this.handleButtonClick.bind(this);
2018-02-24 01:24:00 +01:00
}
2018-03-26 23:32:43 +02:00
handleButtonClick: () => void;
handleFileCreation(filename: string, data: any) {
2018-02-24 01:24:00 +01:00
const { onFileCreated } = this.props;
fs.writeFile(filename, data, err => {
if (err) throw err;
// Do something after creation
onFileCreated && onFileCreated(filename);
});
}
handleButtonClick() {
2018-03-22 16:43:35 +01:00
const { title, data, defaultPath, filters } = this.props;
2018-02-24 01:24:00 +01:00
const options = {
title,
defaultPath,
2018-03-22 16:43:35 +01:00
filters: [
{
name: 'CSV',
extensions: ['csv'],
},
{
name: 'JSON',
extensions: ['json'],
},
],
2018-02-24 01:24:00 +01:00
};
remote.dialog.showSaveDialog(remote.getCurrentWindow(), options, filename => {
2018-02-24 01:24:00 +01:00
// User hit cancel so do nothing:
if (!filename) return;
// Get extension and remove initial dot
const format = path.extname(filename).replace(/\./g, '');
// Parse data to string with the chosen format
2018-03-22 16:43:35 +01:00
const parsed = parseData(data, format, filters);
2018-02-24 01:24:00 +01:00
// Write file
parsed && this.handleFileCreation(filename, parsed);
});
}
render() {
const { title, label } = this.props;
return (
2018-03-26 23:32:43 +02:00
<Button
2018-02-24 03:12:51 +01:00
button="primary"
2018-02-24 01:24:00 +01:00
icon={icons.DOWNLOAD}
label={label || __('Export')}
2018-03-26 23:32:43 +02:00
onClick={this.handleButtonClick}
2018-02-24 01:24:00 +01:00
/>
);
}
}
export default FileExporter;