|
| 1 | +import type { |
| 2 | + ConfirmOptions, |
| 3 | + DialogSeverity, |
| 4 | + IDialog, |
| 5 | + PickFileOptions, |
| 6 | +} from "@posthog/platform/dialog"; |
| 7 | +import { |
| 8 | + BrowserWindow, |
| 9 | + dialog, |
| 10 | + type MessageBoxOptions, |
| 11 | + type OpenDialogOptions, |
| 12 | +} from "electron"; |
| 13 | +import { injectable } from "inversify"; |
| 14 | + |
| 15 | +type OpenDialogProperty = NonNullable<OpenDialogOptions["properties"]>[number]; |
| 16 | + |
| 17 | +function severityToType(severity?: DialogSeverity): MessageBoxOptions["type"] { |
| 18 | + return severity ?? "none"; |
| 19 | +} |
| 20 | + |
| 21 | +function buildProperties(options: PickFileOptions): OpenDialogProperty[] { |
| 22 | + const properties: OpenDialogProperty[] = [ |
| 23 | + options.directories ? "openDirectory" : "openFile", |
| 24 | + "treatPackageAsDirectory", |
| 25 | + ]; |
| 26 | + if (options.multiple) properties.push("multiSelections"); |
| 27 | + if (options.createDirectories) properties.push("createDirectory"); |
| 28 | + return properties; |
| 29 | +} |
| 30 | + |
| 31 | +@injectable() |
| 32 | +export class ElectronDialog implements IDialog { |
| 33 | + public async confirm(options: ConfirmOptions): Promise<number> { |
| 34 | + const parent = BrowserWindow.getFocusedWindow(); |
| 35 | + const electronOptions: MessageBoxOptions = { |
| 36 | + type: severityToType(options.severity), |
| 37 | + title: options.title, |
| 38 | + message: options.message, |
| 39 | + detail: options.detail, |
| 40 | + buttons: options.options, |
| 41 | + defaultId: options.defaultIndex, |
| 42 | + cancelId: options.cancelIndex, |
| 43 | + }; |
| 44 | + const result = parent |
| 45 | + ? await dialog.showMessageBox(parent, electronOptions) |
| 46 | + : await dialog.showMessageBox(electronOptions); |
| 47 | + return result.response; |
| 48 | + } |
| 49 | + |
| 50 | + public async pickFile(options: PickFileOptions): Promise<string[]> { |
| 51 | + const parent = BrowserWindow.getFocusedWindow(); |
| 52 | + const electronOptions: OpenDialogOptions = { |
| 53 | + title: options.title, |
| 54 | + properties: buildProperties(options), |
| 55 | + }; |
| 56 | + const result = parent |
| 57 | + ? await dialog.showOpenDialog(parent, electronOptions) |
| 58 | + : await dialog.showOpenDialog(electronOptions); |
| 59 | + return result.canceled ? [] : result.filePaths; |
| 60 | + } |
| 61 | +} |
0 commit comments