-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
245 lines (225 loc) · 7.23 KB
/
Copy pathmain.js
File metadata and controls
245 lines (225 loc) · 7.23 KB
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
import { app, BrowserWindow, ipcMain, Menu, Notification } from 'electron';
import { fileURLToPath } from 'url';
import path from 'path';
import fs from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let mainWindow = null;
// ─── Paths ───────────────────────────────────────────────────────────────────────
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
const userDataPath = app.getPath('userData');
const tasksFilePath = path.join(userDataPath, 'tasks.json');
// ─── Persistence helpers ─────────────────────────────────────────────────────────
function loadTasksFromDisk() {
try {
console.log(`[Main] Loading tasks from: ${tasksFilePath}`);
if (fs.existsSync(tasksFilePath)) {
const raw = fs.readFileSync(tasksFilePath, 'utf-8');
const tasks = JSON.parse(raw);
console.log(`[Main] Loaded ${tasks.length} tasks from disk`);
return tasks;
} else {
console.log('[Main] No tasks file found, returning empty array');
}
} catch (err) {
console.error('[Main] Failed to load tasks:', err);
}
return [];
}
function saveTasksToDisk(tasks) {
try {
console.log(`[Main] Saving ${tasks.length} tasks to: ${tasksFilePath}`);
const dir = path.dirname(tasksFilePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
console.log(`[Main] Created directory: ${dir}`);
}
fs.writeFileSync(tasksFilePath, JSON.stringify(tasks, null, 2), 'utf-8');
console.log('[Main] Tasks saved successfully');
} catch (err) {
console.error('[Main] Failed to save tasks:', err);
}
}
// ─── Application menu ────────────────────────────────────────────────────────────
function buildAppMenu() {
const template = [
{
label: 'File',
submenu: [
{
label: 'New Task',
accelerator: 'CmdOrCtrl+N',
click: () => {
if (mainWindow) mainWindow.webContents.send('new-task');
},
},
{
label: 'Clear All Tasks',
accelerator: 'CmdOrCtrl+Shift+C',
click: () => {
if (mainWindow) mainWindow.webContents.send('clear-tasks');
},
},
{ type: 'separator' },
{ role: 'quit' },
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectAll' },
],
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
{
label: 'Window',
submenu: [
{ role: 'minimize' },
{ role: 'close' },
],
},
{
label: 'Help',
submenu: [
{
label: 'About ToDoList',
click: () => {
if (mainWindow) {
const { dialog } = require('electron');
dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'About ToDoList',
message: 'ToDoList Electron App',
detail: `Version: ${app.getVersion()}\nBuilt with Electron + React + Vite`,
});
}
},
},
],
},
];
// On macOS, add the app-name menu
if (process.platform === 'darwin') {
template.unshift({
label: app.getName(),
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
});
}
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// ─── Create main window ──────────────────────────────────────────────────────────
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 700,
minWidth: 400,
minHeight: 500,
title: 'To Do List',
show: false, // Show when ready to prevent flash
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true, // Security: isolate renderer
nodeIntegration: false, // Security: no Node in renderer
sandbox: false, // Required for preload to use Node APIs
},
});
// Load the app
if (isDev) {
// In development, load from Vite dev server
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
// In production, load from built dist
const distPath = path.join(__dirname, 'dist', 'index.html');
mainWindow.loadFile(distPath);
}
// Show window when ready to avoid white flash
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// ─── IPC Handlers ────────────────────────────────────────────────────────────────
function registerIpcHandlers() {
// Load tasks from disk
ipcMain.handle('load-tasks', () => {
return loadTasksFromDisk();
});
// Save tasks to disk
ipcMain.handle('save-tasks', (_event, tasks) => {
saveTasksToDisk(tasks);
return true;
});
// Get app version
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
// Show native notification
ipcMain.on('show-notification', (_event, title, body) => {
if (Notification.isSupported()) {
new Notification({ title, body }).show();
}
});
}
// ─── App lifecycle ───────────────────────────────────────────────────────────────
app.whenReady().then(() => {
buildAppMenu();
registerIpcHandlers();
createWindow();
// macOS: re-create window when dock icon is clicked
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// Quit when all windows are closed (except on macOS)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Prevent multiple instances
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}