Skip to content

Commit

Permalink
feat: update runtime.selectFile() to also return the file name
Browse files Browse the repository at this point in the history
  • Loading branch information
achou11 committed Jan 7, 2025
1 parent 7380da9 commit d363615
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 7 deletions.
10 changes: 9 additions & 1 deletion src/main/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { randomBytes } from 'node:crypto'
import { basename } from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineMessages } from '@formatjs/intl'
import debug from 'debug'
Expand Down Expand Up @@ -243,7 +244,14 @@ function initMainWindow({ appMode, services }) {
: undefined,
})

return result.filePaths[0]
const selectedFilePath = result.filePaths[0]

if (!selectedFilePath) return undefined

return {
name: basename(selectedFilePath),
path: selectedFilePath,
}
})

APP_STATE.browserWindows.set(mainWindow, {
Expand Down
30 changes: 25 additions & 5 deletions src/preload/main-window.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,36 @@ const runtimeApi = {

// Files
async selectFile(extensionFilters) {
const filePath = await ipcRenderer.invoke('files:select', {
/** @type {unknown} */
const result = await ipcRenderer.invoke('files:select', {
extensionFilters,
})

if (!(typeof filePath === 'string' || typeof filePath === 'undefined')) {
throw new Error(`File path is unexpected type: ${typeof filePath}`)
}
if (!result) return undefined

validateSelectedFileResult(result)

return filePath
return result
},
}

/**
* @param {NonNullable<unknown>} value
*
* @returns {asserts value is import('./runtime.js').SelectedFile}
*/
function validateSelectedFileResult(value) {
if (!('path' in value && 'name' in value)) {
throw new Error('Value has invalid shape')
}

if (typeof value.path !== 'string') {
throw new Error('Value has invalid path field')
}

if (typeof value.name !== 'string') {
throw new Error('Value has invalid name field')
}
}

contextBridge.exposeInMainWorld('runtime', runtimeApi)
9 changes: 8 additions & 1 deletion src/preload/runtime.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
export type SelectedFile = {
path: string
name: string
}

export type RuntimeApi = {
getLocale: () => Promise<string>
updateLocale: (locale: string) => void
selectFile: (extensionFilters?: Array<string>) => Promise<string | undefined>
selectFile: (
extensionFilters?: Array<string>,
) => Promise<SelectedFile | undefined>
}

0 comments on commit d363615

Please sign in to comment.