Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5
6import * as Electron from "electron";
7
8const CONFIRM_BUTTON_INDEX = 1;
9
10export interface ElectronDialogPickFolderInput {
11 readonly owner: Option.Option<Electron.BrowserWindow>;
12 readonly defaultPath: Option.Option<string>;
13}
14
15export interface ElectronDialogConfirmInput {
16 readonly owner: Option.Option<Electron.BrowserWindow>;
17 readonly message: string;
18}
19
20export interface ElectronDialogShape {
21 readonly pickFolder: (
22 input: ElectronDialogPickFolderInput,
23 ) => Effect.Effect<Option.Option<string>>;
24 readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
25 readonly showMessageBox: (
26 options: Electron.MessageBoxOptions,
27 ) => Effect.Effect<Electron.MessageBoxReturnValue>;
28 readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
29}
30
31export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
32 "t3/desktop/electron/Dialog",
33) {}
34
35const make = ElectronDialog.of({
36 pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
37 const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
38 onNone: () => ({
39 properties: ["openDirectory", "createDirectory"],
40 }),
41 onSome: (defaultPath) => ({
42 properties: ["openDirectory", "createDirectory"],
43 defaultPath,
44 }),
45 });
46 const result = yield* Option.match(input.owner, {
47 onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
48 onSome: (owner) =>
49 Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
50 });
51
52 if (result.canceled) {
53 return Option.none();
54 }
55 return Option.fromNullishOr(result.filePaths[0]);
56 }),
57 confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
58 const normalizedMessage = input.message.trim();
59 if (normalizedMessage.length === 0) {
60 return false;
61 }
62
63 const options = {
64 type: "question" as const,
65 buttons: ["No", "Yes"],
66 defaultId: 0,
67 cancelId: 0,
68 noLink: true,
69 message: normalizedMessage,
70 };
71 const result = yield* Option.match(input.owner, {
72 onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
73 onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
74 });
75 return result.response === CONFIRM_BUTTON_INDEX;
76 }),
77 showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
78 showErrorBox: (title, content) =>
79 Effect.sync(() => {
80 Electron.dialog.showErrorBox(title, content);
81 }),
82});
83
84export const layer = Layer.succeed(ElectronDialog, make);