-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
104 lines (91 loc) · 2.78 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const { BrowserWindow, app, ipcMain, dialog, Notification, Menu } = require("electron");
const path = require('path');
const fs = require("fs");
let mainWindow;
let openedFilePath;
function createWindow() {
mainWindow = new BrowserWindow({
width: 900,
height: 700,
titleBarStyle: "hidden",
webPreferences: {
preload: path.join(app.getAppPath(), "renderer.js"),
sandbox: false
}
});
if (process.env.NODE_ENV==="development") {
mainWindow.webContents.openDevTools();
}
mainWindow.loadFile("index.html");
const menuTemplate = [{
label: "File",
submenu: [
{
label: "Add New File",
click: () => ipcMain.emit("open-document-triggered")
},
{
label: "Create New File",
click: () => ipcMain.emit("create-document-triggered")
}
],
},
{
role: "editMenu"
},
{
role: "quit"
}];
const menu = Menu.buildFromTemplate(menuTemplate);
mainWindow.setMenu(menu);
}
app.whenReady().then(createWindow);
function handleError() {
new Notification({
title: "Error",
body: "Sorry, something went wrong"
}).show();
}
ipcMain.on("create-document-triggered", () => {
dialog.showSaveDialog(mainWindow, {
filters: [{name: "text files", extensions: ["txt"]}]
}).then(({ filePath }) => {
console.log(":", filePath);
openedFilePath = filePath;
fs.writeFile(filePath, "", (error) => {
if (error) {
handleError();
} else {
app.addRecentDocument(filePath)
mainWindow.webContents.send("document-created", filePath);
}
});
});
});
ipcMain.on("open-document-triggered", () => {
dialog.showOpenDialog({
properties: ["openFile"],
filters: [{ name: "text files", extenstions: ["txt"]}]
}).then(({filePaths}) => {
const filePath = filePaths[0];
fs.readFile(filePath + "hehe", "utf-8", (error, content) => {
if (error) {
handleError();
} else {
app.addRecentDocument(filePath)
openedFilePath = filePath;
mainWindow.webContents.send("document-opened", { filePath, content});
}
});
});
});
ipcMain.on("save-document", (_, textAreaContent) => {
if (openedFilePath === undefined) { return; }
fs.writeFile(openedFilePath, textAreaContent, (error) => {
if (error) {
handleError();
} else {
console.log("saved");
}
});
});