|
| 1 | +import * as React from 'react' |
| 2 | +import { connect } from 'react-redux' |
| 3 | +import Check from '@material-ui/icons/Check' |
| 4 | +import CustomIconButton from './CustomIconButton' |
| 5 | + |
| 6 | +import { SaveAlt } from '@material-ui/icons' |
| 7 | +import { bindActionCreators } from 'redux' |
| 8 | +import { rendererRpc, writeToFile } from '../../../../events' |
| 9 | +import { makeSaveDialogRpc } from '../../../../events/OpenDialogRequest' |
| 10 | + |
| 11 | +import { globalActions } from '../../actions' |
| 12 | + |
| 13 | +export async function saveToFile(data: string): Promise<string | undefined> { |
| 14 | + const rejectReasons = { |
| 15 | + errorWritingFile: 'Error writing file', |
| 16 | + } |
| 17 | + |
| 18 | + const { canceled, filePath } = await rendererRpc.call(makeSaveDialogRpc(), { |
| 19 | + securityScopedBookmarks: true, |
| 20 | + }) |
| 21 | + |
| 22 | + if (!canceled && filePath !== undefined) { |
| 23 | + try { |
| 24 | + const filename = await rendererRpc.call(writeToFile, { filePath, data }) |
| 25 | + return filePath |
| 26 | + } catch (error) { |
| 27 | + throw rejectReasons.errorWritingFile |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +interface Props { |
| 33 | + getData: () => string | undefined |
| 34 | + actions: { |
| 35 | + global: typeof globalActions |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +interface State { |
| 40 | + didSave: boolean |
| 41 | +} |
| 42 | + |
| 43 | +class Save extends React.PureComponent<Props, State> { |
| 44 | + constructor(props: Props) { |
| 45 | + super(props) |
| 46 | + this.state = { didSave: false } |
| 47 | + } |
| 48 | + |
| 49 | + private handleClick = async (event: React.MouseEvent) => { |
| 50 | + event.stopPropagation() |
| 51 | + const data = this.props.getData() |
| 52 | + if (data != undefined) { |
| 53 | + const filename = await saveToFile(data) |
| 54 | + this.props.actions.global.showNotification(`Saved to ${filename}`) |
| 55 | + this.setState({ didSave: true }) |
| 56 | + setTimeout(() => { |
| 57 | + this.setState({ didSave: false }) |
| 58 | + }, 1500) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + public render() { |
| 63 | + const icon = !this.state.didSave ? ( |
| 64 | + <SaveAlt fontSize="inherit" /> |
| 65 | + ) : ( |
| 66 | + <Check fontSize="inherit" style={{ cursor: 'default' }} /> |
| 67 | + ) |
| 68 | + |
| 69 | + return ( |
| 70 | + <CustomIconButton onClick={this.handleClick} tooltip="Save to file"> |
| 71 | + <div style={{ marginTop: '2px' }}>{icon}</div> |
| 72 | + </CustomIconButton> |
| 73 | + ) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +const mapDispatchToProps = (dispatch: any) => { |
| 78 | + return { |
| 79 | + actions: { |
| 80 | + global: bindActionCreators(globalActions, dispatch), |
| 81 | + }, |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +export default connect(undefined, mapDispatchToProps)(Save) |
0 commit comments