lbry-desktop/src/renderer/component/file-exporter.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-02-24 01:24:00 +01:00
import fs from 'fs';
import path from 'path';
import React from 'react';
import PropTypes from 'prop-types';
import Link from 'component/link';
import parseData from 'util/parseData';
import * as icons from 'constants/icons';
const { remote } = require('electron');
class FileExporter extends React.PureComponent {
static propTypes = {
data: PropTypes.array,
title: PropTypes.string,
2018-02-25 22:53:17 +01:00
label: PropTypes.string,
2018-03-22 16:43:35 +01:00
filters: PropTypes.arrayOf(PropTypes.string),
2018-02-24 01:58:59 +01:00
defaultPath: PropTypes.string,
2018-02-24 01:24:00 +01:00
onFileCreated: PropTypes.func,
};
2018-03-22 16:43:35 +01:00
static defaultProps = {
filters: [],
};
2018-02-24 01:24:00 +01:00
constructor(props) {
super(props);
}
handleFileCreation(filename, data) {
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(options, filename => {
// 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 (
<Link
2018-02-24 03:12:51 +01:00
button="primary"
2018-02-24 01:24:00 +01:00
icon={icons.DOWNLOAD}
title={title || __('Export')}
label={label || __('Export')}
onClick={() => this.handleButtonClick()}
/>
);
}
}
export default FileExporter;