~dricottone/noticable

noticable/main.js -rw-r--r-- 10.3 KiB
3ec618a6Dominic Ricottone Flatten if/else blocks into one-liners 2 years ago
                                                                                
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
////////////////////////////
// Global state goes here //
////////////////////////////

const { app, BrowserWindow, ipcMain, dialog, shell, Menu } = require("electron");
const path = require("path");
const os = require("os");
var win;

const dirNotes = path.join(os.homedir(), "notes");

const filePreload = path.join(__dirname, "preload.js");
const fileIndex = path.join(__dirname, "index.html");

const urlProject = "https://github.com/dricottone/noticable";
const urlBugTracker = "https://github.com/dricottone/noticable/issues";

// Options for prompt to discard or save changes.
const optionsDiscard = {
  message: "You have made changes in the editor. Do you want to discard those changes, or save to a file?",
  buttons: ["&Discard", "&Save", "Save &As..."],
  type: "question",
  normalizeAccessKeys: true,
};

// Options for error message that saving failed.
const optionsReSaveAs = {
  message: "File could not be saved.",
  buttons: ["&Cancel", "&Try Again"],
  type: "error",
  normalizeAccessKeys: true,
};

// Options for prompt to save a file.
const optionsSaveAs = {
  title: "Create new note",
  defaultPath: dirNotes,
  properties: ["showOverwriteConfirmation"],
  filters: [
    { name: "Markdown", extensions: ["md"] },
    { name: "Plain Text", extensions: ["txt"] },
  ],
};


///////////////////////
// Functions go here //
///////////////////////

// Push filenames to be relative to the notes directory.
function relativeNotePath(filename) {
  return path.relative(dirNotes, filename);
}

// Prompt to save a file.
function promptSave() {
  dialog.showSaveDialog(win, optionsSaveAs)
  .then(r => {
    if (r.canceled) announceFileNotSaved();
    else preloadSaveFile(relativeNotePath(r.filePath));
  });
};

// Prompt to save a file after already attempting to do so.
function rePromptSave() {
  dialog.showMessageBox(win, optionsSaveError)
  .then(r => {
    if (r.response==0) announceFileNotSaved();
    else {
      dialog.showSaveDialog(win, optionsSaveAs)
      .then(r => {
        if (r.canceled) announceFileNotSaved();
        else preloadReSaveFile(relativeNotePath(r.filePath));
      });
    }
  });
};

// Prompt to save a file then open a new file. Discard the file if the prompt
// is cancelled.
function promptSaveDiscardableThenNew() {
  dialog.showMessageBox(win, optionsDiscard)
  .then(r => {
    if (r.response==0) announceFileDiscardedForNewFile();
    else if (r.response==1) preloadTrySaveFileThenNewFile();
    else {
      dialog.showSaveDialog(win, optionsSaveAs)
      .then(r => {
        if (r.canceled) announceFileDiscardedForNewFile();
        else preloadSaveFileThenNewFile(relativeNotePath(r.filePath));
      });
    }
  });
};

// Prompt to save a file then read a file. Discard the file if the prompt is
// cancelled.
function promptSaveDiscardableThenRead(filename) {
  dialog.showMessageBox(win, optionsDiscard)
  .then(r => {
    if (r.response==0) announceFileDiscardedForReadFile(filename);
    else if (r.response==1) preloadTrySaveFileThenReadFile(filename);
    else {
      dialog.showSaveDialog(win, optionsSaveAs)
      .then(r => {
        if (r.canceled) announceFileDiscardedForReadFile(filename);
        else preloadSaveFileThenReadFile(relativeNotePath(r.filePath), filename);
      });
    }
  });
};

// Prompt to save a file after already attempting to do so. Discard the file if
// the prompt is cancelled.
function rePromptSaveDiscardableThenNew() {
  dialog.showMessageBox(win, optionsSaveError)
  .then(r => {
    if (r.response==0) announceFileDiscardedForNewFile();
    else {
      dialog.showSaveDialog(win, optionsSaveAs)
      .then(r => {
        if (r.canceled) announceFileDiscardedForNewFile();
        else preloadReSaveFileThenNewFile(relativeNotePath(r.filePath));
      });
    }
  });
};

// Ask preload to save a file.
function preloadSaveFile(filename) {
  win.webContents.send("saveFile", filename);
};

// Ask preload to *try* to save a file.
// NOTE: We don't know if preload has a cached file name. There is no real
//       advantage to querying this first. Same number of IPC calls in worst
//       case (i.e. no known file name) and excessive calls in best case.
function preloadTrySaveFile() {
  win.webContents.send("trySaveFile", "");
};

// Ask preload to save a file.
// NOTE: Triggers different logic. Preload skips querying the renderer for the
//       note (because this is a *re*-save).
function preloadReSaveFile(filename) {
  win.webContents.send("reSaveFile", filename);
};

// Ask preload to save a file then show a new file.
function preloadSaveFileThenNewFile(filename) {
  win.webContents.send("saveFileThenNewFile", filename);
};

// Ask preload to *try* to save a file then show a new file.
// NOTE: We don't know if preload has a cached file name. There is no real
//       advantage to querying this first. Same number of IPC calls in worst
//       case (i.e. no known file name) and excessive calls in best case.
function preloadTrySaveFileThenNewFile() {
  win.webContents.send("trySaveFileThenNewFile", "");
};

