Refactor typescript code

This commit is contained in:
Vishwas Shashidhar 2018-10-26 17:09:51 +05:30 committed by Kiran Niranjan
parent 7fcc6aadb3
commit 6c33d92806
16 changed files with 40 additions and 223 deletions

View File

@ -11,7 +11,7 @@
"scripts": {
"tsc": "git clean -xdf ./lib && npm run lint && tsc",
"lint": "tslint --project tsconfig.json",
"start": "npm run tsc && electron .",
"start": "npm run tsc && cross-env ELECTRON_DEV=true electron .",
"prebuild": "npm run rebuild && npm run browserify-preload",
"browserify-preload": "browserify -o js/preload/_preloadMain.js -x electron --insert-global-vars=__filename,__dirname js/preload/preloadMain.js --exclude electron-spellchecker",
"rebuild": "electron-rebuild -f",

View File

@ -1,6 +1,6 @@
import AutoLaunch = require('auto-launch');
import { isMac } from '../common/mics';
import { isMac } from '../common/env';
import { config, IConfig } from './config-handler';
const { autoLaunchPath }: IConfig = config.getGlobalConfigFields([ 'autoLaunchPath' ]);

View File

@ -1,7 +1,7 @@
import { app } from 'electron';
import getCmdLineArg from '../common/get-command-line-args';
import { isDevEnv } from '../common/mics';
import { isDevEnv } from '../common/env';
import { getCommandLineArgs } from '../common/utils';
import { config, IConfig } from './config-handler';
export default function setChromeFlags() {
@ -26,7 +26,7 @@ export default function setChromeFlags() {
}
if (isDevEnv) {
const chromeFlagsFromCmd = getCmdLineArg(process.argv, '--chrome-flags=', false);
const chromeFlagsFromCmd = getCommandLineArgs(process.argv, '--chrome-flags=', false);
if (!chromeFlagsFromCmd) {
return;
}
@ -56,7 +56,6 @@ export default function setChromeFlags() {
if (flagArray && Array.isArray(flagArray) && flagArray.length > 0) {
const chromeFlagKey = flagArray[0];
const chromeFlagValue = flagArray[1];
// log.send(logLevels.INFO, `Setting chrome flag ${chromeFlagKey} to ${chromeFlagValue}`);
app.commandLine.appendSwitch(chromeFlagKey, chromeFlagValue);
}
}

View File

@ -3,10 +3,9 @@ import * as fs from 'fs';
import * as path from 'path';
import { omit } from 'lodash';
import compareSemVersions from '../common/compare-sem-versions';
import { isDevEnv, isMac } from '../common/env';
import { logger } from '../common/logger';
import { isDevEnv, isMac } from '../common/mics';
import pick from '../common/pick';
import { compareVersions, pick } from '../common/utils';
const ignoreSettings = [
'minimizeOnClose',
@ -195,7 +194,7 @@ class Config {
if (!(userConfigVersion
&& typeof userConfigVersion === 'string'
&& (compareSemVersions(appVersionString, userConfigVersion) !== 1)) && shouldUpdateUserConfig) {
&& (compareVersions(appVersionString, userConfigVersion) !== 1)) && shouldUpdateUserConfig) {
this.isFirstTime = true;
return;
}

View File

@ -1,16 +1,16 @@
import { app } from 'electron';
import getCmdLineArg from '../common/get-command-line-args';
import { isDevEnv } from '../common/env';
import { logger } from '../common/logger';
import { isDevEnv } from '../common/mics';
import {getCommandLineArgs} from '../common/utils';
import { cleanUpAppCache, createAppCacheFile } from './app-cache-handler';
import { autoLaunchInstance } from './auto-launch-controller';
import setChromeFlags from './chrome-flags';
import { config } from './config-handler';
import { windowHandler } from './window-handler';
const allowMultiInstance: string | boolean = getCmdLineArg(process.argv, '--multiInstance', true) || isDevEnv;
const singleInstanceLock: boolean = allowMultiInstance ? false : app.requestSingleInstanceLock();
const allowMultiInstance: string | boolean = getCommandLineArgs(process.argv, '--multiInstance', true) || isDevEnv;
const singleInstanceLock: boolean = allowMultiInstance ? true : app.requestSingleInstanceLock();
if (!singleInstanceLock) {
app.quit();
@ -19,7 +19,7 @@ if (!singleInstanceLock) {
}
async function main() {
await appReady();
await app.whenReady();
createAppCacheFile();
windowHandler.showLoadingScreen();
windowHandler.createApplication();
@ -40,10 +40,6 @@ async function main() {
setChromeFlags();
}
async function appReady(): Promise<any> {
await new Promise((res) => app.once('ready', res));
}
/**
* Is triggered when all the windows are closed
* In which case we quit the app

View File

@ -2,8 +2,8 @@ import * as url from 'url';
// import log from '../logs';
// import { LogLevels } from '../logs/interface';
import getCmdLineArg from '../common/get-command-line-args';
import { isMac } from '../common/mics';
import { isMac } from '../common/env';
import { getCommandLineArgs } from '../common/utils';
import { windowHandler } from './window-handler';
let protocolWindow: Electron.WebContents;
@ -39,7 +39,7 @@ export function processProtocolArgv(argv: string[], isAppAlreadyOpen: boolean):
return;
}
const protocolUri = getCmdLineArg(argv, 'symphony://', false);
const protocolUri = getCommandLineArgs(argv, 'symphony://', false);
// log.send(LogLevels.INFO, `Trying to process a protocol action for uri ${protocolUri}`);
if (protocolUri) {

View File

@ -2,10 +2,11 @@ import { BrowserWindow, crashReporter } from 'electron';
import * as path from 'path';
import * as url from 'url';
import getCmdLineArg from '../common/get-command-line-args';
import { getCommandLineArgs } from '../common/utils';
import { config, IConfig } from './config-handler';
export class WindowHandler {
private static getMainWindowOpts() {
return {
alwaysOnTop: false,
@ -38,6 +39,16 @@ export class WindowHandler {
};
}
private static validateURL(configURL: string): string {
const parsedUrl = url.parse(configURL);
if (!parsedUrl.protocol || parsedUrl.protocol !== 'https') {
parsedUrl.protocol = 'https:';
parsedUrl.slashes = true;
}
return url.format(parsedUrl);
}
private readonly windowOpts: Electron.BrowserWindowConstructorOptions;
private readonly globalConfig: IConfig;
private mainWindow: Electron.BrowserWindow | null;
@ -60,8 +71,8 @@ export class WindowHandler {
public createApplication() {
this.mainWindow = new BrowserWindow(this.windowOpts);
const urlFromCmd = getCmdLineArg(process.argv, '--url=', false);
this.mainWindow.loadURL(urlFromCmd && urlFromCmd.substr(6) || this.validateURL(this.globalConfig.url));
const urlFromCmd = getCommandLineArgs(process.argv, '--url=', false);
this.mainWindow.loadURL(urlFromCmd && urlFromCmd.substr(6) || WindowHandler.validateURL(this.globalConfig.url));
this.mainWindow.webContents.on('did-finish-load', () => {
if (this.loadingWindow) {
this.loadingWindow.destroy();
@ -76,16 +87,6 @@ export class WindowHandler {
return this.mainWindow;
}
public validateURL(configURL: string): string {
const parsedUrl = url.parse(configURL);
if (!parsedUrl.protocol || parsedUrl.protocol !== 'https') {
parsedUrl.protocol = 'https:';
parsedUrl.slashes = true;
}
return url.format(parsedUrl);
}
/**
* Displays a loading window until the main
* application is loaded

View File

@ -1,81 +0,0 @@
// regex match the semver (semantic version) this checks for the pattern X.Y.Z
// ex-valid v1.2.0, 1.2.0, 2.3.4-r51
const semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(?:-[\da-z-]+(?:\.[\da-z-]+)*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?)?)?$/i;
const patch = /-([0-9A-Za-z-.]+)/;
/**
* This function splits the versions
* into major, minor and patch
* @param v
* @returns {String[]}
*/
function split(v: string): string[] {
const temp = v.replace(/^v/, '').split('.');
const arr = temp.splice(0, 2);
arr.push(temp.join('.'));
return arr;
}
function tryParse(v: string): string | number {
return Number.isNaN(Number(v)) ? v : Number(v);
}
/**
* This validates the version
* with the semver regex and returns
* -1 if not valid else 1
* @param version
* @returns {number}
*/
function validate(version: string): number {
if (!semver.test(version)) {
return -1;
}
return 1;
}
/**
* This function compares the v1 version
* with the v2 version for all major, minor, patch
* if v1 > v2 returns 1
* if v1 < v2 returns -1
* if v1 = v2 returns 0
* @param v1
* @param v2
* @returns {number}
*/
export default function check(v1: string, v2: string): number {
if (validate(v1) === -1 || validate(v2) === -1) {
return -1;
}
const s1 = split(v1);
const s2 = split(v2);
for (let i = 0; i < 3; i++) {
const n1 = parseInt(s1[i] || '0', 10);
const n2 = parseInt(s2[i] || '0', 10);
if (n1 > n2) return 1;
if (n2 > n1) return -1;
}
if ([ s1[2], s2[2] ].every(patch.test.bind(patch))) {
// @ts-ignore
const p1 = patch.exec(s1[2])[1].split('.').map(tryParse);
// @ts-ignore
const p2 = patch.exec(s2[2])[1].split('.').map(tryParse);
for (let k = 0; k < Math.max(p1.length, p2.length); k++) {
if (p1[k] === undefined || typeof p2[k] === 'string' && typeof p1[k] === 'number') return -1;
if (p2[k] === undefined || typeof p1[k] === 'string' && typeof p2[k] === 'number') return 1;
if (p1[k] > p2[k]) return 1;
if (p2[k] > p1[k]) return -1;
}
} else if ([ s1[2], s2[2] ].some(patch.test.bind(patch))) {
return patch.test(s1[2]) ? -1 : 1;
}
return 0;
}

View File

@ -1,25 +0,0 @@
/**
* Search given argv for argName using exact match or starts with. Comparison is case insensitive
* @param {Array} argv Array of strings
* @param {String} argName Arg name to search for.
* @param {Boolean} exactMatch If true then look for exact match otherwise
* try finding arg that starts with argName.
* @return {String} If found, returns the arg, otherwise null.
*/
export default function getCmdLineArg(argv: string[], argName: string, exactMatch: boolean): string | null {
if (!Array.isArray(argv)) {
throw new Error(`get-command-line-args: TypeError invalid func arg, must be an array: ${argv}`);
}
const argNameToFind = argName.toLocaleLowerCase();
for (let i = 0, len = argv.length; i < len; i++) {
const arg = argv[i].toLocaleLowerCase();
if ((exactMatch && arg === argNameToFind) ||
(!exactMatch && arg.startsWith(argNameToFind))) {
return argv[i];
}
}
return null;
}

View File

@ -1,14 +0,0 @@
/**
* Generates a guid,
* http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*
* @return {String} guid value in string
*/
export default function getGuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
(c) => {
const r = Math.random() * 16 | 0; // tslint:disable-line:no-bitwise
const v = c === 'x' ? r : (r & 0x3 | 0x8); // tslint:disable-line:no-bitwise
return v.toString(16);
});
}

View File

@ -2,9 +2,9 @@ import { app } from 'electron';
import electronLog, { LogLevel, transports } from 'electron-log';
import * as path from 'path';
import getCmdLineArg from './get-command-line-args';
import { isElectronQA } from './mics';
import stringFormat from './string-format';
import { isElectronQA } from './env';
import { getCommandLineArgs } from './utils';
import { formatString } from './utils';
interface ILogMsg {
level: LogLevel;
@ -28,8 +28,10 @@ export class Logger {
private loggerWindow: Electron.WebContents | null;
constructor() {
this.loggerWindow = null;
this.logQueue = [];
if (!isElectronQA) {
transports.file.file = path.join(app.getPath('logs'), 'app.log');
transports.file.level = 'debug';
@ -38,7 +40,7 @@ export class Logger {
transports.file.appName = 'Symphony';
}
const logLevel = getCmdLineArg(process.argv, '--logLevel=', false);
const logLevel = getCommandLineArgs(process.argv, '--logLevel=', false);
if (logLevel) {
const level = logLevel.split('=')[1];
if (level) {
@ -46,7 +48,7 @@ export class Logger {
}
}
if (getCmdLineArg(process.argv, '--enableConsoleLogging', false)) {
if (getCommandLineArgs(process.argv, '--enableConsoleLogging', false)) {
this.showInConsole = true;
}
}
@ -87,7 +89,7 @@ export class Logger {
}
private log(logLevel: LogLevel, message: string, data?: object): void {
message = stringFormat(message, data);
message = formatString(message, data);
if (!isElectronQA) {
switch (logLevel) {
case 'error': electronLog.error(message); break;

View File

@ -1,9 +0,0 @@
export default function pick(object: object, fields: string[]) {
const obj = {};
for (const field of fields) {
if (object[field]) {
obj[field] = object[field];
}
}
return obj;
}

View File

@ -1,30 +0,0 @@
/**
* Injects content into string
* @param str {String}
* @param data {Object} - content to replace
*
* @example
* StringFormat(this will log {time}`, { time: '1234' })
*
* result:
* this will log 1234
*
* @return {*}
*/
export default function StringFormat(str: string, data?: object): string {
if (!str || !data) return str;
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
return str.replace(/({([^}]+)})/g, (i) => {
const replacedKey = i.replace(/{/, '').replace(/}/, '');
if (!data[replacedKey]) {
return i;
}
return data[replacedKey];
});
}
}
return str;
}

View File

@ -1,22 +0,0 @@
/**
* limits your function to be called at most every milliseconds
*
* @param func
* @param wait
* @example const throttled = throttle(anyFunc, 500);
*/
export default function throttle(func: () => void, wait: number): () => void {
if (wait <= 0) {
throw Error('throttle: invalid throttleTime arg, must be a number: ' + wait);
}
let isCalled: boolean = false;
return (...args) => {
if (!isCalled) {
func(...args);
isCalled = true;
setTimeout(() => isCalled = false, wait);
}
};
}

View File

@ -61,6 +61,7 @@
"check-decl",
"check-operator",
"check-type"
]
],
"completed-docs": [true, "functions", "methods"]
}
}