Skip to content

Commit

Permalink
feat: save value to file
Browse files Browse the repository at this point in the history
  • Loading branch information
bj00rn committed May 27, 2024
1 parent 349c3b9 commit 6d80bb8
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 10 deletions.
19 changes: 12 additions & 7 deletions app/src/actions/Publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,31 +17,36 @@ export const setTopic = (topic?: string): Action => {
export const openFile = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
try {
const file = await getFileContent()
dispatch(
setPayload(Base64Message.fromBuffer(file.data).toUnicodeString()
))
if (file) {
dispatch(
setPayload(Base64Message.fromBuffer(file.data).toUnicodeString()
))
}
} catch (error) {
dispatch(showError(error))
}

}

type FileParameters = {
name: string,
data: Buffer
}
async function getFileContent(): Promise<FileParameters> {
async function getFileContent(): Promise<FileParameters | undefined> {
const rejectReasons = {
noFileSelected: 'No file selected',
errorReadingFile: 'Error reading file'
}

const openDialogReturnValue = await rendererRpc.call(makeOpenDialogRpc(), {
const { canceled, filePaths } = await rendererRpc.call(makeOpenDialogRpc(), {
properties: ['openFile'],
securityScopedBookmarks: true,
})

const selectedFile = openDialogReturnValue.filePaths && openDialogReturnValue.filePaths[0]
if (canceled) {
return
}

const selectedFile = filePaths[0]
if (!selectedFile) {
throw rejectReasons.noFileSelected
}
Expand Down
12 changes: 11 additions & 1 deletion app/src/components/Sidebar/ValueRenderer/ValuePanel.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as q from '../../../../../backend/src/Model'
import ActionButtons from './ActionButtons'
import Copy from '../../helper/Copy'
import Save from '../../helper/Save'
import DateFormatter from '../../helper/DateFormatter'
import MessageHistory from './MessageHistory'
import Panel from '../Panel'
Expand Down Expand Up @@ -59,6 +60,12 @@ function ValuePanel(props: Props) {
return node?.message && decodeMessage(node.message)?.message?.toUnicodeString()
}, [node, decodeMessage])

const getBuffer = () => {
if (node?.message && node.message.payload) {
return node.message.payload.toBuffer()
}
}

function messageMetaInfo() {
if (!props.node || !props.node.message) {
return null
Expand Down Expand Up @@ -93,10 +100,13 @@ function ValuePanel(props: Props) {
const [value] =
node && node.message && node.message.payload ? node.message.payload?.format(node.type) : [null, undefined]
const copyValue = value ? <Copy getValue={getDecodedValue} /> : null
const saveValue = value ? <Save getBuffer={getBuffer} /> : null

return (
<Panel>
<span>Value {copyValue}</span>
<span>
Value {copyValue} {saveValue}
</span>
<span style={{ width: '100%' }}>
{renderViewOptions()}
<div style={{ marginBottom: '-8px', marginTop: '8px' }}>
Expand Down
85 changes: 85 additions & 0 deletions app/src/components/helper/Save.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as React from 'react'
import { connect } from 'react-redux'
import Check from '@material-ui/icons/Check'
import CustomIconButton from './CustomIconButton'
import { promises as fsPromise } from 'fs'
import { SaveAlt } from '@material-ui/icons'
import { bindActionCreators } from 'redux'
import { rendererRpc } from '../../../../events'
import { makeSaveDialogRpc } from '../../../../events/OpenDialogRequest'

import { globalActions } from '../../actions'

export async function saveToFile(buffer: Buffer | string): Promise<string | undefined> {
const rejectReasons = {
errorWritingFile: 'Error writing file',
}

const { canceled, filePath } = await rendererRpc.call(makeSaveDialogRpc(), {
securityScopedBookmarks: true,
})

if (!canceled && filePath !== undefined) {
try {
await fsPromise.writeFile(filePath, buffer, { encoding: 'base64' })
return filePath
} catch (error) {
throw rejectReasons.errorWritingFile
}
}
}

interface Props {
getBuffer: () => Buffer | undefined
actions: {
global: typeof globalActions
}
}

interface State {
didSave: boolean
}

class Save extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props)
this.state = { didSave: false }
}

private handleClick = async (event: React.MouseEvent) => {
event.stopPropagation()
const buffer = this.props.getBuffer()
if (buffer !== undefined) {
const filename = await saveToFile(buffer)
this.props.actions.global.showNotification(`Saved to ${filename}`)
this.setState({ didSave: true })
setTimeout(() => {
this.setState({ didSave: false })
}, 1500)
}
}

public render() {
const icon = !this.state.didSave ? (
<SaveAlt fontSize="inherit" />
) : (
<Check fontSize="inherit" style={{ cursor: 'default' }} />
)

return (
<CustomIconButton onClick={this.handleClick} tooltip="Save to file">
<div style={{ marginTop: '2px' }}>{icon}</div>
</CustomIconButton>
)
}
}

const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
global: bindActionCreators(globalActions, dispatch),
},
}
}

export default connect(undefined, mapDispatchToProps)(Save)
8 changes: 7 additions & 1 deletion events/OpenDialogRequest.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { OpenDialogOptions, OpenDialogReturnValue } from 'electron'
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
import { RpcEvent } from './EventSystem/Rpc'

export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogReturnValue> {
return {
topic: 'openDialog',
}
}

export function makeSaveDialogRpc(): RpcEvent<SaveDialogOptions, SaveDialogReturnValue> {
return {
topic: 'saveDialog',
}
}
7 changes: 6 additions & 1 deletion src/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import buildOptions from './buildOptions'
import { waitForDevServer, isDev, runningUiTestOnCi, loadDevTools } from './development'
import { shouldAutoUpdate, handleAutoUpdate } from './autoUpdater'
import { registerCrashReporter } from './registerCrashReporter'
import { makeOpenDialogRpc } from '../events/OpenDialogRequest'
import { makeOpenDialogRpc, makeSaveDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion } from '../events'

registerCrashReporter()
Expand All @@ -25,6 +25,11 @@ app.whenReady().then(() => {
backendRpc.on(makeOpenDialogRpc(), async request => {
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})

backendRpc.on(makeSaveDialogRpc(), async request => {
return dialog.showSaveDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})

backendRpc.on(getAppVersion, async () => app.getVersion())
})

Expand Down

0 comments on commit 6d80bb8

Please sign in to comment.