// Ask preload to save a file then show a new file.
// NOTE: Triggers different logic. Preload skips querying the renderer for the
//       note (because this is a *re*-save).
function preloadReSaveFileThenNewFile(toSaveFilename, toReadFilename) {
  win.webContents.send("reSaveFileThenNewFile", { toSave: toSaveFilename, toRead: toReadFilename });
};

// Ask preload to save a file then read another file.
function preloadSaveFileThenReadFile(toSaveFilename, toReadFilename) {
  win.webContents.send("saveFileThenReadFile", { toSave: toSaveFilename, toRead: toReadFilename });
};

// Ask preload to *try* to save a file then read another file.
// NOTE: We don't know if preload has a cached file name. There is no real
//       advantage to querying this first. Same number of IPC calls in worst
//       case (i.e. no known file name) and excessive calls in best case.
function preloadTrySaveFileThenReadFile(filename) {
  win.webContents.send("trySaveFileThenReadFile", filename);
};

// Announce that a file was not saved.
function announceFileNotSaved() {
  win.webContents.send("fileNotSaved", "");
};

// Announce that a file was not saved and changes should be discarded for a new
// file.
function announceFileDiscardedForNewFile() {
  win.webContents.send("fileDiscardedForNewFile", "");
};

// Announce that a file was not saved and changes should be discarded for
// another file to be read.
function announceFileDiscardedForReadFile(filename) {
  win.webContents.send("fileDiscardedForReadFile", filename);
};

// Ask renderer to sent editor content to be checked against the cached content
// then reset the editor.
function preloadRendererSendContentForCheckThenNew() {
  win.webContents.send("rendererSendContentForCheckThenNew", "");
};

// Ask renderer to send content for rendering.
function preloadRendererSendContentForRender() {
  win.webContents.send("rendererSendContentForRender", "");
};

// Ask renderer to show the editor.
function preloadRendererShowEditor() {
  win.webContents.send("rendererShowEditor", "");
};

// Ask renderer to send content for rendering and show the viewer.
function preloadRendererShowViewer() {
  preloadRendererSendContentForRender();
  win.webContents.send("rendererShowViewer", "");
};


//////////////////////////////
// Electron magic goes here //
//////////////////////////////

const template = [
  {
    label: "File",
    submenu: [
      {
        label: "Save",
        accelerator: "CmdOrCtrl+S",
        click: preloadTrySaveFile,
      },
      {
        label: "Save As...",
        accelerator: "CmdOrCtrl+Shift+S",
        click: () => {
          promptSave(win);
        }
      },
      {
        label: "Render Note",
        accelerator: "CmdOrCtrl+R",
        click: preloadRendererSendContentForRender,
      },
      {
        label: "New",
        accelerator: "CmdOrCtrl+N",
        click: preloadRendererSendContentForCheckThenNew,
      },
      { type: "separator" },
      {
        label: "Show Notes Directory",
        click: async () => {
          await shell.openPath(dirNotes);
        }
      },
      { type: "separator" },
      { role: "quit" }
    ]
  },
  {
    label: "Edit",
    submenu: [
      { role: "undo" },
      { role: "redo" },
      { type: "separator" },
      { role: "cut" },
      { role: "copy" },
      { role: "paste" },
      { role: "delete" },
      { type: "separator" },
      { role: "selectAll" }
    ]
  },
  {
    label: "View",
    submenu: [
      {
        label: "Show Editor",
        accelerator: "CmdOrCtrl+E",
        click: preloadRendererShowEditor,
      },
      {
        label: "Show Viewer",
        accelerator: "CmdOrCtrl+Shift+E",
        click: preloadRendererShowViewer,
      },
      { type: "separator" },
      // NOTE: I believe these should not be enabled in a production build
      // { role: "reload" },
      // { role: "forceReload" },
      // { role: "toggleDevTools" },
      // { type: "separator" },
      { role: "resetZoom" },
      { role: "zoomIn" },
      { role: "zoomOut" },
      { type: "separator" },
      { role: "togglefullscreen" },
    ]
  },
  {
    label: "Window",
    submenu: [
      { role: "minimize" }
    ]
  },
  {
    label: "Help",
    submenu: [
      {
        label: "About",
        click: async () => {
          await shell.openExternal(urlProject);
        }
      },
      {
        label: "Report Bugs",
        click: async () => {
          await shell.openExternal(urlBugTracker);
        }
      }
    ]
  }
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));

function initializeWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: filePreload,
    }
  });
  win.loadFile(fileIndex);

  ////////////////////////////
  // Listen for events here //
  ////////////////////////////
  ipcMain.on("promptSave", promptSave);
  ipcMain.on("promptSaveDiscardableThenNew", promptSaveDiscardableThenNew);
  ipcMain.on("promptSaveDiscardableThenRead", (_, filename) => promptSaveDiscardableThenRead(filename));
  ipcMain.on("rePromptSave", rePromptSave);
  //ipcMain.on("fileUnreadable", () => {});
  //ipcMain.on("fileUnunwritable", () => {});

  win.on("closed", () => {
    win = null;
  });
};

app.on("ready", initializeWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", () => {
  if (win === null) initializeWindow();
});