From 2228e934764168ade13c9d5247e75399829cb38c Mon Sep 17 00:00:00 2001 From: Rodrigo Nascimento Date: Wed, 11 Jan 2017 12:20:54 -0200 Subject: [PATCH 1/3] Fix and configure ESLint --- .editorconfig | 2 +- .eslintignore | 6 + .eslintrc | 9 +- src/app.js | 12 +- src/background.custom.js | 208 ++++----- src/background.js | 10 +- src/background/certificate.js | 182 ++++---- src/background/servers.js | 28 +- src/background/windowState.js | 78 ++-- src/helpers/window.js | 2 +- src/menu/dev_menu_template.js | 4 +- src/public/preload.js | 606 ++++++++++++------------- src/scripts/menus.js | 808 +++++++++++++++++----------------- src/scripts/servers.js | 414 ++++++++--------- src/scripts/sidebar.js | 508 ++++++++++----------- src/scripts/start.js | 42 +- src/scripts/tray.js | 17 +- src/scripts/webview.js | 268 +++++------ 18 files changed, 1607 insertions(+), 1597 deletions(-) create mode 100644 .eslintignore diff --git a/.editorconfig b/.editorconfig index 23d04f8dd4e5..dbe95beaf7ee 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,7 +9,7 @@ trim_trailing_whitespace = true insert_final_newline = true [*.{js,coffee,html,less,json}] -indent_style = tab +indent_style = space [*.md] trim_trailing_whitespace = false diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000000..7b8fdd2a0872 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,6 @@ +node_modules +app +e2e +src/public/lib/bugsnag.js +src/public/vendor/jquery-1.12.0.js +scripts/istanbul-reporter.js diff --git a/.eslintrc b/.eslintrc index 182840c83c15..fbc2d7b4402d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -51,10 +51,9 @@ "no-trailing-spaces": 2, "complexity": [1, 31], "space-in-parens": [2, "never"], - "space-before-function-paren": [2, "never"], + "space-before-function-paren": [2, "always"], "space-before-blocks": [2, "always"], - "indent": [2, "tab", {"SwitchCase": 1}], - "comma-dangle": [2, "never"], + "indent": [2, 4, {"SwitchCase": 1}], "keyword-spacing": 2, "block-spacing": 2, "brace-style": [2, "1tbs", { "allowSingleLine": true }], @@ -72,10 +71,10 @@ "use-isnan": 2, "valid-typeof": 2, "linebreak-style": [2, "unix"], - "quotes": [2, "single"], "semi": [2, "always"] }, "globals": { - "_" : false + "_" : false, + "Bugsnag" : false } } diff --git a/src/app.js b/src/app.js index 769692c29fee..ba9b6a341327 100644 --- a/src/app.js +++ b/src/app.js @@ -4,12 +4,12 @@ import { remote } from 'electron'; var app = remote.app; Bugsnag.metaData = { - // platformId: app.process.platform, - // platformArch: app.process.arch, - // electronVersion: app.process.versions.electron, - version: app.getVersion() - // platformVersion: cordova.platformVersion - // build: appInfo.build + // platformId: app.process.platform, + // platformArch: app.process.arch, + // electronVersion: app.process.versions.electron, + version: app.getVersion() + // platformVersion: cordova.platformVersion + // build: appInfo.build }; Bugsnag.appVersion = app.getVersion(); diff --git a/src/background.custom.js b/src/background.custom.js index 8c6a0350fbf0..f937f87e5ff1 100644 --- a/src/background.custom.js +++ b/src/background.custom.js @@ -13,110 +13,110 @@ import idle from '@paulcbetts/system-idle-time'; process.env.GOOGLE_API_KEY = 'AIzaSyADqUh_c1Qhji3Cp1NE43YrcpuPkmhXD-c'; /* system idle time synchronous event process */ -ipcMain.on('getSystemIdleTime', function(event) { - /* why does this fire twice?!?!? */ - event.returnValue = idle.getIdleTime(); +ipcMain.on('getSystemIdleTime', function (event) { + /* why does this fire twice?!?!? */ + event.returnValue = idle.getIdleTime(); }); -export function afterMainWindow(mainWindow) { - if (process.platform !== 'darwin') { - var shouldQuit = app.makeSingleInstance(function() { - // Someone tried to run a second instance, we should focus our window. - if (mainWindow) { - mainWindow.show(); - mainWindow.focus(); - } - }); - - if (shouldQuit) { - app.quit(); - } - } - - // Preserver of the window size and position between app launches. - var mainWindowState = windowStateKeeper('main', { - width: 1000, - height: 600 - }); - - if (mainWindowState.x !== undefined && mainWindowState.y !== undefined) { - mainWindow.setPosition(mainWindowState.x, mainWindowState.y, false); - } - if (mainWindowState.width !== undefined && mainWindowState.height !== undefined) { - mainWindow.setSize(mainWindowState.width, mainWindowState.height, false); - } - mainWindow.setMinimumSize(600, 400); - - if (mainWindowState.isMaximized) { - mainWindow.maximize(); - } - - if (mainWindowState.isMinimized) { - mainWindow.minimize(); - } - - if (mainWindowState.isHidden) { - mainWindow.hide(); - } - - mainWindow.on('close', function (event) { - if (mainWindow.forceClose) { - mainWindowState.saveState(mainWindow); - return; - } - event.preventDefault(); - mainWindow.hide(); - mainWindowState.saveState(mainWindow); - }); - - app.on('before-quit', function() { - mainWindowState.saveState(mainWindow); - mainWindow.forceClose = true; - }); - - mainWindow.on('resize', function() { - mainWindowState.saveState(mainWindow); - }); - - mainWindow.on('move', function() { - mainWindowState.saveState(mainWindow); - }); - - app.on('activate', function(){ - mainWindow.show(); - }); - - mainWindow.webContents.on('will-navigate', function(event) { - event.preventDefault(); - }); - - // ==== Quick check to fetch Operating System and it's version ==>> - // Add here any OS without native support for notifications to Toaster is used - var useToaster = false; - - // Windows 7 or older - if (os.platform() === 'win32' || os.platform() === 'win64') { - if (parseFloat(os.release()) < 6.2) { - useToaster = true; - } - }; - - if (useToaster) { - const toaster = new Toaster(); - toaster.init(mainWindow); - - ipcMain.on('notification-shim', (e, msg) => { - mainWindow.webContents.executeJavaScript(` - require('electron').ipcRenderer.send('electron-toaster-message', { - title: '${msg.title}', - message: \`${msg.options.body}\`, - width: 400, - focus: false, - htmlFile: 'file://'+__dirname+'/notification.html?' - }); - `); - }); - }; - - certificate.initWindow(mainWindow); +export function afterMainWindow (mainWindow) { + if (process.platform !== 'darwin') { + var shouldQuit = app.makeSingleInstance(function () { + // Someone tried to run a second instance, we should focus our window. + if (mainWindow) { + mainWindow.show(); + mainWindow.focus(); + } + }); + + if (shouldQuit) { + app.quit(); + } + } + + // Preserver of the window size and position between app launches. + var mainWindowState = windowStateKeeper('main', { + width: 1000, + height: 600 + }); + + if (mainWindowState.x !== undefined && mainWindowState.y !== undefined) { + mainWindow.setPosition(mainWindowState.x, mainWindowState.y, false); + } + if (mainWindowState.width !== undefined && mainWindowState.height !== undefined) { + mainWindow.setSize(mainWindowState.width, mainWindowState.height, false); + } + mainWindow.setMinimumSize(600, 400); + + if (mainWindowState.isMaximized) { + mainWindow.maximize(); + } + + if (mainWindowState.isMinimized) { + mainWindow.minimize(); + } + + if (mainWindowState.isHidden) { + mainWindow.hide(); + } + + mainWindow.on('close', function (event) { + if (mainWindow.forceClose) { + mainWindowState.saveState(mainWindow); + return; + } + event.preventDefault(); + mainWindow.hide(); + mainWindowState.saveState(mainWindow); + }); + + app.on('before-quit', function () { + mainWindowState.saveState(mainWindow); + mainWindow.forceClose = true; + }); + + mainWindow.on('resize', function () { + mainWindowState.saveState(mainWindow); + }); + + mainWindow.on('move', function () { + mainWindowState.saveState(mainWindow); + }); + + app.on('activate', function () { + mainWindow.show(); + }); + + mainWindow.webContents.on('will-navigate', function (event) { + event.preventDefault(); + }); + + // ==== Quick check to fetch Operating System and it's version ==>> + // Add here any OS without native support for notifications to Toaster is used + var useToaster = false; + + // Windows 7 or older + if (os.platform() === 'win32' || os.platform() === 'win64') { + if (parseFloat(os.release()) < 6.2) { + useToaster = true; + } + } + + if (useToaster) { + const toaster = new Toaster(); + toaster.init(mainWindow); + + ipcMain.on('notification-shim', (e, msg) => { + mainWindow.webContents.executeJavaScript(` + require('electron').ipcRenderer.send('electron-toaster-message', { + title: '${msg.title}', + message: \`${msg.options.body}\`, + width: 400, + focus: false, + htmlFile: 'file://'+__dirname+'/notification.html?' + }); + `); + }); + } + + certificate.initWindow(mainWindow); } diff --git a/src/background.js b/src/background.js index 72e179563722..cd1638d0407d 100644 --- a/src/background.js +++ b/src/background.js @@ -9,18 +9,16 @@ import { app, Menu } from 'electron'; import { devMenuTemplate } from './menu/dev_menu_template'; import { editMenuTemplate } from './menu/edit_menu_template'; import createWindow from './helpers/window'; -import './background/certificate' +import './background/certificate'; -export { default as remoteServers } from './background/servers' -export { default as certificate } from './background/certificate' -import { afterMainWindow } from './background.custom' +export { default as remoteServers } from './background/servers'; +export { default as certificate } from './background/certificate'; +import { afterMainWindow } from './background.custom'; // Special module holding environment variables which you declared // in config/env_xxx.json file. import env from './env'; -var mainWindow; - var setApplicationMenu = function () { var menus = [editMenuTemplate]; if (env.name !== 'production') { diff --git a/src/background/certificate.js b/src/background/certificate.js index 4c45294557ef..1741127c8ca2 100644 --- a/src/background/certificate.js +++ b/src/background/certificate.js @@ -3,97 +3,97 @@ import jetpack from 'fs-jetpack'; import url from 'url'; class CertificateStore { - initWindow(win) { - this.storeFileName = 'certificate.json'; - this.userDataDir = jetpack.cwd(app.getPath('userData')); - - this.load(); - - this.window = win; - app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { - if (this.isTrusted(url, certificate)) { - event.preventDefault(); - callback(true); - return; - } - - var detail = `URL: ${url}\nError: ${error}`; - if (this.isExisting(url)) { - detail = `Certificate is different from previous one.\n\n` + detail; - } - - dialog.showMessageBox(this.window, { - title: 'Certificate error', - message: `Do you trust certificate from "${certificate.issuerName}"?`, - detail: detail, - type: 'warning', - buttons: [ - 'Yes', - 'No' - ], - cancelId: 1 - }, (response) => { - if (response === 0) { - this.add(url, certificate); - this.save(); - if (webContents.getURL().indexOf('file://') === 0) { - webContents.send('certificate-reload', url); - } else { - webContents.loadURL(url); - } - } - }); - callback(false); - }); - } - - load() { - try { - this.data = this.userDataDir.read(this.storeFileName, 'json'); - } catch (e) { - console.error(e); - this.data = {}; - } - - if (this.data === undefined) { - this.clear(); - } - } - - clear() { - this.data = {}; - this.save(); - } - - save() { - this.userDataDir.write(this.storeFileName, this.data, { atomic: true }); - } - - parseCertificate(certificate) { - return certificate.issuerName + '\n' + certificate.data.toString(); - } - - getHost(certUrl) { - return url.parse(certUrl).host; - } - - add(certUrl, certificate) { - const host = this.getHost(certUrl); - this.data[host] = this.parseCertificate(certificate); - } - - isExisting(certUrl) { - const host = this.getHost(certUrl); - return this.data.hasOwnProperty(host); - } - - isTrusted(certUrl, certificate) { - var host = this.getHost(certUrl); - if (!this.isExisting(certUrl)) { - return false; - } - return this.data[host] === this.parseCertificate(certificate); - } + initWindow (win) { + this.storeFileName = 'certificate.json'; + this.userDataDir = jetpack.cwd(app.getPath('userData')); + + this.load(); + + this.window = win; + app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { + if (this.isTrusted(url, certificate)) { + event.preventDefault(); + callback(true); + return; + } + + var detail = `URL: ${url}\nError: ${error}`; + if (this.isExisting(url)) { + detail = `Certificate is different from previous one.\n\n ${detail}`; + } + + dialog.showMessageBox(this.window, { + title: 'Certificate error', + message: `Do you trust certificate from "${certificate.issuerName}"?`, + detail: detail, + type: 'warning', + buttons: [ + 'Yes', + 'No' + ], + cancelId: 1 + }, (response) => { + if (response === 0) { + this.add(url, certificate); + this.save(); + if (webContents.getURL().indexOf('file://') === 0) { + webContents.send('certificate-reload', url); + } else { + webContents.loadURL(url); + } + } + }); + callback(false); + }); + } + + load () { + try { + this.data = this.userDataDir.read(this.storeFileName, 'json'); + } catch (e) { + console.error(e); + this.data = {}; + } + + if (this.data === undefined) { + this.clear(); + } + } + + clear () { + this.data = {}; + this.save(); + } + + save () { + this.userDataDir.write(this.storeFileName, this.data, { atomic: true }); + } + + parseCertificate (certificate) { + return certificate.issuerName + '\n' + certificate.data.toString(); + } + + getHost (certUrl) { + return url.parse(certUrl).host; + } + + add (certUrl, certificate) { + const host = this.getHost(certUrl); + this.data[host] = this.parseCertificate(certificate); + } + + isExisting (certUrl) { + const host = this.getHost(certUrl); + return this.data.hasOwnProperty(host); + } + + isTrusted (certUrl, certificate) { + var host = this.getHost(certUrl); + if (!this.isExisting(certUrl)) { + return false; + } + return this.data[host] === this.parseCertificate(certificate); + } } const certificateStore = new CertificateStore(); diff --git a/src/background/servers.js b/src/background/servers.js index e5e0d9efa830..66675a7b4c9a 100644 --- a/src/background/servers.js +++ b/src/background/servers.js @@ -3,21 +3,21 @@ import { app } from 'electron'; let servers = {}; export default { - loadServers(s) { - servers = s; - }, + loadServers (s) { + servers = s; + }, - getServers() { - return servers; - } + getServers () { + return servers; + } }; -app.on('login', function(event, webContents, request, authInfo, callback) { - for (let url in servers) { - const server = servers[url]; - if (request.url.indexOf(url) === 0 && server.username) { - callback(server.username, server.password); - break; - } - } +app.on('login', function (event, webContents, request, authInfo, callback) { + for (const url of Object.keys(servers)) { + const server = servers[url]; + if (request.url.indexOf(url) === 0 && server.username) { + callback(server.username, server.password); + break; + } + } }); diff --git a/src/background/windowState.js b/src/background/windowState.js index aec82ee5305c..f9b93b2fc735 100644 --- a/src/background/windowState.js +++ b/src/background/windowState.js @@ -7,46 +7,46 @@ import jetpack from 'fs-jetpack'; export default function (name, defaults) { - var userDataDir = jetpack.cwd(app.getPath('userData')); - var stateStoreFile = 'window-state-' + name +'.json'; - var state = { - width: defaults.width, - height: defaults.height - }; + var userDataDir = jetpack.cwd(app.getPath('userData')); + var stateStoreFile = 'window-state-' + name +'.json'; + var state = { + width: defaults.width, + height: defaults.height + }; - try { - var loadedState = userDataDir.read(stateStoreFile, 'json'); - if (loadedState != null) { - state = loadedState; - } - } catch (err) { - // For some reason json can't be read. - // No worries, we have defaults. - } + try { + var loadedState = userDataDir.read(stateStoreFile, 'json'); + if (loadedState != null) { + state = loadedState; + } + } catch (err) { + // For some reason json can't be read. + // No worries, we have defaults. + } - var saveState = function (win) { - if (!win.isMaximized() && !win.isMinimized() && win.isVisible()) { - var position = win.getPosition(); - var size = win.getSize(); - state.x = position[0]; - state.y = position[1]; - state.width = size[0]; - state.height = size[1]; - } - state.isMaximized = win.isMaximized(); - state.isMinimized = win.isMinimized(); - state.isHidden = !win.isMinimized() && !win.isVisible(); - userDataDir.write(stateStoreFile, state, { atomic: true }); - }; + var saveState = function (win) { + if (!win.isMaximized() && !win.isMinimized() && win.isVisible()) { + var position = win.getPosition(); + var size = win.getSize(); + state.x = position[0]; + state.y = position[1]; + state.width = size[0]; + state.height = size[1]; + } + state.isMaximized = win.isMaximized(); + state.isMinimized = win.isMinimized(); + state.isHidden = !win.isMinimized() && !win.isVisible(); + userDataDir.write(stateStoreFile, state, { atomic: true }); + }; - return { - get x() { return state.x; }, - get y() { return state.y; }, - get width() { return state.width; }, - get height() { return state.height; }, - get isMaximized() { return state.isMaximized; }, - get isMinimized() { return state.isMinimized; }, - get isHidden() { return state.isHidden; }, - saveState: saveState - }; + return { + get x () { return state.x; }, + get y () { return state.y; }, + get width () { return state.width; }, + get height () { return state.height; }, + get isMaximized () { return state.isMaximized; }, + get isMinimized () { return state.isMinimized; }, + get isHidden () { return state.isHidden; }, + saveState: saveState + }; } diff --git a/src/helpers/window.js b/src/helpers/window.js index befd29f879be..98885d0cc196 100644 --- a/src/helpers/window.js +++ b/src/helpers/window.js @@ -46,7 +46,7 @@ export default function (name, options) { windowState.y + windowState.height <= bounds.y + bounds.height; }; - var resetToDefaults = function (windowState) { + var resetToDefaults = function (/*windowState*/) { var bounds = screen.getPrimaryDisplay().bounds; return Object.assign({}, defaultSize, { x: (bounds.width - defaultSize.width) / 2, diff --git a/src/menu/dev_menu_template.js b/src/menu/dev_menu_template.js index 63f341620e65..b86d5fd7cb34 100644 --- a/src/menu/dev_menu_template.js +++ b/src/menu/dev_menu_template.js @@ -8,13 +8,13 @@ export var devMenuTemplate = { click: function () { BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache(); } - },{ + }, { label: 'Toggle DevTools', accelerator: 'Alt+CmdOrCtrl+I', click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } - },{ + }, { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function () { diff --git a/src/public/preload.js b/src/public/preload.js index d99689e6a7b9..147b23f337fe 100644 --- a/src/public/preload.js +++ b/src/public/preload.js @@ -1,4 +1,4 @@ -/* globals Meteor, Tracker, RocketChat, UserPresence */ +/* globals Meteor, Tracker, RocketChat */ 'use strict'; var IPC = require('electron').ipcRenderer; @@ -6,66 +6,66 @@ var IPC = require('electron').ipcRenderer; require('electron-notification-shim')(); class Notification extends window.Notification { - get onclick() { - return super.onclick; - } - - set onclick(fn) { - var result = super.onclick = () => { - IPC.sendToHost('focus'); - fn.apply(this, arguments); - }; - return result; - } + get onclick () { + return super.onclick; + } + + set onclick (fn) { + var result = super.onclick = () => { + IPC.sendToHost('focus'); + fn.apply(this, arguments); + }; + return result; + } } window.Notification = Notification; var events = ['unread-changed']; -events.forEach(function(e) { - window.addEventListener(e, function(event) { - IPC.sendToHost(e, event.detail); - }); +events.forEach(function (e) { + window.addEventListener(e, function (event) { + IPC.sendToHost(e, event.detail); + }); }); -window.addEventListener('load', function() { - Meteor.startup(function() { - Tracker.autorun(function() { - var siteName = RocketChat.settings.get('Site_Name'); - if (siteName) { - IPC.sendToHost('title-changed', siteName); - } - }); - }); +window.addEventListener('load', function () { + Meteor.startup(function () { + Tracker.autorun(function () { + var siteName = RocketChat.settings.get('Site_Name'); + if (siteName) { + IPC.sendToHost('title-changed', siteName); + } + }); + }); }); const {shell} = require('electron'); -var supportExternalLinks = function(e) { - var href; - var isExternal = false; - - var checkDomElement = function(element) { - if (element.nodeName === 'A') { - if (element.classList.contains('swipebox') === false) { - href = element.getAttribute('href') || ''; - } - } - - if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/ ) { - isExternal = true; - } - - if (href && isExternal) { - shell.openExternal(href); - e.preventDefault(); - } else if (element.parentElement) { - checkDomElement(element.parentElement); - } - }; - - checkDomElement(e.target); +var supportExternalLinks = function (e) { + var href; + var isExternal = false; + + var checkDomElement = function (element) { + if (element.nodeName === 'A') { + if (element.classList.contains('swipebox') === false) { + href = element.getAttribute('href') || ''; + } + } + + if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/) { + isExternal = true; + } + + if (href && isExternal) { + shell.openExternal(href); + e.preventDefault(); + } else if (element.parentElement) { + checkDomElement(element.parentElement); + } + }; + + checkDomElement(e.target); }; document.addEventListener('click', supportExternalLinks, false); @@ -80,36 +80,36 @@ var menu = new remote.Menu(); var path = remote.require('path'); // // set the initial context menu so that a context menu exists even before spellcheck is called -var getTemplate = function() { - return [ - { - label: 'Undo', - role: 'undo' - }, - { - label: 'Redo', - role: 'redo' - }, - { - type: 'separator' - }, - { - label: 'Cut', - role: 'cut' - }, - { - label: 'Copy', - role: 'copy' - }, - { - label: 'Paste', - role: 'paste' - }, - { - label: 'Select All', - role: 'selectall' - } - ]; +var getTemplate = function () { + return [ + { + label: 'Undo', + role: 'undo' + }, + { + label: 'Redo', + role: 'redo' + }, + { + type: 'separator' + }, + { + label: 'Cut', + role: 'cut' + }, + { + label: 'Copy', + role: 'copy' + }, + { + label: 'Paste', + role: 'paste' + }, + { + label: 'Select All', + role: 'selectall' + } + ]; }; let languagesMenu; @@ -119,245 +119,245 @@ let availableDictionaries = []; let dictionariesPath; if (localStorage.getItem('spellcheckerDictionaries')) { - let spellcheckerDictionaries = JSON.parse(localStorage.getItem('spellcheckerDictionaries')); - if (Array.isArray(spellcheckerDictionaries)) { - enabledDictionaries.push.apply(enabledDictionaries, spellcheckerDictionaries); - } + let spellcheckerDictionaries = JSON.parse(localStorage.getItem('spellcheckerDictionaries')); + if (Array.isArray(spellcheckerDictionaries)) { + enabledDictionaries.push.apply(enabledDictionaries, spellcheckerDictionaries); + } } -const saveEnabledDictionaries = function() { - localStorage.setItem('spellcheckerDictionaries', JSON.stringify(enabledDictionaries)); +const saveEnabledDictionaries = function () { + localStorage.setItem('spellcheckerDictionaries', JSON.stringify(enabledDictionaries)); }; -const isCorrect = function(text) { - if (!checker || enabledDictionaries.length === 0) { - return true; - } +const isCorrect = function (text) { + if (!checker || enabledDictionaries.length === 0) { + return true; + } - let isCorrect = false; - enabledDictionaries.forEach(function(enabledDictionary) { - if (availableDictionaries.indexOf(enabledDictionary) === -1) { - return; - } + let isCorrect = false; + enabledDictionaries.forEach(function (enabledDictionary) { + if (availableDictionaries.indexOf(enabledDictionary) === -1) { + return; + } - checker.setDictionary(enabledDictionary, dictionariesPath); - if (!checker.isMisspelled(text)) { - isCorrect = true; - } - }); + checker.setDictionary(enabledDictionary, dictionariesPath); + if (!checker.isMisspelled(text)) { + isCorrect = true; + } + }); - return isCorrect; + return isCorrect; }; -const getCorrections = function(text) { - // Create an array of arrays of corrections - // One array of corrections per language - let allCorrections = []; - enabledDictionaries.forEach(function(enabledDictionary) { - if (availableDictionaries.indexOf(enabledDictionary) === -1) { - return; - } - - checker.setDictionary(enabledDictionary, dictionariesPath); - const languageCorrections = checker.getCorrectionsForMisspelling(text); - if (languageCorrections.length > 0) { - allCorrections.push(languageCorrections); - } - }); - - // Get the size of biggest array - let length = 0; - allCorrections.forEach(function(items) { - length = Math.max(length, items.length); - }); - - // Merge all arrays until the size of the biggest array - // To get the best suggestions of each language first - // Ex: [[1,2,3], [a,b]] => [1,a,2,b,3] - const corrections = []; - for (let i = 0; i < length; i++) { - for (var j = 0; j < allCorrections.length; j++) { - if (allCorrections[j][i]) { - corrections.push(allCorrections[j][i]); - } - } - } - - // Remove duplicateds - corrections.forEach(function(item, index) { - const dupIndex = corrections.indexOf(item, index+1); - if (dupIndex > -1) { - corrections.splice(dupIndex, 1); - } - }); - - return corrections; +const getCorrections = function (text) { + // Create an array of arrays of corrections + // One array of corrections per language + let allCorrections = []; + enabledDictionaries.forEach(function (enabledDictionary) { + if (availableDictionaries.indexOf(enabledDictionary) === -1) { + return; + } + + checker.setDictionary(enabledDictionary, dictionariesPath); + const languageCorrections = checker.getCorrectionsForMisspelling(text); + if (languageCorrections.length > 0) { + allCorrections.push(languageCorrections); + } + }); + + // Get the size of biggest array + let length = 0; + allCorrections.forEach(function (items) { + length = Math.max(length, items.length); + }); + + // Merge all arrays until the size of the biggest array + // To get the best suggestions of each language first + // Ex: [[1,2,3], [a,b]] => [1,a,2,b,3] + const corrections = []; + for (let i = 0; i < length; i++) { + for (var j = 0; j < allCorrections.length; j++) { + if (allCorrections[j][i]) { + corrections.push(allCorrections[j][i]); + } + } + } + + // Remove duplicateds + corrections.forEach(function (item, index) { + const dupIndex = corrections.indexOf(item, index+1); + if (dupIndex > -1) { + corrections.splice(dupIndex, 1); + } + }); + + return corrections; }; try { - checker = require('spellchecker'); - - availableDictionaries = checker.getAvailableDictionaries(); - - if (availableDictionaries.length === 0) { - dictionariesPath = path.join(remote.app.getAppPath(), '../dictionaries'); - availableDictionaries = [ - 'en_US', - 'es_ES', - 'pt_BR' - ]; - } else { - for (var i = 0; i < availableDictionaries.length; i++) { - availableDictionaries[i] = availableDictionaries[i].replace('-', '_'); - } - } - - availableDictionaries = availableDictionaries.sort(function(a, b) { - if (a > b) { - return 1; - } - if (a < b) { - return -1; - } - return 0; - }); - - for (var i = enabledDictionaries.length - 1; i >= 0; i--) { - if (availableDictionaries.indexOf(enabledDictionaries[i]) === -1) { - enabledDictionaries.splice(i, 1); - } - } - - if (enabledDictionaries.length === 0) { - if (localStorage.getItem('userLanguage')) { - let userLanguage = localStorage.getItem('userLanguage').replace('-', '_'); - if (availableDictionaries.indexOf(userLanguage) > -1) { - enabledDictionaries.push(userLanguage); - } - if (userLanguage.indexOf('_') > -1) { - userLanguage = userLanguage.split('_')[0]; - if (availableDictionaries.indexOf(userLanguage) > -1) { - enabledDictionaries.push(userLanguage); - } - } - } - - let navigatorLanguage = navigator.language.replace('-', '_'); - if (availableDictionaries.indexOf(navigatorLanguage) > -1) { - enabledDictionaries.push(navigatorLanguage); - } - if (navigatorLanguage.indexOf('_') > -1) { - navigatorLanguage = navigatorLanguage.split('_')[0]; - if (availableDictionaries.indexOf(navigatorLanguage) > -1) { - enabledDictionaries.push(navigatorLanguage); - } - } - } - - if (enabledDictionaries.length === 0) { - let defaultLanguage = 'en_US'; - if (availableDictionaries.indexOf(defaultLanguage) > -1) { - enabledDictionaries.push(defaultLanguage); - } - defaultLanguage = defaultLanguage.split('_')[0]; - if (availableDictionaries.indexOf(defaultLanguage) > -1) { - enabledDictionaries.push(defaultLanguage); - } - } - - languagesMenu = { - label: 'Spelling languages', - submenu: [] - }; - - availableDictionaries.forEach((dictionary) => { - const menu = { - label: dictionary, - type: 'checkbox', - checked: enabledDictionaries.indexOf(dictionary) > -1, - click: function(menuItem) { - menu.checked = menuItem.checked; - if (menuItem.checked) { - enabledDictionaries.push(dictionary); - } else { - enabledDictionaries.splice(enabledDictionaries.indexOf(dictionary), 1); - } - saveEnabledDictionaries(); - } - }; - languagesMenu.submenu.push(menu); - }); - - webFrame.setSpellCheckProvider('', false, { - spellCheck: function(text) { - return isCorrect(text); - } - }); -} catch(e) { - console.log('Spellchecker module unavailable \n' + e.message); + checker = require('spellchecker'); + + availableDictionaries = checker.getAvailableDictionaries(); + + if (availableDictionaries.length === 0) { + dictionariesPath = path.join(remote.app.getAppPath(), '../dictionaries'); + availableDictionaries = [ + 'en_US', + 'es_ES', + 'pt_BR' + ]; + } else { + for (let i = 0; i < availableDictionaries.length; i++) { + availableDictionaries[i] = availableDictionaries[i].replace('-', '_'); + } + } + + availableDictionaries = availableDictionaries.sort(function (a, b) { + if (a > b) { + return 1; + } + if (a < b) { + return -1; + } + return 0; + }); + + for (var i = enabledDictionaries.length - 1; i >= 0; i--) { + if (availableDictionaries.indexOf(enabledDictionaries[i]) === -1) { + enabledDictionaries.splice(i, 1); + } + } + + if (enabledDictionaries.length === 0) { + if (localStorage.getItem('userLanguage')) { + let userLanguage = localStorage.getItem('userLanguage').replace('-', '_'); + if (availableDictionaries.indexOf(userLanguage) > -1) { + enabledDictionaries.push(userLanguage); + } + if (userLanguage.indexOf('_') > -1) { + userLanguage = userLanguage.split('_')[0]; + if (availableDictionaries.indexOf(userLanguage) > -1) { + enabledDictionaries.push(userLanguage); + } + } + } + + let navigatorLanguage = navigator.language.replace('-', '_'); + if (availableDictionaries.indexOf(navigatorLanguage) > -1) { + enabledDictionaries.push(navigatorLanguage); + } + if (navigatorLanguage.indexOf('_') > -1) { + navigatorLanguage = navigatorLanguage.split('_')[0]; + if (availableDictionaries.indexOf(navigatorLanguage) > -1) { + enabledDictionaries.push(navigatorLanguage); + } + } + } + + if (enabledDictionaries.length === 0) { + let defaultLanguage = 'en_US'; + if (availableDictionaries.indexOf(defaultLanguage) > -1) { + enabledDictionaries.push(defaultLanguage); + } + defaultLanguage = defaultLanguage.split('_')[0]; + if (availableDictionaries.indexOf(defaultLanguage) > -1) { + enabledDictionaries.push(defaultLanguage); + } + } + + languagesMenu = { + label: 'Spelling languages', + submenu: [] + }; + + availableDictionaries.forEach((dictionary) => { + const menu = { + label: dictionary, + type: 'checkbox', + checked: enabledDictionaries.indexOf(dictionary) > -1, + click: function (menuItem) { + menu.checked = menuItem.checked; + if (menuItem.checked) { + enabledDictionaries.push(dictionary); + } else { + enabledDictionaries.splice(enabledDictionaries.indexOf(dictionary), 1); + } + saveEnabledDictionaries(); + } + }; + languagesMenu.submenu.push(menu); + }); + + webFrame.setSpellCheckProvider('', false, { + spellCheck: function (text) { + return isCorrect(text); + } + }); +} catch (e) { + console.log('Spellchecker module unavailable \n' + e.message); } -window.addEventListener('contextmenu', function(event){ - event.preventDefault(); - - const template = getTemplate(); - - if (languagesMenu) { - template.unshift({ type: 'separator' }); - template.unshift(languagesMenu); - } - - setTimeout(function() { - if (['TEXTAREA', 'INPUT'].indexOf(event.target.nodeName) > -1) { - const text = window.getSelection().toString().trim(); - if (text !== '' && !isCorrect(text)) { - const options = getCorrections(text); - const maxItems = Math.min(options.length, 6); - - if (maxItems > 0) { - const suggestions = []; - const onClick = function(menuItem) { - webContents.replaceMisspelling(menuItem.label); - }; - - for (let i = 0; i < options.length; i++) { - const item = options[i]; - suggestions.push({ label: item, click: onClick }); - } - - template.unshift({ type: 'separator' }); - - if (suggestions.length > maxItems) { - const morSuggestions = { - label: 'More spelling suggestions', - submenu: suggestions.slice(maxItems) - }; - template.unshift(morSuggestions); - } - - template.unshift.apply(template, suggestions.slice(0, maxItems)); - } else { - template.unshift({ label: 'no suggestions', click: function() { } }); - } - } - } - - menu = remote.Menu.buildFromTemplate(template); - menu.popup(remote.getCurrentWindow()); - }, 0); +window.addEventListener('contextmenu', function (event) { + event.preventDefault(); + + const template = getTemplate(); + + if (languagesMenu) { + template.unshift({ type: 'separator' }); + template.unshift(languagesMenu); + } + + setTimeout(function () { + if (['TEXTAREA', 'INPUT'].indexOf(event.target.nodeName) > -1) { + const text = window.getSelection().toString().trim(); + if (text !== '' && !isCorrect(text)) { + const options = getCorrections(text); + const maxItems = Math.min(options.length, 6); + + if (maxItems > 0) { + const suggestions = []; + const onClick = function (menuItem) { + webContents.replaceMisspelling(menuItem.label); + }; + + for (let i = 0; i < options.length; i++) { + const item = options[i]; + suggestions.push({ label: item, click: onClick }); + } + + template.unshift({ type: 'separator' }); + + if (suggestions.length > maxItems) { + const morSuggestions = { + label: 'More spelling suggestions', + submenu: suggestions.slice(maxItems) + }; + template.unshift(morSuggestions); + } + + template.unshift.apply(template, suggestions.slice(0, maxItems)); + } else { + template.unshift({ label: 'no suggestions', click: function () { } }); + } + } + } + + menu = remote.Menu.buildFromTemplate(template); + menu.popup(remote.getCurrentWindow()); + }, 0); }, false); /* userPresence away timer based on system idle time */ -function getSystemIdleTime() { - return IPC.sendSync('getSystemIdleTime'); -} - -// setInterval(function(){ -// try { -// if(getSystemIdleTime() < UserPresence.awayTime) { -// UserPresence.setOnline(); -// } -// } catch(e) { -// console.error(e); -// } +// function getSystemIdleTime () { +// return IPC.sendSync('getSystemIdleTime'); +// } + +// setInterval(function (){ +// try { +// if(getSystemIdleTime() < UserPresence.awayTime) { +// UserPresence.setOnline(); +// } +// } catch(e) { +// console.error(e); +// } // }, 1e3); diff --git a/src/scripts/menus.js b/src/scripts/menus.js index c77d7a58f2af..18856c9fd4c7 100644 --- a/src/scripts/menus.js +++ b/src/scripts/menus.js @@ -15,411 +15,411 @@ var certificate = remote.require('./background').certificate; document.title = APP_NAME; if (process.platform === 'darwin') { - template = [ - { - label: APP_NAME, - submenu: [ - { - label: 'About ' + APP_NAME, - role: 'about' - }, - { - type: 'separator' - }, - { - label: 'Hide ' + APP_NAME, - accelerator: 'Command+H', - role: 'hide' - }, - { - label: 'Hide Others', - accelerator: 'Command+Alt+H', - role: 'hideothers' - }, - { - label: 'Show All', - role: 'unhide' - }, - { - type: 'separator' - }, - { - label: 'Quit ' + APP_NAME, - accelerator: 'Command+Q', - click: function() { - remote.app.quit(); - } - } - ] - }, - { - label: 'Edit', - submenu: [ - { - label: 'Undo', - accelerator: 'Command+Z', - role: 'undo' - }, - { - label: 'Redo', - accelerator: 'Command+Shift+Z', - role: 'redo' - }, - { - type: 'separator' - }, - { - label: 'Cut', - accelerator: 'Command+X', - role: 'cut' - }, - { - label: 'Copy', - accelerator: 'Command+C', - role: 'copy' - }, - { - label: 'Paste', - accelerator: 'Command+V', - role: 'paste' - }, - { - label: 'Select All', - accelerator: 'Command+A', - role: 'selectall' - } - ] - }, - { - label: 'View', - submenu: [ - { - label: 'Original Zoom', - accelerator: 'CommandOrControl+0', - role: 'resetzoom' - }, - { - label: 'Zoom In', - accelerator: 'CommandOrControl+Plus', - role: 'zoomout' - }, - { - label: 'Zoom Out', - accelerator: 'CommandOrControl+-', - role: 'zoomin' - }, - { - type: 'separator' - }, - { - label: 'Current Server - Reload', - accelerator: 'Command+R', - click: function() { - const activeWebview = webview.getActive(); - if (activeWebview) { - activeWebview.reload(); - } - } - }, - { - label: 'Current Server - Toggle DevTools', - accelerator: 'Command+Alt+I', - click: function() { - const activeWebview = webview.getActive(); - if (activeWebview) { - activeWebview.openDevTools(); - } - } - }, - { - type: 'separator' - }, - { - label: 'Application - Reload', - accelerator: 'Command+Shift+R', - click: function() { - var mainWindow = remote.getCurrentWindow(); - if (mainWindow.tray) { - mainWindow.tray.destroy(); - } - mainWindow.reload(); - } - }, - { - label: 'Application - Toggle DevTools', - click: function() { - remote.getCurrentWindow().toggleDevTools(); - } - }, - { - type: 'separator' - }, - { - label: 'Toggle server list', - click: function() { - sidebar.toggle(); - } - }, - { - type: 'separator' - }, - { - label: 'Clear', - submenu: [ - { - label: 'Clear Trusted Certificates', - click: function() { - certificate.clear(); - } - } - ] - } - ] - }, - { - label: 'Window', - id: 'window', - role: 'window', - submenu: [ - { - label: 'Minimize', - accelerator: 'Command+M', - role: 'minimize' - }, - { - label: 'Close', - accelerator: 'Command+W', - role: 'close' - }, - { - type: 'separator' - }, - { - type: 'separator', - id: 'server-list-separator', - visible: false - }, - { - label: 'Add new server', - accelerator: 'Command+N', - click: function() { - var mainWindow = remote.getCurrentWindow(); - mainWindow.show(); - servers.clearActive(); - } - }, - { - type: 'separator' - }, - { - label: 'Bring All to Front', - click: function() { - var mainWindow = remote.getCurrentWindow(); - mainWindow.show(); - } - } - ] - }, - { - label: 'Help', - role: 'help', - submenu: [ - { - label: APP_NAME + ' Help', - click: function() { - remote.shell.openExternal('https://rocket.chat/docs'); - } - }, - { - type: 'separator' - }, - { - label: 'Learn More', - click: function() { - remote.shell.openExternal('https://rocket.chat'); - } - } - ] - } - ]; + template = [ + { + label: APP_NAME, + submenu: [ + { + label: 'About ' + APP_NAME, + role: 'about' + }, + { + type: 'separator' + }, + { + label: 'Hide ' + APP_NAME, + accelerator: 'Command+H', + role: 'hide' + }, + { + label: 'Hide Others', + accelerator: 'Command+Alt+H', + role: 'hideothers' + }, + { + label: 'Show All', + role: 'unhide' + }, + { + type: 'separator' + }, + { + label: 'Quit ' + APP_NAME, + accelerator: 'Command+Q', + click: function () { + remote.app.quit(); + } + } + ] + }, + { + label: 'Edit', + submenu: [ + { + label: 'Undo', + accelerator: 'Command+Z', + role: 'undo' + }, + { + label: 'Redo', + accelerator: 'Command+Shift+Z', + role: 'redo' + }, + { + type: 'separator' + }, + { + label: 'Cut', + accelerator: 'Command+X', + role: 'cut' + }, + { + label: 'Copy', + accelerator: 'Command+C', + role: 'copy' + }, + { + label: 'Paste', + accelerator: 'Command+V', + role: 'paste' + }, + { + label: 'Select All', + accelerator: 'Command+A', + role: 'selectall' + } + ] + }, + { + label: 'View', + submenu: [ + { + label: 'Original Zoom', + accelerator: 'CommandOrControl+0', + role: 'resetzoom' + }, + { + label: 'Zoom In', + accelerator: 'CommandOrControl+Plus', + role: 'zoomout' + }, + { + label: 'Zoom Out', + accelerator: 'CommandOrControl+-', + role: 'zoomin' + }, + { + type: 'separator' + }, + { + label: 'Current Server - Reload', + accelerator: 'Command+R', + click: function () { + const activeWebview = webview.getActive(); + if (activeWebview) { + activeWebview.reload(); + } + } + }, + { + label: 'Current Server - Toggle DevTools', + accelerator: 'Command+Alt+I', + click: function () { + const activeWebview = webview.getActive(); + if (activeWebview) { + activeWebview.openDevTools(); + } + } + }, + { + type: 'separator' + }, + { + label: 'Application - Reload', + accelerator: 'Command+Shift+R', + click: function () { + var mainWindow = remote.getCurrentWindow(); + if (mainWindow.tray) { + mainWindow.tray.destroy(); + } + mainWindow.reload(); + } + }, + { + label: 'Application - Toggle DevTools', + click: function () { + remote.getCurrentWindow().toggleDevTools(); + } + }, + { + type: 'separator' + }, + { + label: 'Toggle server list', + click: function () { + sidebar.toggle(); + } + }, + { + type: 'separator' + }, + { + label: 'Clear', + submenu: [ + { + label: 'Clear Trusted Certificates', + click: function () { + certificate.clear(); + } + } + ] + } + ] + }, + { + label: 'Window', + id: 'window', + role: 'window', + submenu: [ + { + label: 'Minimize', + accelerator: 'Command+M', + role: 'minimize' + }, + { + label: 'Close', + accelerator: 'Command+W', + role: 'close' + }, + { + type: 'separator' + }, + { + type: 'separator', + id: 'server-list-separator', + visible: false + }, + { + label: 'Add new server', + accelerator: 'Command+N', + click: function () { + var mainWindow = remote.getCurrentWindow(); + mainWindow.show(); + servers.clearActive(); + } + }, + { + type: 'separator' + }, + { + label: 'Bring All to Front', + click: function () { + var mainWindow = remote.getCurrentWindow(); + mainWindow.show(); + } + } + ] + }, + { + label: 'Help', + role: 'help', + submenu: [ + { + label: APP_NAME + ' Help', + click: function () { + remote.shell.openExternal('https://rocket.chat/docs'); + } + }, + { + type: 'separator' + }, + { + label: 'Learn More', + click: function () { + remote.shell.openExternal('https://rocket.chat'); + } + } + ] + } + ]; } else { - template = [ - { - label: '&' + APP_NAME, - submenu: [ - { - label: 'About ' + APP_NAME, - click: function() { - const win = new remote.BrowserWindow({ width: 310, height: 200, minWidth: 310, minHeight: 200, maxWidth: 310, maxHeight: 200, show: false, maximizable: false, minimizable: false, title: ' ' }); - win.loadURL('file://' + __dirname + '/about.html'); - win.show(); - } - }, - { - type: 'separator' - }, - { - label: 'Quit', - accelerator: 'Ctrl+Q', - click: function() { - remote.app.quit(); - } - } - ] - }, - { - label: '&Edit', - submenu: [ - { - label: 'Undo', - accelerator: 'Ctrl+Z', - role: 'undo' - }, - { - label: 'Redo', - accelerator: 'Ctrl+Shift+Z', - role: 'redo' - }, - { - type: 'separator' - }, - { - label: 'Cut', - accelerator: 'Ctrl+X', - role: 'cut' - }, - { - label: 'Copy', - accelerator: 'Ctrl+C', - role: 'copy' - }, - { - label: 'Paste', - accelerator: 'Ctrl+V', - role: 'paste' - }, - { - label: 'Select All', - accelerator: 'Ctrl+A', - role: 'selectall' - } - ] - }, - { - label: '&View', - submenu: [ - { - label: 'Original Zoom', - accelerator: 'CommandOrControl+0', - role: 'resetzoom' - }, - { - label: 'Zoom In', - accelerator: 'CommandOrControl+Plus', - role: 'zoomout' - }, - { - label: 'Zoom Out', - accelerator: 'CommandOrControl+-', - role: 'zoomin' - }, - { - type: 'separator' - }, - { - label: 'Current Server - Reload', - accelerator: 'Ctrl+R', - click: function() { - const activeWebview = webview.getActive(); - if (activeWebview) { - activeWebview.reload(); - } - } - }, - { - label: 'Current Server - Toggle DevTools', - accelerator: 'Ctrl+Shift+I', - click: function() { - const activeWebview = webview.getActive(); - if (activeWebview) { - activeWebview.openDevTools(); - } - } - }, - { - type: 'separator' - }, - { - label: 'Application - Reload', - accelerator: 'Ctrl+Shift+R', - click: function() { - var mainWindow = remote.getCurrentWindow(); - if (mainWindow.tray) { - mainWindow.tray.destroy(); - } - mainWindow.reload(); - } - }, - { - label: 'Application - Toggle DevTools', - click: function() { - remote.getCurrentWindow().toggleDevTools(); - } - }, - { - type: 'separator' - }, - { - label: 'Toggle server list', - click: function() { - sidebar.toggle(); - } - }, - { - type: 'separator' - }, - { - label: 'Clear', - submenu: [ - { - label: 'Clear Trusted Certificates', - click: function() { - certificate.clear(); - } - } - ] - } - ] - }, - { - label: '&Window', - id: 'window', - submenu: [ - { - type: 'separator', - id: 'server-list-separator', - visible: false - }, - { - label: 'Add new server', - accelerator: 'Ctrl+N', - click: function() { - servers.clearActive(); - } - }, - { - type: 'separator' - }, - { - label: 'Close', - accelerator: 'Ctrl+W', - click: function() { - remote.getCurrentWindow().close(); - } - } - ] - } - ]; + template = [ + { + label: '&' + APP_NAME, + submenu: [ + { + label: 'About ' + APP_NAME, + click: function () { + const win = new remote.BrowserWindow({ width: 310, height: 200, minWidth: 310, minHeight: 200, maxWidth: 310, maxHeight: 200, show: false, maximizable: false, minimizable: false, title: ' ' }); + win.loadURL('file://' + __dirname + '/about.html'); + win.show(); + } + }, + { + type: 'separator' + }, + { + label: 'Quit', + accelerator: 'Ctrl+Q', + click: function () { + remote.app.quit(); + } + } + ] + }, + { + label: '&Edit', + submenu: [ + { + label: 'Undo', + accelerator: 'Ctrl+Z', + role: 'undo' + }, + { + label: 'Redo', + accelerator: 'Ctrl+Shift+Z', + role: 'redo' + }, + { + type: 'separator' + }, + { + label: 'Cut', + accelerator: 'Ctrl+X', + role: 'cut' + }, + { + label: 'Copy', + accelerator: 'Ctrl+C', + role: 'copy' + }, + { + label: 'Paste', + accelerator: 'Ctrl+V', + role: 'paste' + }, + { + label: 'Select All', + accelerator: 'Ctrl+A', + role: 'selectall' + } + ] + }, + { + label: '&View', + submenu: [ + { + label: 'Original Zoom', + accelerator: 'CommandOrControl+0', + role: 'resetzoom' + }, + { + label: 'Zoom In', + accelerator: 'CommandOrControl+Plus', + role: 'zoomout' + }, + { + label: 'Zoom Out', + accelerator: 'CommandOrControl+-', + role: 'zoomin' + }, + { + type: 'separator' + }, + { + label: 'Current Server - Reload', + accelerator: 'Ctrl+R', + click: function () { + const activeWebview = webview.getActive(); + if (activeWebview) { + activeWebview.reload(); + } + } + }, + { + label: 'Current Server - Toggle DevTools', + accelerator: 'Ctrl+Shift+I', + click: function () { + const activeWebview = webview.getActive(); + if (activeWebview) { + activeWebview.openDevTools(); + } + } + }, + { + type: 'separator' + }, + { + label: 'Application - Reload', + accelerator: 'Ctrl+Shift+R', + click: function () { + var mainWindow = remote.getCurrentWindow(); + if (mainWindow.tray) { + mainWindow.tray.destroy(); + } + mainWindow.reload(); + } + }, + { + label: 'Application - Toggle DevTools', + click: function () { + remote.getCurrentWindow().toggleDevTools(); + } + }, + { + type: 'separator' + }, + { + label: 'Toggle server list', + click: function () { + sidebar.toggle(); + } + }, + { + type: 'separator' + }, + { + label: 'Clear', + submenu: [ + { + label: 'Clear Trusted Certificates', + click: function () { + certificate.clear(); + } + } + ] + } + ] + }, + { + label: '&Window', + id: 'window', + submenu: [ + { + type: 'separator', + id: 'server-list-separator', + visible: false + }, + { + label: 'Add new server', + accelerator: 'Ctrl+N', + click: function () { + servers.clearActive(); + } + }, + { + type: 'separator' + }, + { + label: 'Close', + accelerator: 'Ctrl+W', + click: function () { + remote.getCurrentWindow().close(); + } + } + ] + } + ]; } export var menuTemplate = template; diff --git a/src/scripts/servers.js b/src/scripts/servers.js index 5007ef3883e6..4768f2a337a4 100644 --- a/src/scripts/servers.js +++ b/src/scripts/servers.js @@ -5,213 +5,213 @@ import { remote } from 'electron'; const remoteServers = remote.require('./background').remoteServers; class Servers extends EventEmitter { - constructor() { - super(); - this.load(); - } - - get hosts() { - return this._hosts; - } - - set hosts(hosts) { - this._hosts = hosts; - this.save(); - return true; - } - - get hostsKey() { - return 'rocket.chat.hosts'; - } - - get activeKey() { - return 'rocket.chat.currentHost'; - } - - load() { - var hosts = localStorage.getItem(this.hostsKey); - - try { - hosts = JSON.parse(hosts); - } catch (e) { - if (typeof hosts === 'string' && hosts.match(/^https?:\/\//)) { - hosts = {}; - hosts[hosts] = { - title: hosts, - url: hosts - }; - } - - localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); - } - - if (hosts === null) { - hosts = {}; - } - - if (Array.isArray(hosts)) { - var oldHosts = hosts; - hosts = {}; - oldHosts.forEach(function(item) { - item = item.replace(/\/$/, ''); - hosts[item] = { - title: item, - url: item - }; - }); - localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); - } - - this._hosts = hosts; - remoteServers.loadServers(this._hosts); - this.emit('loaded'); - } - - save() { - localStorage.setItem(this.hostsKey, JSON.stringify(this._hosts)); - this.emit('saved'); - } - - get(hostUrl) { - return this.hosts[hostUrl]; - } - - forEach(cb) { - for (var host in this.hosts) { - if (this.hosts.hasOwnProperty(host)) { - cb(this.hosts[host]); - } - } - } - - validateHost(hostUrl, timeout) { - console.log('Validating hostUrl', hostUrl); - timeout = timeout || 5000; - return new Promise(function(resolve, reject) { - var resolved = false; - $.getJSON(`${hostUrl}/api/info`).then(function() { - if (resolved) { - return; - } - resolved = true; - console.log('HostUrl valid', hostUrl); - resolve(); - }, function(request) { - if (request.status === 401) { - let authHeader = request.getResponseHeader('www-authenticate'); - if (authHeader && authHeader.toLowerCase().indexOf('basic ') === 0) { - resolved = true; - console.log('HostUrl needs basic auth', hostUrl); - reject('basic-auth'); - } - } - if (resolved) { - return; - } - resolved = true; - console.log('HostUrl invalid', hostUrl); - reject('invalid'); - }); - if (timeout) { - setTimeout(function() { - if (resolved) { - return; - } - resolved = true; - console.log('Validating hostUrl TIMEOUT', hostUrl); - reject('timeout'); - }, timeout); - } - }); - } - - hostExists(hostUrl) { - var hosts = this.hosts; - - return !!hosts[hostUrl]; - } - - addHost(hostUrl) { - var hosts = this.hosts; - - let match = hostUrl.match(/^(https?:\/\/)([^:]+):([^@]+)@(.+)$/); - let username; - let password; - let authUrl; - if (match) { - authUrl = hostUrl; - hostUrl = match[1] + match[4]; - username = match[2]; - password = match[3]; - } - - if (this.hostExists(hostUrl) === true) { - return false; - } - - hosts[hostUrl] = { - title: hostUrl, - url: hostUrl, - authUrl: authUrl, - username: username, - password: password - }; - this.hosts = hosts; - - remoteServers.loadServers(this.hosts); - - this.emit('host-added', hostUrl); - - return hostUrl; - } - - removeHost(hostUrl) { - var hosts = this.hosts; - if (hosts[hostUrl]) { - delete hosts[hostUrl]; - this.hosts = hosts; - - remoteServers.loadServers(this.hosts); - - if (this.active === hostUrl) { - this.clearActive(); - } - this.emit('host-removed', hostUrl); - } - } - - get active() { - return localStorage.getItem(this.activeKey); - } - - setActive(hostUrl) { - if (this.hostExists(hostUrl)) { - localStorage.setItem(this.activeKey, hostUrl); - this.emit('active-setted', hostUrl); - return true; - } - return false; - } - - restoreActive() { - this.setActive(this.active); - } - - clearActive() { - localStorage.removeItem(this.activeKey); - this.emit('active-cleared'); - return true; - } - - setHostTitle(hostUrl, title) { - if (title === 'Rocket.Chat' && /https?:\/\/demo\.rocket\.chat/.test(hostUrl) === false) { - title += ' - ' + hostUrl; - } - var hosts = this.hosts; - hosts[hostUrl].title = title; - this.hosts = hosts; - this.emit('title-setted', hostUrl, title); - } + constructor () { + super(); + this.load(); + } + + get hosts () { + return this._hosts; + } + + set hosts (hosts) { + this._hosts = hosts; + this.save(); + return true; + } + + get hostsKey () { + return 'rocket.chat.hosts'; + } + + get activeKey () { + return 'rocket.chat.currentHost'; + } + + load () { + var hosts = localStorage.getItem(this.hostsKey); + + try { + hosts = JSON.parse(hosts); + } catch (e) { + if (typeof hosts === 'string' && hosts.match(/^https?:\/\//)) { + hosts = {}; + hosts[hosts] = { + title: hosts, + url: hosts + }; + } + + localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); + } + + if (hosts === null) { + hosts = {}; + } + + if (Array.isArray(hosts)) { + var oldHosts = hosts; + hosts = {}; + oldHosts.forEach(function (item) { + item = item.replace(/\/$/, ''); + hosts[item] = { + title: item, + url: item + }; + }); + localStorage.setItem(this.hostsKey, JSON.stringify(hosts)); + } + + this._hosts = hosts; + remoteServers.loadServers(this._hosts); + this.emit('loaded'); + } + + save () { + localStorage.setItem(this.hostsKey, JSON.stringify(this._hosts)); + this.emit('saved'); + } + + get (hostUrl) { + return this.hosts[hostUrl]; + } + + forEach (cb) { + for (var host in this.hosts) { + if (this.hosts.hasOwnProperty(host)) { + cb(this.hosts[host]); + } + } + } + + validateHost (hostUrl, timeout) { + console.log('Validating hostUrl', hostUrl); + timeout = timeout || 5000; + return new Promise(function (resolve, reject) { + var resolved = false; + $.getJSON(`${hostUrl}/api/info`).then(function () { + if (resolved) { + return; + } + resolved = true; + console.log('HostUrl valid', hostUrl); + resolve(); + }, function (request) { + if (request.status === 401) { + let authHeader = request.getResponseHeader('www-authenticate'); + if (authHeader && authHeader.toLowerCase().indexOf('basic ') === 0) { + resolved = true; + console.log('HostUrl needs basic auth', hostUrl); + reject('basic-auth'); + } + } + if (resolved) { + return; + } + resolved = true; + console.log('HostUrl invalid', hostUrl); + reject('invalid'); + }); + if (timeout) { + setTimeout(function () { + if (resolved) { + return; + } + resolved = true; + console.log('Validating hostUrl TIMEOUT', hostUrl); + reject('timeout'); + }, timeout); + } + }); + } + + hostExists (hostUrl) { + var hosts = this.hosts; + + return !!hosts[hostUrl]; + } + + addHost (hostUrl) { + var hosts = this.hosts; + + let match = hostUrl.match(/^(https?:\/\/)([^:]+):([^@]+)@(.+)$/); + let username; + let password; + let authUrl; + if (match) { + authUrl = hostUrl; + hostUrl = match[1] + match[4]; + username = match[2]; + password = match[3]; + } + + if (this.hostExists(hostUrl) === true) { + return false; + } + + hosts[hostUrl] = { + title: hostUrl, + url: hostUrl, + authUrl: authUrl, + username: username, + password: password + }; + this.hosts = hosts; + + remoteServers.loadServers(this.hosts); + + this.emit('host-added', hostUrl); + + return hostUrl; + } + + removeHost (hostUrl) { + var hosts = this.hosts; + if (hosts[hostUrl]) { + delete hosts[hostUrl]; + this.hosts = hosts; + + remoteServers.loadServers(this.hosts); + + if (this.active === hostUrl) { + this.clearActive(); + } + this.emit('host-removed', hostUrl); + } + } + + get active () { + return localStorage.getItem(this.activeKey); + } + + setActive (hostUrl) { + if (this.hostExists(hostUrl)) { + localStorage.setItem(this.activeKey, hostUrl); + this.emit('active-setted', hostUrl); + return true; + } + return false; + } + + restoreActive () { + this.setActive(this.active); + } + + clearActive () { + localStorage.removeItem(this.activeKey); + this.emit('active-cleared'); + return true; + } + + setHostTitle (hostUrl, title) { + if (title === 'Rocket.Chat' && /https?:\/\/demo\.rocket\.chat/.test(hostUrl) === false) { + title += ' - ' + hostUrl; + } + var hosts = this.hosts; + hosts[hostUrl].title = title; + this.hosts = hosts; + this.emit('title-setted', hostUrl, title); + } } export var servers = new Servers(); diff --git a/src/scripts/sidebar.js b/src/scripts/sidebar.js index dadec79428e5..41b86e3a48a4 100644 --- a/src/scripts/sidebar.js +++ b/src/scripts/sidebar.js @@ -6,238 +6,244 @@ import { menuTemplate } from './menus'; var Menu = remote.Menu; -var windowMenuPosition = menuTemplate.findIndex(function(i) {return i.id === 'window';}); +var windowMenuPosition = menuTemplate.findIndex(function (i) { + return i.id === 'window'; +}); var windowMenu = menuTemplate[windowMenuPosition]; -var serverListSeparatorPosition = windowMenu.submenu.findIndex(function(i) {return i.id === 'server-list-separator';}); +var serverListSeparatorPosition = windowMenu.submenu.findIndex(function (i) { + return i.id === 'server-list-separator'; +}); var serverListSeparator = windowMenu.submenu[serverListSeparatorPosition]; class SideBar extends EventEmitter { - constructor() { - super(); - - this.hostCount = 0; - - this.listElement = document.getElementById('serverList'); - - servers.forEach((host) => { - this.add(host); - }); - - servers.on('host-added', (hostUrl) => { - this.add(servers.get(hostUrl)); - }); - - servers.on('host-removed', (hostUrl) => { - this.remove(hostUrl); - }); - - servers.on('active-setted', (hostUrl) => { - this.setActive(hostUrl); - }); - - servers.on('active-cleared', (hostUrl) => { - this.deactiveAll(hostUrl); - }); - - servers.on('title-setted', (hostUrl, title) => { - this.setLabel(hostUrl, title); - }); - - webview.on('dom-ready', (hostUrl) => { - this.setImage(hostUrl); - }); - - if (this.isHidden()) { - this.hide(); - } else { - this.show(); - } - } - - add(host) { - var name = host.title.replace(/^https?:\/\/(?:www\.)?([^\/]+)(.*)/, '$1'); - name = name.split('.'); - name = name[0][0] + (name[1] ? name[1][0] : ''); - name = name.toUpperCase(); - - var initials = document.createElement('span'); - initials.innerHTML = name; - - var tooltip = document.createElement('div'); - tooltip.classList.add('tooltip'); - tooltip.innerHTML = host.title; - - var badge = document.createElement('div'); - badge.classList.add('badge'); - - var img = document.createElement('img'); - img.onload = function() { - img.style.display = 'initial'; - initials.style.display = 'none'; - }; - // img.src = `${host.url}/assets/favicon.svg?v=${Math.round(Math.random()*10000)}`; - - var hotkey = document.createElement('div'); - hotkey.classList.add('name'); - if (process.platform === 'darwin') { - hotkey.innerHTML = '⌘' + (++this.hostCount); - } else { - hotkey.innerHTML = '^' + (++this.hostCount); - } - - var item = document.createElement('li'); - item.appendChild(initials); - item.appendChild(tooltip); - item.appendChild(badge); - item.appendChild(img); - item.appendChild(hotkey); - - item.dataset.host = host.url; - item.setAttribute('server', host.url); - item.classList.add('instance'); - - item.onclick = () => { - this.emit('click', host.url); - servers.setActive(host.url); - }; - - this.listElement.appendChild(item); - - serverListSeparator.visible = true; - - var menuItem = { - label: host.title, - accelerator: 'CmdOrCtrl+' + this.hostCount, - position: 'before=server-list-separator', - id: host.url, - click: () => { - var mainWindow = remote.getCurrentWindow(); - mainWindow.show(); - this.emit('click', host.url); - servers.setActive(host.url); - } - }; - - windowMenu.submenu.push(menuItem); - Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate)); - } - - setImage(hostUrl) { - const img = this.getByUrl(hostUrl).querySelector('img'); - img.src = `${hostUrl}/assets/favicon.svg?v=${Math.round(Math.random()*10000)}`; - } - - remove(hostUrl) { - var el = this.getByUrl(hostUrl); - if (el) { - el.remove(); - - var index = windowMenu.submenu.findIndex(function(i) {return i.id === hostUrl;}); - windowMenu.submenu.splice(index, 1); - Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate)); - } - } - - getByUrl(hostUrl) { - return this.listElement.querySelector(`.instance[server="${hostUrl}"]`); - } - - getActive() { - return this.listElement.querySelector('.instance.active'); - } - - isActive(hostUrl) { - return !!this.listElement.querySelector(`.instance.active[server="${hostUrl}"]`); - } - - setActive(hostUrl) { - if (this.isActive(hostUrl)) { - return; - } - - this.deactiveAll(); - var item = this.getByUrl(hostUrl); - if (item) { - item.classList.add('active'); - } - } - - deactiveAll() { - var item; - while (!(item = this.getActive()) === false) { - item.classList.remove('active'); - } - } - - setLabel(hostUrl, label) { - this.listElement.querySelector(`.instance[server="${hostUrl}"] .tooltip`).innerHTML = label; - } - - setBadge(hostUrl, badge) { - var item = this.getByUrl(hostUrl); - var badgeEl = item.querySelector('.badge'); - - if (badge !== null && badge !== undefined && badge !== '') { - item.classList.add('unread'); - if (isNaN(parseInt(badge))) { - badgeEl.innerHTML = ''; - } else { - badgeEl.innerHTML = badge; - } - } else { - badge = undefined; - item.classList.remove('unread'); - badgeEl.innerHTML = ''; - } - this.emit('badge-setted', hostUrl, badge); - } - - getGlobalBadge() { - var count = 0; - var alert = ''; - var instanceEls = this.listElement.querySelectorAll('li.instance'); - for (var i = instanceEls.length - 1; i >= 0; i--) { - var instanceEl = instanceEls[i]; - var text = instanceEl.querySelector('.badge').innerHTML; - if (!isNaN(parseInt(text))) { - count += parseInt(text); - } - - if (alert === '' && instanceEl.classList.contains('unread') === true) { - alert = '•'; - } - } - - if (count > 0) { - return String(count); - } else { - return alert; - } - } - - hide() { - document.body.classList.add('hide-server-list'); - localStorage.setItem('sidebar-closed', 'true'); - this.emit('hide'); - } - - show() { - document.body.classList.remove('hide-server-list'); - localStorage.setItem('sidebar-closed', 'false'); - this.emit('show'); - } - - toggle() { - if (this.isHidden()) { - this.show(); - } else { - this.hide(); - } - } - - isHidden() { - return localStorage.getItem('sidebar-closed') === 'true'; - } + constructor () { + super(); + + this.hostCount = 0; + + this.listElement = document.getElementById('serverList'); + + servers.forEach((host) => { + this.add(host); + }); + + servers.on('host-added', (hostUrl) => { + this.add(servers.get(hostUrl)); + }); + + servers.on('host-removed', (hostUrl) => { + this.remove(hostUrl); + }); + + servers.on('active-setted', (hostUrl) => { + this.setActive(hostUrl); + }); + + servers.on('active-cleared', (hostUrl) => { + this.deactiveAll(hostUrl); + }); + + servers.on('title-setted', (hostUrl, title) => { + this.setLabel(hostUrl, title); + }); + + webview.on('dom-ready', (hostUrl) => { + this.setImage(hostUrl); + }); + + if (this.isHidden()) { + this.hide(); + } else { + this.show(); + } + } + + add (host) { + var name = host.title.replace(/^https?:\/\/(?:www\.)?([^\/]+)(.*)/, '$1'); + name = name.split('.'); + name = name[0][0] + (name[1] ? name[1][0] : ''); + name = name.toUpperCase(); + + var initials = document.createElement('span'); + initials.innerHTML = name; + + var tooltip = document.createElement('div'); + tooltip.classList.add('tooltip'); + tooltip.innerHTML = host.title; + + var badge = document.createElement('div'); + badge.classList.add('badge'); + + var img = document.createElement('img'); + img.onload = function () { + img.style.display = 'initial'; + initials.style.display = 'none'; + }; + // img.src = `${host.url}/assets/favicon.svg?v=${Math.round(Math.random()*10000)}`; + + var hotkey = document.createElement('div'); + hotkey.classList.add('name'); + if (process.platform === 'darwin') { + hotkey.innerHTML = '⌘' + (++this.hostCount); + } else { + hotkey.innerHTML = '^' + (++this.hostCount); + } + + var item = document.createElement('li'); + item.appendChild(initials); + item.appendChild(tooltip); + item.appendChild(badge); + item.appendChild(img); + item.appendChild(hotkey); + + item.dataset.host = host.url; + item.setAttribute('server', host.url); + item.classList.add('instance'); + + item.onclick = () => { + this.emit('click', host.url); + servers.setActive(host.url); + }; + + this.listElement.appendChild(item); + + serverListSeparator.visible = true; + + var menuItem = { + label: host.title, + accelerator: 'CmdOrCtrl+' + this.hostCount, + position: 'before=server-list-separator', + id: host.url, + click: () => { + var mainWindow = remote.getCurrentWindow(); + mainWindow.show(); + this.emit('click', host.url); + servers.setActive(host.url); + } + }; + + windowMenu.submenu.push(menuItem); + Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate)); + } + + setImage (hostUrl) { + const img = this.getByUrl(hostUrl).querySelector('img'); + img.src = `${hostUrl}/assets/favicon.svg?v=${Math.round(Math.random()*10000)}`; + } + + remove (hostUrl) { + var el = this.getByUrl(hostUrl); + if (el) { + el.remove(); + + var index = windowMenu.submenu.findIndex(function (i) { + return i.id === hostUrl; + }); + windowMenu.submenu.splice(index, 1); + Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate)); + } + } + + getByUrl (hostUrl) { + return this.listElement.querySelector(`.instance[server="${hostUrl}"]`); + } + + getActive () { + return this.listElement.querySelector('.instance.active'); + } + + isActive (hostUrl) { + return !!this.listElement.querySelector(`.instance.active[server="${hostUrl}"]`); + } + + setActive (hostUrl) { + if (this.isActive(hostUrl)) { + return; + } + + this.deactiveAll(); + var item = this.getByUrl(hostUrl); + if (item) { + item.classList.add('active'); + } + } + + deactiveAll () { + var item; + while (!(item = this.getActive()) === false) { + item.classList.remove('active'); + } + } + + setLabel (hostUrl, label) { + this.listElement.querySelector(`.instance[server="${hostUrl}"] .tooltip`).innerHTML = label; + } + + setBadge (hostUrl, badge) { + var item = this.getByUrl(hostUrl); + var badgeEl = item.querySelector('.badge'); + + if (badge !== null && badge !== undefined && badge !== '') { + item.classList.add('unread'); + if (isNaN(parseInt(badge))) { + badgeEl.innerHTML = ''; + } else { + badgeEl.innerHTML = badge; + } + } else { + badge = undefined; + item.classList.remove('unread'); + badgeEl.innerHTML = ''; + } + this.emit('badge-setted', hostUrl, badge); + } + + getGlobalBadge () { + var count = 0; + var alert = ''; + var instanceEls = this.listElement.querySelectorAll('li.instance'); + for (var i = instanceEls.length - 1; i >= 0; i--) { + var instanceEl = instanceEls[i]; + var text = instanceEl.querySelector('.badge').innerHTML; + if (!isNaN(parseInt(text))) { + count += parseInt(text); + } + + if (alert === '' && instanceEl.classList.contains('unread') === true) { + alert = '•'; + } + } + + if (count > 0) { + return String(count); + } else { + return alert; + } + } + + hide () { + document.body.classList.add('hide-server-list'); + localStorage.setItem('sidebar-closed', 'true'); + this.emit('hide'); + } + + show () { + document.body.classList.remove('hide-server-list'); + localStorage.setItem('sidebar-closed', 'false'); + this.emit('show'); + } + + toggle () { + if (this.isHidden()) { + this.show(); + } else { + this.hide(); + } + } + + isHidden () { + return localStorage.getItem('sidebar-closed') === 'true'; + } } export var sidebar = new SideBar(); @@ -245,31 +251,31 @@ export var sidebar = new SideBar(); var selectedInstance = null; var instanceMenu = remote.Menu.buildFromTemplate([{ - label: 'Reload server', - click: function() { - webview.getByUrl(selectedInstance.dataset.host).reload(); - } + label: 'Reload server', + click: function () { + webview.getByUrl(selectedInstance.dataset.host).reload(); + } }, { - label: 'Remove server', - click: function() { - servers.removeHost(selectedInstance.dataset.host); - } + label: 'Remove server', + click: function () { + servers.removeHost(selectedInstance.dataset.host); + } }, { - label: 'Open DevTools', - click: function() { - webview.getByUrl(selectedInstance.dataset.host).openDevTools(); - } + label: 'Open DevTools', + click: function () { + webview.getByUrl(selectedInstance.dataset.host).openDevTools(); + } }]); -window.addEventListener('contextmenu', function(e) { - if (e.target.classList.contains('instance') || e.target.parentNode.classList.contains('instance')) { - e.preventDefault(); - if (e.target.classList.contains('instance')) { - selectedInstance = e.target; - } else { - selectedInstance = e.target.parentNode; - } - - instanceMenu.popup(remote.getCurrentWindow()); - } +window.addEventListener('contextmenu', function (e) { + if (e.target.classList.contains('instance') || e.target.parentNode.classList.contains('instance')) { + e.preventDefault(); + if (e.target.classList.contains('instance')) { + selectedInstance = e.target; + } else { + selectedInstance = e.target.parentNode; + } + + instanceMenu.popup(remote.getCurrentWindow()); + } }, false); diff --git a/src/scripts/start.js b/src/scripts/start.js index 73bca68fcc95..4f363cb697a7 100644 --- a/src/scripts/start.js +++ b/src/scripts/start.js @@ -7,7 +7,7 @@ import { webview } from './webview'; import tray from './tray'; import './menus'; -sidebar.on('badge-setted', function() { +sidebar.on('badge-setted', function () { var badge = sidebar.getGlobalBadge(); if (process.platform === 'darwin') { @@ -16,15 +16,15 @@ sidebar.on('badge-setted', function() { tray.showTrayAlert(!isNaN(parseInt(badge)) && badge > 0, badge); }); -export var start = function() { +export var start = function () { var defaultInstance = 'https://demo.rocket.chat'; // connection check - function online() { + function online () { document.body.classList.remove('offline'); } - function offline() { + function offline () { document.body.classList.add('offline'); } @@ -40,13 +40,13 @@ export var start = function() { var button = form.querySelector('[type="submit"]'); var invalidUrl = form.querySelector('#invalidUrl'); - window.addEventListener('load', function() { + window.addEventListener('load', function () { hostField.focus(); }); - function validateHost() { - return new Promise(function(resolve, reject) { - var execValidation = function() { + function validateHost () { + return new Promise(function (resolve, reject) { + var execValidation = function () { invalidUrl.style.display = 'none'; hostField.classList.remove('wrong'); @@ -64,11 +64,11 @@ export var start = function() { button.value = 'Validating...'; button.disabled = true; - servers.validateHost(host, 2000).then(function() { + servers.validateHost(host, 2000).then(function () { button.value = 'Connect'; button.disabled = false; resolve(); - }, function(status) { + }, function (status) { // If the url begins with HTTP, mark as invalid if (/^https?:\/\/.+/.test(host) || status === 'basic-auth') { button.value = 'Invalid url'; @@ -113,17 +113,17 @@ export var start = function() { }); } - hostField.addEventListener('blur', function() { - validateHost().then(function() {}, function() {}); + hostField.addEventListener('blur', function () { + validateHost().then(function () {}, function () {}); }); - ipcRenderer.on('certificate-reload', function(event, url) { + ipcRenderer.on('certificate-reload', function (event, url) { hostField.value = url.replace(/\/api\/info$/, ''); - validateHost().then(function() {}, function() {}); + validateHost().then(function () {}, function () {}); }); - var submit = function() { - validateHost().then(function() { + var submit = function () { + validateHost().then(function () { var input = form.querySelector('[name="host"]'); var url = input.value; @@ -138,10 +138,10 @@ export var start = function() { } input.value = ''; - }, function() {}); + }, function () {}); }; - hostField.addEventListener('keydown', function(ev) { + hostField.addEventListener('keydown', function (ev) { if (ev.which === 13) { ev.preventDefault(); ev.stopPropagation(); @@ -150,20 +150,20 @@ export var start = function() { } }); - form.addEventListener('submit', function(ev) { + form.addEventListener('submit', function (ev) { ev.preventDefault(); ev.stopPropagation(); submit(); return false; }); - $('.add-server').on('click', function() { + $('.add-server').on('click', function () { servers.clearActive(); }); servers.restoreActive(); }; -window.addEventListener('focus', function() { +window.addEventListener('focus', function () { webview.focusActive(); }); diff --git a/src/scripts/tray.js b/src/scripts/tray.js index 516a0cb9259d..eb1bbd6e3e43 100644 --- a/src/scripts/tray.js +++ b/src/scripts/tray.js @@ -9,15 +9,15 @@ var Menu = remote.Menu; let mainWindow = remote.getCurrentWindow(); var icons = { - 'win32': { + win32: { dir: 'windows' }, - 'linux': { + linux: { dir: 'linux' }, - 'darwin': { + darwin: { dir: 'osx', icon: 'icon-trayTemplate.png' } @@ -26,22 +26,23 @@ var icons = { let _iconTray = path.join(__dirname, 'images', icons[process.platform].dir, icons[process.platform].icon || 'icon-tray.png'); let _iconTrayAlert = path.join(__dirname, 'images', icons[process.platform].dir, icons[process.platform].iconAlert || 'icon-tray-alert.png'); -function createAppTray() { +function createAppTray () { let _tray = new Tray(_iconTray); var contextMenu = Menu.buildFromTemplate([{ label: 'Quit', - click: function() { + click: function () { remote.app.quit(); } + }]); _tray.setToolTip(remote.app.getName()); - _tray.on('right-click', function(e, b) { + _tray.on('right-click', function (e, b) { _tray.popUpContextMenu(contextMenu, b); }); - _tray.on('click', function(e, b) { + _tray.on('click', function (e, b) { if (e.ctrlKey === true) { _tray.popUpContextMenu(contextMenu, b); return; @@ -58,7 +59,7 @@ function createAppTray() { mainWindow.tray = _tray; } -function showTrayAlert(showAlert, title) { +function showTrayAlert (showAlert, title) { if (mainWindow.tray === null || mainWindow.tray === undefined) { return; } diff --git a/src/scripts/webview.js b/src/scripts/webview.js index 565adb18e0f9..34c9e8e5dea9 100644 --- a/src/scripts/webview.js +++ b/src/scripts/webview.js @@ -4,140 +4,140 @@ import { sidebar } from './sidebar'; import { shell } from 'electron'; class WebView extends EventEmitter { - constructor() { - super(); - - this.webviewParentElement = document.body; - - servers.forEach((host) => { - this.add(host); - }); - - servers.on('host-added', (hostUrl) => { - this.add(servers.get(hostUrl)); - }); - - servers.on('host-removed', (hostUrl) => { - this.remove(hostUrl); - }); - - servers.on('active-setted', (hostUrl) => { - this.setActive(hostUrl); - }); - - servers.on('active-cleared', (hostUrl) => { - this.deactiveAll(hostUrl); - }); - } - - add(host) { - var webviewObj = this.getByUrl(host.url); - if (webviewObj) { - return; - } - - webviewObj = document.createElement('webview'); - webviewObj.setAttribute('server', host.url); - webviewObj.setAttribute('preload', './preload.js'); - webviewObj.setAttribute('allowpopups', 'on'); - webviewObj.setAttribute('disablewebsecurity', 'on'); - - webviewObj.addEventListener('did-navigate-in-page', (lastPath) => { - this.saveLastPath(host.url, lastPath.url); - }); - - webviewObj.addEventListener('console-message', function(e) { - console.log('webview:', e.message); - }); - - webviewObj.addEventListener('ipc-message', (event) => { - this.emit('ipc-message-'+event.channel, host.url, event.args); - - switch (event.channel) { - case 'title-changed': - servers.setHostTitle(host.url, event.args[0]); - break; - case 'unread-changed': - sidebar.setBadge(host.url, event.args[0]); - break; - case 'focus': - servers.setActive(host.url); - break; - } - }); - - webviewObj.addEventListener('dom-ready', () => { - this.emit('dom-ready', host.url); - }); - - // Open external app on clicked link. e.g. mailto:, tel:, etc... - webviewObj.addEventListener('new-window', (e) => { - if (/^https?:\/\//.test(e.url)) { - return; - } - shell.openExternal(e.url); - }); - - this.webviewParentElement.appendChild(webviewObj); - - webviewObj.src = host.lastPath || host.url; - } - - remove(hostUrl) { - var el = this.getByUrl(hostUrl); - if (el) { - el.remove(); - } - } - - saveLastPath(hostUrl, lastPathUrl) { - var hosts = servers.hosts; - hosts[hostUrl].lastPath = lastPathUrl; - servers.hosts = hosts; - } - - getByUrl(hostUrl) { - return this.webviewParentElement.querySelector(`webview[server="${hostUrl}"]`); - } - - getActive() { - return document.querySelector('webview.active'); - } - - isActive(hostUrl) { - return !!this.webviewParentElement.querySelector(`webview.active[server="${hostUrl}"]`); - } - - deactiveAll() { - var item; - while (!(item = this.getActive()) === false) { - item.classList.remove('active'); - } - } - - setActive(hostUrl) { - console.log('active setted', hostUrl); - if (this.isActive(hostUrl)) { - return; - } - - this.deactiveAll(); - var item = this.getByUrl(hostUrl); - if (item) { - item.classList.add('active'); - } - - this.focusActive(); - } - - focusActive() { - var active = this.getActive(); - if (active) { - active.focus(); - return true; - } - return false; - } + constructor () { + super(); + + this.webviewParentElement = document.body; + + servers.forEach((host) => { + this.add(host); + }); + + servers.on('host-added', (hostUrl) => { + this.add(servers.get(hostUrl)); + }); + + servers.on('host-removed', (hostUrl) => { + this.remove(hostUrl); + }); + + servers.on('active-setted', (hostUrl) => { + this.setActive(hostUrl); + }); + + servers.on('active-cleared', (hostUrl) => { + this.deactiveAll(hostUrl); + }); + } + + add (host) { + var webviewObj = this.getByUrl(host.url); + if (webviewObj) { + return; + } + + webviewObj = document.createElement('webview'); + webviewObj.setAttribute('server', host.url); + webviewObj.setAttribute('preload', './preload.js'); + webviewObj.setAttribute('allowpopups', 'on'); + webviewObj.setAttribute('disablewebsecurity', 'on'); + + webviewObj.addEventListener('did-navigate-in-page', (lastPath) => { + this.saveLastPath(host.url, lastPath.url); + }); + + webviewObj.addEventListener('console-message', function (e) { + console.log('webview:', e.message); + }); + + webviewObj.addEventListener('ipc-message', (event) => { + this.emit('ipc-message-'+event.channel, host.url, event.args); + + switch (event.channel) { + case 'title-changed': + servers.setHostTitle(host.url, event.args[0]); + break; + case 'unread-changed': + sidebar.setBadge(host.url, event.args[0]); + break; + case 'focus': + servers.setActive(host.url); + break; + } + }); + + webviewObj.addEventListener('dom-ready', () => { + this.emit('dom-ready', host.url); + }); + + // Open external app on clicked link. e.g. mailto:, tel:, etc... + webviewObj.addEventListener('new-window', (e) => { + if (/^https?:\/\//.test(e.url)) { + return; + } + shell.openExternal(e.url); + }); + + this.webviewParentElement.appendChild(webviewObj); + + webviewObj.src = host.lastPath || host.url; + } + + remove (hostUrl) { + var el = this.getByUrl(hostUrl); + if (el) { + el.remove(); + } + } + + saveLastPath (hostUrl, lastPathUrl) { + var hosts = servers.hosts; + hosts[hostUrl].lastPath = lastPathUrl; + servers.hosts = hosts; + } + + getByUrl (hostUrl) { + return this.webviewParentElement.querySelector(`webview[server="${hostUrl}"]`); + } + + getActive () { + return document.querySelector('webview.active'); + } + + isActive (hostUrl) { + return !!this.webviewParentElement.querySelector(`webview.active[server="${hostUrl}"]`); + } + + deactiveAll () { + var item; + while (!(item = this.getActive()) === false) { + item.classList.remove('active'); + } + } + + setActive (hostUrl) { + console.log('active setted', hostUrl); + if (this.isActive(hostUrl)) { + return; + } + + this.deactiveAll(); + var item = this.getByUrl(hostUrl); + if (item) { + item.classList.add('active'); + } + + this.focusActive(); + } + + focusActive () { + var active = this.getActive(); + if (active) { + active.focus(); + return true; + } + return false; + } } export var webview = new WebView(); From 4edb091a1e6a60708ee9fe86695570bdd35ae7bc Mon Sep 17 00:00:00 2001 From: Rodrigo Nascimento Date: Wed, 11 Jan 2017 12:41:29 -0200 Subject: [PATCH 2/3] Rename .eslintrc to .eslintrc.json --- .eslintrc | 80 -------------------------------------------------- .eslintrc.json | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 80 deletions(-) delete mode 100644 .eslintrc create mode 100644 .eslintrc.json diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index fbc2d7b4402d..000000000000 --- a/.eslintrc +++ /dev/null @@ -1,80 +0,0 @@ -{ - "parserOptions": { - "sourceType": "module" - }, - "env": { - "browser": true, - "commonjs": true, - "es6": true, - "node": true, - "jquery": true - }, - "rules": { - "no-multi-spaces": 2, - "no-eval": 2, - "no-extend-native": 2, - "no-multi-str": 2, - "no-use-before-define": 2, - "no-const-assign": 2, - "no-cond-assign": 2, - "no-constant-condition": 2, - "no-control-regex": 2, - "no-debugger": 2, - "no-delete-var": 2, - "no-dupe-keys": 2, - "no-dupe-args": 2, - "no-duplicate-case": 2, - "no-empty": 2, - "no-empty-character-class": 2, - "no-ex-assign": 2, - "no-extra-boolean-cast": 2, - "no-extra-semi": 2, - "no-fallthrough": 2, - "no-func-assign": 2, - "no-inner-declarations": [2, "functions"], - "no-invalid-regexp": 2, - "no-irregular-whitespace": 2, - "no-mixed-spaces-and-tabs": 2, - "no-sparse-arrays": 2, - "no-negated-in-lhs": 2, - "no-obj-calls": 2, - "no-octal": 2, - "no-redeclare": 2, - "no-regex-spaces": 2, - "no-undef": 2, - "no-unreachable": 2, - "no-unused-vars": [2, { - "vars": "all", - "args": "after-used" - }], - "no-lonely-if": 2, - "no-trailing-spaces": 2, - "complexity": [1, 31], - "space-in-parens": [2, "never"], - "space-before-function-paren": [2, "always"], - "space-before-blocks": [2, "always"], - "indent": [2, 4, {"SwitchCase": 1}], - "keyword-spacing": 2, - "block-spacing": 2, - "brace-style": [2, "1tbs", { "allowSingleLine": true }], - "computed-property-spacing": 2, - "comma-spacing": 2, - "comma-style": 2, - "guard-for-in": 2, - "wrap-iife": 2, - "block-scoped-var": 2, - "curly": [2, "all"], - "eqeqeq": [2, "allow-null"], - "new-cap": [2, { - "capIsNewExceptions": ["Match.Optional", "Match.Maybe", "Match.ObjectIncluding"] - }], - "use-isnan": 2, - "valid-typeof": 2, - "linebreak-style": [2, "unix"], - "semi": [2, "always"] - }, - "globals": { - "_" : false, - "Bugsnag" : false - } -} diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 000000000000..7ca56db05a8e --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,80 @@ +{ + "parserOptions": { + "sourceType": "module" + }, + "env": { + "browser": true, + "commonjs": true, + "es6": true, + "node": true, + "jquery": true + }, + "rules": { + "no-multi-spaces": 2, + "no-eval": 2, + "no-extend-native": 2, + "no-multi-str": 2, + "no-use-before-define": 2, + "no-const-assign": 2, + "no-cond-assign": 2, + "no-constant-condition": 2, + "no-control-regex": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-dupe-keys": 2, + "no-dupe-args": 2, + "no-duplicate-case": 2, + "no-empty": 2, + "no-empty-character-class": 2, + "no-ex-assign": 2, + "no-extra-boolean-cast": 2, + "no-extra-semi": 2, + "no-fallthrough": 2, + "no-func-assign": 2, + "no-inner-declarations": [2, "functions"], + "no-invalid-regexp": 2, + "no-irregular-whitespace": 2, + "no-mixed-spaces-and-tabs": 2, + "no-sparse-arrays": 2, + "no-negated-in-lhs": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-redeclare": 2, + "no-regex-spaces": 2, + "no-undef": 2, + "no-unreachable": 2, + "no-unused-vars": [2, { + "vars": "all", + "args": "after-used" + }], + "no-lonely-if": 2, + "no-trailing-spaces": 2, + "complexity": [1, 31], + "space-in-parens": [2, "never"], + "space-before-function-paren": [2, "always"], + "space-before-blocks": [2, "always"], + "indent": [2, 4, {"SwitchCase": 1}], + "keyword-spacing": 2, + "block-spacing": 2, + "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "computed-property-spacing": 2, + "comma-spacing": 2, + "comma-style": 2, + "guard-for-in": 2, + "wrap-iife": 2, + "block-scoped-var": 2, + "curly": [2, "all"], + "eqeqeq": [2, "allow-null"], + "new-cap": [2, { + "capIsNewExceptions": ["Match.Optional", "Match.Maybe", "Match.ObjectIncluding"] + }], + "use-isnan": 2, + "valid-typeof": 2, + "linebreak-style": [2, "unix"], + "semi": [2, "always"] + }, + "globals": { + "_" : false, + "Bugsnag" : false + } +} From 1e747bde1f3a5873bd29c749e5a7288e6579c865 Mon Sep 17 00:00:00 2001 From: Rodrigo Nascimento Date: Wed, 11 Jan 2017 12:58:40 -0200 Subject: [PATCH 3/3] Add project badges --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 84ecc9f454b8..fd2decab032c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# electron-boilerplate [![Build Status](https://travis-ci.org/szwacz/electron-boilerplate.svg?branch=master)](https://travis-ci.org/szwacz/electron-boilerplate) [![Build status](https://ci.appveyor.com/api/projects/status/s9htc1k5ojkn08fr?svg=true)](https://ci.appveyor.com/project/szwacz/electron-boilerplate) +# electron-boilerplate [![Build Status](https://img.shields.io/travis/RocketChat/Rocket.Chat.Electron/master.svg)](https://travis-ci.org/RocketChat/Rocket.Chat.Electron) [![Build status](https://ci.appveyor.com/api/projects/status/k72eq3gm42wt4j8b?svg=true)](https://ci.appveyor.com/project/RocketChat/rocket-chat-electron) [![Project Dependencies](https://david-dm.org/RocketChat/Rocket.Chat.Electron.svg)](https://david-dm.org/RocketChat/Rocket.Chat.Electron) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/54ebf39732d14cb19a1a992b46bd0da6)](https://www.codacy.com/app/RocketChat/Rocket-Chat-Electron?utm_source=github.com&utm_medium=referral&utm_content=RocketChat/Rocket.Chat.Electron&utm_campaign=Badge_Grade) A minimalistic yet comprehensive boilerplate application for [Electron runtime](http://electron.atom.io). Tested on macOS, Windows and Linux.