Skip to content

Commit

Permalink
feat(app): 修改app主进程从 commonjs 改成 ts
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Jun 4, 2022
1 parent 45a2c22 commit 3e29f82
Show file tree
Hide file tree
Showing 21 changed files with 304 additions and 302 deletions.
27 changes: 15 additions & 12 deletions packages/app/index.js → packages/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
// @ts-check

const { app } = require('electron');
const { handleOpenFile } = require('./src/tasks/handle.file.open');
const { remoteRegister } = require('./src/tasks/remote.register');
const { initStore } = require('./src/tasks/init.store');
const { autoLaunch } = require('./src/tasks/auto.launch');
const { createWindow } = require('./src/main');
const { globalListenerRegister } = require('./src/tasks/global.listener');
const { task } = require('./src/utils');
const { handleError } = require('./src/tasks/error.handler');
const { updater } = require('./src/tasks/updater');
import { app } from 'electron';
import { handleOpenFile } from './src/tasks/handle.open';
import { remoteRegister } from './src/tasks/remote.register';
import { initStore } from './src/tasks/init.store';
import { autoLaunch } from './src/tasks/auto.launch';
import { createWindow } from './src/main';
import { globalListenerRegister } from './src/tasks/global.listener';
import { task } from './src/utils';
import { handleError } from './src/tasks/error.handler';
import { updater } from './src/tasks/updater';
import path from 'path';
import { startupServer } from './src/tasks/startup.server';

/** 获取单进程锁 */
const gotTheLock = app.requestSingleInstanceLock();
Expand All @@ -20,13 +22,14 @@ if (!gotTheLock) {
}

/** 启动渲染进程 */
function bootstrap () {
function bootstrap() {
task('OCS启动程序', () =>
Promise.all([
task('初始化错误处理', () => handleError()),
task('初始化本地设置', () => initStore()),
task('初始化自动启动', () => autoLaunch()),
task('处理打开文件', () => handleOpenFile(process.argv)),
task('启动接口服务', () => startupServer()),

task('启动渲染进程', async () => {
await app.whenReady();
Expand All @@ -37,7 +40,7 @@ function bootstrap () {
task('注册app事件监听器', () => globalListenerRegister(window));

if (app.isPackaged) {
await window.loadFile('public/index.html');
await window.loadFile(path.resolve('./public/index.html'));
} else {
await window.loadURL('http://localhost:3000');
}
Expand Down
64 changes: 0 additions & 64 deletions packages/app/src/logger.core.js

This file was deleted.

61 changes: 61 additions & 0 deletions packages/app/src/logger.core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// @ts-check
import { join, dirname } from 'path';
import { inspect } from 'util';
import { existsSync, mkdirSync, appendFileSync } from 'fs';

function formatDate() {
const date = new Date();
return [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, '0'),
date.getDate().toString().padStart(2, '0')
].join('-');
}

/**
* 日志对象
* ```js
* const l = new LoggerCore(app.getPath("logs"), true, 'test') // create `${logs}/YYYY-MM-DD/test.log`
* const l2 = new LoggerCore(app.getPath("logs"), true,'project','error','1') // create `${logs}/YYYY-MM-DD/project/error/1.log`
* ```
*/
export class LoggerCore {
basePath
withConsole
dest
constructor(basePath: string, withConsole = true, ...name: string[]) {
this.basePath = basePath;
this.withConsole = withConsole;
this.dest = join(this.basePath, '/', formatDate(), '/', name.join('/') + '.log');
}

log = (...msg: any[]) => this._log(this.dest, '信息', ...msg)
info = (...msg: any[]) => this._log(this.dest, '信息', ...msg)
error = (...msg: any[]) => this._log(this.dest, '错误', ...msg)
debug = (...msg: any[]) => this._log(this.dest, '调试', ...msg)
warn = (...msg: any[]) => this._log(this.dest, '警告', ...msg)

_log(dest: string, level: string, ...msg: string[]) {
const data = msg
.map((s) => {
if (typeof s === 'object' || typeof s === 'function') {
s = inspect(s);
}
return s;
})
.join(' ');
const txt = `[${level}] ${new Date().toLocaleString()} \t ` + data;

if (this.withConsole) {
console.log(txt);
}

return new Promise<void>((resolve) => {
if (!existsSync(dirname(dest))) {
mkdirSync(dirname(dest), { recursive: true });
}
appendFileSync(dest, txt + '\n');
resolve();
});
}
}
7 changes: 0 additions & 7 deletions packages/app/src/logger.js

This file was deleted.

7 changes: 7 additions & 0 deletions packages/app/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// @ts-check
import { LoggerCore } from './logger.core';
import { app } from 'electron';

export function Logger(...name: any[]) {
return new LoggerCore(app.getPath('logs'), true, ...name);
};
52 changes: 0 additions & 52 deletions packages/app/src/main.js

This file was deleted.

43 changes: 43 additions & 0 deletions packages/app/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// @ts-check
import { BrowserWindow, app, shell } from 'electron';
import path from 'path';

app.disableHardwareAcceleration();

export function createWindow() {
const win = new BrowserWindow({
title: 'ocs',
icon: path.resolve('./public/favicon.ico'),

minHeight: 500,
minWidth: 800,
center: true,
frame: false,
show: false,
backgroundColor: '#fff',
hasShadow: true,

webPreferences: {
// 关闭拼写矫正
spellcheck: false,
webSecurity: true,
// 开启node
nodeIntegration: true,
contextIsolation: false
}
});

win.on('new-window-for-tab', (event: any, url: any) => {
event.preventDefault();
shell.openExternal(url);
});

win.webContents.setWindowOpenHandler((detail) => {
shell.openExternal(detail.url);
return {
action: 'deny'
};
});

return win;
}
27 changes: 27 additions & 0 deletions packages/app/src/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { app } from 'electron';
import path from 'path';
import { getValidBrowsers } from '@ocsjs/common';
import { UserScripts } from '../types';

export const appStore = {
name: app.getName(),
version: app.getVersion(),
'user-data-path': app.getPath('userData'),
'exe-path': app.getPath('exe'),
'logs-path': app.getPath('logs'),
'config-path': path.resolve(app.getPath('userData'), './config.json'),
workspace: path.resolve(app.getPath('userData'), './workspace'),
'auto-launch': false,
alwaysOnTop: false,
notify: [] as any[],
/** 脚本启动设置 */
script: {} as any,
/** 脚本默认设置 */
setting: {
answererWrappers: []
},
/** 用户脚本列表 */
userScripts: [] as UserScripts[],
/** 可以浏览器 */
validBrowsers: getValidBrowsers()
};
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
const { app } = require('electron');
const Store = require('electron-store');
import { app } from 'electron';
import Store from 'electron-store';

/** 配置自动启动 */
function autoLaunch () {
export function autoLaunch() {
if (app.isPackaged) {
const store = new Store();
app.setLoginItemSettings({
openAtLogin: Boolean(store.get('auto-launch') || false)
});
}
}

exports.autoLaunch = autoLaunch;
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const { app } = require('electron');
const { Logger } = require('../logger');
import { app } from 'electron';
import { Logger } from '../logger';

/**
* 处理错误
*/
exports.handleError = function () {
export function handleError() {
const logger = Logger('error');

app.on('render-process-gone', (e, c, details) => {
Expand All @@ -22,4 +22,4 @@ exports.handleError = function () {
process.on('unhandledRejection', (e) => {
logger.error('unhandledRejection', e);
});
};
}
29 changes: 0 additions & 29 deletions packages/app/src/tasks/global.listener.js

This file was deleted.

Loading

0 comments on commit 3e29f82

Please sign in to comment.