const { app, BrowserWindow, dialog, ipcMain, shell } = require('electron'); const path = require('path'); const url = require('url'); const { initialStorageEvents, storage } = require('./storage'); let mainWindow; function createWindow() { //创建窗口 mainWindow = new BrowserWindow({ height: 900, webPreferences: { preload: path.join(__dirname, 'preload.js'), webSecurity: false, nodeIntegration: true, }, backgroundColor: '#2e2c29', darkTheme: true, title: 'Locking', width: 1700, frame: false, minWidth: 1300, minHeight: 900, }); // 隐藏菜单栏 mainWindow.setMenuBarVisibility(false); if (process.env.NODE_ENV === 'development') { // 开发环境 // 加载页面并打开调试工具,根据 NODE_ENV // umijs 在dev时会给出相应的url,直接加载即可 mainWindow.loadURL('http://localhost:8000/'); mainWindow.webContents.openDevTools(); } else { //生产环境 // 加载html文件 // 这里的路径是umi输出的html路径,如果没有修改过,路径和下面是一样的 mainWindow.webContents.openDevTools(); // mainWindow.loadFile(path.join(__dirname, '../dist/index.html')); mainWindow.loadURL( url.format({ pathname: path.join(__dirname, '../dist/index.html'), protocol: 'file:', slashes: true, }), ); } // 加载初始localStorage数据 mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.send('initialStorageData', storage.getAllItem()); }); mainWindow.on('closed', () => { mainWindow = null; }); } // 监听必要的自定义事件 ipcMain.handle('manipulate-window', (event, { action }) => { // console.log('manipulate-window', event, action); const iWindow = BrowserWindow.fromId(event.frameId); if (!iWindow) { return; } if (action === 'close') { // 关闭窗口 iWindow.close(); } if (action === 'zoom') { // 最大化/恢复窗口 if (iWindow.isMaximized()) { iWindow.unmaximize(); } else { iWindow.maximize(); } } if (action === 'minimize') { // 最小化窗口 iWindow.minimize(); } }); // 选择文件夹 ipcMain.handle('project-choose-folders', async (event, args) => { const res = await dialog.showOpenDialog({ properties: ['multiSelections', 'openDirectory'], }); return res; }); // 打开浏览器 ipcMain.handle('open-browser', (event, url) => { shell.openExternal(url); }); // 初始化electron-store相关API initialStorageEvents(ipcMain); app.on('ready', () => { createWindow(); app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });