From 6c33d9280634815735deb96a7b9000ea8a894c63 Mon Sep 17 00:00:00 2001 From: Vishwas Shashidhar Date: Fri, 26 Oct 2018 17:09:51 +0530 Subject: [PATCH] Refactor typescript code --- package.json | 2 +- src/browser/auto-launch-controller.ts | 2 +- src/browser/chrome-flags.ts | 7 +-- src/browser/config-handler.ts | 7 +-- src/browser/main.ts | 14 ++--- src/browser/protocol-handler.ts | 6 +- src/browser/window-handler.ts | 27 ++++----- src/common/compare-sem-versions.ts | 81 --------------------------- src/common/{mics.ts => env.ts} | 0 src/common/get-command-line-args.ts | 25 --------- src/common/get-guid.ts | 14 ----- src/common/logger.ts | 14 +++-- src/common/pick.ts | 9 --- src/common/string-format.ts | 30 ---------- src/common/throttle.ts | 22 -------- tslint.json | 3 +- 16 files changed, 40 insertions(+), 223 deletions(-) delete mode 100644 src/common/compare-sem-versions.ts rename src/common/{mics.ts => env.ts} (100%) delete mode 100644 src/common/get-command-line-args.ts delete mode 100644 src/common/get-guid.ts delete mode 100644 src/common/pick.ts delete mode 100644 src/common/string-format.ts delete mode 100644 src/common/throttle.ts diff --git a/package.json b/package.json index c7f72df9..730be7cc 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/browser/auto-launch-controller.ts b/src/browser/auto-launch-controller.ts index a9ea573d..be92e7f7 100644 --- a/src/browser/auto-launch-controller.ts +++ b/src/browser/auto-launch-controller.ts @@ -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' ]); diff --git a/src/browser/chrome-flags.ts b/src/browser/chrome-flags.ts index 09a75822..94740d86 100644 --- a/src/browser/chrome-flags.ts +++ b/src/browser/chrome-flags.ts @@ -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); } } diff --git a/src/browser/config-handler.ts b/src/browser/config-handler.ts index 00249699..dfcb8fe9 100644 --- a/src/browser/config-handler.ts +++ b/src/browser/config-handler.ts @@ -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; } diff --git a/src/browser/main.ts b/src/browser/main.ts index 5e56686d..e8f44d41 100644 --- a/src/browser/main.ts +++ b/src/browser/main.ts @@ -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 { - await new Promise((res) => app.once('ready', res)); -} - /** * Is triggered when all the windows are closed * In which case we quit the app diff --git a/src/browser/protocol-handler.ts b/src/browser/protocol-handler.ts index 98847225..b233a650 100644 --- a/src/browser/protocol-handler.ts +++ b/src/browser/protocol-handler.ts @@ -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) { diff --git a/src/browser/window-handler.ts b/src/browser/window-handler.ts index ae6ac7a2..ae95b27a 100644 --- a/src/browser/window-handler.ts +++ b/src/browser/window-handler.ts @@ -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 diff --git a/src/common/compare-sem-versions.ts b/src/common/compare-sem-versions.ts deleted file mode 100644 index 919fd7fd..00000000 --- a/src/common/compare-sem-versions.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/src/common/mics.ts b/src/common/env.ts similarity index 100% rename from src/common/mics.ts rename to src/common/env.ts diff --git a/src/common/get-command-line-args.ts b/src/common/get-command-line-args.ts deleted file mode 100644 index 1858fb27..00000000 --- a/src/common/get-command-line-args.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/src/common/get-guid.ts b/src/common/get-guid.ts deleted file mode 100644 index cdabaaba..00000000 --- a/src/common/get-guid.ts +++ /dev/null @@ -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); - }); -} \ No newline at end of file diff --git a/src/common/logger.ts b/src/common/logger.ts index c69013ea..28e8fd61 100644 --- a/src/common/logger.ts +++ b/src/common/logger.ts @@ -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; diff --git a/src/common/pick.ts b/src/common/pick.ts deleted file mode 100644 index 85f0fac4..00000000 --- a/src/common/pick.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/src/common/string-format.ts b/src/common/string-format.ts deleted file mode 100644 index 1a23d43b..00000000 --- a/src/common/string-format.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/src/common/throttle.ts b/src/common/throttle.ts deleted file mode 100644 index f6bd9029..00000000 --- a/src/common/throttle.ts +++ /dev/null @@ -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); - } - }; -} \ No newline at end of file diff --git a/tslint.json b/tslint.json index d2f4f61e..b4172b11 100644 --- a/tslint.json +++ b/tslint.json @@ -61,6 +61,7 @@ "check-decl", "check-operator", "check-type" - ] + ], + "completed-docs": [true, "functions", "methods"] } } \ No newline at end of file