diff --git a/dev/App/Abstract.js b/dev/App/Abstract.js index bb59ece4b..bc63a3242 100644 --- a/dev/App/Abstract.js +++ b/dev/App/Abstract.js @@ -1,4 +1,3 @@ - import window from 'window'; import $ from '$'; import _ from '_'; @@ -7,19 +6,31 @@ import key from 'key'; import ssm from 'ssm'; import { - $win, $html, $doc, - startMicrotime, leftPanelDisabled, leftPanelType, - sUserAgent, bMobileDevice, bAnimationSupported + $win, + $html, + $doc, + startMicrotime, + leftPanelDisabled, + leftPanelType, + sUserAgent, + bMobileDevice, + bAnimationSupported } from 'Common/Globals'; import { - noop, isNormal, pString, inArray, microtime, timestamp, - detectDropdownVisibility, windowResizeCallback + noop, + isNormal, + pString, + inArray, + microtime, + timestamp, + detectDropdownVisibility, + windowResizeCallback } from 'Common/Utils'; -import {KeyState, Magics} from 'Common/Enums'; -import {root, rootAdmin, rootUser, populateAuthSuffix} from 'Common/Links'; -import {initOnStartOrLangChange, initNotificationLanguage} from 'Common/Translator'; +import { KeyState, Magics } from 'Common/Enums'; +import { root, rootAdmin, rootUser, populateAuthSuffix } from 'Common/Links'; +import { initOnStartOrLangChange, initNotificationLanguage } from 'Common/Translator'; import * as Events from 'Common/Events'; import * as Settings from 'Storage/Settings'; @@ -27,16 +38,14 @@ import LanguageStore from 'Stores/Language'; import ThemeStore from 'Stores/Theme'; import SocialStore from 'Stores/Social'; -import {routeOff, setHash} from 'Knoin/Knoin'; -import {AbstractBoot} from 'Knoin/AbstractBoot'; +import { routeOff, setHash } from 'Knoin/Knoin'; +import { AbstractBoot } from 'Knoin/AbstractBoot'; -class AbstractApp extends AbstractBoot -{ +class AbstractApp extends AbstractBoot { /** * @param {RemoteStorage|AdminRemoteStorage} Remote */ - constructor(Remote) - { + constructor(Remote) { super(); this.googlePreviewSupportedCache = null; @@ -47,14 +56,15 @@ class AbstractApp extends AbstractBoot this.iframe = $('').appendTo('body'); $win.on('error', (event) => { - if (event && event.originalEvent && event.originalEvent.message && - -1 === inArray(event.originalEvent.message, [ - 'Script error.', 'Uncaught Error: Error calling method on NPObject.' - ])) - { + if ( + event && + event.originalEvent && + event.originalEvent.message && + -1 === + inArray(event.originalEvent.message, ['Script error.', 'Uncaught Error: Error calling method on NPObject.']) + ) { const time = timestamp(); - if (this.lastErrorTime >= time) - { + if (this.lastErrorTime >= time) { return; } @@ -76,19 +86,20 @@ class AbstractApp extends AbstractBoot Events.pub('window.resize'); }); - Events.sub('window.resize', _.throttle(() => { - const - iH = $win.height(), - iW = $win.height(); + Events.sub( + 'window.resize', + _.throttle(() => { + const iH = $win.height(), + iW = $win.height(); - if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) - { - $win.__sizes[0] = iH; - $win.__sizes[1] = iW; + if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) { + $win.__sizes[0] = iH; + $win.__sizes[1] = iW; - Events.pub('window.resize.real'); - } - }, Magics.Time50ms)); + Events.pub('window.resize.real'); + } + }, Magics.Time50ms) + ); // DEBUG // Events.sub({ @@ -100,21 +111,24 @@ class AbstractApp extends AbstractBoot // } // }); - $doc.on('keydown', (event) => { - if (event && event.ctrlKey) - { - $html.addClass('rl-ctrl-key-pressed'); - } - }).on('keyup', (event) => { - if (event && !event.ctrlKey) - { - $html.removeClass('rl-ctrl-key-pressed'); - } - }); + $doc + .on('keydown', (event) => { + if (event && event.ctrlKey) { + $html.addClass('rl-ctrl-key-pressed'); + } + }) + .on('keyup', (event) => { + if (event && !event.ctrlKey) { + $html.removeClass('rl-ctrl-key-pressed'); + } + }); - $doc.on('mousemove keypress click', _.debounce(() => { - Events.pub('rl.auto-logout-refresh'); - }, Magics.Time5s)); + $doc.on( + 'mousemove keypress click', + _.debounce(() => { + Events.pub('rl.auto-logout-refresh'); + }, Magics.Time5s) + ); key('esc, enter', KeyState.All, () => { detectDropdownVisibility(); @@ -138,17 +152,13 @@ class AbstractApp extends AbstractBoot * @returns {boolean} */ download(link) { - - if (sUserAgent && (-1 < sUserAgent.indexOf('chrome') || -1 < sUserAgent.indexOf('chrome'))) - { + if (sUserAgent && (-1 < sUserAgent.indexOf('chrome') || -1 < sUserAgent.indexOf('chrome'))) { const oLink = window.document.createElement('a'); oLink.href = link; - if (window.document && window.document.createEvent) - { + if (window.document && window.document.createEvent) { const oE = window.document.createEvent.MouseEvents; - if (oE && oE.initEvent && oLink.dispatchEvent) - { + if (oE && oE.initEvent && oLink.dispatchEvent) { oE.initEvent('click', true, true); oLink.dispatchEvent(oE); return true; @@ -156,13 +166,10 @@ class AbstractApp extends AbstractBoot } } - if (bMobileDevice) - { + if (bMobileDevice) { window.open(link, '_self'); window.focus(); - } - else - { + } else { this.iframe.attr('src', link); // window.document.location.href = link; } @@ -174,10 +181,9 @@ class AbstractApp extends AbstractBoot * @returns {boolean} */ googlePreviewSupported() { - if (null === this.googlePreviewSupportedCache) - { - this.googlePreviewSupportedCache = !!Settings.settingsGet('AllowGoogleSocial') && - !!Settings.settingsGet('AllowGoogleSocialPreview'); + if (null === this.googlePreviewSupportedCache) { + this.googlePreviewSupportedCache = + !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialPreview'); } return this.googlePreviewSupportedCache; @@ -187,9 +193,8 @@ class AbstractApp extends AbstractBoot * @param {string} title */ setWindowTitle(title) { - title = ((isNormal(title) && 0 < title.length) ? '' + title : ''); - if (Settings.settingsGet('Title')) - { + title = isNormal(title) && 0 < title.length ? '' + title : ''; + if (Settings.settingsGet('Title')) { title += (title ? ' - ' : '') + Settings.settingsGet('Title'); } @@ -204,8 +209,7 @@ class AbstractApp extends AbstractBoot } clearClientSideToken() { - if (window.__rlah_clear) - { + if (window.__rlah_clear) { window.__rlah_clear(); } } @@ -214,8 +218,7 @@ class AbstractApp extends AbstractBoot * @param {string} token */ setClientSideToken(token) { - if (window.__rlah_set) - { + if (window.__rlah_set) { window.__rlah_set(token); Settings.settingsSet('AuthAccountHash', token); @@ -229,58 +232,42 @@ class AbstractApp extends AbstractBoot * @param {boolean=} close = false */ loginAndLogoutReload(admin = false, logout = false, close = false) { - const inIframe = !!Settings.appSettingsGet('inIframe'); let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink')); - if (logout) - { + if (logout) { this.clearClientSideToken(); } - if (logout && close && window.close) - { + if (logout && close && window.close) { window.close(); } customLogoutLink = customLogoutLink || (admin ? rootAdmin() : rootUser()); - if (logout && window.location.href !== customLogoutLink) - { + if (logout && window.location.href !== customLogoutLink) { _.delay(() => { - - if (inIframe && window.parent) - { + if (inIframe && window.parent) { window.parent.location.href = customLogoutLink; - } - else - { + } else { window.location.href = customLogoutLink; } $win.trigger('rl.tooltips.diactivate'); - }, Magics.Time100ms); - } - else - { + } else { routeOff(); setHash(root(), true); routeOff(); _.delay(() => { - - if (inIframe && window.parent) - { + if (inIframe && window.parent) { window.parent.location.reload(); - } - else - { + } else { window.location.reload(); } $win.trigger('rl.tooltips.diactivate'); - }, Magics.Time100ms); } } @@ -290,7 +277,6 @@ class AbstractApp extends AbstractBoot } bootstart() { - // log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); Events.pub('rl.bootstart'); @@ -307,13 +293,10 @@ class AbstractApp extends AbstractBoot ko.components.register('x-script', require('Component/Script').default); // ko.components.register('svg-icon', require('Component/SvgIcon').default); - if (Settings.appSettingsGet('materialDesign') && bAnimationSupported) - { + if (Settings.appSettingsGet('materialDesign') && bAnimationSupported) { ko.components.register('Checkbox', require('Component/MaterialDesign/Checkbox').default); ko.components.register('CheckboxSimple', require('Component/Checkbox').default); - } - else - { + } else { // ko.components.register('Checkbox', require('Component/Classic/Checkbox').default); // ko.components.register('CheckboxSimple', require('Component/Classic/Checkbox').default); ko.components.register('Checkbox', require('Component/Checkbox').default); @@ -332,8 +315,7 @@ class AbstractApp extends AbstractBoot leftPanelDisabled(false); }); - if (!mobile) - { + if (!mobile) { $html.addClass('rl-desktop'); ssm.addState({ @@ -381,9 +363,7 @@ class AbstractApp extends AbstractBoot $html.removeClass('ssm-state-desktop-large'); } }); - } - else - { + } else { $html.addClass('ssm-state-mobile').addClass('rl-mobile'); Events.pub('ssm.mobile-enter'); } @@ -406,4 +386,4 @@ class AbstractApp extends AbstractBoot } } -export {AbstractApp, AbstractApp as default}; +export { AbstractApp, AbstractApp as default }; diff --git a/dev/App/Admin.js b/dev/App/Admin.js index b4e507ef0..16e52eee2 100644 --- a/dev/App/Admin.js +++ b/dev/App/Admin.js @@ -1,13 +1,12 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; import progressJs from 'progressJs'; -import {root} from 'Common/Links'; -import {getNotification} from 'Common/Translator'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {pInt, isNormal, isArray, inArray, isUnd} from 'Common/Utils'; +import { root } from 'Common/Links'; +import { getNotification } from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { pInt, isNormal, isArray, inArray, isUnd } from 'Common/Utils'; import * as Settings from 'Storage/Settings'; @@ -20,14 +19,13 @@ import PackageStore from 'Stores/Admin/Package'; import CoreStore from 'Stores/Admin/Core'; import Remote from 'Remote/Admin/Ajax'; -import {SettingsAdminScreen} from 'Screen/Admin/Settings'; -import {LoginAdminScreen} from 'Screen/Admin/Login'; +import { SettingsAdminScreen } from 'Screen/Admin/Settings'; +import { LoginAdminScreen } from 'Screen/Admin/Login'; -import {hideLoading, routeOff, setHash, startScreens} from 'Knoin/Knoin'; -import {AbstractApp} from 'App/Abstract'; +import { hideLoading, routeOff, setHash, startScreens } from 'Knoin/Knoin'; +import { AbstractApp } from 'App/Abstract'; -class AdminApp extends AbstractApp -{ +class AdminApp extends AbstractApp { constructor() { super(Remote); } @@ -40,14 +38,15 @@ class AdminApp extends AbstractApp DomainStore.domains.loading(true); Remote.domainList((result, data) => { DomainStore.domains.loading(false); - if (StorageResultType.Success === result && data && data.Result) - { - DomainStore.domains(_.map(data.Result, ([enabled, alias], name) => ({ - name: name, - disabled: ko.observable(!enabled), - alias: alias, - deleteAccess: ko.observable(false) - }))); + if (StorageResultType.Success === result && data && data.Result) { + DomainStore.domains( + _.map(data.Result, ([enabled, alias], name) => ({ + name: name, + disabled: ko.observable(!enabled), + alias: alias, + deleteAccess: ko.observable(false) + })) + ); } }); } @@ -56,13 +55,14 @@ class AdminApp extends AbstractApp PluginStore.plugins.loading(true); Remote.pluginList((result, data) => { PluginStore.plugins.loading(false); - if (StorageResultType.Success === result && data && data.Result) - { - PluginStore.plugins(_.map(data.Result, (item) => ({ - name: item.Name, - disabled: ko.observable(!item.Enabled), - configured: ko.observable(!!item.Configured) - }))); + if (StorageResultType.Success === result && data && data.Result) { + PluginStore.plugins( + _.map(data.Result, (item) => ({ + name: item.Name, + disabled: ko.observable(!item.Enabled), + configured: ko.observable(!!item.Configured) + })) + ); } }); } @@ -72,8 +72,7 @@ class AdminApp extends AbstractApp PackageStore.packagesReal(true); Remote.packagesList((result, data) => { PackageStore.packages.loading(false); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { PackageStore.packagesReal(!!data.Result.Real); PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable); @@ -81,28 +80,25 @@ class AdminApp extends AbstractApp const loading = {}; _.each(PackageStore.packages(), (item) => { - if (item && item.loading()) - { + if (item && item.loading()) { loading[item.file] = item; } }); - if (isArray(data.Result.List)) - { - list = _.compact(_.map(data.Result.List, (item) => { - if (item) - { - item.loading = ko.observable(!isUnd(loading[item.file])); - return 'core' === item.type && !item.canBeInstalled ? null : item; - } - return null; - })); + if (isArray(data.Result.List)) { + list = _.compact( + _.map(data.Result.List, (item) => { + if (item) { + item.loading = ko.observable(!isUnd(loading[item.file])); + return 'core' === item.type && !item.canBeInstalled ? null : item; + } + return null; + }) + ); } PackageStore.packages(list); - } - else - { + } else { PackageStore.packagesReal(false); } }); @@ -116,13 +112,10 @@ class AdminApp extends AbstractApp CoreStore.coreRemoteVersion(''); CoreStore.coreRemoteRelease(''); CoreStore.coreVersionCompare(-2); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { CoreStore.coreReal(true); window.location.reload(); - } - else - { + } else { CoreStore.coreReal(false); } }); @@ -133,8 +126,7 @@ class AdminApp extends AbstractApp CoreStore.coreReal(true); Remote.coreData((result, data) => { CoreStore.coreChecking(false); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { CoreStore.coreReal(!!data.Result.Real); CoreStore.coreChannel(data.Result.Channel || 'stable'); CoreStore.coreType(data.Result.Type || 'stable'); @@ -145,9 +137,7 @@ class AdminApp extends AbstractApp CoreStore.coreRemoteVersion(data.Result.RemoteVersion || ''); CoreStore.coreRemoteRelease(data.Result.RemoteRelease || ''); CoreStore.coreVersionCompare(pInt(data.Result.VersionCompare)); - } - else - { + } else { CoreStore.coreReal(false); CoreStore.coreChannel('stable'); CoreStore.coreType('stable'); @@ -168,33 +158,25 @@ class AdminApp extends AbstractApp LicenseStore.licenseError(''); Remote.licensing((result, data) => { LicenseStore.licensingProcess(false); - if (StorageResultType.Success === result && data && data.Result && isNormal(data.Result.Expired)) - { + if (StorageResultType.Success === result && data && data.Result && isNormal(data.Result.Expired)) { LicenseStore.licenseValid(true); LicenseStore.licenseExpired(pInt(data.Result.Expired)); LicenseStore.licenseError(''); LicenseStore.licensing(true); AppStore.prem(true); - } - else - { - if (data && data.ErrorCode && -1 < inArray(pInt(data.ErrorCode), [ - Notification.LicensingServerIsUnavailable, - Notification.LicensingExpired - ])) - { + } else { + if ( + data && + data.ErrorCode && + -1 < inArray(pInt(data.ErrorCode), [Notification.LicensingServerIsUnavailable, Notification.LicensingExpired]) + ) { LicenseStore.licenseError(getNotification(pInt(data.ErrorCode))); LicenseStore.licensing(true); - } - else - { - if (StorageResultType.Abort === result) - { + } else { + if (StorageResultType.Abort === result) { LicenseStore.licenseError(getNotification(Notification.LicensingServerIsUnavailable)); LicenseStore.licensing(true); - } - else - { + } else { LicenseStore.licensing(false); } } @@ -203,19 +185,16 @@ class AdminApp extends AbstractApp } bootend(bootendCallback = null) { - if (progressJs) - { + if (progressJs) { progressJs.end(); } - if (bootendCallback) - { + if (bootendCallback) { bootendCallback(); } } bootstart() { - super.bootstart(); AppStore.populate(); @@ -223,8 +202,7 @@ class AdminApp extends AbstractApp hideLoading(); - if (!Settings.appSettingsGet('allowAdminPanel')) - { + if (!Settings.appSettingsGet('allowAdminPanel')) { routeOff(); setHash(root(), true); routeOff(); @@ -232,20 +210,11 @@ class AdminApp extends AbstractApp _.defer(() => { window.location.href = '/'; }); - } - else - { - if (Settings.settingsGet('Auth')) - { - startScreens([ - SettingsAdminScreen - ]); - } - else - { - startScreens([ - LoginAdminScreen - ]); + } else { + if (Settings.settingsGet('Auth')) { + startScreens([SettingsAdminScreen]); + } else { + startScreens([LoginAdminScreen]); } } diff --git a/dev/App/User.js b/dev/App/User.js index 6400c0b75..427a14a5d 100644 --- a/dev/App/User.js +++ b/dev/App/User.js @@ -1,45 +1,70 @@ - import window from 'window'; import _ from '_'; import $ from '$'; import progressJs from 'progressJs'; import { - noop, trim, log, has, isArray, inArray, isUnd, isNormal, isPosNumeric, isNonEmptyArray, - pInt, pString, delegateRunOnDestroy, mailToHelper, windowResize, jassl + noop, + trim, + log, + has, + isArray, + inArray, + isUnd, + isNormal, + isPosNumeric, + isNonEmptyArray, + pInt, + pString, + delegateRunOnDestroy, + mailToHelper, + windowResize, + jassl } from 'Common/Utils'; import { - Layout, Capa, StorageResultType, Notification, FolderType, - SetSystemFoldersNotification, MessageSetAction, ClientSideKeyName, Magics + Layout, + Capa, + StorageResultType, + Notification, + FolderType, + SetSystemFoldersNotification, + MessageSetAction, + ClientSideKeyName, + Magics } from 'Common/Enums'; -import { - $html, - leftPanelWidth, leftPanelDisabled, - bAnimationSupported, bMobileDevice -} from 'Common/Globals'; +import { $html, leftPanelWidth, leftPanelDisabled, bAnimationSupported, bMobileDevice } from 'Common/Globals'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {runHook} from 'Common/Plugins'; -import {momentNowUnix, reload as momentReload} from 'Common/Momentor'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { runHook } from 'Common/Plugins'; +import { momentNowUnix, reload as momentReload } from 'Common/Momentor'; import { - initMessageFlagsFromCache, setFolderHash, getFolderHash, getFolderInboxName, - getFolderFromCacheList, clearMessageFlagsFromCacheByFolder, + initMessageFlagsFromCache, + setFolderHash, + getFolderHash, + getFolderInboxName, + getFolderFromCacheList, + clearMessageFlagsFromCacheByFolder, storeMessageFlagsToCacheBySetAction, storeMessageFlagsToCacheByFolderAndUid } from 'Common/Cache'; import { - userBackground, mailBox, root, - openPgpWorkerJs, openPgpJs, - socialGoogle, socialTwitter, socialFacebook + userBackground, + mailBox, + root, + openPgpWorkerJs, + openPgpJs, + socialGoogle, + socialTwitter, + socialFacebook } from 'Common/Links'; import * as Events from 'Common/Events'; -import {getNotification, i18n} from 'Common/Translator'; +import { getNotification, i18n } from 'Common/Translator'; import SocialStore from 'Stores/Social'; import AppStore from 'Stores/User/App'; @@ -56,31 +81,27 @@ import QuotaStore from 'Stores/User/Quota'; import * as Local from 'Storage/Client'; import * as Settings from 'Storage/Settings'; -import {checkTimestamp} from 'Storage/RainLoop'; +import { checkTimestamp } from 'Storage/RainLoop'; import Remote from 'Remote/User/Ajax'; import Promises from 'Promises/User/Ajax'; -import {EmailModel} from 'Model/Email'; -import {AccountModel} from 'Model/Account'; -import {IdentityModel} from 'Model/Identity'; -import {TemplateModel} from 'Model/Template'; -import {OpenPgpKeyModel} from 'Model/OpenPgpKey'; +import { EmailModel } from 'Model/Email'; +import { AccountModel } from 'Model/Account'; +import { IdentityModel } from 'Model/Identity'; +import { TemplateModel } from 'Model/Template'; +import { OpenPgpKeyModel } from 'Model/OpenPgpKey'; // import {AboutUserScreen} from 'Screen/User/About'; -import {LoginUserScreen} from 'Screen/User/Login'; -import {MailBoxUserScreen} from 'Screen/User/MailBox'; -import {SettingsUserScreen} from 'Screen/User/Settings'; +import { LoginUserScreen } from 'Screen/User/Login'; +import { MailBoxUserScreen } from 'Screen/User/MailBox'; +import { SettingsUserScreen } from 'Screen/User/Settings'; -import { - hideLoading, routeOff, routeOn, setHash, - startScreens, showScreenPopup -} from 'Knoin/Knoin'; +import { hideLoading, routeOff, routeOn, setHash, startScreens, showScreenPopup } from 'Knoin/Knoin'; -import {AbstractApp} from 'App/Abstract'; +import { AbstractApp } from 'App/Abstract'; -class AppUser extends AbstractApp -{ +class AppUser extends AbstractApp { constructor() { super(Remote); @@ -101,31 +122,33 @@ class AppUser extends AbstractApp window.setInterval(() => Events.pub('interval.20m'), Magics.Time20m); window.setTimeout(() => window.setInterval(() => Events.pub('interval.2m-after5m'), Magics.Time2m), Magics.Time5m); - window.setTimeout(() => window.setInterval(() => Events.pub('interval.5m-after5m'), Magics.Time5m), Magics.Time5m); - window.setTimeout(() => window.setInterval(() => Events.pub('interval.10m-after5m'), Magics.Time10m), Magics.Time5m); + window.setTimeout(() => window.setInterval(() => Events.pub('interval.5m-after5m'), Magics.Time5m), Magics.Time5m); + window.setTimeout( + () => window.setInterval(() => Events.pub('interval.10m-after5m'), Magics.Time10m), + Magics.Time5m + ); - $.wakeUp(() => { - if (checkTimestamp()) - { - this.reload(); - } - - Remote.jsVersion((sResult, oData) => { - if (StorageResultType.Success === sResult && oData && !oData.Result) - { + $.wakeUp( + () => { + if (checkTimestamp()) { this.reload(); } - }, Settings.appSettingsGet('version')); - }, {}, Magics.Time60m); + Remote.jsVersion((sResult, oData) => { + if (StorageResultType.Success === sResult && oData && !oData.Result) { + this.reload(); + } + }, Settings.appSettingsGet('version')); + }, + {}, + Magics.Time60m + ); - if (checkTimestamp()) - { + if (checkTimestamp()) { this.reload(); } - if (Settings.settingsGet('UserBackgroundHash')) - { + if (Settings.settingsGet('UserBackgroundHash')) { _.delay(() => { $('#rl-bg') .attr('style', 'background-image: none !important;') @@ -146,12 +169,9 @@ class AppUser extends AbstractApp } reload() { - if (window.parent && !!Settings.appSettingsGet('inIframe')) - { + if (window.parent && !!Settings.appSettingsGet('inIframe')) { window.parent.location.reload(); - } - else - { + } else { window.location.reload(); } } @@ -168,54 +188,47 @@ class AppUser extends AbstractApp * @param {boolean=} bDropCurrenFolderCache = false */ reloadMessageList(bDropPagePosition = false, bDropCurrenFolderCache = false) { + let iOffset = (MessageStore.messageListPage() - 1) * SettingsStore.messagesPerPage(); - let - iOffset = (MessageStore.messageListPage() - 1) * SettingsStore.messagesPerPage(); - - if (bDropCurrenFolderCache) - { + if (bDropCurrenFolderCache) { setFolderHash(FolderStore.currentFolderFullNameRaw(), ''); } - if (bDropPagePosition) - { + if (bDropPagePosition) { MessageStore.messageListPage(1); MessageStore.messageListPageBeforeThread(1); iOffset = 0; - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - MessageStore.messageListPage(), - MessageStore.messageListSearch(), - MessageStore.messageListThreadUid() - ), true, true); + setHash( + mailBox( + FolderStore.currentFolderFullNameHash(), + MessageStore.messageListPage(), + MessageStore.messageListSearch(), + MessageStore.messageListThreadUid() + ), + true, + true + ); } MessageStore.messageListLoading(true); Remote.messageList( (sResult, oData, bCached) => { - - if (StorageResultType.Success === sResult && oData && oData.Result) - { + if (StorageResultType.Success === sResult && oData && oData.Result) { MessageStore.messageListError(''); MessageStore.messageListLoading(false); MessageStore.setMessageList(oData, bCached); - } - else if (StorageResultType.Unload === sResult) - { + } else if (StorageResultType.Unload === sResult) { MessageStore.messageListError(''); MessageStore.messageListLoading(false); - } - else if (StorageResultType.Abort !== sResult) - { + } else if (StorageResultType.Abort !== sResult) { MessageStore.messageList([]); MessageStore.messageListLoading(false); - MessageStore.messageListError(oData && oData.ErrorCode ? - getNotification(oData.ErrorCode) : i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST') + MessageStore.messageListError( + oData && oData.ErrorCode ? getNotification(oData.ErrorCode) : i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST') ); } - }, FolderStore.currentFolderFullNameRaw(), iOffset, @@ -234,21 +247,22 @@ class AppUser extends AbstractApp * @returns {boolean} */ contactsSync(fResultFunc) { - const oContacts = ContactStore.contacts; - if (oContacts.importing() || oContacts.syncing() || !ContactStore.enableContactsSync() || !ContactStore.allowContactsSync()) - { + if ( + oContacts.importing() || + oContacts.syncing() || + !ContactStore.enableContactsSync() || + !ContactStore.allowContactsSync() + ) { return false; } oContacts.syncing(true); Remote.contactsSync((sResult, oData) => { - oContacts.syncing(false); - if (fResultFunc) - { + if (fResultFunc) { fResultFunc(sResult, oData); } }); @@ -257,30 +271,30 @@ class AppUser extends AbstractApp } messagesMoveTrigger() { - - const - sTrashFolder = FolderStore.trashFolder(), + const sTrashFolder = FolderStore.trashFolder(), sSpamFolder = FolderStore.spamFolder(); _.each(this.moveCache, (item) => { - - const - isSpam = sSpamFolder === item.To, + const isSpam = sSpamFolder === item.To, isTrash = sTrashFolder === item.To, isHam = !isSpam && sSpamFolder === item.From && getFolderInboxName() === item.To; - Remote.messagesMove(this.moveOrDeleteResponseHelper, item.From, item.To, item.Uid, - isSpam ? 'SPAM' : (isHam ? 'HAM' : ''), isSpam || isTrash); + Remote.messagesMove( + this.moveOrDeleteResponseHelper, + item.From, + item.To, + item.Uid, + isSpam ? 'SPAM' : isHam ? 'HAM' : '', + isSpam || isTrash + ); }); this.moveCache = {}; } messagesMoveHelper(fromFolderFullNameRaw, toFolderFullNameRaw, uidsForMove) { - const hash = '$$' + fromFolderFullNameRaw + '$$' + toFolderFullNameRaw + '$$'; - if (!this.moveCache[hash]) - { + if (!this.moveCache[hash]) { this.moveCache[hash] = { From: fromFolderFullNameRaw, To: toFolderFullNameRaw, @@ -293,37 +307,21 @@ class AppUser extends AbstractApp } messagesCopyHelper(sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy) { - Remote.messagesCopy( - this.moveOrDeleteResponseHelper, - sFromFolderFullNameRaw, - sToFolderFullNameRaw, - aUidForCopy - ); + Remote.messagesCopy(this.moveOrDeleteResponseHelper, sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy); } messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove) { - Remote.messagesDelete( - this.moveOrDeleteResponseHelper, - sFromFolderFullNameRaw, - aUidForRemove - ); + Remote.messagesDelete(this.moveOrDeleteResponseHelper, sFromFolderFullNameRaw, aUidForRemove); } moveOrDeleteResponseHelper(sResult, oData) { - - if (StorageResultType.Success === sResult && FolderStore.currentFolder()) - { - if (oData && isArray(oData.Result) && 2 === oData.Result.length) - { + if (StorageResultType.Success === sResult && FolderStore.currentFolder()) { + if (oData && isArray(oData.Result) && 2 === oData.Result.length) { setFolderHash(oData.Result[0], oData.Result[1]); - } - else - { + } else { setFolderHash(FolderStore.currentFolderFullNameRaw(), ''); - if (oData && -1 < inArray(oData.ErrorCode, - [Notification.CantMoveMessage, Notification.CantCopyMessage])) - { + if (oData && -1 < inArray(oData.ErrorCode, [Notification.CantMoveMessage, Notification.CantCopyMessage])) { window.alert(getNotification(oData.ErrorCode)); } } @@ -349,13 +347,10 @@ class AppUser extends AbstractApp * @param {boolean=} bUseFolder = true */ deleteMessagesFromFolder(iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder) { - - let - oMoveFolder = null, + let oMoveFolder = null, nSetSystemFoldersNotification = null; - switch (iDeleteType) - { + switch (iDeleteType) { case FolderType.Spam: oMoveFolder = getFolderFromCacheList(FolderStore.spamFolder()); nSetSystemFoldersNotification = SetSystemFoldersNotification.Spam; @@ -375,30 +370,31 @@ class AppUser extends AbstractApp } bUseFolder = isUnd(bUseFolder) ? true : !!bUseFolder; - if (bUseFolder) - { - if ((FolderType.Spam === iDeleteType && UNUSED_OPTION_VALUE === FolderStore.spamFolder()) || + if (bUseFolder) { + if ( + (FolderType.Spam === iDeleteType && UNUSED_OPTION_VALUE === FolderStore.spamFolder()) || (FolderType.Trash === iDeleteType && UNUSED_OPTION_VALUE === FolderStore.trashFolder()) || - (FolderType.Archive === iDeleteType && UNUSED_OPTION_VALUE === FolderStore.archiveFolder())) - { + (FolderType.Archive === iDeleteType && UNUSED_OPTION_VALUE === FolderStore.archiveFolder()) + ) { bUseFolder = false; } } - if (!oMoveFolder && bUseFolder) - { + if (!oMoveFolder && bUseFolder) { showScreenPopup(require('View/Popup/FolderSystem'), [nSetSystemFoldersNotification]); - } - else if (!bUseFolder || (FolderType.Trash === iDeleteType && - (sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder()))) - { - showScreenPopup(require('View/Popup/Ask'), [i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => { - this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); - MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove); - }]); - } - else if (oMoveFolder) - { + } else if ( + !bUseFolder || + (FolderType.Trash === iDeleteType && + (sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder())) + ) { + showScreenPopup(require('View/Popup/Ask'), [ + i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), + () => { + this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); + MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove); + } + ]); + } else if (oMoveFolder) { this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove); MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw); } @@ -411,21 +407,14 @@ class AppUser extends AbstractApp * @param {boolean=} bCopy = false */ moveMessagesToFolder(sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy) { - - if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && isArray(aUidForMove) && 0 < aUidForMove.length) - { - const - oFromFolder = getFolderFromCacheList(sFromFolderFullNameRaw), + if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && isArray(aUidForMove) && 0 < aUidForMove.length) { + const oFromFolder = getFolderFromCacheList(sFromFolderFullNameRaw), oToFolder = getFolderFromCacheList(sToFolderFullNameRaw); - if (oFromFolder && oToFolder) - { - if (isUnd(bCopy) ? false : !!bCopy) - { + if (oFromFolder && oToFolder) { + if (isUnd(bCopy) ? false : !!bCopy) { this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove); - } - else - { + } else { this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove); } @@ -442,61 +431,60 @@ class AppUser extends AbstractApp */ foldersReload(callback = null) { const prom = Promises.foldersReload(FolderStore.foldersLoading); - if (callback) - { - prom.then((value) => !!value).then(callback).catch(() => { - _.delay(() => { - if (callback) - { - callback(false); // eslint-disable-line callback-return - } - }, 1); - }); + if (callback) { + prom + .then((value) => !!value) + .then(callback) + .catch(() => { + _.delay(() => { + if (callback) { + callback(false); // eslint-disable-line callback-return + } + }, 1); + }); } } foldersPromisesActionHelper(promise, errorDefCode) { - Promises - .abort('Folders') + Promises.abort('Folders') .fastResolve(true) .then(() => promise) - .then(() => { - Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); - }, (errorCode) => { - FolderStore.folderList.error(getNotification(errorCode, '', errorDefCode)); - Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); - }); + .then( + () => { + Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); + }, + (errorCode) => { + FolderStore.folderList.error(getNotification(errorCode, '', errorDefCode)); + Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); + } + ); } reloadOpenPgpKeys() { - - if (PgpStore.capaOpenPGP()) - { - const - keys = [], + if (PgpStore.capaOpenPGP()) { + const keys = [], email = new EmailModel(), openpgpKeyring = PgpStore.openpgpKeyring, openpgpKeys = openpgpKeyring ? openpgpKeyring.getAllKeys() : []; _.each(openpgpKeys, (oItem, iIndex) => { - if (oItem && oItem.primaryKey) - { - const - aEmails = [], + if (oItem && oItem.primaryKey) { + const aEmails = [], aUsers = [], primaryUser = oItem.getPrimaryUser(), - user = (primaryUser && primaryUser.user) ? primaryUser.user.userId.userid : - (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : ''); + user = + primaryUser && primaryUser.user + ? primaryUser.user.userId.userid + : oItem.users && oItem.users[0] + ? oItem.users[0].userId.userid + : ''; - if (oItem.users) - { + if (oItem.users) { _.each(oItem.users, (item) => { - if (item.userId) - { + if (item.userId) { email.clear(); email.parse(item.userId.userid); - if (email.validate()) - { + if (email.validate()) { aEmails.push(email.email); aUsers.push(item.userId.userid); } @@ -504,20 +492,22 @@ class AppUser extends AbstractApp }); } - if (aEmails.length) - { - keys.push(new OpenPgpKeyModel( - iIndex, - oItem.primaryKey.getFingerprint(), - oItem.primaryKey.getKeyId().toHex().toLowerCase(), - _.uniq(_.compact(_.map( - oItem.getKeyIds(), (item) => (item && item.toHex ? item.toHex() : null) - ))), - aUsers, - aEmails, - oItem.isPrivate(), - oItem.armor(), - user) + if (aEmails.length) { + keys.push( + new OpenPgpKeyModel( + iIndex, + oItem.primaryKey.getFingerprint(), + oItem.primaryKey + .getKeyId() + .toHex() + .toLowerCase(), + _.uniq(_.compact(_.map(oItem.getKeyIds(), (item) => (item && item.toHex ? item.toHex() : null)))), + aUsers, + aEmails, + oItem.isPrivate(), + oItem.armor(), + user + ) ); } } @@ -559,94 +549,95 @@ class AppUser extends AbstractApp } accountsAndIdentities(bBoot) { - AccountStore.accounts.loading(true); IdentityStore.identities.loading(true); Remote.accountsAndIdentities((sResult, oData) => { - AccountStore.accounts.loading(false); IdentityStore.identities.loading(false); - if (StorageResultType.Success === sResult && oData.Result) - { - const - counts = {}, + if (StorageResultType.Success === sResult && oData.Result) { + const counts = {}, sAccountEmail = AccountStore.email(); - let - parentEmail = Settings.settingsGet('ParentEmail'); + let parentEmail = Settings.settingsGet('ParentEmail'); parentEmail = '' === parentEmail ? sAccountEmail : parentEmail; - if (isArray(oData.Result.Accounts)) - { + if (isArray(oData.Result.Accounts)) { _.each(AccountStore.accounts(), (oAccount) => { counts[oAccount.email] = oAccount.count(); }); delegateRunOnDestroy(AccountStore.accounts()); - AccountStore.accounts(_.map(oData.Result.Accounts, - (sValue) => new AccountModel(sValue, sValue !== parentEmail, counts[sValue] || 0))); + AccountStore.accounts( + _.map( + oData.Result.Accounts, + (sValue) => new AccountModel(sValue, sValue !== parentEmail, counts[sValue] || 0) + ) + ); } - if (isUnd(bBoot) ? false : !!bBoot) - { + if (isUnd(bBoot) ? false : !!bBoot) { _.delay(() => this.accountsCounts(), 1000 * 5); Events.sub('interval.10m-after5m', () => this.accountsCounts()); } - if (isArray(oData.Result.Identities)) - { + if (isArray(oData.Result.Identities)) { delegateRunOnDestroy(IdentityStore.identities()); - IdentityStore.identities(_.map(oData.Result.Identities, (identityData) => { + IdentityStore.identities( + _.map(oData.Result.Identities, (identityData) => { + const id = pString(identityData.Id), + email = pString(identityData.Email), + identity = new IdentityModel(id, email); - const - id = pString(identityData.Id), - email = pString(identityData.Email), - identity = new IdentityModel(id, email); + identity.name(pString(identityData.Name)); + identity.replyTo(pString(identityData.ReplyTo)); + identity.bcc(pString(identityData.Bcc)); + identity.signature(pString(identityData.Signature)); + identity.signatureInsertBefore(!!identityData.SignatureInsertBefore); - identity.name(pString(identityData.Name)); - identity.replyTo(pString(identityData.ReplyTo)); - identity.bcc(pString(identityData.Bcc)); - identity.signature(pString(identityData.Signature)); - identity.signatureInsertBefore(!!identityData.SignatureInsertBefore); - - return identity; - })); + return identity; + }) + ); } } }); } templates() { - TemplateStore.templates.loading(true); Remote.templates((result, data) => { - TemplateStore.templates.loading(false); - if (StorageResultType.Success === result && data.Result && - isArray(data.Result.Templates)) - { + if (StorageResultType.Success === result && data.Result && isArray(data.Result.Templates)) { delegateRunOnDestroy(TemplateStore.templates()); - TemplateStore.templates(_.compact(_.map(data.Result.Templates, (templateData) => { - const template = new TemplateModel(); - return template.parse(templateData) ? template : null; - }))); + TemplateStore.templates( + _.compact( + _.map(data.Result.Templates, (templateData) => { + const template = new TemplateModel(); + return template.parse(templateData) ? template : null; + }) + ) + ); } }); } quota() { Remote.quota((result, data) => { - if (StorageResultType.Success === result && data && data.Result && - isArray(data.Result) && 1 < data.Result.length && - isPosNumeric(data.Result[0], true) && isPosNumeric(data.Result[1], true)) - { + if ( + StorageResultType.Success === result && + data && + data.Result && + isArray(data.Result) && + 1 < data.Result.length && + isPosNumeric(data.Result[0], true) && + isPosNumeric(data.Result[1], true) + ) { QuotaStore.populateData(pInt(data.Result[1]), pInt(data.Result[0])); } }); @@ -657,86 +648,80 @@ class AppUser extends AbstractApp * @param {Array=} list = [] */ folderInformation(folder, list) { - if ('' !== trim(folder)) - { - Remote.folderInformation((result, data) => { - if (StorageResultType.Success === result) - { - if (data && data.Result && data.Result.Hash && data.Result.Folder) - { - let - uid = '', - check = false, - unreadCountChange = false; + if ('' !== trim(folder)) { + Remote.folderInformation( + (result, data) => { + if (StorageResultType.Success === result) { + if (data && data.Result && data.Result.Hash && data.Result.Folder) { + let uid = '', + check = false, + unreadCountChange = false; - const folderFromCache = getFolderFromCacheList(data.Result.Folder); - if (folderFromCache) - { - folderFromCache.interval = momentNowUnix(); + const folderFromCache = getFolderFromCacheList(data.Result.Folder); + if (folderFromCache) { + folderFromCache.interval = momentNowUnix(); - if (data.Result.Hash) - { - setFolderHash(data.Result.Folder, data.Result.Hash); - } - - if (isNormal(data.Result.MessageCount)) - { - folderFromCache.messageCountAll(data.Result.MessageCount); - } - - if (isNormal(data.Result.MessageUnseenCount)) - { - if (pInt(folderFromCache.messageCountUnread()) !== pInt(data.Result.MessageUnseenCount)) - { - unreadCountChange = true; + if (data.Result.Hash) { + setFolderHash(data.Result.Folder, data.Result.Hash); } - folderFromCache.messageCountUnread(data.Result.MessageUnseenCount); - } + if (isNormal(data.Result.MessageCount)) { + folderFromCache.messageCountAll(data.Result.MessageCount); + } - if (unreadCountChange) - { - clearMessageFlagsFromCacheByFolder(folderFromCache.fullNameRaw); - } + if (isNormal(data.Result.MessageUnseenCount)) { + if (pInt(folderFromCache.messageCountUnread()) !== pInt(data.Result.MessageUnseenCount)) { + unreadCountChange = true; + } - if (data.Result.Flags) - { - for (uid in data.Result.Flags) - { - if (has(data.Result.Flags, uid)) - { - check = true; - const flags = data.Result.Flags[uid]; - storeMessageFlagsToCacheByFolderAndUid(folderFromCache.fullNameRaw, uid.toString(), [ - !flags.IsSeen, !!flags.IsFlagged, !!flags.IsAnswered, !!flags.IsForwarded, !!flags.IsReadReceipt - ]); + folderFromCache.messageCountUnread(data.Result.MessageUnseenCount); + } + + if (unreadCountChange) { + clearMessageFlagsFromCacheByFolder(folderFromCache.fullNameRaw); + } + + if (data.Result.Flags) { + for (uid in data.Result.Flags) { + if (has(data.Result.Flags, uid)) { + check = true; + const flags = data.Result.Flags[uid]; + storeMessageFlagsToCacheByFolderAndUid(folderFromCache.fullNameRaw, uid.toString(), [ + !flags.IsSeen, + !!flags.IsFlagged, + !!flags.IsAnswered, + !!flags.IsForwarded, + !!flags.IsReadReceipt + ]); + } + } + + if (check) { + this.reloadFlagsCurrentMessageListAndMessageFromCache(); } } - if (check) - { - this.reloadFlagsCurrentMessageListAndMessageFromCache(); - } - } + MessageStore.initUidNextAndNewMessages( + folderFromCache.fullNameRaw, + data.Result.UidNext, + data.Result.NewMessages + ); - MessageStore.initUidNextAndNewMessages(folderFromCache.fullNameRaw, data.Result.UidNext, data.Result.NewMessages); - - const hash = getFolderHash(data.Result.Folder); - if (data.Result.Hash !== hash || '' === hash || unreadCountChange) - { - if (folderFromCache.fullNameRaw === FolderStore.currentFolderFullNameRaw()) - { - this.reloadMessageList(); - } - else if (getFolderInboxName() === folderFromCache.fullNameRaw) - { - this.recacheInboxMessageList(); + const hash = getFolderHash(data.Result.Folder); + if (data.Result.Hash !== hash || '' === hash || unreadCountChange) { + if (folderFromCache.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { + this.reloadMessageList(); + } else if (getFolderInboxName() === folderFromCache.fullNameRaw) { + this.recacheInboxMessageList(); + } } } } } - } - }, folder, list); + }, + folder, + list + ); } } @@ -744,67 +729,48 @@ class AppUser extends AbstractApp * @param {boolean=} boot = false */ folderInformationMultiply(boot = false) { - const folders = FolderStore.getNextFolderNames(); - if (isNonEmptyArray(folders)) - { + if (isNonEmptyArray(folders)) { Remote.folderInformationMultiply((sResult, oData) => { - if (StorageResultType.Success === sResult) - { - if (oData && oData.Result && oData.Result.List && isNonEmptyArray(oData.Result.List)) - { + if (StorageResultType.Success === sResult) { + if (oData && oData.Result && oData.Result.List && isNonEmptyArray(oData.Result.List)) { const utc = momentNowUnix(); _.each(oData.Result.List, (item) => { - - const - hash = getFolderHash(item.Folder), + const hash = getFolderHash(item.Folder), folder = getFolderFromCacheList(item.Folder); - let - unreadCountChange = false; + let unreadCountChange = false; - if (folder) - { + if (folder) { folder.interval = utc; - if (item.Hash) - { + if (item.Hash) { setFolderHash(item.Folder, item.Hash); } - if (isNormal(item.MessageCount)) - { + if (isNormal(item.MessageCount)) { folder.messageCountAll(item.MessageCount); } - if (isNormal(item.MessageUnseenCount)) - { - if (pInt(folder.messageCountUnread()) !== pInt(item.MessageUnseenCount)) - { + if (isNormal(item.MessageUnseenCount)) { + if (pInt(folder.messageCountUnread()) !== pInt(item.MessageUnseenCount)) { unreadCountChange = true; } folder.messageCountUnread(item.MessageUnseenCount); } - if (unreadCountChange) - { + if (unreadCountChange) { clearMessageFlagsFromCacheByFolder(folder.fullNameRaw); } - if (item.Hash !== hash || '' === hash) - { - if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) - { + if (item.Hash !== hash || '' === hash) { + if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { this.reloadMessageList(); } - } - else if (unreadCountChange) - { - if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) - { + } else if (unreadCountChange) { + if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { const list = MessageStore.messageList(); - if (isNonEmptyArray(list)) - { + if (isNonEmptyArray(list)) { this.folderInformation(folder.fullNameRaw, list); } } @@ -812,8 +778,7 @@ class AppUser extends AbstractApp } }); - if (boot) - { + if (boot) { _.delay(() => this.folderInformationMultiply(true), 2000); } } @@ -828,32 +793,25 @@ class AppUser extends AbstractApp * @param {Array=} messages = null */ messageListAction(sFolderFullNameRaw, iSetAction, messages) { - - let - folder = null, + let folder = null, alreadyUnread = 0, rootUids = []; - if (isUnd(messages) || !messages) - { + if (isUnd(messages) || !messages) { messages = MessageStore.messageListChecked(); } rootUids = _.uniq(_.compact(_.map(messages, (oMessage) => (oMessage && oMessage.uid ? oMessage.uid : null)))); - if ('' !== sFolderFullNameRaw && 0 < rootUids.length) - { - switch (iSetAction) - { + if ('' !== sFolderFullNameRaw && 0 < rootUids.length) { + switch (iSetAction) { case MessageSetAction.SetSeen: - _.each(rootUids, (sSubUid) => { alreadyUnread += storeMessageFlagsToCacheBySetAction(sFolderFullNameRaw, sSubUid, iSetAction); }); folder = getFolderFromCacheList(sFolderFullNameRaw); - if (folder) - { + if (folder) { folder.messageCountUnread(folder.messageCountUnread() - alreadyUnread); } @@ -861,15 +819,12 @@ class AppUser extends AbstractApp break; case MessageSetAction.UnsetSeen: - _.each(rootUids, (sSubUid) => { - alreadyUnread += storeMessageFlagsToCacheBySetAction( - sFolderFullNameRaw, sSubUid, iSetAction); + alreadyUnread += storeMessageFlagsToCacheBySetAction(sFolderFullNameRaw, sSubUid, iSetAction); }); folder = getFolderFromCacheList(sFolderFullNameRaw); - if (folder) - { + if (folder) { folder.messageCountUnread(folder.messageCountUnread() - alreadyUnread + rootUids.length); } @@ -877,7 +832,6 @@ class AppUser extends AbstractApp break; case MessageSetAction.SetFlag: - _.each(rootUids, (sSubUid) => { storeMessageFlagsToCacheBySetAction(sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -886,7 +840,6 @@ class AppUser extends AbstractApp break; case MessageSetAction.UnsetFlag: - _.each(rootUids, (sSubUid) => { storeMessageFlagsToCacheBySetAction(sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -902,38 +855,45 @@ class AppUser extends AbstractApp } googleConnect() { - window.open(socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open( + socialGoogle(), + 'Google', + 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes' + ); } twitterConnect() { - window.open(socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open( + socialTwitter(), + 'Twitter', + 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes' + ); } facebookConnect() { - window.open(socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open( + socialFacebook(), + 'Facebook', + 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes' + ); } /** * @param {boolean=} fireAllActions = false */ socialUsers(fireAllActions = false) { - if (true === fireAllActions) - { + if (true === fireAllActions) { SocialStore.google.loading(true); SocialStore.facebook.loading(true); SocialStore.twitter.loading(true); } Remote.socialUsers((result, data) => { - - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { SocialStore.google.userName(data.Result.Google || ''); SocialStore.facebook.userName(data.Result.Facebook || ''); SocialStore.twitter.userName(data.Result.Twitter || ''); - } - else - { + } else { SocialStore.google.userName(''); SocialStore.facebook.userName(''); SocialStore.twitter.userName(''); @@ -966,12 +926,11 @@ class AppUser extends AbstractApp */ getAutocomplete(query, autocompleteCallback) { Remote.suggestions((result, data) => { - if (StorageResultType.Success === result && data && isArray(data.Result)) - { - autocompleteCallback(_.compact(_.map(data.Result, (item) => (item && item[0] ? new EmailModel(item[0], item[1]) : null)))); - } - else if (StorageResultType.Abort !== result) - { + if (StorageResultType.Success === result && data && isArray(data.Result)) { + autocompleteCallback( + _.compact(_.map(data.Result, (item) => (item && item[0] ? new EmailModel(item[0], item[1]) : null))) + ); + } else if (StorageResultType.Abort !== result) { autocompleteCallback([]); } }, query); @@ -983,18 +942,14 @@ class AppUser extends AbstractApp */ setExpandedFolder(sFullNameHash, bExpanded) { let aExpandedList = Local.get(ClientSideKeyName.ExpandedFolders); - if (!isArray(aExpandedList)) - { + if (!isArray(aExpandedList)) { aExpandedList = []; } - if (bExpanded) - { + if (bExpanded) { aExpandedList.push(sFullNameHash); aExpandedList = _.uniq(aExpandedList); - } - else - { + } else { aExpandedList = _.without(aExpandedList, sFullNameHash); } @@ -1002,33 +957,26 @@ class AppUser extends AbstractApp } initHorizontalLayoutResizer(sClientSideKeyName) { - - let - top = null, + let top = null, bottom = null; - const - minHeight = 200, + const minHeight = 200, maxHeight = 500, fSetHeight = (height) => { - if (height) - { - if (top) - { + if (height) { + if (top) { top.attr('style', 'height:' + height + 'px'); } - if (bottom) - { + if (bottom) { bottom.attr('style', 'top:' + (55 /* top toolbar */ + height) + 'px'); } } }, - fResizeCreateFunction = (event) => { - if (event && event.target) - { - $(event.target).find('.ui-resizable-handle') + if (event && event.target) { + $(event.target) + .find('.ui-resizable-handle') .on('mousedown', () => { $html.addClass('rl-resizer'); }) @@ -1037,19 +985,19 @@ class AppUser extends AbstractApp }); } }, - fResizeStartFunction = () => { $html.addClass('rl-resizer'); }, - - fResizeResizeFunction = _.debounce(() => { - $html.addClass('rl-resizer'); - }, 500, true), - + fResizeResizeFunction = _.debounce( + () => { + $html.addClass('rl-resizer'); + }, + 500, + true + ), fResizeStopFunction = (oEvent, oObject) => { $html.removeClass('rl-resizer'); - if (oObject && oObject.size && oObject.size.height) - { + if (oObject && oObject.size && oObject.size.height) { Local.set(sClientSideKeyName, oObject.size.height); fSetHeight(oObject.size.height); @@ -1057,7 +1005,6 @@ class AppUser extends AbstractApp windowResize(); } }, - oOptions = { helper: 'ui-resizable-helper-h', minHeight: minHeight, @@ -1068,29 +1015,20 @@ class AppUser extends AbstractApp start: fResizeStartFunction, stop: fResizeStopFunction }, - fDisable = (bDisable) => { - if (bDisable) - { - if (top && top.hasClass('ui-resizable')) - { - top - .resizable('destroy') - .removeAttr('style'); + if (bDisable) { + if (top && top.hasClass('ui-resizable')) { + top.resizable('destroy').removeAttr('style'); } - if (bottom) - { + if (bottom) { bottom.removeAttr('style'); } - } - else if ($html.hasClass('rl-bottom-preview-pane')) - { + } else if ($html.hasClass('rl-bottom-preview-pane')) { top = $('.b-message-list-wrapper'); bottom = $('.b-message-view-wrapper'); - if (!top.hasClass('ui-resizable')) - { + if (!top.hasClass('ui-resizable')) { top.resizable(oOptions); } @@ -1107,18 +1045,13 @@ class AppUser extends AbstractApp } initVerticalLayoutResizer(sClientSideKeyName) { - - const - disabledWidth = 60, + const disabledWidth = 60, minWidth = 155, lLeft = $('#rl-left'), right = $('#rl-right'), - mLeftWidth = Local.get(sClientSideKeyName) || null, - fSetWidth = (iWidth) => { - if (iWidth) - { + if (iWidth) { leftPanelWidth(iWidth); $html.removeClass('rl-resizer'); @@ -1132,25 +1065,20 @@ class AppUser extends AbstractApp }); } }, - fDisable = (bDisable) => { - if (bDisable) - { + if (bDisable) { lLeft.resizable('disable'); fSetWidth(disabledWidth); - } - else - { + } else { lLeft.resizable('enable'); const width = pInt(Local.get(sClientSideKeyName)) || minWidth; fSetWidth(width > minWidth ? width : minWidth); } }, - fResizeCreateFunction = (event) => { - if (event && event.target) - { - $(event.target).find('.ui-resizable-handle') + if (event && event.target) { + $(event.target) + .find('.ui-resizable-handle') .on('mousedown', () => { $html.addClass('rl-resizer'); }) @@ -1159,16 +1087,19 @@ class AppUser extends AbstractApp }); } }, - fResizeResizeFunction = _.debounce(() => { - $html.addClass('rl-resizer'); - }, 500, true), + fResizeResizeFunction = _.debounce( + () => { + $html.addClass('rl-resizer'); + }, + 500, + true + ), fResizeStartFunction = () => { $html.addClass('rl-resizer'); }, fResizeStopFunction = (event, obj) => { $html.removeClass('rl-resizer'); - if (obj && obj.size && obj.size.width) - { + if (obj && obj.size && obj.size.width) { Local.set(sClientSideKeyName, obj.size.width); leftPanelWidth(obj.size.width); @@ -1186,8 +1117,7 @@ class AppUser extends AbstractApp } }; - if (null !== mLeftWidth) - { + if (null !== mLeftWidth) { fSetWidth(mLeftWidth > minWidth ? mLeftWidth : minWidth); } @@ -1213,8 +1143,11 @@ class AppUser extends AbstractApp logout() { Remote.logout(() => { - this.loginAndLogoutReload(false, true, - Settings.settingsGet('ParentEmail') && 0 < Settings.settingsGet('ParentEmail').length); + this.loginAndLogoutReload( + false, + true, + Settings.settingsGet('ParentEmail') && 0 < Settings.settingsGet('ParentEmail').length + ); }); } @@ -1227,21 +1160,15 @@ class AppUser extends AbstractApp } bootstartLoginScreen() { - $html.removeClass('rl-user-auth').addClass('rl-user-no-auth'); const customLoginLink = pString(Settings.appSettingsGet('customLoginLink')); - if (!customLoginLink) - { - startScreens([ - LoginUserScreen - ]); + if (!customLoginLink) { + startScreens([LoginUserScreen]); runHook('rl-start-login-screens'); Events.pub('rl.bootstart-login-screens'); - } - else - { + } else { routeOff(); setHash(root(), true); routeOff(); @@ -1253,15 +1180,13 @@ class AppUser extends AbstractApp } bootend() { - if (progressJs) - { + if (progressJs) { progressJs.set(100).end(); } hideLoading(); } bootstart() { - super.bootstart(); AppStore.populate(); @@ -1270,18 +1195,15 @@ class AppUser extends AbstractApp AccountStore.populate(); ContactStore.populate(); - let - contactsSyncInterval = pInt(Settings.settingsGet('ContactsSyncInterval')); + let contactsSyncInterval = pInt(Settings.settingsGet('ContactsSyncInterval')); - const - jsHash = Settings.appSettingsGet('jsHash'), + const jsHash = Settings.appSettingsGet('jsHash'), startupUrl = pString(Settings.settingsGet('StartupUrl')), allowGoogle = Settings.settingsGet('AllowGoogleSocial'), allowFacebook = Settings.settingsGet('AllowFacebookSocial'), allowTwitter = Settings.settingsGet('AllowTwitterSocial'); - if (progressJs) - { + if (progressJs) { progressJs.set(90); } @@ -1290,50 +1212,39 @@ class AppUser extends AbstractApp }); this.setWindowTitle(''); - if (Settings.settingsGet('Auth')) - { + if (Settings.settingsGet('Auth')) { $html.addClass('rl-user-auth'); - if (Settings.capa(Capa.TwoFactor) && + if ( + Settings.capa(Capa.TwoFactor) && Settings.capa(Capa.TwoFactorForce) && - Settings.settingsGet('RequireTwoFactor')) - { + Settings.settingsGet('RequireTwoFactor') + ) { this.bootend(); this.bootstartTwoFactorScreen(); - } - else - { + } else { this.setWindowTitle(i18n('TITLES/LOADING')); // require.ensure([], function() { // require code splitting this.foldersReload((value) => { - this.bootend(); - if (value) - { - if ('' !== startupUrl) - { + if (value) { + if ('' !== startupUrl) { routeOff(); setHash(root(startupUrl), true); routeOn(); } - if (jassl && window.crypto && window.crypto.getRandomValues && Settings.capa(Capa.OpenPGP)) - { + if (jassl && window.crypto && window.crypto.getRandomValues && Settings.capa(Capa.OpenPGP)) { const openpgpCallback = (openpgp) => { - PgpStore.openpgp = openpgp; - if (window.Worker) - { - try - { - PgpStore.openpgp.initWorker({path: openPgpWorkerJs()}); - } - catch (e) - { + if (window.Worker) { + try { + PgpStore.openpgp.initWorker({ path: openPgpWorkerJs() }); + } catch (e) { log(e); } } @@ -1346,22 +1257,16 @@ class AppUser extends AbstractApp this.reloadOpenPgpKeys(); }; - if (window.openpgp) - { + if (window.openpgp) { openpgpCallback(window.openpgp); - } - else - { + } else { jassl(openPgpJs()).then(() => { - if (window.openpgp) - { + if (window.openpgp) { openpgpCallback(window.openpgp); } }); } - } - else - { + } else { PgpStore.capaOpenPGP(false); } @@ -1371,16 +1276,14 @@ class AppUser extends AbstractApp // false ? AboutUserScreen : null ]); - if (allowGoogle || allowFacebook || allowTwitter) - { + if (allowGoogle || allowFacebook || allowTwitter) { this.socialUsers(true); } Events.sub('interval.2m', () => this.folderInformation(getFolderInboxName())); Events.sub('interval.3m', () => { const sF = FolderStore.currentFolderFullNameRaw(); - if (getFolderInboxName() !== sF) - { + if (getFolderInboxName() !== sF) { this.folderInformation(sF); } }); @@ -1401,8 +1304,7 @@ class AppUser extends AbstractApp _.delay(() => { const sF = FolderStore.currentFolderFullNameRaw(); - if (getFolderInboxName() !== sF) - { + if (getFolderInboxName() !== sF) { this.folderInformation(sF); } }, 1000); @@ -1415,68 +1317,60 @@ class AppUser extends AbstractApp runHook('rl-start-user-screens'); Events.pub('rl.bootstart-user-screens'); - if (Settings.settingsGet('WelcomePageUrl')) - { + if (Settings.settingsGet('WelcomePageUrl')) { _.delay(() => this.bootstartWelcomePopup(Settings.settingsGet('WelcomePageUrl')), 1000); } - if (!!Settings.settingsGet('AccountSignMe') && + if ( + !!Settings.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler && - Settings.capa(Capa.Composer)) - { + Settings.capa(Capa.Composer) + ) { _.delay(() => { try { - window.navigator.registerProtocolHandler('mailto', + window.navigator.registerProtocolHandler( + 'mailto', window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s', - '' + (Settings.settingsGet('Title') || 'RainLoop')); - } - catch (e) {} // eslint-disable-line no-empty + '' + (Settings.settingsGet('Title') || 'RainLoop') + ); + } catch (e) {} // eslint-disable-line no-empty - if (Settings.settingsGet('MailToEmail')) - { + if (Settings.settingsGet('MailToEmail')) { mailToHelper(Settings.settingsGet('MailToEmail'), require('View/Popup/Compose')); } }, 500); } - if (!bMobileDevice) - { + if (!bMobileDevice) { _.defer(() => this.initVerticalLayoutResizer(ClientSideKeyName.FolderListSize)); } - } - else - { + } else { this.logout(); } }); // }); // require code splitting } - } - else - { + } else { this.bootend(); this.bootstartLoginScreen(); } - if (allowGoogle) - { + if (allowGoogle) { window['rl_' + jsHash + '_google_service'] = () => { SocialStore.google.loading(true); this.socialUsers(); }; } - if (allowFacebook) - { + if (allowFacebook) { window['rl_' + jsHash + '_facebook_service'] = () => { SocialStore.facebook.loading(true); this.socialUsers(); }; } - if (allowTwitter) - { + if (allowTwitter) { window['rl_' + jsHash + '_twitter_service'] = () => { SocialStore.twitter.loading(true); this.socialUsers(); diff --git a/dev/Common/Audio.js b/dev/Common/Audio.js index 41acf17da..5fc7fe704 100644 --- a/dev/Common/Audio.js +++ b/dev/Common/Audio.js @@ -1,12 +1,10 @@ - import window from 'window'; -import {bMobileDevice, bSafari} from 'Common/Globals'; +import { bMobileDevice, bSafari } from 'Common/Globals'; import * as Links from 'Common/Links'; import * as Events from 'Common/Events'; -import {trim} from 'Common/Utils'; +import { trim } from 'Common/Utils'; -class Audio -{ +class Audio { notificator = null; player = null; @@ -20,16 +18,14 @@ class Audio this.player = this.createNewObject(); this.supported = !bMobileDevice && !bSafari && !!this.player && !!this.player.play; - if (this.supported && this.player && this.player.canPlayType) - { + if (this.supported && this.player && this.player.canPlayType) { this.supportedMp3 = '' !== this.player.canPlayType('audio/mpeg;').replace(/no/, ''); this.supportedWav = '' !== this.player.canPlayType('audio/wav; codecs="1"').replace(/no/, ''); this.supportedOgg = '' !== this.player.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''); this.supportedNotification = this.supported && this.supportedMp3; } - if (!this.player || (!this.supportedMp3 && !this.supportedOgg && !this.supportedWav)) - { + if (!this.player || (!this.supportedMp3 && !this.supportedOgg && !this.supportedWav)) { this.supported = false; this.supportedMp3 = false; this.supportedOgg = false; @@ -37,8 +33,7 @@ class Audio this.supportedNotification = false; } - if (this.supported && this.player) - { + if (this.supported && this.player) { const stopFn = () => this.stop(); this.player.addEventListener('ended', stopFn); @@ -50,8 +45,7 @@ class Audio createNewObject() { const player = window.Audio ? new window.Audio() : null; - if (player && player.canPlayType && player.pause && player.play) - { + if (player && player.canPlayType && player.pause && player.play) { player.preload = 'none'; player.loop = false; player.autoplay = false; @@ -66,8 +60,7 @@ class Audio } stop() { - if (this.supported && this.player.pause) - { + if (this.supported && this.player.pause) { this.player.pause(); } @@ -79,10 +72,8 @@ class Audio } clearName(name = '', ext = '') { - name = trim(name); - if (ext && '.' + ext === name.toLowerCase().substr((ext.length + 1) * -1)) - { + if (ext && '.' + ext === name.toLowerCase().substr((ext.length + 1) * -1)) { name = trim(name.substr(0, name.length - 4)); } @@ -90,8 +81,7 @@ class Audio } playMp3(url, name) { - if (this.supported && this.supportedMp3) - { + if (this.supported && this.supportedMp3) { this.player.src = url; this.player.play(); @@ -100,8 +90,7 @@ class Audio } playOgg(url, name) { - if (this.supported && this.supportedOgg) - { + if (this.supported && this.supportedOgg) { this.player.src = url; this.player.play(); @@ -113,8 +102,7 @@ class Audio } playWav(url, name) { - if (this.supported && this.supportedWav) - { + if (this.supported && this.supportedWav) { this.player.src = url; this.player.play(); @@ -123,16 +111,13 @@ class Audio } playNotification() { - if (this.supported && this.supportedMp3) - { - if (!this.notificator) - { + if (this.supported && this.supportedMp3) { + if (!this.notificator) { this.notificator = this.createNewObject(); this.notificator.src = Links.sound('new-mail.mp3'); } - if (this.notificator && this.notificator.play) - { + if (this.notificator && this.notificator.play) { this.notificator.play(); } } diff --git a/dev/Common/Base64.js b/dev/Common/Base64.js index b3b801e19..463b3b6a4 100644 --- a/dev/Common/Base64.js +++ b/dev/Common/Base64.js @@ -1,4 +1,3 @@ - // Base64 encode / decode // http://www.webtoolkit.info/ @@ -6,23 +5,28 @@ const BASE_64_CHR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456 /* eslint-disable */ const Base64 = { - // public method for urlsafe encoding - urlsafe_encode: (input) => Base64.encode(input) - .replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, ''), + urlsafe_encode: (input) => + Base64.encode(input) + .replace(/[+]/g, '-') + .replace(/[\/]/g, '_') + .replace(/[=]/g, ''), // public method for encoding encode: (input) => { - - let - output = '', - chr1, chr2, chr3, enc1, enc2, enc3, enc4, + let output = '', + chr1, + chr2, + chr3, + enc1, + enc2, + enc3, + enc4, i = 0; input = Base64._utf8_encode(input); - while (i < input.length) - { + while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); @@ -32,18 +36,18 @@ const Base64 = { enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; - if (isNaN(chr2)) - { + if (isNaN(chr2)) { enc3 = enc4 = 64; - } - else if (isNaN(chr3)) - { + } else if (isNaN(chr3)) { enc4 = 64; } - output = output + - BASE_64_CHR.charAt(enc1) + BASE_64_CHR.charAt(enc2) + - BASE_64_CHR.charAt(enc3) + BASE_64_CHR.charAt(enc4); + output = + output + + BASE_64_CHR.charAt(enc1) + + BASE_64_CHR.charAt(enc2) + + BASE_64_CHR.charAt(enc3) + + BASE_64_CHR.charAt(enc4); } return output; @@ -51,16 +55,19 @@ const Base64 = { // public method for decoding decode: (input) => { - - let - output = '', - chr1, chr2, chr3, enc1, enc2, enc3, enc4, + let output = '', + chr1, + chr2, + chr3, + enc1, + enc2, + enc3, + enc4, i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); - while (i < input.length) - { + while (i < input.length) { enc1 = BASE_64_CHR.indexOf(input.charAt(i++)); enc2 = BASE_64_CHR.indexOf(input.charAt(i++)); enc3 = BASE_64_CHR.indexOf(input.charAt(i++)); @@ -72,13 +79,11 @@ const Base64 = { output = output + String.fromCharCode(chr1); - if (enc3 !== 64) - { + if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } - if (enc4 !== 64) - { + if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } @@ -88,30 +93,22 @@ const Base64 = { // private method for UTF-8 encoding _utf8_encode: (string) => { + string = string.replace(/\r\n/g, '\n'); - string = string.replace(/\r\n/g, "\n"); - - let - utftext = '', + let utftext = '', n = 0, l = string.length, c = 0; for (; n < l; n++) { - c = string.charCodeAt(n); - if (c < 128) - { + if (c < 128) { utftext += String.fromCharCode(c); - } - else if ((c > 127) && (c < 2048)) - { + } else if (c > 127 && c < 2048) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); - } - else - { + } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); @@ -123,33 +120,25 @@ const Base64 = { // private method for UTF-8 decoding _utf8_decode: (utftext) => { - - let - string = '', + let string = '', i = 0, c = 0, c2 = 0, c3 = 0; - while ( i < utftext.length ) - { + while (i < utftext.length) { c = utftext.charCodeAt(i); - if (c < 128) - { + if (c < 128) { string += String.fromCharCode(c); i++; - } - else if((c > 191) && (c < 224)) - { - c2 = utftext.charCodeAt(i+1); + } else if (c > 191 && c < 224) { + c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; - } - else - { - c2 = utftext.charCodeAt(i+1); - c3 = utftext.charCodeAt(i+2); + } else { + c2 = utftext.charCodeAt(i + 1); + c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } diff --git a/dev/Common/Booter.js b/dev/Common/Booter.js index 393e3bd8c..f3ca0a320 100644 --- a/dev/Common/Booter.js +++ b/dev/Common/Booter.js @@ -1,9 +1,8 @@ - import window from 'window'; import progressJs from 'progressJs'; -import {jassl} from 'Common/Jassl'; -import {getHash, setHash, clearHash} from 'Storage/RainLoop'; +import { jassl } from 'Common/Jassl'; +import { getHash, setHash, clearHash } from 'Storage/RainLoop'; let RL_APP_DATA_STORAGE = null; @@ -14,38 +13,38 @@ window.__rlah_clear = () => clearHash(); window.__rlah_data = () => RL_APP_DATA_STORAGE; const useJsNextBundle = (function() { -// try { -// -// (function() { -// eval(` -// // let + const -//const x = 5; let y = 4; var z = 4; -// -// // Arrow Function -//const f = () => 'rainloop'; -// -// // Default + Rest + Spread -//const d = (test = 1, ...t) => 'rainloop'; -//d(...[1, 2, 3]); -// -//// Destructuring -//let [a, b] = [1, 2]; -//({a, b} = {a: 1, b: 2}); -// -//// Class -//class Q1 { constructor() {} } -// -//// Class extends + super -//class Q2 extends Q1 { constructor() { super() } } -// -//`); -// }()); -// -// return true; -// } -// catch (e) {} + // try { + // + // (function() { + // eval(` + // // let + const + //const x = 5; let y = 4; var z = 4; + // + // // Arrow Function + //const f = () => 'rainloop'; + // + // // Default + Rest + Spread + //const d = (test = 1, ...t) => 'rainloop'; + //d(...[1, 2, 3]); + // + //// Destructuring + //let [a, b] = [1, 2]; + //({a, b} = {a: 1, b: 2}); + // + //// Class + //class Q1 { constructor() {} } + // + //// Class extends + super + //class Q2 extends Q1 { constructor() { super() } } + // + //`); + // }()); + // + // return true; + // } + // catch (e) {} return false; -}()); +})(); /* eslint-enable */ /** @@ -53,19 +52,20 @@ const useJsNextBundle = (function() { * @param {string} name * @returns {string} */ -function getComputedStyle(id, name) -{ +function getComputedStyle(id, name) { const element = window.document.getElementById(id); - return element && element.currentStyle ? element.currentStyle[name] : - (window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null); + return element && element.currentStyle + ? element.currentStyle[name] + : window.getComputedStyle + ? window.getComputedStyle(element, null).getPropertyValue(name) + : null; } /** * @param {string} styles * @returns {void} */ -function includeStyle(styles) -{ +function includeStyle(styles) { window.document.write(unescape('%3Csty' + 'le%3E' + styles + '"%3E%3C/' + 'sty' + 'le%3E')); // eslint-disable-line no-useless-concat } @@ -73,22 +73,31 @@ function includeStyle(styles) * @param {string} src * @returns {void} */ -function includeScr(src) -{ - window.document.write(unescape('%3Csc' + 'ript type="text/jav' + 'ascr' + 'ipt" data-cfasync="false" sr' + 'c="' + src + '"%3E%3C/' + 'scr' + 'ipt%3E')); // eslint-disable-line no-useless-concat +function includeScr(src) { + window.document.write( + unescape( + '%3Csc' + + 'ript type="text/jav' + + 'ascr' + + 'ipt" data-cfasync="false" sr' + + 'c="' + + src + + '"%3E%3C/' + + 'scr' + + 'ipt%3E' + ) + ); // eslint-disable-line no-useless-concat } /** * @returns {boolean} */ -function includeLayout() -{ +function includeLayout() { const app = window.document.getElementById('rl-app'); require('Styles/@Boot.css'); - if (app) - { + if (app) { const layout = require('Html/Layout.html'); app.innerHTML = ((layout && layout.default ? layout.default : layout) || '').replace(/[\r\n\t]+/g, ''); return true; @@ -103,8 +112,7 @@ function includeLayout() * @param {boolean} mobileDevice = false * @returns {void} */ -function includeAppScr({admin = false, mobile = false, mobileDevice = false}) -{ +function includeAppScr({ admin = false, mobile = false, mobileDevice = false }) { let src = './?/'; src += admin ? 'Admin' : ''; src += 'AppData@'; @@ -112,19 +120,25 @@ function includeAppScr({admin = false, mobile = false, mobileDevice = false}) src += mobileDevice ? '-1' : '-0'; src += '/'; - includeScr(src + (window.__rlah ? window.__rlah() || '0' : '0') + '/' + window.Math.random().toString().substr(2) + '/'); + includeScr( + src + + (window.__rlah ? window.__rlah() || '0' : '0') + + '/' + + window.Math.random() + .toString() + .substr(2) + + '/' + ); } /** * @returns {object} */ -function getRainloopBootData() -{ +function getRainloopBootData() { let result = {}; const meta = window.document.getElementById('app-boot-data'); - if (meta && meta.getAttribute) - { + if (meta && meta.getAttribute) { result = JSON.parse(meta.getAttribute('content')) || {}; } @@ -135,31 +149,25 @@ function getRainloopBootData() * @param {string} additionalError * @returns {void} */ -function showError(additionalError) -{ - const - oR = window.document.getElementById('rl-loading'), +function showError(additionalError) { + const oR = window.document.getElementById('rl-loading'), oL = window.document.getElementById('rl-loading-error'), oLA = window.document.getElementById('rl-loading-error-additional'); - if (oR) - { + if (oR) { oR.style.display = 'none'; } - if (oL) - { + if (oL) { oL.style.display = 'block'; } - if (oLA && additionalError) - { + if (oLA && additionalError) { oLA.style.display = 'block'; oLA.innerHTML = additionalError; } - if (progressJs) - { + if (progressJs) { progressJs.set(100).end(); } } @@ -168,19 +176,15 @@ function showError(additionalError) * @param {string} description * @returns {void} */ -function showDescriptionAndLoading(description) -{ - const - oE = window.document.getElementById('rl-loading'), +function showDescriptionAndLoading(description) { + const oE = window.document.getElementById('rl-loading'), oElDesc = window.document.getElementById('rl-loading-desc'); - if (oElDesc && description) - { + if (oElDesc && description) { oElDesc.innerHTML = description; } - if (oE && oE.style) - { + if (oE && oE.style) { oE.style.opacity = 0; window.setTimeout(() => { oE.style.opacity = 1; @@ -193,16 +197,12 @@ function showDescriptionAndLoading(description) * @param {string} additionalError * @returns {void} */ -function runMainBoot(withError, additionalError) -{ - if (window.__APP_BOOT && !withError) - { +function runMainBoot(withError, additionalError) { + if (window.__APP_BOOT && !withError) { window.__APP_BOOT(() => { showError(additionalError); }); - } - else - { + } else { showError(additionalError); } } @@ -210,43 +210,47 @@ function runMainBoot(withError, additionalError) /** * @returns {void} */ -function runApp() -{ +function runApp() { const appData = window.__rlah_data(); - if (jassl && progressJs && appData && appData.TemplatesLink && appData.LangLink && - appData.StaticLibJsLink && appData.StaticAppJsLink && appData.StaticAppJsNextLink && appData.StaticEditorJsLink) - { + if ( + jassl && + progressJs && + appData && + appData.TemplatesLink && + appData.LangLink && + appData.StaticLibJsLink && + appData.StaticAppJsLink && + appData.StaticAppJsNextLink && + appData.StaticEditorJsLink + ) { const p = progressJs; - p.setOptions({theme: 'rainloop'}); + p.setOptions({ theme: 'rainloop' }); p.start().set(5); - const libs = () => jassl(appData.StaticLibJsLink).then(() => { - if (window.$) - { - window.$('#rl-check').remove(); + const libs = () => + jassl(appData.StaticLibJsLink).then(() => { + if (window.$) { + window.$('#rl-check').remove(); - if (appData.IncludeBackground) - { - window.$('#rl-bg') - .attr('style', 'background-image: none !important;') - .backstretch( - appData.IncludeBackground.replace('{{USER}}', (window.__rlah ? (window.__rlah() || '0') : '0')), - {fade: 100, centeredX: true, centeredY: true} - ) - .removeAttr('style'); + if (appData.IncludeBackground) { + window + .$('#rl-bg') + .attr('style', 'background-image: none !important;') + .backstretch( + appData.IncludeBackground.replace('{{USER}}', window.__rlah ? window.__rlah() || '0' : '0'), + { fade: 100, centeredX: true, centeredY: true } + ) + .removeAttr('style'); + } } - } - }); + }); libs() .then(() => { p.set(20); - return window.Promise.all([ - jassl(appData.TemplatesLink), - jassl(appData.LangLink) - ]); + return window.Promise.all([jassl(appData.TemplatesLink), jassl(appData.LangLink)]); }) .then(() => { p.set(30); @@ -271,9 +275,7 @@ function runApp() window.__initEditor = null; } }); - } - else - { + } else { runMainBoot(true); } } @@ -283,20 +285,16 @@ function runApp() * @returns {void} */ window.__initAppData = function(data) { - RL_APP_DATA_STORAGE = data; window.__rlah_set(); - if (RL_APP_DATA_STORAGE) - { - if (RL_APP_DATA_STORAGE.NewThemeLink) - { + if (RL_APP_DATA_STORAGE) { + if (RL_APP_DATA_STORAGE.NewThemeLink) { (window.document.getElementById('app-theme-link') || {}).href = RL_APP_DATA_STORAGE.NewThemeLink; } - if (RL_APP_DATA_STORAGE.IncludeCss) - { + if (RL_APP_DATA_STORAGE.IncludeCss) { includeStyle(RL_APP_DATA_STORAGE.IncludeCss); } @@ -310,26 +308,20 @@ window.__initAppData = function(data) { * @returns {void} */ window.__runBoot = function() { - - if (!window.navigator || !window.navigator.cookieEnabled) - { + if (!window.navigator || !window.navigator.cookieEnabled) { window.document.location.replace('./?/NoCookie'); } const root = window.document.documentElement; - if ('none' !== getComputedStyle('rl-check', 'display')) - { + if ('none' !== getComputedStyle('rl-check', 'display')) { root.className += ' no-css'; } - if (useJsNextBundle) - { + if (useJsNextBundle) { root.className += ' js-next'; } - if (includeLayout()) - { + if (includeLayout()) { includeAppScr(getRainloopBootData()); } }; - diff --git a/dev/Common/Cache.js b/dev/Common/Cache.js index 763ae3186..47668ee3a 100644 --- a/dev/Common/Cache.js +++ b/dev/Common/Cache.js @@ -1,7 +1,6 @@ - import _ from '_'; -import {Capa, MessageSetAction} from 'Common/Enums'; -import {trim, pInt, isArray} from 'Common/Utils'; +import { Capa, MessageSetAction } from 'Common/Enums'; +import { trim, pInt, isArray } from 'Common/Utils'; import * as Links from 'Common/Links'; import * as Settings from 'Storage/Settings'; @@ -19,8 +18,7 @@ const REQUESTED_MESSAGE_CACHE = {}, /** * @returns {void} */ -export function clear() -{ +export function clear() { FOLDERS_CACHE = {}; FOLDERS_NAME_CACHE = {}; FOLDERS_HASH_CACHE = {}; @@ -33,8 +31,7 @@ export function clear() * @param {Function} callback * @returns {string} */ -export function getUserPic(email, callback) -{ +export function getUserPic(email, callback) { email = trim(email); callback(capaGravatar && '' !== email ? Links.avatarLink(email) : '', email); } @@ -44,8 +41,7 @@ export function getUserPic(email, callback) * @param {string} uid * @returns {string} */ -export function getMessageKey(folderFullNameRaw, uid) -{ +export function getMessageKey(folderFullNameRaw, uid) { return `${folderFullNameRaw}#${uid}`; } @@ -53,8 +49,7 @@ export function getMessageKey(folderFullNameRaw, uid) * @param {string} folder * @param {string} uid */ -export function addRequestedMessage(folder, uid) -{ +export function addRequestedMessage(folder, uid) { REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)] = true; } @@ -63,8 +58,7 @@ export function addRequestedMessage(folder, uid) * @param {string} uid * @returns {boolean} */ -export function hasRequestedMessage(folder, uid) -{ +export function hasRequestedMessage(folder, uid) { return true === REQUESTED_MESSAGE_CACHE[getMessageKey(folder, uid)]; } @@ -72,8 +66,7 @@ export function hasRequestedMessage(folder, uid) * @param {string} folderFullNameRaw * @param {string} uid */ -export function addNewMessageCache(folderFullNameRaw, uid) -{ +export function addNewMessageCache(folderFullNameRaw, uid) { NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = true; } @@ -81,10 +74,8 @@ export function addNewMessageCache(folderFullNameRaw, uid) * @param {string} folderFullNameRaw * @param {string} uid */ -export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) -{ - if (NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)]) - { +export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) { + if (NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)]) { NEW_MESSAGE_CACHE[getMessageKey(folderFullNameRaw, uid)] = null; return true; } @@ -94,16 +85,14 @@ export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) /** * @returns {void} */ -export function clearNewMessageCache() -{ +export function clearNewMessageCache() { NEW_MESSAGE_CACHE = {}; } /** * @returns {string} */ -export function getFolderInboxName() -{ +export function getFolderInboxName() { return '' === inboxFolderName ? 'INBOX' : inboxFolderName; } @@ -111,8 +100,7 @@ export function getFolderInboxName() * @param {string} folderHash * @returns {string} */ -export function getFolderFullNameRaw(folderHash) -{ +export function getFolderFullNameRaw(folderHash) { return '' !== folderHash && FOLDERS_NAME_CACHE[folderHash] ? FOLDERS_NAME_CACHE[folderHash] : ''; } @@ -120,11 +108,9 @@ export function getFolderFullNameRaw(folderHash) * @param {string} folderHash * @param {string} folderFullNameRaw */ -export function setFolderFullNameRaw(folderHash, folderFullNameRaw) -{ +export function setFolderFullNameRaw(folderHash, folderFullNameRaw) { FOLDERS_NAME_CACHE[folderHash] = folderFullNameRaw; - if ('INBOX' === folderFullNameRaw || '' === inboxFolderName) - { + if ('INBOX' === folderFullNameRaw || '' === inboxFolderName) { inboxFolderName = folderFullNameRaw; } } @@ -133,8 +119,7 @@ export function setFolderFullNameRaw(folderHash, folderFullNameRaw) * @param {string} folderFullNameRaw * @returns {string} */ -export function getFolderHash(folderFullNameRaw) -{ +export function getFolderHash(folderFullNameRaw) { return '' !== folderFullNameRaw && FOLDERS_HASH_CACHE[folderFullNameRaw] ? FOLDERS_HASH_CACHE[folderFullNameRaw] : ''; } @@ -142,10 +127,8 @@ export function getFolderHash(folderFullNameRaw) * @param {string} folderFullNameRaw * @param {string} folderHash */ -export function setFolderHash(folderFullNameRaw, folderHash) -{ - if ('' !== folderFullNameRaw) - { +export function setFolderHash(folderFullNameRaw, folderHash) { + if ('' !== folderFullNameRaw) { FOLDERS_HASH_CACHE[folderFullNameRaw] = folderHash; } } @@ -154,17 +137,17 @@ export function setFolderHash(folderFullNameRaw, folderHash) * @param {string} folderFullNameRaw * @returns {string} */ -export function getFolderUidNext(folderFullNameRaw) -{ - return '' !== folderFullNameRaw && FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] ? FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] : ''; +export function getFolderUidNext(folderFullNameRaw) { + return '' !== folderFullNameRaw && FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] + ? FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] + : ''; } /** * @param {string} folderFullNameRaw * @param {string} uidNext */ -export function setFolderUidNext(folderFullNameRaw, uidNext) -{ +export function setFolderUidNext(folderFullNameRaw, uidNext) { FOLDERS_UID_NEXT_CACHE[folderFullNameRaw] = uidNext; } @@ -172,8 +155,7 @@ export function setFolderUidNext(folderFullNameRaw, uidNext) * @param {string} folderFullNameRaw * @returns {?FolderModel} */ -export function getFolderFromCacheList(folderFullNameRaw) -{ +export function getFolderFromCacheList(folderFullNameRaw) { return '' !== folderFullNameRaw && FOLDERS_CACHE[folderFullNameRaw] ? FOLDERS_CACHE[folderFullNameRaw] : null; } @@ -181,16 +163,14 @@ export function getFolderFromCacheList(folderFullNameRaw) * @param {string} folderFullNameRaw * @param {?FolderModel} folder */ -export function setFolderToCacheList(folderFullNameRaw, folder) -{ +export function setFolderToCacheList(folderFullNameRaw, folder) { FOLDERS_CACHE[folderFullNameRaw] = folder; } /** * @param {string} folderFullNameRaw */ -export function removeFolderFromCacheList(folderFullNameRaw) -{ +export function removeFolderFromCacheList(folderFullNameRaw) { setFolderToCacheList(folderFullNameRaw, null); } @@ -199,10 +179,10 @@ export function removeFolderFromCacheList(folderFullNameRaw) * @param {string} uid * @returns {?Array} */ -export function getMessageFlagsFromCache(folderFullName, uid) -{ - return MESSAGE_FLAGS_CACHE[folderFullName] && MESSAGE_FLAGS_CACHE[folderFullName][uid] ? - MESSAGE_FLAGS_CACHE[folderFullName][uid] : null; +export function getMessageFlagsFromCache(folderFullName, uid) { + return MESSAGE_FLAGS_CACHE[folderFullName] && MESSAGE_FLAGS_CACHE[folderFullName][uid] + ? MESSAGE_FLAGS_CACHE[folderFullName][uid] + : null; } /** @@ -210,10 +190,8 @@ export function getMessageFlagsFromCache(folderFullName, uid) * @param {string} uid * @param {Array} flagsCache */ -export function setMessageFlagsToCache(folderFullName, uid, flagsCache) -{ - if (!MESSAGE_FLAGS_CACHE[folderFullName]) - { +export function setMessageFlagsToCache(folderFullName, uid, flagsCache) { + if (!MESSAGE_FLAGS_CACHE[folderFullName]) { MESSAGE_FLAGS_CACHE[folderFullName] = {}; } @@ -223,29 +201,22 @@ export function setMessageFlagsToCache(folderFullName, uid, flagsCache) /** * @param {string} folderFullName */ -export function clearMessageFlagsFromCacheByFolder(folderFullName) -{ +export function clearMessageFlagsFromCacheByFolder(folderFullName) { MESSAGE_FLAGS_CACHE[folderFullName] = {}; } /** * @param {(MessageModel|null)} message */ -export function initMessageFlagsFromCache(message) -{ - - if (message) - { - const - uid = message.uid, +export function initMessageFlagsFromCache(message) { + if (message) { + const uid = message.uid, flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid); - if (flags && 0 < flags.length) - { + if (flags && 0 < flags.length) { message.flagged(!!flags[1]); - if (!message.isSimpleMessage) - { + if (!message.isSimpleMessage) { message.unseen(!!flags[0]); message.answered(!!flags[2]); message.forwarded(!!flags[3]); @@ -254,8 +225,7 @@ export function initMessageFlagsFromCache(message) } } - if (0 < message.threads().length) - { + if (0 < message.threads().length) { const unseenSubUid = _.find(message.threads(), (sSubUid) => { if (uid !== sSubUid) { const subFlags = getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); @@ -281,15 +251,16 @@ export function initMessageFlagsFromCache(message) /** * @param {(MessageModel|null)} message */ -export function storeMessageFlagsToCache(message) -{ - if (message) - { - setMessageFlagsToCache( - message.folderFullNameRaw, message.uid, - [message.unseen(), message.flagged(), message.answered(), message.forwarded(), - message.isReadReceipt(), message.deletedMark()] - ); +export function storeMessageFlagsToCache(message) { + if (message) { + setMessageFlagsToCache(message.folderFullNameRaw, message.uid, [ + message.unseen(), + message.flagged(), + message.answered(), + message.forwarded(), + message.isReadReceipt(), + message.deletedMark() + ]); } } @@ -298,10 +269,8 @@ export function storeMessageFlagsToCache(message) * @param {string} uid * @param {Array} flags */ -export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) -{ - if (isArray(flags) && 0 < flags.length) - { +export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) { + if (isArray(flags) && 0 < flags.length) { setMessageFlagsToCache(folder, uid, flags); } } @@ -311,21 +280,16 @@ export function storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) * @param {string} uid * @param {number} setAction */ -export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction) -{ - +export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction) { let unread = 0; const flags = getMessageFlagsFromCache(folder, uid); - if (isArray(flags) && 0 < flags.length) - { - if (flags[0]) - { + if (isArray(flags) && 0 < flags.length) { + if (flags[0]) { unread = 1; } - switch (setAction) - { + switch (setAction) { case MessageSetAction.SetSeen: flags[0] = false; break; diff --git a/dev/Common/ClientStorageDriver/Cookie.js b/dev/Common/ClientStorageDriver/Cookie.js index 8a7bd3070..ee37525cd 100644 --- a/dev/Common/ClientStorageDriver/Cookie.js +++ b/dev/Common/ClientStorageDriver/Cookie.js @@ -1,39 +1,31 @@ - import window from 'window'; import Cookies from 'js-cookie'; -import {isUnd} from 'Common/Utils'; -import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; +import { isUnd } from 'Common/Utils'; +import { CLIENT_SIDE_STORAGE_INDEX_NAME } from 'Common/Consts'; -class CookieDriver -{ +class CookieDriver { /** * @param {string} key * @param {*} data * @returns {boolean} */ set(key, data) { - - let - result = false, + let result = false, storageResult = null; - try - { + try { storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME); - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty (storageResult || (storageResult = {}))[key] = data; - try - { + try { Cookies.set(CLIENT_SIDE_STORAGE_INDEX_NAME, storageResult, { expires: 30 }); result = true; - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty return result; } @@ -43,15 +35,12 @@ class CookieDriver * @returns {*} */ get(key) { - let result = null; - try - { + try { const storageResult = Cookies.getJSON(CLIENT_SIDE_STORAGE_INDEX_NAME); - result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; - } - catch (e) {} // eslint-disable-line no-empty + result = storageResult && !isUnd(storageResult[key]) ? storageResult[key] : null; + } catch (e) {} // eslint-disable-line no-empty return result; } @@ -64,4 +53,4 @@ class CookieDriver } } -export {CookieDriver, CookieDriver as default}; +export { CookieDriver, CookieDriver as default }; diff --git a/dev/Common/ClientStorageDriver/LocalStorage.js b/dev/Common/ClientStorageDriver/LocalStorage.js index c85613383..711c342e2 100644 --- a/dev/Common/ClientStorageDriver/LocalStorage.js +++ b/dev/Common/ClientStorageDriver/LocalStorage.js @@ -1,11 +1,9 @@ - import window from 'window'; -import {isUnd} from 'Common/Utils'; -import {isStorageSupported} from 'Storage/RainLoop'; -import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; +import { isUnd } from 'Common/Utils'; +import { isStorageSupported } from 'Storage/RainLoop'; +import { CLIENT_SIDE_STORAGE_INDEX_NAME } from 'Common/Consts'; -class LocalStorageDriver -{ +class LocalStorageDriver { s = null; constructor() { @@ -18,27 +16,22 @@ class LocalStorageDriver * @returns {boolean} */ set(key, data) { - if (!this.s) - { + if (!this.s) { return false; } let storageResult = null; - try - { + try { const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null; storageResult = null === storageValue ? null : window.JSON.parse(storageValue); - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty (storageResult || (storageResult = {}))[key] = data; - try - { + try { this.s.setItem(CLIENT_SIDE_STORAGE_INDEX_NAME, window.JSON.stringify(storageResult)); return true; - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty return false; } @@ -48,20 +41,16 @@ class LocalStorageDriver * @returns {*} */ get(key) { - if (!this.s) - { + if (!this.s) { return null; } - try - { - const - storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null, + try { + const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null, storageResult = null === storageValue ? null : window.JSON.parse(storageValue); - return (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; - } - catch (e) {} // eslint-disable-line no-empty + return storageResult && !isUnd(storageResult[key]) ? storageResult[key] : null; + } catch (e) {} // eslint-disable-line no-empty return null; } @@ -74,4 +63,4 @@ class LocalStorageDriver } } -export {LocalStorageDriver, LocalStorageDriver as default}; +export { LocalStorageDriver, LocalStorageDriver as default }; diff --git a/dev/Common/Consts.js b/dev/Common/Consts.js index 9199e528c..d5a40db69 100644 --- a/dev/Common/Consts.js +++ b/dev/Common/Consts.js @@ -1,4 +1,3 @@ - export const MESSAGES_PER_PAGE = 20; export const MESSAGES_PER_PAGE_VALUES = [10, 20, 30, 50, 100]; @@ -38,8 +37,11 @@ export const TOKEN_ERROR_LIMIT = 10; export const RAINLOOP_TRIAL_KEY = 'RAINLOOP-TRIAL-KEY'; /* eslint max-len: 0 */ -export const DATA_IMAGE_USER_DOT_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAYAAABXuSs3AAAHHklEQVRoQ7VZW08bVxCeXRuwIbTGXIwNtBBaqjwgVUiR8lDlbza9qe1DpVZ9aNQ/0KpPeaJK07SpcuEeCEmUAObm21bfrL9lONjexSYrWfbunj37zXdmvpkz9oIgCKTD0Wg0xPd94TDP83Q0zvWa50vzklSrdanVanqf4/D84GBGr+F+Op3S8fqoJxLOdnZgTvsO/nYhenHA+UC7CWF1uXwkb9++ldPTUwVerVbVqFQqpR8YPjQ0JCMjI5LNDijoRgP3PQVu5+5Eor2XGLg7IV4GkIdHJ/LmzRs5ODiIwNbrdR0O0GCcq4Xz4eFhmZyclP7+tDQaIik/BG5XKQn4SwG3zJTLZXn9+rUclI8UHD5YVoDDN8bSzXhONwL48fFxGR4eilzFZT1uFRIB5yT8BqCdnR3Z3d0VP9Un6XRawYJpggVrZBv38ME4XKtUKnLt2jUplUoy1PR/l3U7T6sVSAQcgMAkj8PDQ9ne3pajoyMRL7zeKsYZWHgWYDGmv78/mmdwcFA+mJlSgziHDWrERrsjEXDXegTi1tZW+DLxI2bxIrqFNYTXyDyCFweMAHCwb8e4RnTNuOsqe3t7sra21pTD0Kct666E8XlcZyzw9/RUUXK5nK5oUinUQI6TQ3cynO/v78vq6qrKXCNwlTiJJpyNGc3nZHp6uqV2dwrQWOCtZBDAV1ZWwsQk7f0wiQn5kffbAu/0/KWBYzIC1+XukfGx0RGZmppKlC2tIV0Bh4aDcZW7HhkfH8urLLZL7T2pihvlkMNnz56FiadHxicL41IsFpN41bkxsYxbRdFo9jwB8KdPn14J8KnSpBQKhQs63nPmbCVRcBUAR2Lq1VVmpksyMTFxAXjcEsQybiegESionjx5osCZOeNe1O4+EhCAX7bQSgQcxRHTMgAgcz5+/Dis/hL4uHU3/B4YGNASGHIKxuEql0k+l05AeIAF1vPnz5VxFFmdDlaJrMtZITJeSsXCOTlMunKxjLtMYOKNjQ158eJFuAuKkUOb5sEwgff19SkJUBVkThZUbnXZrtCKBQ6gbnWIkjZpyne3ejAWoGnA7Icz6irvBLgbOMicCM6TkxPx/LAkbXfgWcsazuE2kFRsKD5Z+CiqDumKncpZvieWcS6dDVD8xiYCNflpJdwcdwJOf9airLmVQ7DPzMxIYWLsXGXoVqLt5k0M3K3JUVPDZdbWNzsCp48TPFdvdnZWUz32nDha7bJ63kgAJPzSdRks9/Kf9xMJAQ1gq2NpaUmy2Yz4zar4nQC3xb99AQwCcGzLAAwuhG8YiWvcOKts+r4GOe5nMhm5efOm9lUA3E3vSZJRrKvE0fnPv//Jy5cvo5cTHIPQbSjhOoqq69evS19f6lxDKK4+sVhigZPtKJqbrQeqxd5+WR4+fKgqgT0k2XX3nhiPgETWXFhYkFzuPZ2yVq1GTSOXpE47/VjgNnD4m4GG7/LhsTx69EiwD4Vr2MwIIxgbAH18fKx1yfz8vEogNvGtWnCuhLZa9UTAreVWFsHy/b/+Vrbdl7E5REMQD2jDoUbByty+/ZnU64GkU2HzyJLhktU1cLv8nARgkYS2d3ajAgwG8qU2oLmDZ92CMaOjo7K4uCiZgbDWaRWgnZhPxLhrMUCvr69riwKZk1LHF7XqrWAO9hJxH6ozNzcnCx/PqztZg9mf6SQMscCtm2C5ke4BGMlHWTUp36036AJajDVrFMzBrhhWslQsSrFYiOqVpMriNYIgqFRq2j3FAb/zffT6zuxFXxsNzs3NTXn16lW4gYiW96w1FyedF+83xG/2FNGCRpU4NjamMsn+OZ9xE5RXqdaDdPpib6RWCzuwKF9RxqI2AVNQBwQYJoK0wdBejnqtEikP3pfP51XjUTESl12FqJEKxsEorARYDD44ONTeID7YpsEnrRvQfWAI2e8WfDaTUSIwJ0iBCmFOtOUAHvVMPp/TPwvYFVYFIuP8l+DBgwdaa2Miqwa0GgYwfeMltovbDfh6c1vIgMYcliSsKv4IWFr6VDHxvldvBAH+1sA+cnl5WYOPmmr9ir+1l9I0Cgz0yjhXjfJJ0JROnmezWbl165ayr/5fqwcBNr7IfhjMqKcvESSM4eRcCasQ3bDNObmKPLdGUGpZsN24cUNLBm9zazu4d++e6qpNBFaTuUS26U5dpuR1CxyA7J9ddrMRqlz4pwLLYawymPd++/2PADt2ugcGwq9gCCdhQ96C6xWwa6j1ceuq+I0EhW0i8MAIVJfeL3d/DVD8EKi12P6/2S2jV/EccVB54O/ejz/9HGCpoBBMta5rXMXLu53D1XAwjhXwvvv+h4BAXVe4bOu3O3ChxF08LiZFG3fel199G9CH3fLyqv24NcB44MRhpdK788U3CpyKwsCw590xmfSpzsBt0Fqc3ud3vtZigxWcVZCklVpSiN0w3q5E/h9TGMIUuA3+EQAAAABJRU5ErkJggg=='; +export const DATA_IMAGE_USER_DOT_PIC = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAYAAABXuSs3AAAHHklEQVRoQ7VZW08bVxCeXRuwIbTGXIwNtBBaqjwgVUiR8lDlbza9qe1DpVZ9aNQ/0KpPeaJK07SpcuEeCEmUAObm21bfrL9lONjexSYrWfbunj37zXdmvpkz9oIgCKTD0Wg0xPd94TDP83Q0zvWa50vzklSrdanVanqf4/D84GBGr+F+Op3S8fqoJxLOdnZgTvsO/nYhenHA+UC7CWF1uXwkb9++ldPTUwVerVbVqFQqpR8YPjQ0JCMjI5LNDijoRgP3PQVu5+5Eor2XGLg7IV4GkIdHJ/LmzRs5ODiIwNbrdR0O0GCcq4Xz4eFhmZyclP7+tDQaIik/BG5XKQn4SwG3zJTLZXn9+rUclI8UHD5YVoDDN8bSzXhONwL48fFxGR4eilzFZT1uFRIB5yT8BqCdnR3Z3d0VP9Un6XRawYJpggVrZBv38ME4XKtUKnLt2jUplUoy1PR/l3U7T6sVSAQcgMAkj8PDQ9ne3pajoyMRL7zeKsYZWHgWYDGmv78/mmdwcFA+mJlSgziHDWrERrsjEXDXegTi1tZW+DLxI2bxIrqFNYTXyDyCFweMAHCwb8e4RnTNuOsqe3t7sra21pTD0Kct666E8XlcZyzw9/RUUXK5nK5oUinUQI6TQ3cynO/v78vq6qrKXCNwlTiJJpyNGc3nZHp6uqV2dwrQWOCtZBDAV1ZWwsQk7f0wiQn5kffbAu/0/KWBYzIC1+XukfGx0RGZmppKlC2tIV0Bh4aDcZW7HhkfH8urLLZL7T2pihvlkMNnz56FiadHxicL41IsFpN41bkxsYxbRdFo9jwB8KdPn14J8KnSpBQKhQs63nPmbCVRcBUAR2Lq1VVmpksyMTFxAXjcEsQybiegESionjx5osCZOeNe1O4+EhCAX7bQSgQcxRHTMgAgcz5+/Dis/hL4uHU3/B4YGNASGHIKxuEql0k+l05AeIAF1vPnz5VxFFmdDlaJrMtZITJeSsXCOTlMunKxjLtMYOKNjQ158eJFuAuKkUOb5sEwgff19SkJUBVkThZUbnXZrtCKBQ6gbnWIkjZpyne3ejAWoGnA7Icz6irvBLgbOMicCM6TkxPx/LAkbXfgWcsazuE2kFRsKD5Z+CiqDumKncpZvieWcS6dDVD8xiYCNflpJdwcdwJOf9airLmVQ7DPzMxIYWLsXGXoVqLt5k0M3K3JUVPDZdbWNzsCp48TPFdvdnZWUz32nDha7bJ63kgAJPzSdRks9/Kf9xMJAQ1gq2NpaUmy2Yz4zar4nQC3xb99AQwCcGzLAAwuhG8YiWvcOKts+r4GOe5nMhm5efOm9lUA3E3vSZJRrKvE0fnPv//Jy5cvo5cTHIPQbSjhOoqq69evS19f6lxDKK4+sVhigZPtKJqbrQeqxd5+WR4+fKgqgT0k2XX3nhiPgETWXFhYkFzuPZ2yVq1GTSOXpE47/VjgNnD4m4GG7/LhsTx69EiwD4Vr2MwIIxgbAH18fKx1yfz8vEogNvGtWnCuhLZa9UTAreVWFsHy/b/+Vrbdl7E5REMQD2jDoUbByty+/ZnU64GkU2HzyJLhktU1cLv8nARgkYS2d3ajAgwG8qU2oLmDZ92CMaOjo7K4uCiZgbDWaRWgnZhPxLhrMUCvr69riwKZk1LHF7XqrWAO9hJxH6ozNzcnCx/PqztZg9mf6SQMscCtm2C5ke4BGMlHWTUp36036AJajDVrFMzBrhhWslQsSrFYiOqVpMriNYIgqFRq2j3FAb/zffT6zuxFXxsNzs3NTXn16lW4gYiW96w1FyedF+83xG/2FNGCRpU4NjamMsn+OZ9xE5RXqdaDdPpib6RWCzuwKF9RxqI2AVNQBwQYJoK0wdBejnqtEikP3pfP51XjUTESl12FqJEKxsEorARYDD44ONTeID7YpsEnrRvQfWAI2e8WfDaTUSIwJ0iBCmFOtOUAHvVMPp/TPwvYFVYFIuP8l+DBgwdaa2Miqwa0GgYwfeMltovbDfh6c1vIgMYcliSsKv4IWFr6VDHxvldvBAH+1sA+cnl5WYOPmmr9ir+1l9I0Cgz0yjhXjfJJ0JROnmezWbl165ayr/5fqwcBNr7IfhjMqKcvESSM4eRcCasQ3bDNObmKPLdGUGpZsN24cUNLBm9zazu4d++e6qpNBFaTuUS26U5dpuR1CxyA7J9ddrMRqlz4pwLLYawymPd++/2PADt2ugcGwq9gCCdhQ96C6xWwa6j1ceuq+I0EhW0i8MAIVJfeL3d/DVD8EKi12P6/2S2jV/EccVB54O/ejz/9HGCpoBBMta5rXMXLu53D1XAwjhXwvvv+h4BAXVe4bOu3O3ChxF08LiZFG3fel199G9CH3fLyqv24NcB44MRhpdK788U3CpyKwsCw590xmfSpzsBt0Fqc3ud3vtZigxWcVZCklVpSiN0w3q5E/h9TGMIUuA3+EQAAAABJRU5ErkJggg=='; -export const DATA_IMAGE_TRANSP_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII='; +export const DATA_IMAGE_TRANSP_PIC = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII='; -export const DATA_IMAGE_LAZY_PLACEHOLDER_PIC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC'; +export const DATA_IMAGE_LAZY_PLACEHOLDER_PIC = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC'; diff --git a/dev/Common/Enums.js b/dev/Common/Enums.js index 47a54b059..e0d146366 100644 --- a/dev/Common/Enums.js +++ b/dev/Common/Enums.js @@ -1,4 +1,3 @@ - /* eslint quote-props: 0 */ /** @@ -387,7 +386,6 @@ export const SignedVerifyStatus = { * @enum {number} */ export const ContactPropertyType = { - 'Unknown': 0, 'FullName': 10, diff --git a/dev/Common/Events.js b/dev/Common/Events.js index 749745e08..00636853d 100644 --- a/dev/Common/Events.js +++ b/dev/Common/Events.js @@ -1,6 +1,5 @@ - import _ from '_'; -import {isObject, isUnd} from 'Common/Utils'; +import { isObject, isUnd } from 'Common/Utils'; import * as Plugins from 'Common/Plugins'; const SUBS = {}; @@ -10,21 +9,16 @@ const SUBS = {}; * @param {Function} func * @param {Object=} context */ -export function sub(name, func, context) -{ - if (isObject(name)) - { +export function sub(name, func, context) { + if (isObject(name)) { context = func || null; func = null; _.each(name, (subFunc, subName) => { sub(subName, subFunc, context); }); - } - else - { - if (isUnd(SUBS[name])) - { + } else { + if (isUnd(SUBS[name])) { SUBS[name] = []; } @@ -36,15 +30,12 @@ export function sub(name, func, context) * @param {string} name * @param {Array=} args */ -export function pub(name, args) -{ +export function pub(name, args) { Plugins.runHook('rl-pub', [name, args]); - if (!isUnd(SUBS[name])) - { + if (!isUnd(SUBS[name])) { _.each(SUBS[name], (items) => { - if (items[0]) - { + if (items[0]) { items[0].apply(items[1] || null, args || []); } }); diff --git a/dev/Common/Globals.js b/dev/Common/Globals.js index 0d4adc5cd..18aa68187 100644 --- a/dev/Common/Globals.js +++ b/dev/Common/Globals.js @@ -3,12 +3,12 @@ import _ from '_'; import $ from '$'; import key from 'key'; import ko from 'ko'; -import {KeyState} from 'Common/Enums'; +import { KeyState } from 'Common/Enums'; const $win = $(window); $win.__sizes = [0, 0]; -export {$win}; +export { $win }; export const $doc = $(window.document); @@ -19,9 +19,12 @@ export const $body = $('body'); export const $div = $('
'); export const $hcont = $(''); -$hcont.attr('area', 'hidden').css({position: 'absolute', left: -5000}).appendTo($body); +$hcont + .attr('area', 'hidden') + .css({ position: 'absolute', left: -5000 }) + .appendTo($body); -export const startMicrotime = (new window.Date()).getTime(); +export const startMicrotime = new window.Date().getTime(); /** * @type {boolean} @@ -31,7 +34,7 @@ export const community = RL_COMMUNITY; /** * @type {?} */ -export const dropdownVisibility = ko.observable(false).extend({rateLimit: 0}); +export const dropdownVisibility = ko.observable(false).extend({ rateLimit: 0 }); /** * @type {boolean} @@ -41,8 +44,8 @@ export const useKeyboardShortcuts = ko.observable(true); /** * @type {string} */ -export const sUserAgent = 'navigator' in window && 'userAgent' in window.navigator && - window.navigator.userAgent.toLowerCase() || ''; +export const sUserAgent = + ('navigator' in window && 'userAgent' in window.navigator && window.navigator.userAgent.toLowerCase()) || ''; /** * @type {boolean} @@ -77,7 +80,8 @@ export const bDisableNanoScroll = bMobileDevice; /** * @type {boolean} */ -export const bAnimationSupported = !bMobileDevice && $html.hasClass('csstransitions') && $html.hasClass('cssanimations'); +export const bAnimationSupported = + !bMobileDevice && $html.hasClass('csstransitions') && $html.hasClass('cssanimations'); /** * @type {boolean} @@ -87,7 +91,8 @@ export const bXMLHttpRequestSupported = !!window.XMLHttpRequest; /** * @type {boolean} */ -export const bIsHttps = window.document && window.document.location ? 'https:' === window.document.location.protocol : false; +export const bIsHttps = + window.document && window.document.location ? 'https:' === window.document.location.protocol : false; /** * @type {Object} @@ -98,15 +103,15 @@ export const htmlEditorDefaultConfig = { 'customConfig': '', 'contentsCss': '', 'toolbarGroups': [ - {name: 'spec'}, - {name: 'styles'}, - {name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'bidi']}, - {name: 'colors'}, - bMobileDevice ? {} : {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']}, - {name: 'links'}, - {name: 'insert'}, - {name: 'document', groups: ['mode', 'document', 'doctools']}, - {name: 'others'} + { name: 'spec' }, + { name: 'styles' }, + { name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'bidi'] }, + { name: 'colors' }, + bMobileDevice ? {} : { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'] }, + { name: 'links' }, + { name: 'insert' }, + { name: 'document', groups: ['mode', 'document', 'doctools'] }, + { name: 'others' } ], 'removePlugins': 'liststyle', @@ -171,17 +176,15 @@ export const htmlEditorLangsMap = { */ let bAllowPdfPreview = !bMobileDevice; -if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) -{ +if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) { bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, (type) => type && 'application/pdf' === type.type); - if (!bAllowPdfPreview) - { + if (!bAllowPdfPreview) { bAllowPdfPreview = 'undefined' !== typeof window.navigator.mimeTypes['application/pdf']; } } -export {bAllowPdfPreview}; +export { bAllowPdfPreview }; export const VIEW_MODELS = { settings: [], @@ -222,26 +225,21 @@ export const keyScopeFake = ko.observable(KeyState.All); export const keyScope = ko.computed({ read: () => keyScopeFake(), write: (value) => { - - if (KeyState.Menu !== value) - { - if (KeyState.Compose === value) - { + if (KeyState.Menu !== value) { + if (KeyState.Compose === value) { // disableKeyFilter key.filter = () => useKeyboardShortcuts(); - } - else - { + } else { // restoreKeyFilter key.filter = (event) => { - - if (useKeyboardShortcuts()) - { - const - el = event.target || event.srcElement, + if (useKeyboardShortcuts()) { + const el = event.target || event.srcElement, tagName = el ? el.tagName.toUpperCase() : ''; - return !('INPUT' === tagName || 'SELECT' === tagName || 'TEXTAREA' === tagName || + return !( + 'INPUT' === tagName || + 'SELECT' === tagName || + 'TEXTAREA' === tagName || (el && 'DIV' === tagName && ('editorHtmlArea' === el.className || 'true' === '' + el.contentEditable)) ); } @@ -251,8 +249,7 @@ export const keyScope = ko.computed({ } keyScopeFake(value); - if (dropdownVisibility()) - { + if (dropdownVisibility()) { value = KeyState.Menu; } } @@ -262,17 +259,14 @@ export const keyScope = ko.computed({ }); keyScopeReal.subscribe((value) => { -// window.console.log('keyScope=' + sValue); // DEBUG + // window.console.log('keyScope=' + sValue); // DEBUG key.setScope(value); }); dropdownVisibility.subscribe((value) => { - if (value) - { + if (value) { keyScope(KeyState.Menu); - } - else if (KeyState.Menu === key.getScope()) - { + } else if (KeyState.Menu === key.getScope()) { keyScope(keyScopeFake()); } }); diff --git a/dev/Common/HtmlEditor.js b/dev/Common/HtmlEditor.js index 13344d03b..b8efb3d48 100644 --- a/dev/Common/HtmlEditor.js +++ b/dev/Common/HtmlEditor.js @@ -1,13 +1,11 @@ - import window from 'window'; import _ from '_'; import $ from '$'; -import {htmlEditorDefaultConfig, htmlEditorLangsMap} from 'Common/Globals'; -import {EventKeyCode, Magics} from 'Common/Enums'; +import { htmlEditorDefaultConfig, htmlEditorLangsMap } from 'Common/Globals'; +import { EventKeyCode, Magics } from 'Common/Enums'; import * as Settings from 'Storage/Settings'; -class HtmlEditor -{ +class HtmlEditor { editor; blurTimer = 0; @@ -29,8 +27,7 @@ class HtmlEditor * @param {Function=} onReady * @param {Function=} onModeChange */ - constructor(element, onBlur = null, onReady = null, onModeChange = null) - { + constructor(element, onBlur = null, onReady = null, onModeChange = null) { this.onBlur = onBlur; this.onReady = onReady; this.onModeChange = onModeChange; @@ -44,15 +41,13 @@ class HtmlEditor } runOnBlur() { - if (this.onBlur) - { + if (this.onBlur) { this.onBlur(); } } blurTrigger() { - if (this.onBlur) - { + if (this.onBlur) { window.clearTimeout(this.blurTimer); this.blurTimer = window.setTimeout(() => { this.runOnBlur(); @@ -61,8 +56,7 @@ class HtmlEditor } focusTrigger() { - if (this.onBlur) - { + if (this.onBlur) { window.clearTimeout(this.blurTimer); } } @@ -78,8 +72,7 @@ class HtmlEditor * @returns {void} */ clearCachedSignature() { - if (this.editor) - { + if (this.editor) { this.editor.execCommand('insertSignature', { clearCache: true }); @@ -93,8 +86,7 @@ class HtmlEditor * @returns {void} */ setSignature(signature, html, insertBefore = false) { - if (this.editor) - { + if (this.editor) { this.editor.execCommand('insertSignature', { isHtml: html, insertBefore: insertBefore, @@ -111,8 +103,7 @@ class HtmlEditor } resetDirty() { - if (this.editor) - { + if (this.editor) { this.editor.resetDirty(); } } @@ -122,24 +113,19 @@ class HtmlEditor * @returns {string} */ getData(wrapIsHtml = false) { - let result = ''; - if (this.editor) - { - try - { - if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) - { + if (this.editor) { + try { + if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) { result = this.editor.__plain.getRawData(); + } else { + result = wrapIsHtml + ? ']*><\/p>/ig, ''); + html = html.replace(/
]*><\/p>/gi, '');
try {
this.editor.setData(html);
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
- if (focus)
- {
+ if (focus) {
this.focus();
}
}
}
replaceHtml(find, replaceHtml) {
- if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode)
- {
+ if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode) {
try {
this.editor.setData(this.editor.getData().replace(find, replaceHtml));
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
setPlain(plain, focus) {
- if (this.editor && this.__inited)
- {
+ if (this.editor && this.__inited) {
this.clearCachedSignature();
this.modeToggle(false);
- if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
- {
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) {
this.editor.__plain.setRawData(plain);
- }
- else
- {
+ } else {
try {
this.editor.setData(plain);
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
- if (focus)
- {
+ if (focus) {
this.focus();
}
}
}
init() {
- if (this.element && !this.editor)
- {
- const
- initFunc = () => {
+ if (this.element && !this.editor) {
+ const initFunc = () => {
+ const config = htmlEditorDefaultConfig,
+ language = Settings.settingsGet('Language'),
+ allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'),
+ biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons');
- const
- config = htmlEditorDefaultConfig,
- language = Settings.settingsGet('Language'),
- allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'),
- biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons');
+ if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited) {
+ config.toolbarGroups.__cfgInited = true;
- if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited)
- {
- config.toolbarGroups.__cfgInited = true;
-
- if (allowSource)
- {
- config.removeButtons = config.removeButtons.replace(',Source', '');
- }
-
- if (!biti)
- {
- config.removePlugins += (config.removePlugins ? ',' : '') + 'bidi';
- }
+ if (allowSource) {
+ config.removeButtons = config.removeButtons.replace(',Source', '');
}
- config.enterMode = window.CKEDITOR.ENTER_BR;
- config.shiftEnterMode = window.CKEDITOR.ENTER_P;
+ if (!biti) {
+ config.removePlugins += (config.removePlugins ? ',' : '') + 'bidi';
+ }
+ }
- config.language = htmlEditorLangsMap[(language || 'en').toLowerCase()] || 'en';
- if (window.CKEDITOR.env)
- {
- window.CKEDITOR.env.isCompatible = true;
+ config.enterMode = window.CKEDITOR.ENTER_BR;
+ config.shiftEnterMode = window.CKEDITOR.ENTER_P;
+
+ config.language = htmlEditorLangsMap[(language || 'en').toLowerCase()] || 'en';
+ if (window.CKEDITOR.env) {
+ window.CKEDITOR.env.isCompatible = true;
+ }
+
+ this.editor = window.CKEDITOR.appendTo(this.element, config);
+
+ this.editor.on('key', (event) => {
+ if (event && event.data && EventKeyCode.Tab === event.data.keyCode) {
+ return false;
}
- this.editor = window.CKEDITOR.appendTo(this.element, config);
+ return true;
+ });
- this.editor.on('key', (event) => {
- if (event && event.data && EventKeyCode.Tab === event.data.keyCode)
- {
- return false;
- }
+ this.editor.on('blur', () => {
+ this.blurTrigger();
+ });
- return true;
- });
+ this.editor.on('mode', () => {
+ this.blurTrigger();
+ if (this.onModeChange) {
+ this.onModeChange('plain' !== this.editor.mode);
+ }
+ });
- this.editor.on('blur', () => {
- this.blurTrigger();
- });
+ this.editor.on('focus', () => {
+ this.focusTrigger();
+ });
- this.editor.on('mode', () => {
- this.blurTrigger();
- if (this.onModeChange)
- {
- this.onModeChange('plain' !== this.editor.mode);
- }
- });
+ if (window.FileReader) {
+ this.editor.on('drop', (event) => {
+ if (0 < event.data.dataTransfer.getFilesCount()) {
+ const file = event.data.dataTransfer.getFile(0);
+ if (file && window.FileReader && event.data.dataTransfer.id && file.type && file.type.match(/^image/i)) {
+ const id = event.data.dataTransfer.id,
+ imageId = `[img=${id}]`,
+ reader = new window.FileReader();
- this.editor.on('focus', () => {
- this.focusTrigger();
- });
+ reader.onloadend = () => {
+ if (reader.result) {
+ this.replaceHtml(imageId, ``);
+ }
+ };
- if (window.FileReader)
- {
- this.editor.on('drop', (event) => {
- if (0 < event.data.dataTransfer.getFilesCount())
- {
- const file = event.data.dataTransfer.getFile(0);
- if (file && window.FileReader && event.data.dataTransfer.id &&
- file.type && file.type.match(/^image/i))
- {
- const
- id = event.data.dataTransfer.id,
- imageId = `[img=${id}]`,
- reader = new window.FileReader();
+ reader.readAsDataURL(file);
- reader.onloadend = () => {
- if (reader.result)
- {
- this.replaceHtml(imageId, `
`);
- }
- };
-
- reader.readAsDataURL(file);
-
- event.data.dataTransfer.setData('text/html', imageId);
- }
+ event.data.dataTransfer.setData('text/html', imageId);
}
- });
+ }
+ });
+ }
+
+ this.editor.on('instanceReady', () => {
+ if (this.editor.removeMenuItem) {
+ this.editor.removeMenuItem('cut');
+ this.editor.removeMenuItem('copy');
+ this.editor.removeMenuItem('paste');
}
- this.editor.on('instanceReady', () => {
+ this.__resizable = true;
+ this.__inited = true;
- if (this.editor.removeMenuItem)
- {
- this.editor.removeMenuItem('cut');
- this.editor.removeMenuItem('copy');
- this.editor.removeMenuItem('paste');
- }
+ this.resize();
- this.__resizable = true;
- this.__inited = true;
+ if (this.onReady) {
+ this.onReady();
+ }
+ });
+ };
- this.resize();
-
- if (this.onReady)
- {
- this.onReady();
- }
-
- });
- };
-
- if (window.CKEDITOR)
- {
+ if (window.CKEDITOR) {
initFunc();
- }
- else
- {
+ } else {
window.__initEditor = initFunc;
}
}
}
focus() {
- if (this.editor)
- {
+ if (this.editor) {
try {
this.editor.focus();
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
hasFocus() {
- if (this.editor)
- {
+ if (this.editor) {
try {
return !!this.editor.focusManager.hasFocus;
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
return false;
}
blur() {
- if (this.editor)
- {
+ if (this.editor) {
try {
this.editor.focusManager.blur(true);
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
resizeEditor() {
- if (this.editor && this.__resizable)
- {
+ if (this.editor && this.__resizable) {
try {
this.editor.resize(this.$element.width(), this.$element.innerHeight());
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
setReadOnly(value) {
- if (this.editor)
- {
+ if (this.editor) {
try {
this.editor.setReadOnly(!!value);
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
@@ -427,4 +359,4 @@ class HtmlEditor
}
}
-export {HtmlEditor, HtmlEditor as default};
+export { HtmlEditor, HtmlEditor as default };
diff --git a/dev/Common/Jassl.js b/dev/Common/Jassl.js
index b5b9bc69b..0ce622ca6 100644
--- a/dev/Common/Jassl.js
+++ b/dev/Common/Jassl.js
@@ -1,4 +1,3 @@
-
import window from 'window';
// let rainloopCaches = window.caches && window.caches.open ? window.caches : null;
@@ -9,19 +8,15 @@ import window from 'window';
* @returns {Promise}
*/
export function jassl(src, async = false) {
-
- if (!window.Promise || !window.Promise.all)
- {
+ if (!window.Promise || !window.Promise.all) {
throw new Error('Promises are not available your environment.');
}
- if (!src)
- {
+ if (!src) {
throw new Error('src should not be empty.');
}
return new window.Promise((resolve, reject) => {
-
const element = window.document.createElement('script');
element.onload = () => {
@@ -36,7 +31,7 @@ export function jassl(src, async = false) {
element.src = src;
window.document.body.appendChild(element);
- })/* .then((s) => {
+ }) /* .then((s) => {
const found = s && rainloopCaches ? s.match(/rainloop\/v\/([^\/]+)\/static\//) : null;
if (found && found[1])
diff --git a/dev/Common/Links.js b/dev/Common/Links.js
index 2c70a680d..1c45f7826 100644
--- a/dev/Common/Links.js
+++ b/dev/Common/Links.js
@@ -1,20 +1,15 @@
-
import window from 'window';
-import {pString, pInt, isUnd, isNormal, trim, encodeURIComponent} from 'Common/Utils';
+import { pString, pInt, isUnd, isNormal, trim, encodeURIComponent } from 'Common/Utils';
import * as Settings from 'Storage/Settings';
-const
- ROOT = './',
+const ROOT = './',
HASH_PREFIX = '#/',
SERVER_PREFIX = './?',
SUB_QUERY_PREFIX = '&q[]=',
-
VERSION = Settings.appSettingsGet('version'),
-
WEB_PREFIX = Settings.appSettingsGet('webPath') || '',
VERSION_PREFIX = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + VERSION + '/',
STATIC_PREFIX = VERSION_PREFIX + 'static/',
-
ADMIN_HOST_USE = !!Settings.appSettingsGet('adminHostUse'),
ADMIN_PATH = Settings.appSettingsGet('adminPath') || 'admin';
@@ -23,16 +18,14 @@ let AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
/**
* @returns {void}
*/
-export function populateAuthSuffix()
-{
+export function populateAuthSuffix() {
AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
}
/**
* @returns {string}
*/
-export function subQueryPrefix()
-{
+export function subQueryPrefix() {
return SUB_QUERY_PREFIX;
}
@@ -40,24 +33,21 @@ export function subQueryPrefix()
* @param {string=} startupUrl
* @returns {string}
*/
-export function root(startupUrl = '')
-{
+export function root(startupUrl = '') {
return HASH_PREFIX + pString(startupUrl);
}
/**
* @returns {string}
*/
-export function rootAdmin()
-{
+export function rootAdmin() {
return ADMIN_HOST_USE ? ROOT : SERVER_PREFIX + ADMIN_PATH;
}
/**
* @returns {string}
*/
-export function rootUser()
-{
+export function rootUser() {
return ROOT;
}
@@ -67,10 +57,21 @@ export function rootUser()
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentRaw(type, download, customSpecSuffix)
-{
+export function attachmentRaw(type, download, customSpecSuffix) {
customSpecSuffix = isUnd(customSpecSuffix) ? AUTH_PREFIX : customSpecSuffix;
- return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + customSpecSuffix + '/' + type + '/' + SUB_QUERY_PREFIX + '/' + download;
+ return (
+ SERVER_PREFIX +
+ '/Raw/' +
+ SUB_QUERY_PREFIX +
+ '/' +
+ customSpecSuffix +
+ '/' +
+ type +
+ '/' +
+ SUB_QUERY_PREFIX +
+ '/' +
+ download
+ );
}
/**
@@ -78,8 +79,7 @@ export function attachmentRaw(type, download, customSpecSuffix)
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentDownload(download, customSpecSuffix)
-{
+export function attachmentDownload(download, customSpecSuffix) {
return attachmentRaw('Download', download, customSpecSuffix);
}
@@ -88,8 +88,7 @@ export function attachmentDownload(download, customSpecSuffix)
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentPreview(download, customSpecSuffix)
-{
+export function attachmentPreview(download, customSpecSuffix) {
return attachmentRaw('View', download, customSpecSuffix);
}
@@ -98,8 +97,7 @@ export function attachmentPreview(download, customSpecSuffix)
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentThumbnailPreview(download, customSpecSuffix)
-{
+export function attachmentThumbnailPreview(download, customSpecSuffix) {
return attachmentRaw('ViewThumbnail', download, customSpecSuffix);
}
@@ -108,8 +106,7 @@ export function attachmentThumbnailPreview(download, customSpecSuffix)
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentPreviewAsPlain(download, customSpecSuffix)
-{
+export function attachmentPreviewAsPlain(download, customSpecSuffix) {
return attachmentRaw('ViewAsPlain', download, customSpecSuffix);
}
@@ -118,8 +115,7 @@ export function attachmentPreviewAsPlain(download, customSpecSuffix)
* @param {string=} customSpecSuffix
* @returns {string}
*/
-export function attachmentFramed(download, customSpecSuffix)
-{
+export function attachmentFramed(download, customSpecSuffix) {
return attachmentRaw('FramedView', download, customSpecSuffix);
}
@@ -127,40 +123,35 @@ export function attachmentFramed(download, customSpecSuffix)
* @param {string} type
* @returns {string}
*/
-export function serverRequest(type)
-{
+export function serverRequest(type) {
return SERVER_PREFIX + '/' + type + '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/';
}
/**
* @returns {string}
*/
-export function upload()
-{
+export function upload() {
return serverRequest('Upload');
}
/**
* @returns {string}
*/
-export function uploadContacts()
-{
+export function uploadContacts() {
return serverRequest('UploadContacts');
}
/**
* @returns {string}
*/
-export function uploadBackground()
-{
+export function uploadBackground() {
return serverRequest('UploadBackground');
}
/**
* @returns {string}
*/
-export function append()
-{
+export function append() {
return serverRequest('Append');
}
@@ -168,8 +159,7 @@ export function append()
* @param {string} email
* @returns {string}
*/
-export function change(email)
-{
+export function change(email) {
return serverRequest('Change') + encodeURIComponent(email) + '/';
}
@@ -177,8 +167,7 @@ export function change(email)
* @param {string} add
* @returns {string}
*/
-export function ajax(add)
-{
+export function ajax(add) {
return serverRequest('Ajax') + add;
}
@@ -186,26 +175,35 @@ export function ajax(add)
* @param {string} requestHash
* @returns {string}
*/
-export function messageViewLink(requestHash)
-{
- return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ViewAsPlain/' + SUB_QUERY_PREFIX + '/' + requestHash;
+export function messageViewLink(requestHash) {
+ return (
+ SERVER_PREFIX +
+ '/Raw/' +
+ SUB_QUERY_PREFIX +
+ '/' +
+ AUTH_PREFIX +
+ '/ViewAsPlain/' +
+ SUB_QUERY_PREFIX +
+ '/' +
+ requestHash
+ );
}
/**
* @param {string} requestHash
* @returns {string}
*/
-export function messageDownloadLink(requestHash)
-{
- return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/Download/' + SUB_QUERY_PREFIX + '/' + requestHash;
+export function messageDownloadLink(requestHash) {
+ return (
+ SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/Download/' + SUB_QUERY_PREFIX + '/' + requestHash
+ );
}
/**
* @param {string} email
* @returns {string}
*/
-export function avatarLink(email)
-{
+export function avatarLink(email) {
return SERVER_PREFIX + '/Raw/0/Avatar/' + encodeURIComponent(email) + '/';
}
@@ -213,8 +211,7 @@ export function avatarLink(email)
* @param {string} hash
* @returns {string}
*/
-export function publicLink(hash)
-{
+export function publicLink(hash) {
return SERVER_PREFIX + '/Raw/0/Public/' + hash + '/';
}
@@ -222,16 +219,16 @@ export function publicLink(hash)
* @param {string} hash
* @returns {string}
*/
-export function userBackground(hash)
-{
- return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/UserBackground/' + SUB_QUERY_PREFIX + '/' + hash;
+export function userBackground(hash) {
+ return (
+ SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/UserBackground/' + SUB_QUERY_PREFIX + '/' + hash
+ );
}
/**
* @returns {string}
*/
-export function phpInfo()
-{
+export function phpInfo() {
return SERVER_PREFIX + '/Info';
}
@@ -240,24 +237,21 @@ export function phpInfo()
* @param {boolean} isAdmin
* @returns {string}
*/
-export function langLink(lang, isAdmin)
-{
+export function langLink(lang, isAdmin) {
return SERVER_PREFIX + '/Lang/0/' + (isAdmin ? 'Admin' : 'App') + '/' + window.encodeURI(lang) + '/' + VERSION + '/';
}
/**
* @returns {string}
*/
-export function exportContactsVcf()
-{
+export function exportContactsVcf() {
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsVcf/';
}
/**
* @returns {string}
*/
-export function exportContactsCsv()
-{
+export function exportContactsCsv() {
return SERVER_PREFIX + '/Raw/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/ContactsCsv/';
}
@@ -265,44 +259,43 @@ export function exportContactsCsv()
* @param {boolean} xauth = false
* @returns {string}
*/
-export function socialGoogle(xauth = false)
-{
- return SERVER_PREFIX + 'SocialGoogle' +
- ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '') + (xauth ? '&xauth=1' : '');
+export function socialGoogle(xauth = false) {
+ return (
+ SERVER_PREFIX +
+ 'SocialGoogle' +
+ ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '') +
+ (xauth ? '&xauth=1' : '')
+ );
}
/**
* @returns {string}
*/
-export function socialTwitter()
-{
- return SERVER_PREFIX + 'SocialTwitter' +
- ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '');
+export function socialTwitter() {
+ return SERVER_PREFIX + 'SocialTwitter' + ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '');
}
/**
* @returns {string}
*/
-export function socialFacebook()
-{
- return SERVER_PREFIX + 'SocialFacebook' +
- ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '');
+export function socialFacebook() {
+ return (
+ SERVER_PREFIX + 'SocialFacebook' + ('' !== AUTH_PREFIX ? '/' + SUB_QUERY_PREFIX + '/' + AUTH_PREFIX + '/' : '')
+ );
}
/**
* @param {string} path
* @returns {string}
*/
-export function staticPrefix(path)
-{
+export function staticPrefix(path) {
return STATIC_PREFIX + path;
}
/**
* @returns {string}
*/
-export function emptyContactPic()
-{
+export function emptyContactPic() {
return staticPrefix('css/images/empty-contact.png');
}
@@ -310,40 +303,35 @@ export function emptyContactPic()
* @param {string} fileName
* @returns {string}
*/
-export function sound(fileName)
-{
+export function sound(fileName) {
return staticPrefix('sounds/' + fileName);
}
/**
* @returns {string}
*/
-export function notificationMailIcon()
-{
+export function notificationMailIcon() {
return staticPrefix('css/images/icom-message-notification.png');
}
/**
* @returns {string}
*/
-export function openPgpJs()
-{
+export function openPgpJs() {
return staticPrefix('js/min/openpgp.min.js');
}
/**
* @returns {string}
*/
-export function openPgpWorkerJs()
-{
+export function openPgpWorkerJs() {
return staticPrefix('js/min/openpgp.worker.min.js');
}
/**
* @returns {string}
*/
-export function openPgpWorkerPath()
-{
+export function openPgpWorkerPath() {
return staticPrefix('js/min/');
}
@@ -351,11 +339,9 @@ export function openPgpWorkerPath()
* @param {string} theme
* @returns {string}
*/
-export function themePreviewLink(theme)
-{
+export function themePreviewLink(theme) {
let prefix = VERSION_PREFIX;
- if ('@custom' === theme.substr(-7))
- {
+ if ('@custom' === theme.substr(-7)) {
theme = trim(theme.substring(0, theme.length - 7));
prefix = WEB_PREFIX;
}
@@ -367,8 +353,7 @@ export function themePreviewLink(theme)
* @param {string} inboxFolderName = 'INBOX'
* @returns {string}
*/
-export function inbox(inboxFolderName = 'INBOX')
-{
+export function inbox(inboxFolderName = 'INBOX') {
return HASH_PREFIX + 'mailbox/' + inboxFolderName;
}
@@ -376,16 +361,14 @@ export function inbox(inboxFolderName = 'INBOX')
* @param {string=} screenName = ''
* @returns {string}
*/
-export function settings(screenName = '')
-{
+export function settings(screenName = '') {
return HASH_PREFIX + 'settings' + (screenName ? '/' + screenName : '');
}
/**
* @returns {string}
*/
-export function about()
-{
+export function about() {
return HASH_PREFIX + 'about';
}
@@ -393,11 +376,9 @@ export function about()
* @param {string} screenName
* @returns {string}
*/
-export function admin(screenName)
-{
+export function admin(screenName) {
let result = HASH_PREFIX;
- switch (screenName)
- {
+ switch (screenName) {
case 'AdminDomains':
result += 'domains';
break;
@@ -420,28 +401,24 @@ export function admin(screenName)
* @param {string=} threadUid = ''
* @returns {string}
*/
-export function mailBox(folder, page = 1, search = '', threadUid = '')
-{
+export function mailBox(folder, page = 1, search = '', threadUid = '') {
page = isNormal(page) ? pInt(page) : 1;
search = pString(search);
let result = HASH_PREFIX + 'mailbox/';
- if ('' !== folder)
- {
+ if ('' !== folder) {
const resultThreadUid = pInt(threadUid);
result += window.encodeURI(folder) + (0 < resultThreadUid ? '~' + resultThreadUid : '');
}
- if (1 < page)
- {
- result = result.replace(/[\/]+$/, '');
+ if (1 < page) {
+ result = result.replace(/[/]+$/, '');
result += '/p' + page;
}
- if ('' !== search)
- {
- result = result.replace(/[\/]+$/, '');
+ if ('' !== search) {
+ result = result.replace(/[/]+$/, '');
result += '/' + window.encodeURI(search);
}
diff --git a/dev/Common/Mime.js b/dev/Common/Mime.js
index a0f3aae78..e0a6863b3 100644
--- a/dev/Common/Mime.js
+++ b/dev/Common/Mime.js
@@ -1,166 +1,165 @@
-
/* eslint key-spacing: 0 */
/* eslint quote-props: 0 */
const Mime = {
- 'eml' : 'message/rfc822',
- 'mime' : 'message/rfc822',
- 'txt' : 'text/plain',
- 'text' : 'text/plain',
- 'def' : 'text/plain',
- 'list' : 'text/plain',
- 'in' : 'text/plain',
- 'ini' : 'text/plain',
- 'log' : 'text/plain',
- 'sql' : 'text/plain',
- 'cfg' : 'text/plain',
- 'conf' : 'text/plain',
- 'asc' : 'text/plain',
- 'rtx' : 'text/richtext',
- 'vcard' : 'text/vcard',
- 'vcf' : 'text/vcard',
- 'htm' : 'text/html',
- 'html' : 'text/html',
- 'csv' : 'text/csv',
- 'ics' : 'text/calendar',
- 'ifb' : 'text/calendar',
- 'xml' : 'text/xml',
- 'json' : 'application/json',
- 'swf' : 'application/x-shockwave-flash',
- 'hlp' : 'application/winhlp',
- 'wgt' : 'application/widget',
- 'chm' : 'application/vnd.ms-htmlhelp',
- 'p10' : 'application/pkcs10',
- 'p7c' : 'application/pkcs7-mime',
- 'p7m' : 'application/pkcs7-mime',
- 'p7s' : 'application/pkcs7-signature',
- 'torrent' : 'application/x-bittorrent',
+ 'eml': 'message/rfc822',
+ 'mime': 'message/rfc822',
+ 'txt': 'text/plain',
+ 'text': 'text/plain',
+ 'def': 'text/plain',
+ 'list': 'text/plain',
+ 'in': 'text/plain',
+ 'ini': 'text/plain',
+ 'log': 'text/plain',
+ 'sql': 'text/plain',
+ 'cfg': 'text/plain',
+ 'conf': 'text/plain',
+ 'asc': 'text/plain',
+ 'rtx': 'text/richtext',
+ 'vcard': 'text/vcard',
+ 'vcf': 'text/vcard',
+ 'htm': 'text/html',
+ 'html': 'text/html',
+ 'csv': 'text/csv',
+ 'ics': 'text/calendar',
+ 'ifb': 'text/calendar',
+ 'xml': 'text/xml',
+ 'json': 'application/json',
+ 'swf': 'application/x-shockwave-flash',
+ 'hlp': 'application/winhlp',
+ 'wgt': 'application/widget',
+ 'chm': 'application/vnd.ms-htmlhelp',
+ 'p10': 'application/pkcs10',
+ 'p7c': 'application/pkcs7-mime',
+ 'p7m': 'application/pkcs7-mime',
+ 'p7s': 'application/pkcs7-signature',
+ 'torrent': 'application/x-bittorrent',
// scripts
- 'js' : 'application/javascript',
- 'pl' : 'text/perl',
- 'css' : 'text/css',
- 'asp' : 'text/asp',
- 'php' : 'application/x-httpd-php',
- 'php3' : 'application/x-httpd-php',
- 'php4' : 'application/x-httpd-php',
- 'php5' : 'application/x-httpd-php',
- 'phtml' : 'application/x-httpd-php',
+ 'js': 'application/javascript',
+ 'pl': 'text/perl',
+ 'css': 'text/css',
+ 'asp': 'text/asp',
+ 'php': 'application/x-httpd-php',
+ 'php3': 'application/x-httpd-php',
+ 'php4': 'application/x-httpd-php',
+ 'php5': 'application/x-httpd-php',
+ 'phtml': 'application/x-httpd-php',
// images
- 'png' : 'image/png',
- 'jpg' : 'image/jpeg',
- 'jpeg' : 'image/jpeg',
- 'jpe' : 'image/jpeg',
- 'jfif' : 'image/jpeg',
- 'gif' : 'image/gif',
- 'bmp' : 'image/bmp',
- 'cgm' : 'image/cgm',
- 'ief' : 'image/ief',
- 'ico' : 'image/x-icon',
- 'tif' : 'image/tiff',
- 'tiff' : 'image/tiff',
- 'svg' : 'image/svg+xml',
- 'svgz' : 'image/svg+xml',
- 'djv' : 'image/vnd.djvu',
- 'djvu' : 'image/vnd.djvu',
- 'webp' : 'image/webp',
+ 'png': 'image/png',
+ 'jpg': 'image/jpeg',
+ 'jpeg': 'image/jpeg',
+ 'jpe': 'image/jpeg',
+ 'jfif': 'image/jpeg',
+ 'gif': 'image/gif',
+ 'bmp': 'image/bmp',
+ 'cgm': 'image/cgm',
+ 'ief': 'image/ief',
+ 'ico': 'image/x-icon',
+ 'tif': 'image/tiff',
+ 'tiff': 'image/tiff',
+ 'svg': 'image/svg+xml',
+ 'svgz': 'image/svg+xml',
+ 'djv': 'image/vnd.djvu',
+ 'djvu': 'image/vnd.djvu',
+ 'webp': 'image/webp',
// archives
- 'zip' : 'application/zip',
- '7z' : 'application/x-7z-compressed',
- 'rar' : 'application/x-rar-compressed',
- 'exe' : 'application/x-msdownload',
- 'dll' : 'application/x-msdownload',
- 'scr' : 'application/x-msdownload',
- 'com' : 'application/x-msdownload',
- 'bat' : 'application/x-msdownload',
- 'msi' : 'application/x-msdownload',
- 'cab' : 'application/vnd.ms-cab-compressed',
- 'gz' : 'application/x-gzip',
- 'tgz' : 'application/x-gzip',
- 'bz' : 'application/x-bzip',
- 'bz2' : 'application/x-bzip2',
- 'deb' : 'application/x-debian-package',
+ 'zip': 'application/zip',
+ '7z': 'application/x-7z-compressed',
+ 'rar': 'application/x-rar-compressed',
+ 'exe': 'application/x-msdownload',
+ 'dll': 'application/x-msdownload',
+ 'scr': 'application/x-msdownload',
+ 'com': 'application/x-msdownload',
+ 'bat': 'application/x-msdownload',
+ 'msi': 'application/x-msdownload',
+ 'cab': 'application/vnd.ms-cab-compressed',
+ 'gz': 'application/x-gzip',
+ 'tgz': 'application/x-gzip',
+ 'bz': 'application/x-bzip',
+ 'bz2': 'application/x-bzip2',
+ 'deb': 'application/x-debian-package',
// fonts
- 'psf' : 'application/x-font-linux-psf',
- 'otf' : 'application/x-font-otf',
- 'pcf' : 'application/x-font-pcf',
- 'snf' : 'application/x-font-snf',
- 'ttf' : 'application/x-font-ttf',
- 'ttc' : 'application/x-font-ttf',
+ 'psf': 'application/x-font-linux-psf',
+ 'otf': 'application/x-font-otf',
+ 'pcf': 'application/x-font-pcf',
+ 'snf': 'application/x-font-snf',
+ 'ttf': 'application/x-font-ttf',
+ 'ttc': 'application/x-font-ttf',
// audio
- 'mp3' : 'audio/mpeg',
- 'amr' : 'audio/amr',
- 'aac' : 'audio/x-aac',
- 'aif' : 'audio/x-aiff',
- 'aifc' : 'audio/x-aiff',
- 'aiff' : 'audio/x-aiff',
- 'wav' : 'audio/x-wav',
- 'wma' : 'audio/x-ms-wma',
- 'wax' : 'audio/x-ms-wax',
- 'midi' : 'audio/midi',
- 'mp4a' : 'audio/mp4',
- 'ogg' : 'audio/ogg',
- 'weba' : 'audio/webm',
- 'ra' : 'audio/x-pn-realaudio',
- 'ram' : 'audio/x-pn-realaudio',
- 'rmp' : 'audio/x-pn-realaudio-plugin',
- 'm3u' : 'audio/x-mpegurl',
+ 'mp3': 'audio/mpeg',
+ 'amr': 'audio/amr',
+ 'aac': 'audio/x-aac',
+ 'aif': 'audio/x-aiff',
+ 'aifc': 'audio/x-aiff',
+ 'aiff': 'audio/x-aiff',
+ 'wav': 'audio/x-wav',
+ 'wma': 'audio/x-ms-wma',
+ 'wax': 'audio/x-ms-wax',
+ 'midi': 'audio/midi',
+ 'mp4a': 'audio/mp4',
+ 'ogg': 'audio/ogg',
+ 'weba': 'audio/webm',
+ 'ra': 'audio/x-pn-realaudio',
+ 'ram': 'audio/x-pn-realaudio',
+ 'rmp': 'audio/x-pn-realaudio-plugin',
+ 'm3u': 'audio/x-mpegurl',
// video
- 'flv' : 'video/x-flv',
- 'qt' : 'video/quicktime',
- 'mov' : 'video/quicktime',
- 'wmv' : 'video/windows-media',
- 'avi' : 'video/x-msvideo',
- 'mpg' : 'video/mpeg',
- 'mpeg' : 'video/mpeg',
- 'mpe' : 'video/mpeg',
- 'm1v' : 'video/mpeg',
- 'm2v' : 'video/mpeg',
- '3gp' : 'video/3gpp',
- '3g2' : 'video/3gpp2',
- 'h261' : 'video/h261',
- 'h263' : 'video/h263',
- 'h264' : 'video/h264',
- 'jpgv' : 'video/jpgv',
- 'mp4' : 'video/mp4',
- 'mp4v' : 'video/mp4',
- 'mpg4' : 'video/mp4',
- 'ogv' : 'video/ogg',
- 'webm' : 'video/webm',
- 'm4v' : 'video/x-m4v',
- 'asf' : 'video/x-ms-asf',
- 'asx' : 'video/x-ms-asf',
- 'wm' : 'video/x-ms-wm',
- 'wmx' : 'video/x-ms-wmx',
- 'wvx' : 'video/x-ms-wvx',
- 'movie' : 'video/x-sgi-movie',
+ 'flv': 'video/x-flv',
+ 'qt': 'video/quicktime',
+ 'mov': 'video/quicktime',
+ 'wmv': 'video/windows-media',
+ 'avi': 'video/x-msvideo',
+ 'mpg': 'video/mpeg',
+ 'mpeg': 'video/mpeg',
+ 'mpe': 'video/mpeg',
+ 'm1v': 'video/mpeg',
+ 'm2v': 'video/mpeg',
+ '3gp': 'video/3gpp',
+ '3g2': 'video/3gpp2',
+ 'h261': 'video/h261',
+ 'h263': 'video/h263',
+ 'h264': 'video/h264',
+ 'jpgv': 'video/jpgv',
+ 'mp4': 'video/mp4',
+ 'mp4v': 'video/mp4',
+ 'mpg4': 'video/mp4',
+ 'ogv': 'video/ogg',
+ 'webm': 'video/webm',
+ 'm4v': 'video/x-m4v',
+ 'asf': 'video/x-ms-asf',
+ 'asx': 'video/x-ms-asf',
+ 'wm': 'video/x-ms-wm',
+ 'wmx': 'video/x-ms-wmx',
+ 'wvx': 'video/x-ms-wvx',
+ 'movie': 'video/x-sgi-movie',
// adobe
- 'pdf' : 'application/pdf',
- 'psd' : 'image/vnd.adobe.photoshop',
- 'ai' : 'application/postscript',
- 'eps' : 'application/postscript',
- 'ps' : 'application/postscript',
+ 'pdf': 'application/pdf',
+ 'psd': 'image/vnd.adobe.photoshop',
+ 'ai': 'application/postscript',
+ 'eps': 'application/postscript',
+ 'ps': 'application/postscript',
// ms office
- 'doc' : 'application/msword',
- 'dot' : 'application/msword',
- 'rtf' : 'application/rtf',
- 'xls' : 'application/vnd.ms-excel',
- 'ppt' : 'application/vnd.ms-powerpoint',
- 'docx' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'xlsx' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'dotx' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
- 'pptx' : 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'doc': 'application/msword',
+ 'dot': 'application/msword',
+ 'rtf': 'application/rtf',
+ 'xls': 'application/vnd.ms-excel',
+ 'ppt': 'application/vnd.ms-powerpoint',
+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'dotx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
+ 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
// open office
- 'odt' : 'application/vnd.oasis.opendocument.text',
- 'ods' : 'application/vnd.oasis.opendocument.spreadsheet'
+ 'odt': 'application/vnd.oasis.opendocument.text',
+ 'ods': 'application/vnd.oasis.opendocument.spreadsheet'
};
-export {Mime, Mime as default};
+export { Mime, Mime as default };
diff --git a/dev/Common/Momentor.js b/dev/Common/Momentor.js
index 35853f30d..1b067daa7 100644
--- a/dev/Common/Momentor.js
+++ b/dev/Common/Momentor.js
@@ -1,26 +1,32 @@
-
import window from 'window';
import _ from '_';
import $ from '$';
import moment from 'moment';
-import {i18n} from 'Common/Translator';
+import { i18n } from 'Common/Translator';
let _moment = null;
let _momentNow = 0;
-const updateMomentNow = _.debounce(() => {
- _moment = moment();
-}, 500, true);
+const updateMomentNow = _.debounce(
+ () => {
+ _moment = moment();
+ },
+ 500,
+ true
+);
-const updateMomentNowUnix = _.debounce(() => {
- _momentNow = moment().unix();
-}, 500, true);
+const updateMomentNowUnix = _.debounce(
+ () => {
+ _momentNow = moment().unix();
+ },
+ 500,
+ true
+);
/**
* @returns {moment}
*/
-export function momentNow()
-{
+export function momentNow() {
updateMomentNow();
return _moment || moment();
}
@@ -28,8 +34,7 @@ export function momentNow()
/**
* @returns {number}
*/
-export function momentNowUnix()
-{
+export function momentNowUnix() {
updateMomentNowUnix();
return _momentNow || 0;
}
@@ -38,29 +43,31 @@ export function momentNowUnix()
* @param {number} date
* @returns {string}
*/
-export function searchSubtractFormatDateHelper(date)
-{
- return momentNow().clone().subtract(date, 'days').format('YYYY.MM.DD');
+export function searchSubtractFormatDateHelper(date) {
+ return momentNow()
+ .clone()
+ .subtract(date, 'days')
+ .format('YYYY.MM.DD');
}
/**
* @param {Object} m
* @returns {string}
*/
-function formatCustomShortDate(m)
-{
+function formatCustomShortDate(m) {
const now = momentNow();
- if (m && now)
- {
- switch (true)
- {
+ if (m && now) {
+ switch (true) {
case 4 >= now.diff(m, 'hours'):
return m.fromNow();
case now.format('L') === m.format('L'):
return i18n('MESSAGE_LIST/TODAY_AT', {
TIME: m.format('LT')
});
- case now.clone().subtract(1, 'days').format('L') === m.format('L'):
+ case now
+ .clone()
+ .subtract(1, 'days')
+ .format('L') === m.format('L'):
return i18n('MESSAGE_LIST/YESTERDAY_AT', {
TIME: m.format('LT')
});
@@ -78,29 +85,23 @@ function formatCustomShortDate(m)
* @param {string} formatStr
* @returns {string}
*/
-export function format(timeStampInUTC, formatStr)
-{
-
- let
- m = null,
+export function format(timeStampInUTC, formatStr) {
+ let m = null,
result = '';
const now = momentNowUnix();
- timeStampInUTC = 0 < timeStampInUTC ? timeStampInUTC : (0 === timeStampInUTC ? now : 0);
+ timeStampInUTC = 0 < timeStampInUTC ? timeStampInUTC : 0 === timeStampInUTC ? now : 0;
timeStampInUTC = now < timeStampInUTC ? now : timeStampInUTC;
m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null;
- if (m && 1970 === m.year())
- {
+ if (m && 1970 === m.year()) {
m = null;
}
- if (m)
- {
- switch (formatStr)
- {
+ if (m) {
+ switch (formatStr) {
case 'FROMNOW':
result = m.fromNow();
break;
@@ -123,26 +124,20 @@ export function format(timeStampInUTC, formatStr)
* @param {Object} element
* @returns {void}
*/
-export function momentToNode(element)
-{
- let
- key = '',
+export function momentToNode(element) {
+ let key = '',
time = 0;
- const
- $el = $(element);
+ const $el = $(element);
time = $el.data('moment-time');
- if (time)
- {
+ if (time) {
key = $el.data('moment-format');
- if (key)
- {
+ if (key) {
$el.text(format(time, key));
}
key = $el.data('moment-format-title');
- if (key)
- {
+ if (key) {
$el.attr('title', format(time, key));
}
}
@@ -151,8 +146,7 @@ export function momentToNode(element)
/**
* @returns {void}
*/
-export function reload()
-{
+export function reload() {
_.defer(() => {
$('.moment', window.document).each((index, item) => {
momentToNode(item);
diff --git a/dev/Common/Plugins.js b/dev/Common/Plugins.js
index 89f202220..eed9f6029 100644
--- a/dev/Common/Plugins.js
+++ b/dev/Common/Plugins.js
@@ -1,11 +1,9 @@
-
import _ from '_';
-import {isFunc, isArray, isUnd} from 'Common/Utils';
-import {data as GlobalsData} from 'Common/Globals';
+import { isFunc, isArray, isUnd } from 'Common/Utils';
+import { data as GlobalsData } from 'Common/Globals';
import * as Settings from 'Storage/Settings';
-const
- SIMPLE_HOOKS = {},
+const SIMPLE_HOOKS = {},
USER_VIEW_MODELS_HOOKS = [],
ADMIN_VIEW_MODELS_HOOKS = [];
@@ -13,12 +11,9 @@ const
* @param {string} name
* @param {Function} callback
*/
-export function addHook(name, callback)
-{
- if (isFunc(callback))
- {
- if (!isArray(SIMPLE_HOOKS[name]))
- {
+export function addHook(name, callback) {
+ if (isFunc(callback)) {
+ if (!isArray(SIMPLE_HOOKS[name])) {
SIMPLE_HOOKS[name] = [];
}
@@ -30,10 +25,8 @@ export function addHook(name, callback)
* @param {string} name
* @param {Array=} args = []
*/
-export function runHook(name, args = [])
-{
- if (isArray(SIMPLE_HOOKS[name]))
- {
+export function runHook(name, args = []) {
+ if (isArray(SIMPLE_HOOKS[name])) {
_.each(SIMPLE_HOOKS[name], (callback) => {
callback(...args);
});
@@ -44,8 +37,7 @@ export function runHook(name, args = [])
* @param {string} name
* @returns {?}
*/
-export function mainSettingsGet(name)
-{
+export function mainSettingsGet(name) {
return Settings.settingsGet(name);
}
@@ -55,10 +47,8 @@ export function mainSettingsGet(name)
* @param {Object=} parameters
* @param {?number=} timeout
*/
-export function remoteRequest(callback, action, parameters, timeout)
-{
- if (GlobalsData.__APP__)
- {
+export function remoteRequest(callback, action, parameters, timeout) {
+ if (GlobalsData.__APP__) {
GlobalsData.__APP__.remote().defaultRequest(callback, 'Plugin' + action, parameters, timeout);
}
}
@@ -69,8 +59,7 @@ export function remoteRequest(callback, action, parameters, timeout)
* @param {string} template
* @param {string} route
*/
-export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route)
-{
+export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route) {
USER_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]);
}
@@ -80,16 +69,14 @@ export function addSettingsViewModel(SettingsViewModelClass, template, labelName
* @param {string} template
* @param {string} route
*/
-export function addSettingsViewModelForAdmin(SettingsViewModelClass, template, labelName, route)
-{
+export function addSettingsViewModelForAdmin(SettingsViewModelClass, template, labelName, route) {
ADMIN_VIEW_MODELS_HOOKS.push([SettingsViewModelClass, template, labelName, route]);
}
/**
* @param {boolean} admin
*/
-export function runSettingsViewModelHooks(admin)
-{
+export function runSettingsViewModelHooks(admin) {
const Knoin = require('Knoin/Knoin');
_.each(admin ? ADMIN_VIEW_MODELS_HOOKS : USER_VIEW_MODELS_HOOKS, (view) => {
Knoin.addSettingsViewModel(view[0], view[1], view[2], view[3]);
@@ -101,8 +88,7 @@ export function runSettingsViewModelHooks(admin)
* @param {string} name
* @returns {?}
*/
-export function settingsGet(pluginSection, name)
-{
+export function settingsGet(pluginSection, name) {
let plugins = Settings.settingsGet('Plugins');
plugins = plugins && !isUnd(plugins[pluginSection]) ? plugins[pluginSection] : null;
return plugins ? (isUnd(plugins[name]) ? null : plugins[name]) : null;
diff --git a/dev/Common/Selector.js b/dev/Common/Selector.js
index 378a56688..fb26047b3 100644
--- a/dev/Common/Selector.js
+++ b/dev/Common/Selector.js
@@ -1,13 +1,11 @@
-
import $ from '$';
import _ from '_';
import key from 'key';
import ko from 'ko';
-import {EventKeyCode} from 'Common/Enums';
-import {isArray, inArray, noop, noopTrue} from 'Common/Utils';
+import { EventKeyCode } from 'Common/Enums';
+import { isArray, inArray, noop, noopTrue } from 'Common/Utils';
-class Selector
-{
+class Selector {
list;
listChecked;
isListChecked;
@@ -41,12 +39,18 @@ class Selector
* @param {string} sItemCheckedSelector
* @param {string} sItemFocusedSelector
*/
- constructor(koList, koSelectedItem, koFocusedItem,
- sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
- {
+ constructor(
+ koList,
+ koSelectedItem,
+ koFocusedItem,
+ sItemSelector,
+ sItemSelectedSelector,
+ sItemCheckedSelector,
+ sItemFocusedSelector
+ ) {
this.list = koList;
- this.listChecked = ko.computed(() => _.filter(this.list(), (item) => item.checked())).extend({rateLimit: 0});
+ this.listChecked = ko.computed(() => _.filter(this.list(), (item) => item.checked())).extend({ rateLimit: 0 });
this.isListChecked = ko.computed(() => 0 < this.listChecked().length);
this.focusedItem = koFocusedItem || ko.observable(null);
@@ -55,51 +59,37 @@ class Selector
this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
this.listChecked.subscribe((items) => {
- if (0 < items.length)
- {
- if (null === this.selectedItem())
- {
- if (this.selectedItem.valueHasMutated)
- {
+ if (0 < items.length) {
+ if (null === this.selectedItem()) {
+ if (this.selectedItem.valueHasMutated) {
this.selectedItem.valueHasMutated();
}
- }
- else
- {
+ } else {
this.selectedItem(null);
}
- }
- else if (this.autoSelect() && this.focusedItem())
- {
+ } else if (this.autoSelect() && this.focusedItem()) {
this.selectedItem(this.focusedItem());
}
}, this);
this.selectedItem.subscribe((item) => {
-
- if (item)
- {
- if (this.isListChecked())
- {
+ if (item) {
+ if (this.isListChecked()) {
_.each(this.listChecked(), (subItem) => {
subItem.checked(false);
});
}
- if (this.selectedItemUseCallback)
- {
+ if (this.selectedItemUseCallback) {
this.itemSelectedThrottle(item);
}
- }
- else if (this.selectedItemUseCallback)
- {
+ } else if (this.selectedItemUseCallback) {
this.itemSelected(null);
}
-
}, this);
- this.selectedItem = this.selectedItem.extend({toggleSubscribeProperty: [this, 'selected']});
- this.focusedItem = this.focusedItem.extend({toggleSubscribeProperty: [null, 'focused']});
+ this.selectedItem = this.selectedItem.extend({ toggleSubscribeProperty: [this, 'selected'] });
+ this.focusedItem = this.focusedItem.extend({ toggleSubscribeProperty: [null, 'focused'] });
this.sItemSelector = sItemSelector;
this.sItemSelectedSelector = sItemSelectedSelector;
@@ -107,87 +97,75 @@ class Selector
this.sItemFocusedSelector = sItemFocusedSelector;
this.focusedItem.subscribe((item) => {
- if (item)
- {
+ if (item) {
this.sLastUid = this.getItemUid(item);
}
}, this);
- let
- aCache = [],
+ let aCache = [],
aCheckedCache = [],
mFocused = null,
mSelected = null;
- this.list.subscribe((items) => {
+ this.list.subscribe(
+ (items) => {
+ if (isArray(items)) {
+ _.each(items, (item) => {
+ if (item) {
+ const uid = this.getItemUid(item);
- if (isArray(items))
- {
- _.each(items, (item) => {
- if (item)
- {
- const uid = this.getItemUid(item);
-
- aCache.push(uid);
- if (item.checked())
- {
- aCheckedCache.push(uid);
+ aCache.push(uid);
+ if (item.checked()) {
+ aCheckedCache.push(uid);
+ }
+ if (null === mFocused && item.focused()) {
+ mFocused = uid;
+ }
+ if (null === mSelected && item.selected()) {
+ mSelected = uid;
+ }
}
- if (null === mFocused && item.focused())
- {
- mFocused = uid;
- }
- if (null === mSelected && item.selected())
- {
- mSelected = uid;
- }
- }
- });
- }
- }, this, 'beforeChange');
+ });
+ }
+ },
+ this,
+ 'beforeChange'
+ );
this.list.subscribe((aItems) => {
-
- let
- temp = null,
+ let temp = null,
getNext = false,
isNextFocused = mFocused,
isChecked = false,
isSelected = false,
len = 0;
- const
- uids = [];
+ const uids = [];
this.selectedItemUseCallback = false;
this.focusedItem(null);
this.selectedItem(null);
- if (isArray(aItems))
- {
+ if (isArray(aItems)) {
len = aCheckedCache.length;
_.each(aItems, (item) => {
-
const uid = this.getItemUid(item);
uids.push(uid);
- if (null !== mFocused && mFocused === uid)
- {
+ if (null !== mFocused && mFocused === uid) {
this.focusedItem(item);
mFocused = null;
}
- if (0 < len && -1 < inArray(uid, aCheckedCache))
- {
+ if (0 < len && -1 < inArray(uid, aCheckedCache)) {
isChecked = true;
item.checked(true);
len -= 1;
}
- if (!isChecked && null !== mSelected && mSelected === uid)
- {
+ if (!isChecked && null !== mSelected && mSelected === uid) {
isSelected = true;
this.selectedItem(item);
mSelected = null;
@@ -196,31 +174,22 @@ class Selector
this.selectedItemUseCallback = true;
- if (!isChecked && !isSelected && this.autoSelect())
- {
- if (this.focusedItem())
- {
+ if (!isChecked && !isSelected && this.autoSelect()) {
+ if (this.focusedItem()) {
this.selectedItem(this.focusedItem());
- }
- else if (0 < aItems.length)
- {
- if (null !== isNextFocused)
- {
+ } else if (0 < aItems.length) {
+ if (null !== isNextFocused) {
getNext = false;
isNextFocused = _.find(aCache, (sUid) => {
- if (getNext && -1 < inArray(sUid, uids))
- {
+ if (getNext && -1 < inArray(sUid, uids)) {
return sUid;
- }
- else if (isNextFocused === sUid)
- {
+ } else if (isNextFocused === sUid) {
getNext = true;
}
return false;
});
- if (isNextFocused)
- {
+ if (isNextFocused) {
temp = _.find(aItems, (oItem) => isNextFocused === this.getItemUid(oItem));
}
}
@@ -230,23 +199,22 @@ class Selector
}
}
- if ((0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) && 0 < aItems.length && !this.focusedItem())
- {
+ if (
+ (0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) &&
+ 0 < aItems.length &&
+ !this.focusedItem()
+ ) {
temp = null;
- if (0 !== this.iFocusedNextHelper)
- {
+ if (0 !== this.iFocusedNextHelper) {
temp = aItems[-1 === this.iFocusedNextHelper ? aItems.length - 1 : 0] || null;
}
- if (!temp && 0 !== this.iSelectNextHelper)
- {
+ if (!temp && 0 !== this.iSelectNextHelper) {
temp = aItems[-1 === this.iSelectNextHelper ? aItems.length - 1 : 0] || null;
}
- if (temp)
- {
- if (0 !== this.iSelectNextHelper)
- {
+ if (temp) {
+ if (0 !== this.iSelectNextHelper) {
this.selectedItem(temp || null);
}
@@ -266,21 +234,15 @@ class Selector
aCheckedCache = [];
mFocused = null;
mSelected = null;
-
});
}
itemSelected(item) {
-
- if (this.isListChecked())
- {
- if (!item)
- {
+ if (this.isListChecked()) {
+ if (!item) {
(this.oCallbacks.onItemSelect || noop)(item || null);
}
- }
- else if (item)
- {
+ } else if (item) {
(this.oCallbacks.onItemSelect || noop)(item);
}
}
@@ -305,16 +267,13 @@ class Selector
}
init(contentVisible, contentScrollable, keyScope = 'all') {
-
this.oContentVisible = contentVisible;
this.oContentScrollable = contentScrollable;
- if (this.oContentVisible && this.oContentScrollable)
- {
+ if (this.oContentVisible && this.oContentScrollable) {
$(this.oContentVisible)
.on('selectstart', (event) => {
- if (event && event.preventDefault)
- {
+ if (event && event.preventDefault) {
event.preventDefault();
}
})
@@ -323,14 +282,10 @@ class Selector
})
.on('click', this.sItemCheckedSelector, (event) => {
const item = ko.dataFor(event.currentTarget);
- if (item)
- {
- if (event && event.shiftKey)
- {
+ if (item) {
+ if (event && event.shiftKey) {
this.actionClick(item, event);
- }
- else
- {
+ } else {
this.focusedItem(item);
item.checked(!item.checked());
}
@@ -338,8 +293,7 @@ class Selector
});
key('enter', keyScope, () => {
- if (this.focusedItem() && !this.focusedItem().selected())
- {
+ if (this.focusedItem() && !this.focusedItem().selected()) {
this.actionClick(this.focusedItem());
return false;
}
@@ -350,11 +304,9 @@ class Selector
key('ctrl+up, command+up, ctrl+down, command+down', keyScope, () => false);
key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', keyScope, (event, handler) => {
- if (event && handler && handler.shortcut)
- {
+ if (event && handler && handler.shortcut) {
let eventKey = 0;
- switch (handler.shortcut)
- {
+ switch (handler.shortcut) {
case 'up':
case 'shift+up':
eventKey = EventKeyCode.Up;
@@ -384,8 +336,7 @@ class Selector
// no default
}
- if (0 < eventKey)
- {
+ if (0 < eventKey) {
this.newSelectPosition(eventKey, key.shift);
return false;
}
@@ -415,12 +366,10 @@ class Selector
* @returns {string}
*/
getItemUid(item) {
-
let uid = '';
const getItemUidCallback = this.oCallbacks.onItemGetUid || null;
- if (getItemUidCallback && item)
- {
+ if (getItemUidCallback && item) {
uid = getItemUidCallback(item);
}
@@ -433,64 +382,56 @@ class Selector
* @param {boolean=} bForceSelect = false
*/
newSelectPosition(iEventKeyCode, bShiftKey, bForceSelect) {
-
- let
- index = 0,
+ let index = 0,
isNext = false,
isStop = false,
result = null;
- const
- pageStep = 10,
+ const pageStep = 10,
list = this.list(),
listLen = list ? list.length : 0,
focused = this.focusedItem();
- if (0 < listLen)
- {
- if (!focused)
- {
- if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Insert === iEventKeyCode ||
- EventKeyCode.Space === iEventKeyCode || EventKeyCode.Home === iEventKeyCode ||
- EventKeyCode.PageUp === iEventKeyCode)
- {
+ if (0 < listLen) {
+ if (!focused) {
+ if (
+ EventKeyCode.Down === iEventKeyCode ||
+ EventKeyCode.Insert === iEventKeyCode ||
+ EventKeyCode.Space === iEventKeyCode ||
+ EventKeyCode.Home === iEventKeyCode ||
+ EventKeyCode.PageUp === iEventKeyCode
+ ) {
result = list[0];
- }
- else if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.End === iEventKeyCode ||
- EventKeyCode.PageDown === iEventKeyCode)
- {
+ } else if (
+ EventKeyCode.Up === iEventKeyCode ||
+ EventKeyCode.End === iEventKeyCode ||
+ EventKeyCode.PageDown === iEventKeyCode
+ ) {
result = list[list.length - 1];
}
- }
- else if (focused)
- {
- if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode ||
- EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
- {
+ } else if (focused) {
+ if (
+ EventKeyCode.Down === iEventKeyCode ||
+ EventKeyCode.Up === iEventKeyCode ||
+ EventKeyCode.Insert === iEventKeyCode ||
+ EventKeyCode.Space === iEventKeyCode
+ ) {
_.each(list, (item) => {
- if (!isStop)
- {
- switch (iEventKeyCode)
- {
+ if (!isStop) {
+ switch (iEventKeyCode) {
case EventKeyCode.Up:
- if (focused === item)
- {
+ if (focused === item) {
isStop = true;
- }
- else
- {
+ } else {
result = item;
}
break;
case EventKeyCode.Down:
case EventKeyCode.Insert:
- if (isNext)
- {
+ if (isNext) {
result = item;
isStop = true;
- }
- else if (focused === item)
- {
+ } else if (focused === item) {
isNext = true;
}
break;
@@ -499,41 +440,27 @@ class Selector
}
});
- if (!result && (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode))
- {
+ if (!result && (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode)) {
this.doUpUpOrDownDown(EventKeyCode.Up === iEventKeyCode);
}
- }
- else if (EventKeyCode.Home === iEventKeyCode || EventKeyCode.End === iEventKeyCode)
- {
- if (EventKeyCode.Home === iEventKeyCode)
- {
+ } else if (EventKeyCode.Home === iEventKeyCode || EventKeyCode.End === iEventKeyCode) {
+ if (EventKeyCode.Home === iEventKeyCode) {
result = list[0];
- }
- else if (EventKeyCode.End === iEventKeyCode)
- {
+ } else if (EventKeyCode.End === iEventKeyCode) {
result = list[list.length - 1];
}
- }
- else if (EventKeyCode.PageDown === iEventKeyCode)
- {
- for (; index < listLen; index++)
- {
- if (focused === list[index])
- {
+ } else if (EventKeyCode.PageDown === iEventKeyCode) {
+ for (; index < listLen; index++) {
+ if (focused === list[index]) {
index += pageStep;
index = listLen - 1 < index ? listLen - 1 : index;
result = list[index];
break;
}
}
- }
- else if (EventKeyCode.PageUp === iEventKeyCode)
- {
- for (index = listLen; 0 <= index; index--)
- {
- if (focused === list[index])
- {
+ } else if (EventKeyCode.PageUp === iEventKeyCode) {
+ for (index = listLen; 0 <= index; index--) {
+ if (focused === list[index]) {
index -= pageStep;
index = 0 > index ? 0 : index;
result = list[index];
@@ -544,41 +471,28 @@ class Selector
}
}
- if (result)
- {
+ if (result) {
this.focusedItem(result);
- if (focused)
- {
- if (bShiftKey)
- {
- if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode)
- {
+ if (focused) {
+ if (bShiftKey) {
+ if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode) {
focused.checked(!focused.checked());
}
- }
- else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
- {
+ } else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode) {
focused.checked(!focused.checked());
}
}
- if ((this.autoSelect() || !!bForceSelect) &&
- !this.isListChecked() && EventKeyCode.Space !== iEventKeyCode)
- {
+ if ((this.autoSelect() || !!bForceSelect) && !this.isListChecked() && EventKeyCode.Space !== iEventKeyCode) {
this.selectedItem(result);
}
this.scrollToFocused();
- }
- else if (focused)
- {
- if (bShiftKey && (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode))
- {
+ } else if (focused) {
+ if (bShiftKey && (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode)) {
focused.checked(!focused.checked());
- }
- else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
- {
+ } else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode) {
focused.checked(!focused.checked());
}
@@ -590,30 +504,25 @@ class Selector
* @returns {boolean}
*/
scrollToFocused() {
-
- if (!this.oContentVisible || !this.oContentScrollable)
- {
+ if (!this.oContentVisible || !this.oContentScrollable) {
return false;
}
- const
- offset = 20,
+ const offset = 20,
list = this.list(),
$focused = $(this.sItemFocusedSelector, this.oContentScrollable),
pos = $focused.position(),
visibleHeight = this.oContentVisible.height(),
focusedHeight = $focused.outerHeight();
- if (list && list[0] && list[0].focused())
- {
+ if (list && list[0] && list[0].focused()) {
this.oContentScrollable.scrollTop(0);
return true;
- }
- else if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight))
- {
- this.oContentScrollable.scrollTop(0 > pos.top ?
- this.oContentScrollable.scrollTop() + pos.top - offset :
- this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
+ } else if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight)) {
+ this.oContentScrollable.scrollTop(
+ 0 > pos.top
+ ? this.oContentScrollable.scrollTop() + pos.top - offset
+ : this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
);
return true;
@@ -627,28 +536,21 @@ class Selector
* @returns {boolean}
*/
scrollToTop(fast = false) {
-
- if (!this.oContentVisible || !this.oContentScrollable)
- {
+ if (!this.oContentVisible || !this.oContentScrollable) {
return false;
}
- if (fast || 50 > this.oContentScrollable.scrollTop())
- {
+ if (fast || 50 > this.oContentScrollable.scrollTop()) {
this.oContentScrollable.scrollTop(0);
- }
- else
- {
- this.oContentScrollable.stop().animate({scrollTop: 0}, 200);
+ } else {
+ this.oContentScrollable.stop().animate({ scrollTop: 0 }, 200);
}
return true;
}
eventClickFunction(item, event) {
-
- let
- index = 0,
+ let index = 0,
length = 0,
changeRange = false,
isInRange = false,
@@ -658,31 +560,25 @@ class Selector
lineUid = '';
const uid = this.getItemUid(item);
- if (event && event.shiftKey)
- {
- if ('' !== uid && '' !== this.sLastUid && uid !== this.sLastUid)
- {
+ if (event && event.shiftKey) {
+ if ('' !== uid && '' !== this.sLastUid && uid !== this.sLastUid) {
list = this.list();
checked = item.checked();
- for (index = 0, length = list.length; index < length; index++)
- {
+ for (index = 0, length = list.length; index < length; index++) {
listItem = list[index];
lineUid = this.getItemUid(listItem);
changeRange = false;
- if (lineUid === this.sLastUid || lineUid === uid)
- {
+ if (lineUid === this.sLastUid || lineUid === uid) {
changeRange = true;
}
- if (changeRange)
- {
+ if (changeRange) {
isInRange = !isInRange;
}
- if (isInRange || changeRange)
- {
+ if (isInRange || changeRange) {
listItem.checked(checked);
}
}
@@ -697,17 +593,12 @@ class Selector
* @param {Object=} event
*/
actionClick(item, event = null) {
-
- if (item)
- {
+ if (item) {
let click = true;
- if (event)
- {
- if (event.shiftKey && !(event.ctrlKey || event.metaKey) && !event.altKey)
- {
+ if (event) {
+ if (event.shiftKey && !(event.ctrlKey || event.metaKey) && !event.altKey) {
click = false;
- if ('' === this.sLastUid)
- {
+ if ('' === this.sLastUid) {
this.sLastUid = this.getItemUid(item);
}
@@ -715,14 +606,11 @@ class Selector
this.eventClickFunction(item, event);
this.focusedItem(item);
- }
- else if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey)
- {
+ } else if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
click = false;
this.focusedItem(item);
- if (this.selectedItem() && item !== this.selectedItem())
- {
+ if (this.selectedItem() && item !== this.selectedItem()) {
this.selectedItem().checked(true);
}
@@ -730,8 +618,7 @@ class Selector
}
}
- if (click)
- {
+ if (click) {
this.selectMessageItem(item);
}
}
@@ -748,4 +635,4 @@ class Selector
}
}
-export {Selector, Selector as default};
+export { Selector, Selector as default };
diff --git a/dev/Common/Translator.js b/dev/Common/Translator.js
index ab7c3b87f..389bd2d02 100644
--- a/dev/Common/Translator.js
+++ b/dev/Common/Translator.js
@@ -1,13 +1,12 @@
-
import window from 'window';
import _ from '_';
import $ from '$';
import ko from 'ko';
-import {Notification, UploadErrorCode} from 'Common/Enums';
-import {pInt, isUnd, isNull, has, microtime, inArray} from 'Common/Utils';
-import {$html, bAnimationSupported} from 'Common/Globals';
-import {reload as momentorReload} from 'Common/Momentor';
-import {langLink} from 'Common/Links';
+import { Notification, UploadErrorCode } from 'Common/Enums';
+import { pInt, isUnd, isNull, has, microtime, inArray } from 'Common/Utils';
+import { $html, bAnimationSupported } from 'Common/Globals';
+import { reload as momentorReload } from 'Common/Momentor';
+import { langLink } from 'Common/Links';
let I18N_DATA = window.rainloopI18N || {};
@@ -91,23 +90,17 @@ export const trigger = ko.observable(false);
* @param {string=} defaulValue
* @returns {string}
*/
-export function i18n(key, valueList, defaulValue)
-{
- let
- valueName = '',
+export function i18n(key, valueList, defaulValue) {
+ let valueName = '',
result = I18N_DATA[key];
- if (isUnd(result))
- {
+ if (isUnd(result)) {
result = isUnd(defaulValue) ? key : defaulValue;
}
- if (!isUnd(valueList) && !isNull(valueList))
- {
- for (valueName in valueList)
- {
- if (has(valueList, valueName))
- {
+ if (!isUnd(valueList) && !isNull(valueList)) {
+ for (valueName in valueList) {
+ if (has(valueList, valueName)) {
result = result.replace('%' + valueName + '%', valueList[valueName]);
}
}
@@ -117,17 +110,12 @@ export function i18n(key, valueList, defaulValue)
}
const i18nToNode = (element) => {
-
- const
- $el = $(element),
+ const $el = $(element),
key = $el.data('i18n');
- if (key)
- {
- if ('[' === key.substr(0, 1))
- {
- switch (key.substr(0, 6))
- {
+ if (key) {
+ if ('[' === key.substr(0, 1)) {
+ switch (key.substr(0, 6)) {
case '[html]':
$el.html(i18n(key.substr(6)));
break;
@@ -139,9 +127,7 @@ const i18nToNode = (element) => {
break;
// no default
}
- }
- else
- {
+ } else {
$el.text(i18n(key));
}
}
@@ -151,16 +137,13 @@ const i18nToNode = (element) => {
* @param {Object} elements
* @param {boolean=} animate = false
*/
-export function i18nToNodes(elements, animate = false)
-{
+export function i18nToNodes(elements, animate = false) {
_.defer(() => {
-
$('[data-i18n]', elements).each((index, item) => {
i18nToNode(item);
});
- if (animate && bAnimationSupported)
- {
+ if (animate && bAnimationSupported) {
$('.i18n-animation[data-i18n]', elements).letterfx({
'fx': 'fall fade',
'backwards': false,
@@ -174,8 +157,7 @@ export function i18nToNodes(elements, animate = false)
}
const reloadData = () => {
- if (window.rainloopI18N)
- {
+ if (window.rainloopI18N) {
I18N_DATA = window.rainloopI18N || {};
i18nToNodes(window.document, true);
@@ -190,8 +172,7 @@ const reloadData = () => {
/**
* @returns {void}
*/
-export function initNotificationLanguage()
-{
+export function initNotificationLanguage() {
I18N_NOTIFICATION_MAP.forEach((item) => {
I18N_NOTIFICATION_DATA[item[0]] = i18n(item[1]);
});
@@ -201,28 +182,21 @@ export function initNotificationLanguage()
* @param {Function} startCallback
* @param {Function=} langCallback = null
*/
-export function initOnStartOrLangChange(startCallback, langCallback = null)
-{
- if (startCallback)
- {
+export function initOnStartOrLangChange(startCallback, langCallback = null) {
+ if (startCallback) {
startCallback();
}
- if (langCallback)
- {
+ if (langCallback) {
trigger.subscribe(() => {
- if (startCallback)
- {
+ if (startCallback) {
startCallback();
}
- if (langCallback)
- {
+ if (langCallback) {
langCallback();
}
});
- }
- else if (startCallback)
- {
+ } else if (startCallback) {
trigger.subscribe(startCallback);
}
}
@@ -233,18 +207,18 @@ export function initOnStartOrLangChange(startCallback, langCallback = null)
* @param {*=} defCode = null
* @returns {string}
*/
-export function getNotification(code, message = '', defCode = null)
-{
+export function getNotification(code, message = '', defCode = null) {
code = window.parseInt(code, 10) || 0;
- if (Notification.ClientViewError === code && message)
- {
+ if (Notification.ClientViewError === code && message) {
return message;
}
- defCode = defCode ? (window.parseInt(defCode, 10)) || 0 : 0;
- return isUnd(I18N_NOTIFICATION_DATA[code]) ? (
- defCode && isUnd(I18N_NOTIFICATION_DATA[defCode]) ? I18N_NOTIFICATION_DATA[defCode] : ''
- ) : I18N_NOTIFICATION_DATA[code];
+ defCode = defCode ? window.parseInt(defCode, 10) || 0 : 0;
+ return isUnd(I18N_NOTIFICATION_DATA[code])
+ ? defCode && isUnd(I18N_NOTIFICATION_DATA[defCode])
+ ? I18N_NOTIFICATION_DATA[defCode]
+ : ''
+ : I18N_NOTIFICATION_DATA[code];
}
/**
@@ -252,21 +226,19 @@ export function getNotification(code, message = '', defCode = null)
* @param {number} defCode = Notification.UnknownNotification
* @returns {string}
*/
-export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification)
-{
- return response && response.ErrorCode ?
- getNotification(pInt(response.ErrorCode), response.ErrorMessage || '') : getNotification(defCode);
+export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification) {
+ return response && response.ErrorCode
+ ? getNotification(pInt(response.ErrorCode), response.ErrorMessage || '')
+ : getNotification(defCode);
}
/**
* @param {*} code
* @returns {string}
*/
-export function getUploadErrorDescByCode(code)
-{
+export function getUploadErrorDescByCode(code) {
let result = '';
- switch (window.parseInt(code, 10) || 0)
- {
+ switch (window.parseInt(code, 10) || 0) {
case UploadErrorCode.FileIsTooBig:
result = i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
break;
@@ -297,8 +269,7 @@ export function getUploadErrorDescByCode(code)
* @param {boolean} admin
* @param {string} language
*/
-export function reload(admin, language)
-{
+export function reload(admin, language) {
const start = microtime();
$html.addClass('rl-changing-language');
@@ -308,27 +279,31 @@ export function reload(admin, language)
url: langLink(language, admin),
dataType: 'script',
cache: true
- }).then(() => {
- _.delay(() => {
+ }).then(
+ () => {
+ _.delay(
+ () => {
+ reloadData();
- reloadData();
+ const isRtl = -1 < inArray((language || '').toLowerCase(), ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']);
- const isRtl = -1 < inArray((language || '').toLowerCase(), ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']);
+ $html
+ .removeClass('rl-changing-language')
+ .removeClass('rl-rtl rl-ltr')
+ // .attr('dir', isRtl ? 'rtl' : 'ltr')
+ .addClass(isRtl ? 'rl-rtl' : 'rl-ltr');
- $html
- .removeClass('rl-changing-language')
- .removeClass('rl-rtl rl-ltr')
- // .attr('dir', isRtl ? 'rtl' : 'ltr')
- .addClass(isRtl ? 'rl-rtl' : 'rl-ltr');
-
- resolve();
-
- }, 500 < microtime() - start ? 1 : 500);
- }, () => {
- $html.removeClass('rl-changing-language');
- window.rainloopI18N = null;
- reject();
- });
+ resolve();
+ },
+ 500 < microtime() - start ? 1 : 500
+ );
+ },
+ () => {
+ $html.removeClass('rl-changing-language');
+ window.rainloopI18N = null;
+ reject();
+ }
+ );
});
}
diff --git a/dev/Common/Utils.js b/dev/Common/Utils.js
index aa53cc4aa..3ad15efb2 100644
--- a/dev/Common/Utils.js
+++ b/dev/Common/Utils.js
@@ -1,14 +1,13 @@
-
import window from 'window';
import $ from '$';
import _ from '_';
import ko from 'ko';
import Autolinker from 'Autolinker';
-import {$win, $div, $hcont, dropdownVisibility, data as GlobalsData} from 'Common/Globals';
-import {ComposeType, EventKeyCode, SaveSettingsStep, FolderType} from 'Common/Enums';
-import {Mime} from 'Common/Mime';
-import {jassl} from 'Common/Jassl';
+import { $win, $div, $hcont, dropdownVisibility, data as GlobalsData } from 'Common/Globals';
+import { ComposeType, EventKeyCode, SaveSettingsStep, FolderType } from 'Common/Enums';
+import { Mime } from 'Common/Mime';
+import { jassl } from 'Common/Jassl';
const trim = $.trim;
const inArray = $.inArray;
@@ -23,25 +22,22 @@ const noop = () => {}; // eslint-disable-line no-empty-function
const noopTrue = () => true;
const noopFalse = () => false;
-export {trim, inArray, isArray, isObject, isFunc, isUnd, isNull, has, bind, noop, noopTrue, noopFalse, jassl};
+export { trim, inArray, isArray, isObject, isFunc, isUnd, isNull, has, bind, noop, noopTrue, noopFalse, jassl };
/**
* @param {Function} func
*/
-export function silentTryCatch(func)
-{
+export function silentTryCatch(func) {
try {
func();
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
/**
* @param {*} value
* @returns {boolean}
*/
-export function isNormal(value)
-{
+export function isNormal(value) {
return !isUnd(value) && !isNull(value);
}
@@ -50,10 +46,12 @@ export function isNormal(value)
* @param {boolean=} includeZero = true
* @returns {boolean}
*/
-export function isPosNumeric(value, includeZero = true)
-{
- return !isNormal(value) ? false :
- (includeZero ? (/^[0-9]*$/).test(value.toString()) : (/^[1-9]+[0-9]*$/).test(value.toString()));
+export function isPosNumeric(value, includeZero = true) {
+ return !isNormal(value)
+ ? false
+ : includeZero
+ ? /^[0-9]*$/.test(value.toString())
+ : /^[1-9]+[0-9]*$/.test(value.toString());
}
/**
@@ -61,8 +59,7 @@ export function isPosNumeric(value, includeZero = true)
* @param {number=} defaultValur = 0
* @returns {number}
*/
-export function pInt(value, defaultValur = 0)
-{
+export function pInt(value, defaultValur = 0) {
const result = isNormal(value) && '' !== value ? window.parseInt(value, 10) : defaultValur;
return window.isNaN(result) ? defaultValur : result;
}
@@ -71,8 +68,7 @@ export function pInt(value, defaultValur = 0)
* @param {*} value
* @returns {string}
*/
-export function pString(value)
-{
+export function pString(value) {
return isNormal(value) ? '' + value : '';
}
@@ -80,8 +76,7 @@ export function pString(value)
* @param {*} value
* @returns {boolean}
*/
-export function pBool(value)
-{
+export function pBool(value) {
return !!value;
}
@@ -89,8 +84,7 @@ export function pBool(value)
* @param {*} value
* @returns {string}
*/
-export function boolToAjax(value)
-{
+export function boolToAjax(value) {
return value ? '1' : '0';
}
@@ -98,8 +92,7 @@ export function boolToAjax(value)
* @param {*} values
* @returns {boolean}
*/
-export function isNonEmptyArray(values)
-{
+export function isNonEmptyArray(values) {
return isArray(values) && 0 < values.length;
}
@@ -107,8 +100,7 @@ export function isNonEmptyArray(values)
* @param {string} component
* @returns {string}
*/
-export function encodeURIComponent(component)
-{
+export function encodeURIComponent(component) {
return window.encodeURIComponent(component);
}
@@ -116,8 +108,7 @@ export function encodeURIComponent(component)
* @param {string} component
* @returns {string}
*/
-export function decodeURIComponent(component)
-{
+export function decodeURIComponent(component) {
return window.decodeURIComponent(component);
}
@@ -125,8 +116,7 @@ export function decodeURIComponent(component)
* @param {string} url
* @returns {string}
*/
-export function decodeURI(url)
-{
+export function decodeURI(url) {
return window.decodeURI(url);
}
@@ -134,8 +124,7 @@ export function decodeURI(url)
* @param {string} url
* @returns {string}
*/
-export function encodeURI(url)
-{
+export function encodeURI(url) {
return window.encodeURI(url);
}
@@ -143,19 +132,15 @@ export function encodeURI(url)
* @param {string} queryString
* @returns {Object}
*/
-export function simpleQueryParser(queryString)
-{
- let
- index = 0,
+export function simpleQueryParser(queryString) {
+ let index = 0,
len = 0,
temp = null;
- const
- queries = queryString.split('&'),
+ const queries = queryString.split('&'),
params = {};
- for (len = queries.length; index < len; index++)
- {
+ for (len = queries.length; index < len; index++) {
temp = queries[index].split('=');
params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
@@ -167,17 +152,14 @@ export function simpleQueryParser(queryString)
* @param {number=} len = 32
* @returns {string}
*/
-export function fakeMd5(len = 32)
-{
- const
- line = '0123456789abcdefghijklmnopqrstuvwxyz',
+export function fakeMd5(len = 32) {
+ const line = '0123456789abcdefghijklmnopqrstuvwxyz',
lineLen = line.length;
len = pInt(len);
let result = '';
- while (result.length < len)
- {
+ while (result.length < len) {
result += line.substr(window.Math.round(window.Math.random() * lineLen), 1);
}
@@ -188,8 +170,7 @@ export function fakeMd5(len = 32)
* @param {string} text
* @returns {string}
*/
-export function encodeHtml(text)
-{
+export function encodeHtml(text) {
return isNormal(text) ? _.escape(text.toString()) : '';
}
@@ -198,28 +179,23 @@ export function encodeHtml(text)
* @param {number=} len = 100
* @returns {string}
*/
-export function splitPlainText(text, len = 100)
-{
- let
- prefix = '',
+export function splitPlainText(text, len = 100) {
+ let prefix = '',
subText = '',
result = text,
spacePos = 0,
newLinePos = 0;
- while (result.length > len)
- {
+ while (result.length > len) {
subText = result.substring(0, len);
spacePos = subText.lastIndexOf(' ');
newLinePos = subText.lastIndexOf('\n');
- if (-1 !== newLinePos)
- {
+ if (-1 !== newLinePos) {
spacePos = newLinePos;
}
- if (-1 === spacePos)
- {
+ if (-1 === spacePos) {
spacePos = len;
}
@@ -237,22 +213,21 @@ const timeOutAction = (function() {
window.clearTimeout(timeOuts[action]);
timeOuts[action] = window.setTimeout(fFunction, timeOut);
};
-}());
+})();
const timeOutActionSecond = (function() {
const timeOuts = {};
return (action, fFunction, timeOut) => {
- if (!timeOuts[action])
- {
+ if (!timeOuts[action]) {
timeOuts[action] = window.setTimeout(() => {
fFunction();
timeOuts[action] = 0;
}, timeOut);
}
};
-}());
+})();
-export {timeOutAction, timeOutActionSecond};
+export { timeOutAction, timeOutActionSecond };
/**
* @param {any} m
@@ -265,20 +240,18 @@ export function deModule(m) {
/**
* @returns {boolean}
*/
-export function inFocus()
-{
+export function inFocus() {
try {
- if (window.document.activeElement)
- {
- if (isUnd(window.document.activeElement.__inFocusCache))
- {
- window.document.activeElement.__inFocusCache = $(window.document.activeElement).is('input,textarea,iframe,.cke_editable');
+ if (window.document.activeElement) {
+ if (isUnd(window.document.activeElement.__inFocusCache)) {
+ window.document.activeElement.__inFocusCache = $(window.document.activeElement).is(
+ 'input,textarea,iframe,.cke_editable'
+ );
}
return !!window.document.activeElement.__inFocusCache;
}
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
return false;
}
@@ -287,45 +260,33 @@ export function inFocus()
* @param {boolean} force
* @returns {void}
*/
-export function removeInFocus(force)
-{
- if (window.document && window.document.activeElement && window.document.activeElement.blur)
- {
+export function removeInFocus(force) {
+ if (window.document && window.document.activeElement && window.document.activeElement.blur) {
try {
const activeEl = $(window.document.activeElement);
- if (activeEl && activeEl.is('input,textarea'))
- {
+ if (activeEl && activeEl.is('input,textarea')) {
+ window.document.activeElement.blur();
+ } else if (force) {
window.document.activeElement.blur();
}
- else if (force)
- {
- window.document.activeElement.blur();
- }
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
}
/**
* @returns {void}
*/
-export function removeSelection()
-{
+export function removeSelection() {
try {
- if (window && window.getSelection)
- {
+ if (window && window.getSelection) {
const sel = window.getSelection();
- if (sel && sel.removeAllRanges)
- {
+ if (sel && sel.removeAllRanges) {
sel.removeAllRanges();
}
- }
- else if (window.document && window.document.selection && window.document.selection.empty)
- {
+ } else if (window.document && window.document.selection && window.document.selection.empty) {
window.document.selection.empty();
}
- }
- catch (e) {} // eslint-disable-line no-empty
+ } catch (e) {} // eslint-disable-line no-empty
}
/**
@@ -333,8 +294,7 @@ export function removeSelection()
* @param {string} subject
* @returns {string}
*/
-export function replySubjectAdd(prefix, subject)
-{
+export function replySubjectAdd(prefix, subject) {
prefix = trim(prefix.toUpperCase());
subject = trim(subject.replace(/[\s]+/g, ' '));
@@ -342,49 +302,34 @@ export function replySubjectAdd(prefix, subject)
re = 'RE' === prefix,
fwd = 'FWD' === prefix;
- const
- parts = [],
+ const parts = [],
prefixIsRe = !fwd;
- if ('' !== subject)
- {
+ if ('' !== subject) {
_.each(subject.split(':'), (part) => {
const trimmedPart = trim(part);
- if (!drop && ((/^(RE|FWD)$/i).test(trimmedPart) || (/^(RE|FWD)[\[\(][\d]+[\]\)]$/i).test(trimmedPart)))
- {
- if (!re)
- {
- re = !!(/^RE/i).test(trimmedPart);
+ if (!drop && (/^(RE|FWD)$/i.test(trimmedPart) || /^(RE|FWD)[[(][\d]+[\])]$/i.test(trimmedPart))) {
+ if (!re) {
+ re = !!/^RE/i.test(trimmedPart);
}
- if (!fwd)
- {
- fwd = !!(/^FWD/i).test(trimmedPart);
+ if (!fwd) {
+ fwd = !!/^FWD/i.test(trimmedPart);
}
- }
- else
- {
+ } else {
parts.push(part);
drop = true;
}
});
}
- if (prefixIsRe)
- {
+ if (prefixIsRe) {
re = false;
- }
- else
- {
+ } else {
fwd = false;
}
- return trim(
- (prefixIsRe ? 'Re: ' : 'Fwd: ') +
- (re ? 'Re: ' : '') +
- (fwd ? 'Fwd: ' : '') +
- trim(parts.join(':'))
- );
+ return trim((prefixIsRe ? 'Re: ' : 'Fwd: ') + (re ? 'Re: ' : '') + (fwd ? 'Fwd: ' : '') + trim(parts.join(':')));
}
/**
@@ -392,8 +337,7 @@ export function replySubjectAdd(prefix, subject)
* @param {number} dec
* @returns {number}
*/
-export function roundNumber(num, dec)
-{
+export function roundNumber(num, dec) {
return window.Math.round(num * window.Math.pow(10, dec)) / window.Math.pow(10, dec);
}
@@ -401,12 +345,10 @@ export function roundNumber(num, dec)
* @param {(number|string)} sizeInBytes
* @returns {string}
*/
-export function friendlySize(sizeInBytes)
-{
+export function friendlySize(sizeInBytes) {
sizeInBytes = pInt(sizeInBytes);
- switch (true)
- {
+ switch (true) {
case 1073741824 <= sizeInBytes:
return roundNumber(sizeInBytes / 1073741824, 1) + 'GB';
case 1048576 <= sizeInBytes:
@@ -422,10 +364,8 @@ export function friendlySize(sizeInBytes)
/**
* @param {string} desc
*/
-export function log(desc)
-{
- if (window.console && window.console.log)
- {
+export function log(desc) {
+ if (window.console && window.console.log) {
window.console.log(desc);
}
}
@@ -436,19 +376,14 @@ export function log(desc)
* @param {Array=} params
* @param {number=} delay = 0
*/
-export function delegateRun(object, methodName, params, delay = 0)
-{
- if (object && object[methodName])
- {
+export function delegateRun(object, methodName, params, delay = 0) {
+ if (object && object[methodName]) {
delay = pInt(delay);
params = isArray(params) ? params : [];
- if (0 >= delay)
- {
+ if (0 >= delay) {
object[methodName](...params);
- }
- else
- {
+ } else {
_.delay(() => {
object[methodName](...params);
}, delay);
@@ -459,32 +394,25 @@ export function delegateRun(object, methodName, params, delay = 0)
/**
* @param {?} event
*/
-export function killCtrlACtrlS(event)
-{
+export function killCtrlACtrlS(event) {
event = event || window.event;
- if (event && event.ctrlKey && !event.shiftKey && !event.altKey)
- {
+ if (event && event.ctrlKey && !event.shiftKey && !event.altKey) {
const key = event.keyCode || event.which;
- if (key === EventKeyCode.S)
- {
+ if (key === EventKeyCode.S) {
event.preventDefault();
return;
- }
- else if (key === EventKeyCode.A)
- {
+ } else if (key === EventKeyCode.A) {
const sender = event.target || event.srcElement;
- if (sender && ('true' === '' + sender.contentEditable ||
- (sender.tagName && sender.tagName.match(/INPUT|TEXTAREA/i))))
- {
+ if (
+ sender &&
+ ('true' === '' + sender.contentEditable || (sender.tagName && sender.tagName.match(/INPUT|TEXTAREA/i)))
+ ) {
return;
}
- if (window.getSelection)
- {
+ if (window.getSelection) {
window.getSelection().removeAllRanges();
- }
- else if (window.document.selection && window.document.selection.clear)
- {
+ } else if (window.document.selection && window.document.selection.clear) {
window.document.selection.clear();
}
@@ -499,12 +427,10 @@ export function killCtrlACtrlS(event)
* @param {(Function|boolean|null)=} fCanExecute = true
* @returns {Function}
*/
-export function createCommandLegacy(context, fExecute, fCanExecute = true)
-{
+export function createCommandLegacy(context, fExecute, fCanExecute = true) {
let fResult = null;
const fNonEmpty = (...args) => {
- if (fResult && fResult.canExecute && fResult.canExecute())
- {
+ if (fResult && fResult.canExecute && fResult.canExecute()) {
fExecute.apply(context, args);
}
return false;
@@ -514,12 +440,9 @@ export function createCommandLegacy(context, fExecute, fCanExecute = true)
fResult.enabled = ko.observable(true);
fResult.isCommand = true;
- if (isFunc(fCanExecute))
- {
+ if (isFunc(fCanExecute)) {
fResult.canExecute = ko.computed(() => fResult && fResult.enabled() && fCanExecute.call(context));
- }
- else
- {
+ } else {
fResult.canExecute = ko.computed(() => fResult && fResult.enabled() && !!fCanExecute);
}
@@ -531,37 +454,37 @@ export function createCommandLegacy(context, fExecute, fCanExecute = true)
* @returns {string}
*/
export const convertThemeName = _.memoize((theme) => {
-
- if ('@custom' === theme.substr(-7))
- {
+ if ('@custom' === theme.substr(-7)) {
theme = trim(theme.substring(0, theme.length - 7));
}
- return trim(theme.replace(/[^a-zA-Z0-9]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
+ return trim(
+ theme
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
+ .replace(/([A-Z])/g, ' $1')
+ .replace(/[\s]+/g, ' ')
+ );
});
/**
* @param {string} name
* @returns {string}
*/
-export function quoteName(name)
-{
+export function quoteName(name) {
return name.replace(/["]/g, '\\"');
}
/**
* @returns {number}
*/
-export function microtime()
-{
- return (new window.Date()).getTime();
+export function microtime() {
+ return new window.Date().getTime();
}
/**
* @returns {number}
*/
-export function timestamp()
-{
+export function timestamp() {
return window.Math.round(microtime() / 1000);
}
@@ -571,22 +494,24 @@ export function timestamp()
* @param {boolean=} isEng = false
* @returns {string}
*/
-export function convertLangName(language, isEng = false)
-{
- return require('Common/Translator').i18n('LANGS_NAMES' + (true === isEng ? '_EN' : '') + '/LANG_' +
- language.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'), null, language);
+export function convertLangName(language, isEng = false) {
+ return require('Common/Translator').i18n(
+ 'LANGS_NAMES' + (true === isEng ? '_EN' : '') + '/LANG_' + language.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'),
+ null,
+ language
+ );
}
/**
* @returns {object}
*/
-export function draggablePlace()
-{
- return $('
]*><\/p>/gi, '') - .replace(/
]*>([\s\S\r\n\t]*)<\/pre>/gmi, convertPre)
+ .replace(/]*>([\s\S\r\n\t]*)<\/pre>/gim, convertPre)
.replace(/[\s]+/gm, ' ')
- .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
- .replace(/
]*>/gmi, '\n')
+ .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gim, fixAttibuteValue)
+ .replace(/
]*>/gim, '\n')
.replace(/<\/h[\d]>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
- .replace(/]*>/gmi, '\n__bq__start__\n') - .replace(/<\/blockquote>/gmi, '\n__bq__end__\n') - .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks) + .replace(/
]*>/gim, '\n_______________________________\n\n') + .replace(/]*>([\s\S\r\n]*)<\/div>/gim, convertDivs) + .replace(/]*>/gim, '\n__bq__start__\n') + .replace(/<\/blockquote>/gim, '\n__bq__end__\n') + .replace(/]*>([\s\S\r\n]*?)<\/a>/gim, convertLinks) .replace(/<\/div>/gi, '\n') .replace(/ /gi, ' ') .replace(/"/gi, '"') @@ -838,41 +758,28 @@ export function htmlToPlain(html) pos = 0; limit = 800; - while (0 < limit) - { + while (0 < limit) { limit -= 1; iP1 = text.indexOf('__bq__start__', pos); - if (-1 < iP1) - { + if (-1 < iP1) { iP2 = text.indexOf('__bq__start__', iP1 + 5); iP3 = text.indexOf('__bq__end__', iP1 + 5); - if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3) - { - text = text.substring(0, iP1) + - convertBlockquote(text.substring(iP1 + 13, iP3)) + - text.substring(iP3 + 11); + if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3) { + text = text.substring(0, iP1) + convertBlockquote(text.substring(iP1 + 13, iP3)) + text.substring(iP3 + 11); pos = 0; - } - else if (-1 < iP2 && iP2 < iP3) - { + } else if (-1 < iP2 && iP2 < iP3) { pos = iP2 - 1; - } - else - { + } else { pos = 0; } - } - else - { + } else { break; } } - text = text - .replace(/__bq__start__/gm, '') - .replace(/__bq__end__/gm, ''); + text = text.replace(/__bq__start__/gm, '').replace(/__bq__end__/gm, ''); return text; } @@ -882,13 +789,11 @@ export function htmlToPlain(html) * @param {boolean} findEmailAndLinksInText = false * @returns {string} */ -export function plainToHtml(plain, findEmailAndLinksInText = false) -{ +export function plainToHtml(plain, findEmailAndLinksInText = false) { plain = plain.toString().replace(/\r/g, ''); plain = plain.replace(/^>[> ]>+/gm, ([match]) => (match ? match.replace(/[ ]+/g, '') : match)); - let - bIn = false, + let bIn = false, bDo = true, bStart = true, aNextText = [], @@ -896,60 +801,47 @@ export function plainToHtml(plain, findEmailAndLinksInText = false) iIndex = 0, aText = plain.split('\n'); - do - { + do { bDo = false; aNextText = []; - for (iIndex = 0; iIndex < aText.length; iIndex++) - { + for (iIndex = 0; iIndex < aText.length; iIndex++) { sLine = aText[iIndex]; bStart = '>' === sLine.substr(0, 1); - if (bStart && !bIn) - { + if (bStart && !bIn) { bDo = true; bIn = true; aNextText.push('~~~blockquote~~~'); aNextText.push(sLine.substr(1)); - } - else if (!bStart && bIn) - { - if ('' !== sLine) - { + } else if (!bStart && bIn) { + if ('' !== sLine) { bIn = false; aNextText.push('~~~/blockquote~~~'); aNextText.push(sLine); - } - else - { + } else { aNextText.push(sLine); } - } - else if (bStart && bIn) - { + } else if (bStart && bIn) { aNextText.push(sLine.substr(1)); - } - else - { + } else { aNextText.push(sLine); } } - if (bIn) - { + if (bIn) { bIn = false; aNextText.push('~~~/blockquote~~~'); } aText = aNextText; - } - while (bDo); + } while (bDo); plain = aText.join('\n'); plain = plain // .replace(/~~~\/blockquote~~~\n~~~blockquote~~~/g, '\n') .replace(/&/g, '&') - .replace(/>/g, '>').replace(//g, '>') + .replace(/') .replace(/[\s]*~~~\/blockquote~~~/g, '') .replace(/\n/g, '
'); @@ -973,11 +865,19 @@ window['rainloop_Utils_plainToHtml'] = plainToHtml; // eslint-disable-line dot-n * @param {boolean=} bBuildUnvisible * @returns {Array} */ -export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines, - iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible) -{ - let - /** +export function folderListOptionsBuilder( + aSystem, + aList, + aDisabled, + aHeaderLines, + iUnDeep, + fDisableCallback, + fVisibleCallback, + fRenameCallback, + bSystem, + bBuildUnvisible +) { + let /** * @type {?FolderModel} */ oItem = null, @@ -995,18 +895,15 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines fVisibleCallback = isNormal(fVisibleCallback) ? fVisibleCallback : null; fRenameCallback = isNormal(fRenameCallback) ? fRenameCallback : null; - if (!isArray(aDisabled)) - { + if (!isArray(aDisabled)) { aDisabled = []; } - if (!isArray(aHeaderLines)) - { + if (!isArray(aHeaderLines)) { aHeaderLines = []; } - for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++) - { + for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++) { aResult.push({ id: aHeaderLines[iIndex][0], name: aHeaderLines[iIndex][1], @@ -1017,13 +914,10 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines } bSep = true; - for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++) - { + for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++) { oItem = aSystem[iIndex]; - if (fVisibleCallback ? fVisibleCallback(oItem) : true) - { - if (bSep && 0 < aResult.length) - { + if (fVisibleCallback ? fVisibleCallback(oItem) : true) { + if (bSep && 0 < aResult.length) { aResult.push({ id: '---', name: '---', @@ -1039,25 +933,25 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines name: fRenameCallback ? fRenameCallback(oItem) : oItem.name(), system: true, seporator: false, - disabled: !oItem.selectable || -1 < inArray(oItem.fullNameRaw, aDisabled) || + disabled: + !oItem.selectable || + -1 < inArray(oItem.fullNameRaw, aDisabled) || (fDisableCallback ? fDisableCallback(oItem) : false) }); } } bSep = true; - for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++) - { + for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++) { oItem = aList[iIndex]; // if (oItem.subScribed() || !oItem.existen || bBuildUnvisible) - if ((oItem.subScribed() || !oItem.existen || bBuildUnvisible) && (oItem.selectable || oItem.hasSubScribedSubfolders())) - { - if (fVisibleCallback ? fVisibleCallback(oItem) : true) - { - if (FolderType.User === oItem.type() || !bSystem || oItem.hasSubScribedSubfolders()) - { - if (bSep && 0 < aResult.length) - { + if ( + (oItem.subScribed() || !oItem.existen || bBuildUnvisible) && + (oItem.selectable || oItem.hasSubScribedSubfolders()) + ) { + if (fVisibleCallback ? fVisibleCallback(oItem) : true) { + if (FolderType.User === oItem.type() || !bSystem || oItem.hasSubScribedSubfolders()) { + if (bSep && 0 < aResult.length) { aResult.push({ id: '---', name: '---', @@ -1070,21 +964,35 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines bSep = false; aResult.push({ id: oItem.fullNameRaw, - name: (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) + + name: + new window.Array(oItem.deep + 1 - iUnDeep).join(sDeepPrefix) + (fRenameCallback ? fRenameCallback(oItem) : oItem.name()), system: false, seporator: false, - disabled: !oItem.selectable || -1 < inArray(oItem.fullNameRaw, aDisabled) || + disabled: + !oItem.selectable || + -1 < inArray(oItem.fullNameRaw, aDisabled) || (fDisableCallback ? fDisableCallback(oItem) : false) }); } } } - if (oItem.subScribed() && 0 < oItem.subFolders().length) - { - aResult = aResult.concat(folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [], - iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)); + if (oItem.subScribed() && 0 < oItem.subFolders().length) { + aResult = aResult.concat( + folderListOptionsBuilder( + [], + oItem.subFolders(), + aDisabled, + [], + iUnDeep, + fDisableCallback, + fVisibleCallback, + fRenameCallback, + bSystem, + bBuildUnvisible + ) + ); } } @@ -1095,22 +1003,17 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines * @param {object} element * @returns {void} */ -export function selectElement(element) -{ - let - sel = null, +export function selectElement(element) { + let sel = null, range = null; - if (window.getSelection) - { + if (window.getSelection) { sel = window.getSelection(); sel.removeAllRanges(); range = window.document.createRange(); range.selectNodeContents(element); sel.addRange(range); - } - else if (window.document.selection) - { + } else if (window.document.selection) { range = window.document.body.createTextRange(); range.moveToElementText(element); range.select(); @@ -1125,17 +1028,13 @@ export const detectDropdownVisibility = _.debounce(() => { * @param {boolean=} delay = false */ export function triggerAutocompleteInputChange(delay = false) { - const fFunc = () => { $('.checkAutocomplete').trigger('change'); }; - if (delay) - { + if (delay) { _.delay(fFunc, 100); - } - else - { + } else { fFunc(); } } @@ -1146,18 +1045,16 @@ const configurationScriptTagCache = {}; * @param {string} configuration * @returns {object} */ -export function getConfigurationFromScriptTag(configuration) -{ - if (!configurationScriptTagCache[configuration]) - { - configurationScriptTagCache[configuration] = $('script[type="application/json"][data-configuration="' + configuration + '"]'); +export function getConfigurationFromScriptTag(configuration) { + if (!configurationScriptTagCache[configuration]) { + configurationScriptTagCache[configuration] = $( + 'script[type="application/json"][data-configuration="' + configuration + '"]' + ); } - try - { + try { return JSON.parse(configurationScriptTagCache[configuration].text()); - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty return {}; } @@ -1166,11 +1063,9 @@ export function getConfigurationFromScriptTag(configuration) * @param {mixed} mPropOrValue * @param {mixed} value */ -export function disposeOne(propOrValue, value) -{ +export function disposeOne(propOrValue, value) { const disposable = value || propOrValue; - if (disposable && 'function' === typeof disposable.dispose) - { + if (disposable && 'function' === typeof disposable.dispose) { disposable.dispose(); } } @@ -1178,12 +1073,9 @@ export function disposeOne(propOrValue, value) /** * @param {Object} object */ -export function disposeObject(object) -{ - if (object) - { - if (isArray(object.disposables)) - { +export function disposeObject(object) { + if (object) { + if (isArray(object.disposables)) { _.each(object.disposables, disposeOne); } @@ -1195,18 +1087,13 @@ export function disposeObject(object) * @param {Object|Array} objectOrObjects * @returns {void} */ -export function delegateRunOnDestroy(objectOrObjects) -{ - if (objectOrObjects) - { - if (isArray(objectOrObjects)) - { +export function delegateRunOnDestroy(objectOrObjects) { + if (objectOrObjects) { + if (isArray(objectOrObjects)) { _.each(objectOrObjects, (item) => { delegateRunOnDestroy(item); }); - } - else if (objectOrObjects && objectOrObjects.onDestroy) - { + } else if (objectOrObjects && objectOrObjects.onDestroy) { objectOrObjects.onDestroy(); } } @@ -1217,16 +1104,11 @@ export function delegateRunOnDestroy(objectOrObjects) * @param {string} css * @returns {boolean} */ -export function appendStyles($styleTag, css) -{ - if ($styleTag && $styleTag[0]) - { - if ($styleTag[0].styleSheet && !isUnd($styleTag[0].styleSheet.cssText)) - { +export function appendStyles($styleTag, css) { + if ($styleTag && $styleTag[0]) { + if ($styleTag[0].styleSheet && !isUnd($styleTag[0].styleSheet.cssText)) { $styleTag[0].styleSheet.cssText = css; - } - else - { + } else { $styleTag.text(css); } @@ -1236,8 +1118,7 @@ export function appendStyles($styleTag, css) return false; } -let - __themeTimer = 0, +let __themeTimer = 0, __themeAjax = null; /** @@ -1245,32 +1126,26 @@ let * @param {function=} themeTrigger = noop * @returns {void} */ -export function changeTheme(value, themeTrigger = noop) -{ - const - themeLink = $('#app-theme-link'), +export function changeTheme(value, themeTrigger = noop) { + const themeLink = $('#app-theme-link'), clearTimer = () => { __themeTimer = window.setTimeout(() => themeTrigger(SaveSettingsStep.Idle), 1000); __themeAjax = null; }; - let - themeStyle = $('#app-theme-style'), + let themeStyle = $('#app-theme-style'), url = themeLink.attr('href'); - if (!url) - { + if (!url) { url = themeStyle.attr('data-href'); } - if (url) - { - url = url.toString().replace(/\/-\/[^\/]+\/\-\//, '/-/' + value + '/-/'); - url = url.replace(/\/Css\/[^\/]+\/User\//, '/Css/0/User/'); - url = url.replace(/\/Hash\/[^\/]+\//, '/Hash/-/'); + if (url) { + url = url.toString().replace(/\/-\/[^/]+\/-\//, '/-/' + value + '/-/'); + url = url.replace(/\/Css\/[^/]+\/User\//, '/Css/0/User/'); + url = url.replace(/\/Hash\/[^/]+\//, '/Hash/-/'); - if ('Json/' !== url.substring(url.length - 5, url.length)) - { + if ('Json/' !== url.substring(url.length - 5, url.length)) { url += 'Json/'; } @@ -1278,53 +1153,44 @@ export function changeTheme(value, themeTrigger = noop) themeTrigger(SaveSettingsStep.Animate); - if (__themeAjax && __themeAjax.abort) - { + if (__themeAjax && __themeAjax.abort) { __themeAjax.abort(); } __themeAjax = $.ajax({ url: url, dataType: 'json' - }).then((data) => { - - if (data && isArray(data) && 2 === data.length) - { - if (themeLink && themeLink[0] && (!themeStyle || !themeStyle[0])) - { - themeStyle = $(''); - themeLink.after(themeStyle); - themeLink.remove(); - } - - if (themeStyle && themeStyle[0]) - { - if (appendStyles(themeStyle, data[1])) - { - themeStyle.attr('data-href', url).attr('data-theme', data[0]); + }) + .then((data) => { + if (data && isArray(data) && 2 === data.length) { + if (themeLink && themeLink[0] && (!themeStyle || !themeStyle[0])) { + themeStyle = $(''); + themeLink.after(themeStyle); + themeLink.remove(); } + + if (themeStyle && themeStyle[0]) { + if (appendStyles(themeStyle, data[1])) { + themeStyle.attr('data-href', url).attr('data-theme', data[0]); + } + } + + themeTrigger(SaveSettingsStep.TrueResult); } - - themeTrigger(SaveSettingsStep.TrueResult); - } - - }).then(clearTimer, clearTimer); + }) + .then(clearTimer, clearTimer); } } /** * @returns {function} */ -export function computedPagenatorHelper(koCurrentPage, koPageCount) -{ +export function computedPagenatorHelper(koCurrentPage, koPageCount) { return () => { - - const - currentPage = koCurrentPage(), + const currentPage = koCurrentPage(), pageCount = koPageCount(), result = [], fAdd = (index, push = true, customName = '') => { - const data = { current: index === currentPage, name: '' === customName ? index.toString() : customName.toString(), @@ -1333,33 +1199,24 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount) value: index.toString() }; - if (push) - { + if (push) { result.push(data); - } - else - { + } else { result.unshift(data); } }; - let - prev = 0, + let prev = 0, next = 0, limit = 2; - if (1 < pageCount || (0 < pageCount && pageCount < currentPage)) - { - if (pageCount < currentPage) - { + if (1 < pageCount || (0 < pageCount && pageCount < currentPage)) { + if (pageCount < currentPage) { fAdd(pageCount); prev = pageCount; next = pageCount; - } - else - { - if (3 >= currentPage || pageCount - 2 <= currentPage) - { + } else { + if (3 >= currentPage || pageCount - 2 <= currentPage) { limit += 2; } @@ -1369,53 +1226,40 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount) } while (0 < limit) { - prev -= 1; next += 1; - if (0 < prev) - { + if (0 < prev) { fAdd(prev, false); limit -= 1; } - if (pageCount >= next) - { + if (pageCount >= next) { fAdd(next, true); limit -= 1; - } - else if (0 >= prev) - { + } else if (0 >= prev) { break; } } - if (3 === prev) - { + if (3 === prev) { fAdd(2, false); - } - else if (3 < prev) - { + } else if (3 < prev) { fAdd(Math.round((prev - 1) / 2), false, '...'); } - if (pageCount - 2 === next) - { + if (pageCount - 2 === next) { fAdd(pageCount - 1, true); - } - else if (pageCount - 2 > next) - { + } else if (pageCount - 2 > next) { fAdd(Math.round((pageCount + next) / 2), true, '...'); } // first and last - if (1 < prev) - { + if (1 < prev) { fAdd(1, false); } - if (pageCount > next) - { + if (pageCount > next) { fAdd(pageCount, true); } } @@ -1428,8 +1272,7 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount) * @param {string} fileName * @returns {string} */ -export function getFileExtension(fileName) -{ +export function getFileExtension(fileName) { fileName = trim(fileName).toLowerCase(); const result = fileName.split('.').pop(); @@ -1440,22 +1283,18 @@ export function getFileExtension(fileName) * @param {string} fileName * @returns {string} */ -export function mimeContentType(fileName) -{ - let - ext = '', +export function mimeContentType(fileName) { + let ext = '', result = 'application/octet-stream'; fileName = trim(fileName).toLowerCase(); - if ('winmail.dat' === fileName) - { + if ('winmail.dat' === fileName) { return 'application/ms-tnef'; } ext = getFileExtension(fileName); - if (ext && 0 < ext.length && !isUnd(Mime[ext])) - { + if (ext && 0 < ext.length && !isUnd(Mime[ext])) { result = Mime[ext]; } @@ -1466,8 +1305,7 @@ export function mimeContentType(fileName) * @param {string} color * @returns {boolean} */ -export function isTransparent(color) -{ +export function isTransparent(color) { return 'rgba(0, 0, 0, 0)' === color || 'transparent' === color; } @@ -1475,9 +1313,11 @@ export function isTransparent(color) * @param {Object} $el * @returns {number} */ -export function getRealHeight($el) -{ - $el.clone().show().appendTo($hcont); +export function getRealHeight($el) { + $el + .clone() + .show() + .appendTo($hcont); const result = $hcont.height(); $hcont.empty(); return result; @@ -1488,27 +1328,20 @@ export function getRealHeight($el) * @param {number} value * @param {Function} fCallback */ -export function resizeAndCrop(url, value, fCallback) -{ +export function resizeAndCrop(url, value, fCallback) { const img = new window.Image(); img.onload = function() { + let diff = [0, 0]; - let - diff = [0, 0]; - - const - canvas = window.document.createElement('canvas'), + const canvas = window.document.createElement('canvas'), ctx = canvas.getContext('2d'); canvas.width = value; canvas.height = value; - if (this.width > this.height) - { + if (this.width > this.height) { diff = [this.width - this.height, 0]; - } - else - { + } else { diff = [0, this.height - this.width]; } @@ -1527,68 +1360,66 @@ export function resizeAndCrop(url, value, fCallback) * @param {Function} PopupComposeViewModel * @returns {boolean} */ -export function mailToHelper(mailToUrl, PopupComposeViewModel) -{ - if (mailToUrl && 'mailto:' === mailToUrl.toString().substr(0, 7).toLowerCase()) - { - if (!PopupComposeViewModel) - { +export function mailToHelper(mailToUrl, PopupComposeViewModel) { + if ( + mailToUrl && + 'mailto:' === + mailToUrl + .toString() + .substr(0, 7) + .toLowerCase() + ) { + if (!PopupComposeViewModel) { return true; } mailToUrl = mailToUrl.toString().substr(7); - let - to = [], + let to = [], cc = null, bcc = null, params = {}; - const - email = mailToUrl.replace(/\?.+$/, ''), - query = mailToUrl.replace(/^[^\?]*\?/, ''), + const email = mailToUrl.replace(/\?.+$/, ''), + query = mailToUrl.replace(/^[^?]*\?/, ''), EmailModel = require('Model/Email').default; params = simpleQueryParser(query); - if (!isUnd(params.to)) - { + if (!isUnd(params.to)) { to = EmailModel.parseEmailLine(decodeURIComponent(email + ',' + params.to)); - to = _.values(to.reduce((result, value) => { - if (value) - { - if (result[value.email]) - { - if (!result[value.email].name) - { + to = _.values( + to.reduce((result, value) => { + if (value) { + if (result[value.email]) { + if (!result[value.email].name) { + result[value.email] = value; + } + } else { result[value.email] = value; } } - else - { - result[value.email] = value; - } - } - return result; - }, {})); - } - else - { + return result; + }, {}) + ); + } else { to = EmailModel.parseEmailLine(email); } - if (!isUnd(params.cc)) - { + if (!isUnd(params.cc)) { cc = EmailModel.parseEmailLine(decodeURIComponent(params.cc)); } - if (!isUnd(params.bcc)) - { + if (!isUnd(params.bcc)) { bcc = EmailModel.parseEmailLine(decodeURIComponent(params.bcc)); } require('Knoin/Knoin').showScreenPopup(PopupComposeViewModel, [ - ComposeType.Empty, null, to, cc, bcc, + ComposeType.Empty, + null, + to, + cc, + bcc, isUnd(params.subject) ? null : pString(decodeURIComponent(params.subject)), isUnd(params.body) ? null : plainToHtml(pString(decodeURIComponent(params.body))) ]); @@ -1603,27 +1434,23 @@ export function mailToHelper(mailToUrl, PopupComposeViewModel) * @param {Function} fn * @returns {void} */ -export function domReady(fn) -{ +export function domReady(fn) { $(() => fn()); -// -// if ('loading' !== window.document.readyState) -// { -// fn(); -// } -// else -// { -// window.document.addEventListener('DOMContentLoaded', fn); -// } + // + // if ('loading' !== window.document.readyState) + // { + // fn(); + // } + // else + // { + // window.document.addEventListener('DOMContentLoaded', fn); + // } } export const windowResize = _.debounce((timeout) => { - if (isUnd(timeout) || isNull(timeout)) - { + if (isUnd(timeout) || isNull(timeout)) { $win.resize(); - } - else - { + } else { window.setTimeout(() => { $win.resize(); }, timeout); @@ -1633,14 +1460,12 @@ export const windowResize = _.debounce((timeout) => { /** * @returns {void} */ -export function windowResizeCallback() -{ +export function windowResizeCallback() { windowResize(); } let substr = window.String.substr; -if ('b' !== 'ab'.substr(-1)) -{ +if ('b' !== 'ab'.substr(-1)) { substr = (str, start, length) => { start = 0 > start ? str.length + start : start; return str.substr(start, length); diff --git a/dev/Component/Abstract.js b/dev/Component/Abstract.js index 6140e543b..bd4b53602 100644 --- a/dev/Component/Abstract.js +++ b/dev/Component/Abstract.js @@ -1,18 +1,15 @@ - import $ from '$'; import ko from 'ko'; -import {isUnd} from 'Common/Utils'; -import {i18nToNodes} from 'Common/Translator'; +import { isUnd } from 'Common/Utils'; +import { i18nToNodes } from 'Common/Translator'; -class AbstractComponent -{ +class AbstractComponent { disposable = []; dispose() { this.disposable.forEach((funcToDispose) => { - if (funcToDispose && funcToDispose.dispose) - { + if (funcToDispose && funcToDispose.dispose) { funcToDispose.dispose(); } }); @@ -25,22 +22,19 @@ class AbstractComponent * @returns {Object} */ const componentExportHelper = (ClassObject, templateID = '') => ({ - template: templateID ? {element: templateID} : '', + template: templateID ? { element: templateID } : '', viewModel: { createViewModel: (params, componentInfo) => { - params = params || {}; params.element = null; - if (componentInfo && componentInfo.element) - { + if (componentInfo && componentInfo.element) { params.component = componentInfo; params.element = $(componentInfo.element); i18nToNodes(params.element); - if (!isUnd(params.inline) && ko.unwrap(params.inline)) - { + if (!isUnd(params.inline) && ko.unwrap(params.inline)) { params.element.css('display', 'inline-block'); } } @@ -50,4 +44,4 @@ const componentExportHelper = (ClassObject, templateID = '') => ({ } }); -export {AbstractComponent, componentExportHelper}; +export { AbstractComponent, componentExportHelper }; diff --git a/dev/Component/AbstractInput.js b/dev/Component/AbstractInput.js index 157ca69e2..d3bf945d8 100644 --- a/dev/Component/AbstractInput.js +++ b/dev/Component/AbstractInput.js @@ -1,16 +1,13 @@ - import ko from 'ko'; -import {isUnd, trim, pInt} from 'Common/Utils'; -import {SaveSettingsStep} from 'Common/Enums'; -import {AbstractComponent} from 'Component/Abstract'; +import { isUnd, trim, pInt } from 'Common/Utils'; +import { SaveSettingsStep } from 'Common/Enums'; +import { AbstractComponent } from 'Component/Abstract'; -class AbstractInput extends AbstractComponent -{ +class AbstractInput extends AbstractComponent { /** * @param {Object} params */ constructor(params) { - super(); this.value = params.value || ''; @@ -28,32 +25,26 @@ class AbstractInput extends AbstractComponent this.classForTrigger = ko.observable(''); this.className = ko.computed(() => { - const - size = ko.unwrap(this.size), + const size = ko.unwrap(this.size), suffixValue = this.trigger ? ' ' + trim('settings-saved-trigger-input ' + this.classForTrigger()) : ''; return (0 < size ? 'span' + size : '') + suffixValue; }); - if (!isUnd(params.width) && params.element) - { + if (!isUnd(params.width) && params.element) { params.element.find('input,select,textarea').css('width', params.width); } this.disposable.push(this.className); - if (this.trigger) - { + if (this.trigger) { this.setTriggerState(this.trigger()); - this.disposable.push( - this.trigger.subscribe(this.setTriggerState, this) - ); + this.disposable.push(this.trigger.subscribe(this.setTriggerState, this)); } } setTriggerState(value) { - switch (pInt(value)) - { + switch (pInt(value)) { case SaveSettingsStep.TrueResult: this.classForTrigger('success'); break; @@ -67,4 +58,4 @@ class AbstractInput extends AbstractComponent } } -export {AbstractInput, AbstractInput as default}; +export { AbstractInput, AbstractInput as default }; diff --git a/dev/Component/Checkbox.js b/dev/Component/Checkbox.js index b49a12d5d..a8c7f6fd6 100644 --- a/dev/Component/Checkbox.js +++ b/dev/Component/Checkbox.js @@ -1,6 +1,5 @@ - -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractCheckbox} from 'Component/AbstractCheckbox'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractCheckbox } from 'Component/AbstractCheckbox'; class CheckboxComponent extends AbstractCheckbox {} diff --git a/dev/Component/Classic/Checkbox.js b/dev/Component/Classic/Checkbox.js index e4611c4d7..cd2af7ea0 100644 --- a/dev/Component/Classic/Checkbox.js +++ b/dev/Component/Classic/Checkbox.js @@ -1,6 +1,5 @@ - -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractCheckbox} from 'Component/AbstractCheckbox'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractCheckbox } from 'Component/AbstractCheckbox'; class ClassicCheckboxComponent extends AbstractCheckbox {} diff --git a/dev/Component/Date.js b/dev/Component/Date.js index 6bba849c0..fe1a60e4a 100644 --- a/dev/Component/Date.js +++ b/dev/Component/Date.js @@ -1,6 +1,5 @@ - -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractInput} from 'Component/AbstractInput'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractInput } from 'Component/AbstractInput'; class DateComponent extends AbstractInput {} diff --git a/dev/Component/Input.js b/dev/Component/Input.js index 45445a85b..c9df0a461 100644 --- a/dev/Component/Input.js +++ b/dev/Component/Input.js @@ -1,6 +1,5 @@ - -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractInput} from 'Component/AbstractInput'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractInput } from 'Component/AbstractInput'; class InputComponent extends AbstractInput {} diff --git a/dev/Component/MaterialDesign/Checkbox.js b/dev/Component/MaterialDesign/Checkbox.js index d3a1e989c..c8de209a5 100644 --- a/dev/Component/MaterialDesign/Checkbox.js +++ b/dev/Component/MaterialDesign/Checkbox.js @@ -1,20 +1,17 @@ - import _ from '_'; import ko from 'ko'; -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractCheckbox} from 'Component/AbstractCheckbox'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractCheckbox } from 'Component/AbstractCheckbox'; -class CheckboxMaterialDesignComponent extends AbstractCheckbox -{ +class CheckboxMaterialDesignComponent extends AbstractCheckbox { /** * @param {Object} params */ constructor(params) { - super(params); - this.animationBox = ko.observable(false).extend({falseTimeout: 200}); - this.animationCheckmark = ko.observable(false).extend({falseTimeout: 200}); + this.animationBox = ko.observable(false).extend({ falseTimeout: 200 }); + this.animationCheckmark = ko.observable(false).extend({ falseTimeout: 200 }); this.animationBoxSetTrue = _.bind(this.animationBoxSetTrue, this); this.animationCheckmarkSetTrue = _.bind(this.animationCheckmarkSetTrue, this); @@ -38,8 +35,7 @@ class CheckboxMaterialDesignComponent extends AbstractCheckbox if (box) { this.animationBoxSetTrue(); _.delay(this.animationCheckmarkSetTrue, 200); - } - else { + } else { this.animationCheckmarkSetTrue(); _.delay(this.animationBoxSetTrue, 200); } diff --git a/dev/Component/Radio.js b/dev/Component/Radio.js index eaf1df911..8eed4b283 100644 --- a/dev/Component/Radio.js +++ b/dev/Component/Radio.js @@ -1,6 +1,5 @@ - -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractRadio} from 'Component/AbstractRadio'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractRadio } from 'Component/AbstractRadio'; class RadioComponent extends AbstractRadio {} diff --git a/dev/Component/SaveTrigger.js b/dev/Component/SaveTrigger.js index 2d73ccdde..29478cdf7 100644 --- a/dev/Component/SaveTrigger.js +++ b/dev/Component/SaveTrigger.js @@ -1,72 +1,74 @@ +import { pInt } from 'Common/Utils'; +import { SaveSettingsStep } from 'Common/Enums'; +import { AbstractComponent, componentExportHelper } from 'Component/Abstract'; -import {pInt} from 'Common/Utils'; -import {SaveSettingsStep} from 'Common/Enums'; -import {AbstractComponent, componentExportHelper} from 'Component/Abstract'; - -class SaveTriggerComponent extends AbstractComponent -{ +class SaveTriggerComponent extends AbstractComponent { /** * @param {Object} params */ constructor(params) { - super(); this.element = params.element || null; this.value = params.value && params.value.subscribe ? params.value : null; - if (this.element) - { - if (this.value) - { + if (this.element) { + if (this.value) { this.element.css('display', 'inline-block'); - if (params.verticalAlign) - { + if (params.verticalAlign) { this.element.css('vertical-align', params.verticalAlign); } this.setState(this.value()); - this.disposable.push( - this.value.subscribe(this.setState, this) - ); - } - else - { + this.disposable.push(this.value.subscribe(this.setState, this)); + } else { this.element.hide(); } } } setState(value) { - - switch (pInt(value)) - { + switch (pInt(value)) { case SaveSettingsStep.TrueResult: this.element - .find('.animated,.error').hide().removeClass('visible') + .find('.animated,.error') + .hide() + .removeClass('visible') .end() - .find('.success').show().addClass('visible'); + .find('.success') + .show() + .addClass('visible'); break; case SaveSettingsStep.FalseResult: this.element - .find('.animated,.success').hide().removeClass('visible') + .find('.animated,.success') + .hide() + .removeClass('visible') .end() - .find('.error').show().addClass('visible'); + .find('.error') + .show() + .addClass('visible'); break; case SaveSettingsStep.Animate: this.element - .find('.error,.success').hide().removeClass('visible') + .find('.error,.success') + .hide() + .removeClass('visible') .end() - .find('.animated').show().addClass('visible'); + .find('.animated') + .show() + .addClass('visible'); break; case SaveSettingsStep.Idle: default: this.element - .find('.animated').hide() + .find('.animated') + .hide() .end() - .find('.error,.success').removeClass('visible'); + .find('.error,.success') + .removeClass('visible'); break; } } diff --git a/dev/Component/Script.js b/dev/Component/Script.js index ef817f36a..1864edb6e 100644 --- a/dev/Component/Script.js +++ b/dev/Component/Script.js @@ -1,36 +1,33 @@ - import $ from '$'; -import {AbstractComponent, componentExportHelper} from 'Component/Abstract'; +import { AbstractComponent, componentExportHelper } from 'Component/Abstract'; -class ScriptComponent extends AbstractComponent -{ +class ScriptComponent extends AbstractComponent { /** * @param {Object} params */ constructor(params) { - super(); - if (params.component && params.component.templateNodes && params.element && - params.element[0] && params.element[0].outerHTML) - { + if ( + params.component && + params.component.templateNodes && + params.element && + params.element[0] && + params.element[0].outerHTML + ) { let script = params.element[0].outerHTML; - script = !script ? '' : script - .replace(/<\/b><\/x-script>/i, ''); + script = !script ? '' : script.replace(/ <\/b><\/x-script>/i, ''); - if (script) - { + if (script) { params.element.text(''); params.element.replaceWith( $(script).text( - params.component.templateNodes[0] && params.component.templateNodes[0].nodeValue ? - params.component.templateNodes[0].nodeValue : '' + params.component.templateNodes[0] && params.component.templateNodes[0].nodeValue + ? params.component.templateNodes[0].nodeValue + : '' ) ); - } - else - { + } else { params.element.remove(); } } diff --git a/dev/Component/Select.js b/dev/Component/Select.js index c17dc5297..0e6836380 100644 --- a/dev/Component/Select.js +++ b/dev/Component/Select.js @@ -1,16 +1,13 @@ +import { i18n } from 'Common/Translator'; +import { defautOptionsAfterRender } from 'Common/Utils'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractInput } from 'Component/AbstractInput'; -import {i18n} from 'Common/Translator'; -import {defautOptionsAfterRender} from 'Common/Utils'; -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractInput} from 'Component/AbstractInput'; - -class SelectComponent extends AbstractInput -{ +class SelectComponent extends AbstractInput { /** * @param {Object} params */ constructor(params) { - super(params); this.options = params.options || ''; @@ -19,8 +16,7 @@ class SelectComponent extends AbstractInput this.optionsValue = params.optionsValue || null; this.optionsCaption = params.optionsCaption || null; - if (this.optionsCaption) - { + if (this.optionsCaption) { this.optionsCaption = i18n(this.optionsCaption); } diff --git a/dev/Component/SvgIcon.js b/dev/Component/SvgIcon.js index 64a87bdf4..75d9b42c8 100644 --- a/dev/Component/SvgIcon.js +++ b/dev/Component/SvgIcon.js @@ -1,10 +1,8 @@ - import $ from '$'; let cachedUrl = null; const getUrl = () => { - if (!cachedUrl) - { + if (!cachedUrl) { const version = $('#rlAppVersion').attr('content') || '0.0.0'; cachedUrl = `rainloop/v/${version}/static/css/svg/icons.svg`; } @@ -15,9 +13,8 @@ const getUrl = () => { export default { template: '', viewModel: { - createViewModel: ({icon = 'null'}, componentInfo) => { - if (componentInfo && componentInfo.element) - { + createViewModel: ({ icon = 'null' }, componentInfo) => { + if (componentInfo && componentInfo.element) { $(componentInfo.element).replaceWith( `` ); diff --git a/dev/Component/TextArea.js b/dev/Component/TextArea.js index ce19a03d2..478f56bc2 100644 --- a/dev/Component/TextArea.js +++ b/dev/Component/TextArea.js @@ -1,17 +1,14 @@ - -import {isUnd} from 'Common/Utils'; -import {componentExportHelper} from 'Component/Abstract'; -import {AbstractInput} from 'Component/AbstractInput'; +import { isUnd } from 'Common/Utils'; +import { componentExportHelper } from 'Component/Abstract'; +import { AbstractInput } from 'Component/AbstractInput'; const DEFAULT_ROWS = 5; -class TextAreaComponent extends AbstractInput -{ +class TextAreaComponent extends AbstractInput { /** * @param {Object} params */ constructor(params) { - super(params); this.rows = params.rows || DEFAULT_ROWS; diff --git a/dev/External/Opentip.js b/dev/External/Opentip.js index d47276068..4287b3a90 100644 --- a/dev/External/Opentip.js +++ b/dev/External/Opentip.js @@ -1,4 +1,3 @@ - import window from 'window'; const Opentip = window.Opentip || {}; @@ -6,7 +5,6 @@ const Opentip = window.Opentip || {}; Opentip.styles = Opentip.styles || {}; Opentip.styles.rainloop = { - 'extends': 'standard', 'fixed': true, @@ -43,4 +41,4 @@ Opentip.styles.rainloopErrorTip = { 'className': 'rainloopErrorTip' }; -export {Opentip, Opentip as default}; +export { Opentip, Opentip as default }; diff --git a/dev/External/ko.js b/dev/External/ko.js index 19657ffef..f7b11f48b 100644 --- a/dev/External/ko.js +++ b/dev/External/ko.js @@ -1,19 +1,16 @@ - import window from 'window'; import _ from '_'; import $ from '$'; import Opentip from 'Opentip'; import Pikaday from 'pikaday'; -import {SaveSettingsStep, Magics} from 'Common/Enums'; +import { SaveSettingsStep, Magics } from 'Common/Enums'; -const - ko = window.ko, +const ko = window.ko, $win = $(window), fDisposalTooltipHelper = (element) => { ko.utils.domNodeDisposal.addDisposeCallback(element, () => { - if (element && element.__opentip) - { + if (element && element.__opentip) { element.__opentip.deactivate(); } }); @@ -21,8 +18,7 @@ const ko.bindingHandlers.updateWidth = { init: (element, fValueAccessor) => { - const - $el = $(element), + const $el = $(element), fValue = fValueAccessor(), fInit = () => { fValue($el.width()); @@ -42,21 +38,17 @@ ko.bindingHandlers.updateWidth = { ko.bindingHandlers.editor = { init: (element, fValueAccessor) => { - let editor = null; - const - fValue = fValueAccessor(), + const fValue = fValueAccessor(), HtmlEditor = require('Common/HtmlEditor').default, fUpdateEditorValue = () => { - if (fValue && fValue.__editor) - { + if (fValue && fValue.__editor) { fValue.__editor.setHtmlOrPlain(fValue()); } }, fUpdateKoValue = () => { - if (fValue && fValue.__editor) - { + if (fValue && fValue.__editor) { fValue(fValue.__editor.getDataWithHtmlMark()); } }, @@ -65,8 +57,7 @@ ko.bindingHandlers.editor = { fUpdateEditorValue(); }; - if (ko.isObservable(fValue) && HtmlEditor) - { + if (ko.isObservable(fValue) && HtmlEditor) { editor = new HtmlEditor(element, fUpdateKoValue, fOnReady, fUpdateKoValue); fValue.__fetchEditorValue = fUpdateKoValue; @@ -90,9 +81,7 @@ ko.bindingHandlers.json = { ko.bindingHandlers.scrollerShadows = { init: (element) => { - - const - limit = 8, + const limit = 8, $el = $(element), cont = $el.find('[data-scroller-shadows-content]')[0] || null, fFunc = _.throttle(() => { @@ -101,8 +90,7 @@ ko.bindingHandlers.scrollerShadows = { .toggleClass('scroller-shadow-bottom', cont.scrollTop + limit < cont.scrollHeight - cont.clientHeight); }, 100); - if (cont) - { + if (cont) { $(cont).on('scroll resize', fFunc); $win.on('resize', fFunc); @@ -116,11 +104,9 @@ ko.bindingHandlers.scrollerShadows = { ko.bindingHandlers.pikaday = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel, bindingContext) => { - ko.bindingHandlers.textInput.init(element, fValueAccessor, fAllBindingsAccessor, viewModel, bindingContext); - if (Pikaday) - { + if (Pikaday) { element.__pikaday = new Pikaday({ field: element }); @@ -153,16 +139,13 @@ ko.bindingHandlers.visibleAnimated = { ko.bindingHandlers.tooltip = { init: (element, fValueAccessor) => { - - const - $el = $(element), + const $el = $(element), fValue = fValueAccessor(), isMobile = 'on' === ($el.data('tooltip-mobile') || 'off'), isI18N = 'on' === ($el.data('tooltip-i18n') || 'on'), Globals = require('Common/Globals'); - if (!Globals.bMobileDevice || isMobile) - { + if (!Globals.bMobileDevice || isMobile) { const sValue = !ko.isObservable(fValue) && _.isFunction(fValue) ? fValue() : ko.unwrap(fValue); element.__opentip = new Opentip(element, { @@ -177,19 +160,15 @@ ko.bindingHandlers.tooltip = { } }); - if ('' === sValue) - { + if ('' === sValue) { element.__opentip.hide(); element.__opentip.deactivate(); element.__opentip.setContent(''); - } - else - { + } else { element.__opentip.activate(); } - if (isI18N) - { + if (isI18N) { const Translator = require('Common/Translator'); element.__opentip.setContent(Translator.i18n(sValue)); @@ -199,14 +178,11 @@ ko.bindingHandlers.tooltip = { }); Globals.dropdownVisibility.subscribe(() => { - if (element && element.__opentip) - { + if (element && element.__opentip) { element.__opentip.setContent(Translator.i18n(sValue)); } }); - } - else - { + } else { element.__opentip.setContent(sValue); } @@ -221,24 +197,18 @@ ko.bindingHandlers.tooltip = { } }, update: (element, fValueAccessor) => { - - const - $el = $(element), + const $el = $(element), fValue = fValueAccessor(), isMobile = 'on' === ($el.data('tooltip-mobile') || 'off'), isI18N = 'on' === ($el.data('tooltip-i18n') || 'on'), Globals = require('Common/Globals'); - if ((!Globals.bMobileDevice || isMobile) && element.__opentip) - { + if ((!Globals.bMobileDevice || isMobile) && element.__opentip) { const sValue = !ko.isObservable(fValue) && _.isFunction(fValue) ? fValue() : ko.unwrap(fValue); - if (sValue) - { + if (sValue) { element.__opentip.setContent(isI18N ? require('Common/Translator').i18n(sValue) : sValue); element.__opentip.activate(); - } - else - { + } else { element.__opentip.hide(); element.__opentip.deactivate(); element.__opentip.setContent(''); @@ -249,7 +219,6 @@ ko.bindingHandlers.tooltip = { ko.bindingHandlers.tooltipErrorTip = { init: function(element) { - const $el = $(element); element.__opentip = new Opentip(element, { @@ -262,8 +231,7 @@ ko.bindingHandlers.tooltipErrorTip = { element.__opentip.deactivate(); $(window.document).on('click', () => { - if (element && element.__opentip) - { + if (element && element.__opentip) { element.__opentip.hide(); } }); @@ -271,32 +239,23 @@ ko.bindingHandlers.tooltipErrorTip = { fDisposalTooltipHelper(element); }, update: (element, fValueAccessor) => { - - const - $el = $(element), + const $el = $(element), fValue = fValueAccessor(), value = !ko.isObservable(fValue) && _.isFunction(fValue) ? fValue() : ko.unwrap(fValue), openTips = element.__opentip; - if (openTips) - { - if ('' === value) - { + if (openTips) { + if ('' === value) { openTips.hide(); openTips.deactivate(); openTips.setContent(''); - } - else - { + } else { _.delay(() => { - if ($el.is(':visible')) - { + if ($el.is(':visible')) { openTips.setContent(value); openTips.activate(); openTips.show(); - } - else - { + } else { openTips.hide(); openTips.deactivate(); openTips.setContent(''); @@ -310,8 +269,7 @@ ko.bindingHandlers.tooltipErrorTip = { ko.bindingHandlers.registrateBootstrapDropdown = { init: (element) => { const Globals = require('Common/Globals'); - if (Globals && Globals.data.aBootstrapDropdowns) - { + if (Globals && Globals.data.aBootstrapDropdowns) { Globals.data.aBootstrapDropdowns.push($(element)); $(element).click(() => { @@ -326,11 +284,9 @@ ko.bindingHandlers.registrateBootstrapDropdown = { ko.bindingHandlers.openDropdownTrigger = { update: (element, fValueAccessor) => { - if (ko.unwrap(fValueAccessor())) - { + if (ko.unwrap(fValueAccessor())) { const $el = $(element); - if (!$el.hasClass('open')) - { + if (!$el.hasClass('open')) { $el.find('.dropdown-toggle').dropdown('toggle'); } @@ -344,9 +300,11 @@ ko.bindingHandlers.openDropdownTrigger = { ko.bindingHandlers.dropdownCloser = { init: (element) => { - $(element).closest('.dropdown').on('click', '.e-item', () => { - $(element).dropdown('toggle'); - }); + $(element) + .closest('.dropdown') + .on('click', '.e-item', () => { + $(element).dropdown('toggle'); + }); } }; @@ -362,25 +320,24 @@ ko.bindingHandlers.popover = { ko.bindingHandlers.csstext = {}; ko.bindingHandlers.csstext.init = ko.bindingHandlers.csstext.update = (element, fValueAccessor) => { - if (element && element.styleSheet && 'undefined' !== typeof element.styleSheet.cssText) - { + if (element && element.styleSheet && 'undefined' !== typeof element.styleSheet.cssText) { element.styleSheet.cssText = ko.unwrap(fValueAccessor()); - } - else - { + } else { $(element).text(ko.unwrap(fValueAccessor())); } }; ko.bindingHandlers.resizecrop = { init: (element) => { - $(element).addClass('resizecrop').resizecrop({ - 'width': '100', - 'height': '100', - 'wrapperCSS': { - 'border-radius': '10px' - } - }); + $(element) + .addClass('resizecrop') + .resizecrop({ + 'width': '100', + 'height': '100', + 'wrapperCSS': { + 'border-radius': '10px' + } + }); }, update: (element, fValueAccessor) => { fValueAccessor()(); @@ -394,8 +351,7 @@ ko.bindingHandlers.resizecrop = { ko.bindingHandlers.onKeyDown = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel) => { $(element).on('keydown.koOnKeyDown', (event) => { - if (event) - { + if (event) { return fValueAccessor().call(viewModel, event); } @@ -411,8 +367,7 @@ ko.bindingHandlers.onKeyDown = { ko.bindingHandlers.onEnter = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel) => { $(element).on('keypress.koOnEnter', (event) => { - if (event && 13 === window.parseInt(event.keyCode, 10)) - { + if (event && 13 === window.parseInt(event.keyCode, 10)) { $(element).trigger('change'); fValueAccessor().call(viewModel); } @@ -427,8 +382,7 @@ ko.bindingHandlers.onEnter = { ko.bindingHandlers.onSpace = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel) => { $(element).on('keyup.koOnSpace', (event) => { - if (event && 32 === window.parseInt(event.keyCode, 10)) - { + if (event && 32 === window.parseInt(event.keyCode, 10)) { fValueAccessor().call(viewModel, event); } }); @@ -442,8 +396,7 @@ ko.bindingHandlers.onSpace = { ko.bindingHandlers.onTab = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel) => { $(element).on('keydown.koOnTab', (event) => { - if (event && 9 === window.parseInt(event.keyCode, 10)) - { + if (event && 9 === window.parseInt(event.keyCode, 10)) { return fValueAccessor().call(viewModel, !!event.shiftKey); } return true; @@ -458,8 +411,7 @@ ko.bindingHandlers.onTab = { ko.bindingHandlers.onEsc = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel) => { $(element).on('keyup.koOnEsc', (event) => { - if (event && 27 === window.parseInt(event.keyCode, 10)) - { + if (event && 27 === window.parseInt(event.keyCode, 10)) { $(element).trigger('change'); fValueAccessor().call(viewModel); } @@ -473,8 +425,7 @@ ko.bindingHandlers.onEsc = { ko.bindingHandlers.clickOnTrue = { update: (element, fValueAccessor) => { - if (ko.unwrap(fValueAccessor())) - { + if (ko.unwrap(fValueAccessor())) { $(element).click(); } } @@ -482,9 +433,7 @@ ko.bindingHandlers.clickOnTrue = { ko.bindingHandlers.modal = { init: (element, fValueAccessor) => { - - const - Globals = require('Common/Globals'), + const Globals = require('Common/Globals'), Utils = require('Common/Utils'); $(element) @@ -494,7 +443,8 @@ ko.bindingHandlers.modal = { 'show': ko.unwrap(fValueAccessor()) }) .on('shown.koModal', Utils.windowResizeCallback) - .find('.close').on('click.koModal', () => { + .find('.close') + .on('click.koModal', () => { fValueAccessor()(false); }); @@ -506,32 +456,29 @@ ko.bindingHandlers.modal = { }); }, update: (element, fValueAccessor) => { - const Globals = require('Common/Globals'); $(element).modal(ko.unwrap(fValueAccessor()) ? 'show' : 'hide'); - if (Globals.$html.hasClass('rl-anim')) - { + if (Globals.$html.hasClass('rl-anim')) { Globals.$html.addClass('rl-modal-animation'); _.delay(() => { Globals.$html.removeClass('rl-modal-animation'); }, Magics.Time500ms); } - } }; ko.bindingHandlers.moment = { init: (element, fValueAccessor) => { require('Common/Momentor').momentToNode( - $(element).addClass('moment').data('moment-time', ko.unwrap(fValueAccessor())) + $(element) + .addClass('moment') + .data('moment-time', ko.unwrap(fValueAccessor())) ); }, update: (element, fValueAccessor) => { - require('Common/Momentor').momentToNode( - $(element).data('moment-time', ko.unwrap(fValueAccessor())) - ); + require('Common/Momentor').momentToNode($(element).data('moment-time', ko.unwrap(fValueAccessor()))); } }; @@ -580,19 +527,16 @@ ko.bindingHandlers.initDom = { ko.bindingHandlers.initFixedTrigger = { init: (element, fValueAccessor) => { - const - values = ko.unwrap(fValueAccessor()), + const values = ko.unwrap(fValueAccessor()), $el = $(element), top = values[1] || 0; let $container = $(values[0] || null); $container = $container[0] ? $container : null; - if ($container) - { + if ($container) { $win.resize(() => { const offset = $container ? $container.offset() : null; - if (offset && offset.top) - { + if (offset && offset.top) { $el.css('top', offset.top + top); } }); @@ -609,24 +553,19 @@ ko.bindingHandlers.initResizeTrigger = { }); }, update: (oElement, fValueAccessor) => { - - const - Utils = require('Common/Utils'), + const Utils = require('Common/Utils'), Globals = require('Common/Globals'), values = ko.unwrap(fValueAccessor()); - let - value = Utils.pInt(values[1]), + let value = Utils.pInt(values[1]), size = 0, offset = $(oElement).offset().top; - if (0 < offset) - { + if (0 < offset) { offset += Utils.pInt(values[2]); size = Globals.$win.height() - offset; - if (value < size) - { + if (value < size) { value = size; } @@ -640,28 +579,28 @@ ko.bindingHandlers.initResizeTrigger = { ko.bindingHandlers.appendDom = { update: (element, fValueAccessor) => { - $(element).hide().empty().append(ko.unwrap(fValueAccessor())).show(); + $(element) + .hide() + .empty() + .append(ko.unwrap(fValueAccessor())) + .show(); } }; ko.bindingHandlers.draggable = { init: (element, fValueAccessor, fAllBindingsAccessor) => { - - const - Globals = require('Common/Globals'), + const Globals = require('Common/Globals'), Utils = require('Common/Utils'); - if (!Globals.bMobileDevice) - { - const - triggerZone = 100, + if (!Globals.bMobileDevice) { + const triggerZone = 100, scrollSpeed = 3, fAllValueFunc = fAllBindingsAccessor(), droppableSelector = fAllValueFunc && fAllValueFunc.droppableSelector ? fAllValueFunc.droppableSelector : '', conf = { distance: 20, handle: '.dragHandle', - cursorAt: {top: 22, left: 3}, + cursorAt: { top: 22, left: 3 }, refreshPositions: true, scroll: true, drag: null, @@ -669,23 +608,18 @@ ko.bindingHandlers.draggable = { helper: null }; - if (droppableSelector) - { + if (droppableSelector) { conf.drag = (event) => { - $(droppableSelector).each(function() { - const - $this = $(this), // eslint-disable-line no-invalid-this + const $this = $(this), // eslint-disable-line no-invalid-this offset = $this.offset(), bottomPos = offset.top + $this.height(); window.clearInterval($this.data('timerScroll')); $this.data('timerScroll', false); - if (event.pageX >= offset.left && event.pageX <= offset.left + $this.width()) - { - if (event.pageY >= bottomPos - triggerZone && event.pageY <= bottomPos) - { + if (event.pageX >= offset.left && event.pageX <= offset.left + $this.width()) { + if (event.pageY >= bottomPos - triggerZone && event.pageY <= bottomPos) { const moveUp = () => { $this.scrollTop($this.scrollTop() + scrollSpeed); Utils.windowResize(); @@ -695,8 +629,7 @@ ko.bindingHandlers.draggable = { moveUp(); } - if (event.pageY >= offset.top && event.pageY <= offset.top + triggerZone) - { + if (event.pageY >= offset.top && event.pageY <= offset.top + triggerZone) { const moveDown = () => { $this.scrollTop($this.scrollTop() - scrollSpeed); Utils.windowResize(); @@ -720,9 +653,11 @@ ko.bindingHandlers.draggable = { conf.helper = (event) => fValueAccessor()(event && event.target ? ko.dataFor(event.target) : null); - $(element).draggable(conf).on('mousedown.koDraggable', () => { - Utils.removeInFocus(); - }); + $(element) + .draggable(conf) + .on('mousedown.koDraggable', () => { + Utils.removeInFocus(); + }); ko.utils.domNodeDisposal.addDisposeCallback(element, () => { $(element) @@ -736,10 +671,8 @@ ko.bindingHandlers.draggable = { ko.bindingHandlers.droppable = { init: (element, fValueAccessor, fAllBindingsAccessor) => { const Globals = require('Common/Globals'); - if (!Globals.bMobileDevice) - { - const - fValueFunc = fValueAccessor(), + if (!Globals.bMobileDevice) { + const fValueFunc = fValueAccessor(), fAllValueFunc = fAllBindingsAccessor(), fOverCallback = fAllValueFunc && fAllValueFunc.droppableOver ? fAllValueFunc.droppableOver : null, fOutCallback = fAllValueFunc && fAllValueFunc.droppableOut ? fAllValueFunc.droppableOut : null, @@ -751,21 +684,18 @@ ko.bindingHandlers.droppable = { out: null }; - if (fValueFunc) - { + if (fValueFunc) { conf.drop = (event, ui) => { fValueFunc(event, ui); }; - if (fOverCallback) - { + if (fOverCallback) { conf.over = (event, ui) => { fOverCallback(event, ui); }; } - if (fOutCallback) - { + if (fOutCallback) { conf.out = (event, ui) => { fOutCallback(event, ui); }; @@ -783,13 +713,10 @@ ko.bindingHandlers.droppable = { ko.bindingHandlers.nano = { init: (element) => { - - const - Globals = require('Common/Globals'), + const Globals = require('Common/Globals'), Settings = require('Storage/Settings'); - if (!Globals.bDisableNanoScroll && !Settings.appSettingsGet('useNativeScrollbars')) - { + if (!Globals.bDisableNanoScroll && !Settings.appSettingsGet('useNativeScrollbars')) { $(element) .addClass('nano') .nanoScroller({ @@ -802,61 +729,73 @@ ko.bindingHandlers.nano = { ko.bindingHandlers.saveTrigger = { init: (element) => { - const $el = $(element); - $el.data('save-trigger-type', $el.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom'); + $el.data( + 'save-trigger-type', + $el.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom' + ); - if ('custom' === $el.data('save-trigger-type')) - { - $el.append( - ' ' - ).addClass('settings-saved-trigger'); - } - else - { + if ('custom' === $el.data('save-trigger-type')) { + $el + .append( + ' ' + + '' + + '' + + '' + ) + .addClass('settings-saved-trigger'); + } else { $el.addClass('settings-saved-trigger-input'); } }, update: (element, fValueAccessor) => { - const - value = ko.unwrap(fValueAccessor()), + const value = ko.unwrap(fValueAccessor()), $el = $(element); - if ('custom' === $el.data('save-trigger-type')) - { - switch (value.toString()) - { + if ('custom' === $el.data('save-trigger-type')) { + switch (value.toString()) { case '1': $el - .find('.animated,.error').hide().removeClass('visible') + .find('.animated,.error') + .hide() + .removeClass('visible') .end() - .find('.success').show().addClass('visible'); + .find('.success') + .show() + .addClass('visible'); break; case '0': $el - .find('.animated,.success').hide().removeClass('visible') + .find('.animated,.success') + .hide() + .removeClass('visible') .end() - .find('.error').show().addClass('visible'); + .find('.error') + .show() + .addClass('visible'); break; case '-2': $el - .find('.error,.success').hide().removeClass('visible') + .find('.error,.success') + .hide() + .removeClass('visible') .end() - .find('.animated').show().addClass('visible'); + .find('.animated') + .show() + .addClass('visible'); break; default: $el - .find('.animated').hide() + .find('.animated') + .hide() .end() - .find('.error,.success').removeClass('visible'); + .find('.error,.success') + .removeClass('visible'); break; } - } - else - { - switch (value.toString()) - { + } else { + switch (value.toString()) { case '1': $el.addClass('success').removeClass('error'); break; @@ -875,19 +814,15 @@ ko.bindingHandlers.saveTrigger = { ko.bindingHandlers.emailsTags = { init: (element, fValueAccessor, fAllBindingsAccessor) => { - - const - Utils = require('Common/Utils'), + const Utils = require('Common/Utils'), EmailModel = require('Model/Email').default, - $el = $(element), fValue = fValueAccessor(), fAllBindings = fAllBindingsAccessor(), fAutoCompleteSource = fAllBindings.autoCompleteSource || null, inputDelimiters = [',', ';', '\n'], fFocusCallback = (value) => { - if (fValue && fValue.focused) - { + if (fValue && fValue.focused) { fValue.focused(!!value); } }; @@ -905,38 +840,34 @@ ko.bindingHandlers.emailsTags = { } return null; }, - parseHook: (input) => _.map( - _.flatten(_.map( - input, - (inputValue) => { - const values = EmailModel.parseEmailLine(inputValue); - return values.length ? values : inputValue; - } - )), - (item) => (_.isObject(item) ? [item.toLine(false), item] : [item, null]) - ), + parseHook: (input) => + _.map( + _.flatten( + _.map(input, (inputValue) => { + const values = EmailModel.parseEmailLine(inputValue); + return values.length ? values : inputValue; + }) + ), + (item) => (_.isObject(item) ? [item.toLine(false), item] : [item, null]) + ), change: (event) => { $el.data('EmailsTagsValue', event.target.value); fValue(event.target.value); } }); - if (fValue && fValue.focused && fValue.focused.subscribe) - { + if (fValue && fValue.focused && fValue.focused.subscribe) { fValue.focused.subscribe((value) => { $el.inputosaurus(value ? 'focus' : 'blur'); }); } }, update: (element, fValueAccessor) => { - - const - $oEl = $(element), + const $oEl = $(element), fValue = fValueAccessor(), value = ko.unwrap(fValue); - if ($oEl.data('EmailsTagsValue') !== value) - { + if ($oEl.data('EmailsTagsValue') !== value) { $oEl.val(value); $oEl.data('EmailsTagsValue', value); $oEl.inputosaurus('refresh'); @@ -946,57 +877,51 @@ ko.bindingHandlers.emailsTags = { ko.bindingHandlers.command = { init: (element, fValueAccessor, fAllBindingsAccessor, viewModel, bindingContext) => { - const - jqElement = $(element), + const jqElement = $(element), command = fValueAccessor(); - if (!command || !command.isCommand) - { + if (!command || !command.isCommand) { throw new Error('Value should be a command'); } - if (!command.enabled) - { + if (!command.enabled) { command.enabled = ko.observable(true); } - if (!command.canExecute) - { + if (!command.canExecute) { const __realCanExecute = command.__realCanExecute; - if (_.isFunction(__realCanExecute)) - { + if (_.isFunction(__realCanExecute)) { command.canExecute = ko.computed(() => command.enabled() && __realCanExecute.call(viewModel, viewModel)); - } - else - { + } else { command.canExecute = ko.computed(() => command.enabled() && !!__realCanExecute); } } jqElement.addClass('command'); - ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'] - .init(element, fValueAccessor, fAllBindingsAccessor, viewModel, bindingContext); + ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init( + element, + fValueAccessor, + fAllBindingsAccessor, + viewModel, + bindingContext + ); }, update: (element, fValueAccessor) => { - - const - jqElement = $(element), + const jqElement = $(element), command = fValueAccessor(); let result = command.enabled(); jqElement.toggleClass('command-not-enabled', !result); - if (result) - { + if (result) { result = command.canExecute(); jqElement.toggleClass('command-can-not-be-execute', !result); } jqElement.toggleClass('command-disabled disable disabled', !result).toggleClass('no-disabled', !!result); - if (jqElement.is('input') || jqElement.is('button')) - { + if (jqElement.is('input') || jqElement.is('button')) { jqElement.prop('disabled', !result); } } @@ -1005,8 +930,7 @@ ko.bindingHandlers.command = { // extenders ko.extenders.trimmer = (target) => { - const - Utils = require('Common/Utils'), + const Utils = require('Common/Utils'), result = ko.computed({ read: target, write: (newValue) => { @@ -1019,19 +943,16 @@ ko.extenders.trimmer = (target) => { }; ko.extenders.posInterer = (target, defaultVal) => { - const - Utils = require('Common/Utils'), + const Utils = require('Common/Utils'), result = ko.computed({ read: target, write: (newValue) => { let val = Utils.pInt(newValue.toString(), defaultVal); - if (0 >= val) - { + if (0 >= val) { val = defaultVal; } - if (val === target() && '' + val !== '' + newValue) - { + if (val === target() && '' + val !== '' + newValue) { target(val + 1); } @@ -1044,44 +965,34 @@ ko.extenders.posInterer = (target, defaultVal) => { }; ko.extenders.limitedList = (target, limitedList) => { - const - Utils = require('Common/Utils'), - result = ko.computed({ - read: target, - write: (newValue) => { + const Utils = require('Common/Utils'), + result = ko + .computed({ + read: target, + write: (newValue) => { + const currentValue = ko.unwrap(target), + list = ko.unwrap(limitedList); - const - currentValue = ko.unwrap(target), - list = ko.unwrap(limitedList); - - if (Utils.isNonEmptyArray(list)) - { - if (-1 < Utils.inArray(newValue, list)) - { - target(newValue); - } - else if (-1 < Utils.inArray(currentValue, list)) - { - target(currentValue + ' '); - target(currentValue); - } - else - { - target(list[0] + ' '); - target(list[0]); + if (Utils.isNonEmptyArray(list)) { + if (-1 < Utils.inArray(newValue, list)) { + target(newValue); + } else if (-1 < Utils.inArray(currentValue, list)) { + target(currentValue + ' '); + target(currentValue); + } else { + target(list[0] + ' '); + target(list[0]); + } + } else { + target(''); } } - else - { - target(''); - } - } - }).extend({notify: 'always'}); + }) + .extend({ notify: 'always' }); result(target()); - if (!result.valueHasMutated) - { + if (!result.valueHasMutated) { result.valueHasMutated = () => { target.valueHasMutated(); }; @@ -1091,7 +1002,6 @@ ko.extenders.limitedList = (target, limitedList) => { }; ko.extenders.reversible = (target) => { - let value = target(); target.commit = () => { @@ -1113,20 +1023,20 @@ ko.extenders.toggleSubscribe = (target, options) => { }; ko.extenders.toggleSubscribeProperty = (target, options) => { - const prop = options[1]; - if (prop) - { - target.subscribe((prev) => { - if (prev && prev[prop]) - { - prev[prop](false); - } - }, options[0], 'beforeChange'); + if (prop) { + target.subscribe( + (prev) => { + if (prev && prev[prop]) { + prev[prop](false); + } + }, + options[0], + 'beforeChange' + ); target.subscribe((next) => { - if (next && next[prop]) - { + if (next && next[prop]) { next[prop](true); } }, options[0]); @@ -1138,8 +1048,7 @@ ko.extenders.toggleSubscribeProperty = (target, options) => { ko.extenders.falseTimeout = (target, option) => { target.iFalseTimeoutTimeout = 0; target.subscribe((value) => { - if (value) - { + if (value) { window.clearTimeout(target.iFalseTimeoutTimeout); target.iFalseTimeoutTimeout = window.setTimeout(() => { target(false); @@ -1153,31 +1062,23 @@ ko.extenders.falseTimeout = (target, option) => { ko.extenders.specialThrottle = (target, option) => { target.iSpecialThrottleTimeoutValue = require('Common/Utils').pInt(option); - if (0 < target.iSpecialThrottleTimeoutValue) - { + if (0 < target.iSpecialThrottleTimeoutValue) { target.iSpecialThrottleTimeout = 0; - target.valueForRead = ko.observable(!!target()).extend({throttle: 10}); + target.valueForRead = ko.observable(!!target()).extend({ throttle: 10 }); return ko.computed({ read: target.valueForRead, write: (bValue) => { - - if (bValue) - { + if (bValue) { target.valueForRead(bValue); - } - else - { - if (target.valueForRead()) - { + } else { + if (target.valueForRead()) { window.clearTimeout(target.iSpecialThrottleTimeout); target.iSpecialThrottleTimeout = window.setTimeout(() => { target.valueForRead(false); target.iSpecialThrottleTimeout = 0; }, target.iSpecialThrottleTimeoutValue); - } - else - { + } else { target.valueForRead(bValue); } } @@ -1196,7 +1097,7 @@ ko.extenders.idleTrigger = (target) => { // functions ko.observable.fn.idleTrigger = function() { - return this.extend({'idleTrigger': true}); + return this.extend({ 'idleTrigger': true }); }; ko.observable.fn.validateNone = function() { @@ -1205,11 +1106,10 @@ ko.observable.fn.validateNone = function() { }; ko.observable.fn.validateEmail = function() { - this.hasError = ko.observable(false); this.subscribe((value) => { - this.hasError('' !== value && !((/^[^@\s]+@[^@\s]+$/).test(value))); + this.hasError('' !== value && !/^[^@\s]+@[^@\s]+$/.test(value)); }); this.valueHasMutated(); @@ -1217,11 +1117,10 @@ ko.observable.fn.validateEmail = function() { }; ko.observable.fn.validateSimpleEmail = function() { - this.hasError = ko.observable(false); this.subscribe((value) => { - this.hasError('' !== value && !((/^.+@.+$/).test(value))); + this.hasError('' !== value && !/^.+@.+$/.test(value)); }); this.valueHasMutated(); @@ -1229,16 +1128,14 @@ ko.observable.fn.validateSimpleEmail = function() { }; ko.observable.fn.deleteAccessHelper = function() { - this.extend({falseTimeout: 3000}).extend({toggleSubscribeProperty: [this, 'deleteAccess']}); + this.extend({ falseTimeout: 3000 }).extend({ toggleSubscribeProperty: [this, 'deleteAccess'] }); return this; }; ko.observable.fn.validateFunc = function(fFunc) { - this.hasFuncError = ko.observable(false); - if (_.isFunction(fFunc)) - { + if (_.isFunction(fFunc)) { this.subscribe((value) => { this.hasFuncError(!fFunc(value)); }); diff --git a/dev/Helper/Apps/Admin.js b/dev/Helper/Apps/Admin.js index 81e807e30..c5c5c5963 100644 --- a/dev/Helper/Apps/Admin.js +++ b/dev/Helper/Apps/Admin.js @@ -1,4 +1,3 @@ - /** * @returns {AppAdmin} */ diff --git a/dev/Helper/Apps/User.js b/dev/Helper/Apps/User.js index 7ace1c022..760bf44f6 100644 --- a/dev/Helper/Apps/User.js +++ b/dev/Helper/Apps/User.js @@ -1,4 +1,3 @@ - /** * @returns {AppUser} */ diff --git a/dev/Helper/Message.js b/dev/Helper/Message.js index 375b75bf9..0c1f6dead 100644 --- a/dev/Helper/Message.js +++ b/dev/Helper/Message.js @@ -1,6 +1,5 @@ - -import {isNonEmptyArray, isUnd} from 'Common/Utils'; -import {EmailModel} from 'Model/Email'; +import { isNonEmptyArray, isUnd } from 'Common/Utils'; +import { EmailModel } from 'Model/Email'; /** * @param {Array. } emails @@ -9,15 +8,12 @@ import {EmailModel} from 'Model/Email'; * @returns {string} */ export function emailArrayToString(emails, friendlyView = false, wrapWithLink = false) { - let - index = 0, + let index = 0, len = 0; const result = []; - if (isNonEmptyArray(emails)) - { - for (len = emails.length; index < len; index++) - { + if (isNonEmptyArray(emails)) { + for (len = emails.length; index < len; index++) { result.push(emails[index].toLine(friendlyView, wrapWithLink)); } } @@ -30,17 +26,13 @@ export function emailArrayToString(emails, friendlyView = false, wrapWithLink = * @returns {string} */ export function emailArrayToStringClear(emails) { - let - index = 0, + let index = 0, len = 0; const result = []; - if (isNonEmptyArray(emails)) - { - for (len = emails.length; index < len; index++) - { - if (emails[index] && emails[index].email && '' !== emails[index].name) - { + if (isNonEmptyArray(emails)) { + for (len = emails.length; index < len; index++) { + if (emails[index] && emails[index].email && '' !== emails[index].name) { result.push(emails[index].email); } } @@ -54,19 +46,15 @@ export function emailArrayToStringClear(emails) { * @returns {Array. } */ export function emailArrayFromJson(json) { - let - index = 0, + let index = 0, len = 0, email = null; const result = []; - if (isNonEmptyArray(json)) - { - for (index = 0, len = json.length; index < len; index++) - { + if (isNonEmptyArray(json)) { + for (index = 0, len = json.length; index < len; index++) { email = EmailModel.newInstanceFromJson(json[index]); - if (email) - { + if (email) { result.push(email); } } @@ -81,16 +69,12 @@ export function emailArrayFromJson(json) { * @param {Array} localEmails */ export function replyHelper(inputEmails, unic, localEmails) { - - if (inputEmails && 0 < inputEmails.length) - { + if (inputEmails && 0 < inputEmails.length) { let index = 0; const len = inputEmails.length; - for (; index < len; index++) - { - if (isUnd(unic[inputEmails[index].email])) - { + for (; index < len; index++) { + if (isUnd(unic[inputEmails[index].email])) { unic[inputEmails[index].email] = true; localEmails.push(inputEmails[index]); } diff --git a/dev/Knoin/AbstractBoot.js b/dev/Knoin/AbstractBoot.js index 6b6c37e89..04ee85db9 100644 --- a/dev/Knoin/AbstractBoot.js +++ b/dev/Knoin/AbstractBoot.js @@ -1,5 +1,5 @@ - -export class AbstractBoot -{ - bootstart() {/* no-empty */} +export class AbstractBoot { + bootstart() { + /* no-empty */ + } } diff --git a/dev/Knoin/AbstractModel.js b/dev/Knoin/AbstractModel.js index 57372c4d6..1ed79a667 100644 --- a/dev/Knoin/AbstractModel.js +++ b/dev/Knoin/AbstractModel.js @@ -1,33 +1,27 @@ +import { isArray, disposeObject } from 'Common/Utils'; -import {isArray, disposeObject} from 'Common/Utils'; - -export class AbstractModel -{ +export class AbstractModel { sModelName = ''; disposables = []; /** * @param {string} modelName = '' */ - constructor(modelName = '') - { + constructor(modelName = '') { this.sModelName = modelName || ''; } regDisposables(value) { - if (isArray(value)) - { + if (isArray(value)) { value.forEach((item) => { this.disposables.push(item); }); - } - else if (value) - { + } else if (value) { this.disposables.push(value); } } - onDestroy() { + onDestroy() { disposeObject(this); } } diff --git a/dev/Knoin/AbstractScreen.js b/dev/Knoin/AbstractScreen.js index 5d6896741..500690426 100644 --- a/dev/Knoin/AbstractScreen.js +++ b/dev/Knoin/AbstractScreen.js @@ -1,16 +1,13 @@ - import _ from '_'; import crossroads from 'crossroads'; -import {isArray, isNonEmptyArray, noop} from 'Common/Utils'; +import { isArray, isNonEmptyArray, noop } from 'Common/Utils'; -export class AbstractScreen -{ +export class AbstractScreen { oCross = null; sScreenName; aViewModels; - constructor(screenName, viewModels = []) - { + constructor(screenName, viewModels = []) { this.sScreenName = screenName; this.aViewModels = isArray(viewModels) ? viewModels : []; } @@ -47,19 +44,16 @@ export class AbstractScreen * @returns {void} */ __start() { - let - route = null, + let route = null, fMatcher = null; const routes = this.routes(); - if (isNonEmptyArray(routes)) - { + if (isNonEmptyArray(routes)) { fMatcher = _.bind(this.onRoute || noop, this); route = crossroads.create(); routes.forEach((item) => { - if (item && route) - { + if (item && route) { route.addRoute(item[0], fMatcher).rules = item[1]; } }); diff --git a/dev/Knoin/AbstractViewNext.js b/dev/Knoin/AbstractViewNext.js index 13ecf6617..228acb05b 100644 --- a/dev/Knoin/AbstractViewNext.js +++ b/dev/Knoin/AbstractViewNext.js @@ -1,18 +1,16 @@ - import ko from 'ko'; -import {delegateRun, inFocus} from 'Common/Utils'; -import {KeyState, EventKeyCode} from 'Common/Enums'; -import {$win, keyScope} from 'Common/Globals'; +import { delegateRun, inFocus } from 'Common/Utils'; +import { KeyState, EventKeyCode } from 'Common/Enums'; +import { $win, keyScope } from 'Common/Globals'; -export class AbstractViewNext -{ +export class AbstractViewNext { bDisabeCloseOnEsc = false; sDefaultKeyScope = KeyState.None; sCurrentKeyScope = KeyState.None; viewModelVisibility = ko.observable(false); - modalVisibility = ko.observable(false).extend({rateLimit: 0}); + modalVisibility = ko.observable(false).extend({ rateLimit: 0 }); viewModelName = ''; viewModelNames = []; @@ -38,15 +36,11 @@ export class AbstractViewNext */ registerPopupKeyDown() { $win.on('keydown', (event) => { - if (event && this.modalVisibility && this.modalVisibility()) - { - if (!this.bDisabeCloseOnEsc && EventKeyCode.Esc === event.keyCode) - { + if (event && this.modalVisibility && this.modalVisibility()) { + if (!this.bDisabeCloseOnEsc && EventKeyCode.Esc === event.keyCode) { delegateRun(this, 'cancelCommand'); return false; - } - else if (EventKeyCode.Backspace === event.keyCode && !inFocus()) - { + } else if (EventKeyCode.Backspace === event.keyCode && !inFocus()) { return false; } } diff --git a/dev/Knoin/Knoin.js b/dev/Knoin/Knoin.js index 50faffdd6..80491bbc6 100644 --- a/dev/Knoin/Knoin.js +++ b/dev/Knoin/Knoin.js @@ -1,21 +1,16 @@ - import _ from '_'; import $ from '$'; import ko from 'ko'; import hasher from 'hasher'; import crossroads from 'crossroads'; -import {Magics} from 'Common/Enums'; -import {runHook} from 'Common/Plugins'; -import {$html, VIEW_MODELS, popupVisibilityNames} from 'Common/Globals'; +import { Magics } from 'Common/Enums'; +import { runHook } from 'Common/Plugins'; +import { $html, VIEW_MODELS, popupVisibilityNames } from 'Common/Globals'; -import { - isArray, isUnd, pString, log, isFunc, - createCommandLegacy, delegateRun, isNonEmptyArray -} from 'Common/Utils'; +import { isArray, isUnd, pString, log, isFunc, createCommandLegacy, delegateRun, isNonEmptyArray } from 'Common/Utils'; -let - currentScreen = null, +let currentScreen = null, defaultScreenName = ''; const SCREENS = {}; @@ -30,10 +25,11 @@ export const ViewType = { /** * @returns {void} */ -export function hideLoading() -{ +export function hideLoading() { $('#rl-content').addClass('rl-content-show'); - $('#rl-loading').hide().remove(); + $('#rl-loading') + .hide() + .remove(); } /** @@ -41,8 +37,7 @@ export function hideLoading() * @param {(Function|boolean|null)=} fCanExecute = true * @returns {Function} */ -export function createCommand(fExecute, fCanExecute = true) -{ +export function createCommand(fExecute, fCanExecute = true) { return createCommandLegacy(null, fExecute, fCanExecute); } @@ -54,8 +49,7 @@ export function createCommand(fExecute, fCanExecute = true) * @param {boolean=} isDefault = false * @returns {void} */ -export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route, isDefault = false) -{ +export function addSettingsViewModel(SettingsViewModelClass, template, labelName, route, isDefault = false) { SettingsViewModelClass.__rlSettingsData = { Label: labelName, Template: template, @@ -70,8 +64,7 @@ export function addSettingsViewModel(SettingsViewModelClass, template, labelName * @param {Function} SettingsViewModelClass * @returns {void} */ -export function removeSettingsViewModel(SettingsViewModelClass) -{ +export function removeSettingsViewModel(SettingsViewModelClass) { VIEW_MODELS['settings-removed'].push(SettingsViewModelClass); } @@ -79,24 +72,21 @@ export function removeSettingsViewModel(SettingsViewModelClass) * @param {Function} SettingsViewModelClass * @returns {void} */ -export function disableSettingsViewModel(SettingsViewModelClass) -{ +export function disableSettingsViewModel(SettingsViewModelClass) { VIEW_MODELS['settings-disabled'].push(SettingsViewModelClass); } /** * @returns {void} */ -export function routeOff() -{ +export function routeOff() { hasher.changed.active = false; } /** * @returns {void} */ -export function routeOn() -{ +export function routeOn() { hasher.changed.active = true; } @@ -104,23 +94,19 @@ export function routeOn() * @param {string} screenName * @returns {?Object} */ -export function screen(screenName) -{ - return ('' !== screenName && !isUnd(SCREENS[screenName])) ? SCREENS[screenName] : null; +export function screen(screenName) { + return '' !== screenName && !isUnd(SCREENS[screenName]) ? SCREENS[screenName] : null; } /** * @param {Function} ViewModelClassToShow * @returns {Function|null} */ -export function getScreenPopup(PopuViewModelClass) -{ +export function getScreenPopup(PopuViewModelClass) { let result = null; - if (PopuViewModelClass) - { + if (PopuViewModelClass) { result = PopuViewModelClass; - if (PopuViewModelClass.default) - { + if (PopuViewModelClass.default) { result = PopuViewModelClass.default; } } @@ -132,11 +118,9 @@ export function getScreenPopup(PopuViewModelClass) * @param {Function} ViewModelClassToHide * @returns {void} */ -export function hideScreenPopup(ViewModelClassToHide) -{ +export function hideScreenPopup(ViewModelClassToHide) { const ModalView = getScreenPopup(ViewModelClassToHide); - if (ModalView && ModalView.__vm && ModalView.__dom) - { + if (ModalView && ModalView.__vm && ModalView.__dom) { ModalView.__vm.modalVisibility(false); } } @@ -146,8 +130,7 @@ export function hideScreenPopup(ViewModelClassToHide) * @param {Function} ViewModelClass * @param {mixed=} params = null */ -export function vmRunHook(hookName, ViewModelClass, params = null) -{ +export function vmRunHook(hookName, ViewModelClass, params = null) { _.each(ViewModelClass.__names, (name) => { runHook(hookName, [name, ViewModelClass.__vm, params]); }); @@ -158,13 +141,10 @@ export function vmRunHook(hookName, ViewModelClass, params = null) * @param {Object=} vmScreen * @returns {*} */ -export function buildViewModel(ViewModelClass, vmScreen) -{ - if (ViewModelClass && !ViewModelClass.__builded) - { +export function buildViewModel(ViewModelClass, vmScreen) { + if (ViewModelClass && !ViewModelClass.__builded) { let vmDom = null; - const - vm = new ViewModelClass(vmScreen), + const vm = new ViewModelClass(vmScreen), position = ViewModelClass.__type || '', vmPlace = position ? $('#rl-content #rl-' + position.toLowerCase()) : null; @@ -179,43 +159,39 @@ export function buildViewModel(ViewModelClass, vmScreen) vm.viewModelTemplateID = ViewModelClass.__templateID; vm.viewModelPosition = ViewModelClass.__type; - if (vmPlace && 1 === vmPlace.length) - { - vmDom = $('').addClass('rl-view-model').addClass('RL-' + vm.viewModelTemplateID).hide(); + if (vmPlace && 1 === vmPlace.length) { + vmDom = $('') + .addClass('rl-view-model') + .addClass('RL-' + vm.viewModelTemplateID) + .hide(); vmDom.appendTo(vmPlace); vm.viewModelDom = vmDom; ViewModelClass.__dom = vmDom; - if (ViewType.Popup === position) - { + if (ViewType.Popup === position) { vm.cancelCommand = vm.closeCommand = createCommand(() => { hideScreenPopup(ViewModelClass); }); vm.modalVisibility.subscribe((value) => { - if (value) - { + if (value) { vm.viewModelDom.show(); vm.storeAndSetKeyScope(); popupVisibilityNames.push(vm.viewModelName); vm.viewModelDom.css('z-index', 3000 + popupVisibilityNames().length + 10); - if (vm.onShowTrigger) - { + if (vm.onShowTrigger) { vm.onShowTrigger(!vm.onShowTrigger()); } delegateRun(vm, 'onShowWithDelay', [], 500); - } - else - { + } else { delegateRun(vm, 'onHide'); delegateRun(vm, 'onHideWithDelay', [], 500); - if (vm.onHideTrigger) - { + if (vm.onHideTrigger) { vm.onHideTrigger(!vm.onHideTrigger()); } @@ -233,21 +209,22 @@ export function buildViewModel(ViewModelClass, vmScreen) vmRunHook('view-model-pre-build', ViewModelClass, vmDom); - ko.applyBindingAccessorsToNode(vmDom[0], { - translatorInit: true, - template: () => ({name: vm.viewModelTemplateID}) - }, vm); + ko.applyBindingAccessorsToNode( + vmDom[0], + { + translatorInit: true, + template: () => ({ name: vm.viewModelTemplateID }) + }, + vm + ); delegateRun(vm, 'onBuild', [vmDom]); - if (vm && ViewType.Popup === position) - { + if (vm && ViewType.Popup === position) { vm.registerPopupKeyDown(); } vmRunHook('view-model-post-build', ViewModelClass, vmDom); - } - else - { + } else { log('Cannot find view model position: ' + position); } } @@ -260,15 +237,12 @@ export function buildViewModel(ViewModelClass, vmScreen) * @param {Array=} params * @returns {void} */ -export function showScreenPopup(ViewModelClassToShow, params = []) -{ +export function showScreenPopup(ViewModelClassToShow, params = []) { const ModalView = getScreenPopup(ViewModelClassToShow); - if (ModalView) - { + if (ModalView) { buildViewModel(ModalView); - if (ModalView.__vm && ModalView.__dom) - { + if (ModalView.__vm && ModalView.__dom) { delegateRun(ModalView.__vm, 'onBeforeShow', params || []); ModalView.__vm.modalVisibility(true); @@ -284,15 +258,12 @@ export function showScreenPopup(ViewModelClassToShow, params = []) * @param {Function} ViewModelClassToShow * @returns {void} */ -export function warmUpScreenPopup(ViewModelClassToShow) -{ +export function warmUpScreenPopup(ViewModelClassToShow) { const ModalView = getScreenPopup(ViewModelClassToShow); - if (ModalView) - { + if (ModalView) { buildViewModel(ModalView); - if (ModalView.__vm && ModalView.__dom) - { + if (ModalView.__vm && ModalView.__dom) { delegateRun(ModalView.__vm, 'onWarmUp'); } } @@ -302,8 +273,7 @@ export function warmUpScreenPopup(ViewModelClassToShow) * @param {Function} ViewModelClassToShow * @returns {boolean} */ -export function isPopupVisible(ViewModelClassToShow) -{ +export function isPopupVisible(ViewModelClassToShow) { const ModalView = getScreenPopup(ViewModelClassToShow); return ModalView && ModalView.__vm ? ModalView.__vm.modalVisibility() : false; } @@ -313,41 +283,32 @@ export function isPopupVisible(ViewModelClassToShow) * @param {string} subPart * @returns {void} */ -export function screenOnRoute(screenName, subPart) -{ - let - vmScreen = null, +export function screenOnRoute(screenName, subPart) { + let vmScreen = null, isSameScreen = false, cross = null; - if ('' === pString(screenName)) - { + if ('' === pString(screenName)) { screenName = defaultScreenName; } - if ('' !== screenName) - { + if ('' !== screenName) { vmScreen = screen(screenName); - if (!vmScreen) - { + if (!vmScreen) { vmScreen = screen(defaultScreenName); - if (vmScreen) - { + if (vmScreen) { subPart = screenName + '/' + subPart; screenName = defaultScreenName; } } - if (vmScreen && vmScreen.__started) - { + if (vmScreen && vmScreen.__started) { isSameScreen = currentScreen && vmScreen === currentScreen; - if (!vmScreen.__builded) - { + if (!vmScreen.__builded) { vmScreen.__builded = true; - if (isNonEmptyArray(vmScreen.viewModels())) - { + if (isNonEmptyArray(vmScreen.viewModels())) { _.each(vmScreen.viewModels(), (ViewModelClass) => { buildViewModel(ViewModelClass, vmScreen); }); @@ -358,29 +319,28 @@ export function screenOnRoute(screenName, subPart) _.defer(() => { // hide screen - if (currentScreen && !isSameScreen) - { + if (currentScreen && !isSameScreen) { delegateRun(currentScreen, 'onHide'); delegateRun(currentScreen, 'onHideWithDelay', [], 500); - if (currentScreen.onHideTrigger) - { + if (currentScreen.onHideTrigger) { currentScreen.onHideTrigger(!currentScreen.onHideTrigger()); } - if (isNonEmptyArray(currentScreen.viewModels())) - { + if (isNonEmptyArray(currentScreen.viewModels())) { _.each(currentScreen.viewModels(), (ViewModelClass) => { - if (ViewModelClass.__vm && ViewModelClass.__dom && ViewType.Popup !== ViewModelClass.__vm.viewModelPosition) - { + if ( + ViewModelClass.__vm && + ViewModelClass.__dom && + ViewType.Popup !== ViewModelClass.__vm.viewModelPosition + ) { ViewModelClass.__dom.hide(); ViewModelClass.__vm.viewModelVisibility(false); delegateRun(ViewModelClass.__vm, 'onHide'); delegateRun(ViewModelClass.__vm, 'onHideWithDelay', [], 500); - if (ViewModelClass.__vm.onHideTrigger) - { + if (ViewModelClass.__vm.onHideTrigger) { ViewModelClass.__vm.onHideTrigger(!ViewModelClass.__vm.onHideTrigger()); } } @@ -392,45 +352,41 @@ export function screenOnRoute(screenName, subPart) currentScreen = vmScreen; // show screen - if (currentScreen && !isSameScreen) - { + if (currentScreen && !isSameScreen) { delegateRun(currentScreen, 'onShow'); - if (currentScreen.onShowTrigger) - { + if (currentScreen.onShowTrigger) { currentScreen.onShowTrigger(!currentScreen.onShowTrigger()); } runHook('screen-on-show', [currentScreen.screenName(), currentScreen]); - if (isNonEmptyArray(currentScreen.viewModels())) - { + if (isNonEmptyArray(currentScreen.viewModels())) { _.each(currentScreen.viewModels(), (ViewModelClass) => { - - if (ViewModelClass.__vm && ViewModelClass.__dom && ViewType.Popup !== ViewModelClass.__vm.viewModelPosition) - { + if ( + ViewModelClass.__vm && + ViewModelClass.__dom && + ViewType.Popup !== ViewModelClass.__vm.viewModelPosition + ) { delegateRun(ViewModelClass.__vm, 'onBeforeShow'); ViewModelClass.__dom.show(); ViewModelClass.__vm.viewModelVisibility(true); delegateRun(ViewModelClass.__vm, 'onShow'); - if (ViewModelClass.__vm.onShowTrigger) - { + if (ViewModelClass.__vm.onShowTrigger) { ViewModelClass.__vm.onShowTrigger(!ViewModelClass.__vm.onShowTrigger()); } delegateRun(ViewModelClass.__vm, 'onShowWithDelay', [], 200); vmRunHook('view-model-on-show', ViewModelClass); } - }); } } // -- cross = vmScreen && vmScreen.__cross ? vmScreen.__cross() : null; - if (cross) - { + if (cross) { cross.parse(subPart); } }); @@ -442,19 +398,14 @@ export function screenOnRoute(screenName, subPart) * @param {Array} screensClasses * @returns {void} */ -export function startScreens(screensClasses) -{ +export function startScreens(screensClasses) { _.each(screensClasses, (CScreen) => { - if (CScreen) - { - const - vmScreen = new CScreen(), + if (CScreen) { + const vmScreen = new CScreen(), screenName = vmScreen ? vmScreen.screenName() : ''; - if (vmScreen && '' !== screenName) - { - if ('' === defaultScreenName) - { + if (vmScreen && '' !== screenName) { + if ('' === defaultScreenName) { defaultScreenName = screenName; } @@ -464,8 +415,7 @@ export function startScreens(screensClasses) }); _.each(SCREENS, (vmScreen) => { - if (vmScreen && !vmScreen.__started && vmScreen.__start) - { + if (vmScreen && !vmScreen.__started && vmScreen.__start) { vmScreen.__started = true; vmScreen.__start(); @@ -476,7 +426,7 @@ export function startScreens(screensClasses) }); const cross = crossroads.create(); - cross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, screenOnRoute); + cross.addRoute(/^([a-zA-Z0-9-]*)\/?(.*)$/, screenOnRoute); hasher.initialized.add(cross.parse, cross); hasher.changed.add(cross.parse, cross); @@ -492,21 +442,17 @@ export function startScreens(screensClasses) * @param {boolean=} replace = false * @returns {void} */ -export function setHash(hash, silence = false, replace = false) -{ +export function setHash(hash, silence = false, replace = false) { hash = '#' === hash.substr(0, 1) ? hash.substr(1) : hash; hash = '/' === hash.substr(0, 1) ? hash.substr(1) : hash; const cmd = replace ? 'replaceHash' : 'setHash'; - if (silence) - { + if (silence) { hasher.changed.active = false; hasher[cmd](hash); hasher.changed.active = true; - } - else - { + } else { hasher.changed.active = true; hasher[cmd](hash); hasher.setHash(hash); @@ -517,32 +463,24 @@ export function setHash(hash, silence = false, replace = false) * @param {Object} params * @returns {Function} */ -function viewDecorator({name, type, templateID}) -{ +function viewDecorator({ name, type, templateID }) { return (target) => { - if (target) - { - if (name) - { - if (isArray(name)) - { + if (target) { + if (name) { + if (isArray(name)) { target.__names = name; - } - else - { + } else { target.__names = [name]; } target.__name = target.__names[0]; } - if (type) - { + if (type) { target.__type = type; } - if (templateID) - { + if (templateID) { target.__templateID = templateID; } } @@ -553,31 +491,25 @@ function viewDecorator({name, type, templateID}) * @param {Object} params * @returns {Function} */ -function popupDecorator({name, templateID}) -{ - return viewDecorator({name, type: ViewType.Popup, templateID}); +function popupDecorator({ name, templateID }) { + return viewDecorator({ name, type: ViewType.Popup, templateID }); } /** * @param {Function} canExecute * @returns {Function} */ -function commandDecorator(canExecute = true) -{ +function commandDecorator(canExecute = true) { return (target, key, descriptor) => { - - if (!key || !key.match(/Command$/)) - { + if (!key || !key.match(/Command$/)) { throw new Error(`name "${key}" should end with Command suffix`); } - const - value = descriptor.value || descriptor.initializer(), + const value = descriptor.value || descriptor.initializer(), normCanExecute = isFunc(canExecute) ? canExecute : () => !!canExecute; descriptor.value = function(...args) { - if (normCanExecute.call(this, this)) - { + if (normCanExecute.call(this, this)) { value.apply(this, args); } @@ -595,37 +527,33 @@ function commandDecorator(canExecute = true) * @param {miced} $items * @returns {Function} */ -function settingsMenuKeysHandler($items) -{ +function settingsMenuKeysHandler($items) { return _.throttle((event, handler) => { - const up = handler && 'up' === handler.shortcut; - if (event && $items.length) - { + if (event && $items.length) { let index = $items.index($items.filter('.selected')); - if (up && 0 < index) - { + if (up && 0 < index) { index -= 1; - } - else if (!up && index < $items.length - 1) - { + } else if (!up && index < $items.length - 1) { index += 1; } const resultHash = $items.eq(index).attr('href'); - if (resultHash) - { + if (resultHash) { setHash(resultHash, false, true); } } - }, Magics.Time200ms); } export { - commandDecorator, commandDecorator as command, - viewDecorator, viewDecorator as view, viewDecorator as viewModel, - popupDecorator, popupDecorator as popup, + commandDecorator, + commandDecorator as command, + viewDecorator, + viewDecorator as view, + viewDecorator as viewModel, + popupDecorator, + popupDecorator as popup, settingsMenuKeysHandler }; diff --git a/dev/Model/Account.js b/dev/Model/Account.js index 787b319d4..35ba27906 100644 --- a/dev/Model/Account.js +++ b/dev/Model/Account.js @@ -1,19 +1,16 @@ - import ko from 'ko'; -import {change} from 'Common/Links'; +import { change } from 'Common/Links'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class AccountModel extends AbstractModel -{ +class AccountModel extends AbstractModel { /** * @param {string} email * @param {boolean=} canBeDelete = true * @param {number=} count = 0 */ - constructor(email, canBeDelete = true, count = 0) - { + constructor(email, canBeDelete = true, count = 0) { super('AccountModel'); this.email = email; @@ -33,4 +30,4 @@ class AccountModel extends AbstractModel } } -export {AccountModel, AccountModel as default}; +export { AccountModel, AccountModel as default }; diff --git a/dev/Model/Attachment.js b/dev/Model/Attachment.js index d9059c64c..0685bd624 100644 --- a/dev/Model/Attachment.js +++ b/dev/Model/Attachment.js @@ -1,14 +1,19 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; -import {FileType} from 'Common/Enums'; -import {bAllowPdfPreview, data as GlobalsData} from 'Common/Globals'; -import {trim, pInt, inArray, isNonEmptyArray, getFileExtension, friendlySize} from 'Common/Utils'; -import {attachmentDownload, attachmentPreview, attachmentFramed, attachmentPreviewAsPlain, attachmentThumbnailPreview} from 'Common/Links'; +import { FileType } from 'Common/Enums'; +import { bAllowPdfPreview, data as GlobalsData } from 'Common/Globals'; +import { trim, pInt, inArray, isNonEmptyArray, getFileExtension, friendlySize } from 'Common/Utils'; +import { + attachmentDownload, + attachmentPreview, + attachmentFramed, + attachmentPreviewAsPlain, + attachmentThumbnailPreview +} from 'Common/Links'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; import Audio from 'Common/Audio'; @@ -24,90 +29,99 @@ export const staticFileType = _.memoize((ext, mimeType) => { let result = FileType.Unknown; const mimeTypeParts = mimeType.split('/'); - switch (true) - { - case 'image' === mimeTypeParts[0] || -1 < inArray(ext, [ - 'png', 'jpg', 'jpeg', 'gif', 'bmp' - ]): + switch (true) { + case 'image' === mimeTypeParts[0] || -1 < inArray(ext, ['png', 'jpg', 'jpeg', 'gif', 'bmp']): result = FileType.Image; break; - case 'audio' === mimeTypeParts[0] || -1 < inArray(ext, [ - 'mp3', 'ogg', 'oga', 'wav' - ]): + case 'audio' === mimeTypeParts[0] || -1 < inArray(ext, ['mp3', 'ogg', 'oga', 'wav']): result = FileType.Audio; break; - case 'video' === mimeTypeParts[0] || -1 < inArray(ext, [ - 'mkv', 'avi' - ]): + case 'video' === mimeTypeParts[0] || -1 < inArray(ext, ['mkv', 'avi']): result = FileType.Video; break; - case -1 < inArray(ext, [ - 'php', 'js', 'css' - ]): + case -1 < inArray(ext, ['php', 'js', 'css']): result = FileType.Code; break; - case 'eml' === ext || -1 < inArray(mimeType, [ - 'message/delivery-status', 'message/rfc822' - ]): + case 'eml' === ext || -1 < inArray(mimeType, ['message/delivery-status', 'message/rfc822']): result = FileType.Eml; break; - case ('text' === mimeTypeParts[0] && 'html' !== mimeTypeParts[1]) || -1 < inArray(ext, [ - 'txt', 'log' - ]): + case ('text' === mimeTypeParts[0] && 'html' !== mimeTypeParts[1]) || -1 < inArray(ext, ['txt', 'log']): result = FileType.Text; break; - case ('text/html' === mimeType) || -1 < inArray(ext, [ - 'html' - ]): + case 'text/html' === mimeType || -1 < inArray(ext, ['html']): result = FileType.Html; break; - case -1 < inArray(mimeTypeParts[1], [ - 'zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed' - ]) || -1 < inArray(ext, ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2']): + case -1 < + inArray(mimeTypeParts[1], [ + 'zip', + '7z', + 'tar', + 'rar', + 'gzip', + 'bzip', + 'bzip2', + 'x-zip', + 'x-7z', + 'x-rar', + 'x-tar', + 'x-gzip', + 'x-bzip', + 'x-bzip2', + 'x-zip-compressed', + 'x-7z-compressed', + 'x-rar-compressed' + ]) || -1 < inArray(ext, ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2']): result = FileType.Archive; break; case -1 < inArray(mimeTypeParts[1], ['pdf', 'x-pdf']) || -1 < inArray(ext, ['pdf']): result = FileType.Pdf; break; - case -1 < inArray(mimeType, [ - 'application/pgp-signature', 'application/pgp-keys' - ]) || -1 < inArray(ext, ['asc', 'pem', 'ppk']): + case -1 < inArray(mimeType, ['application/pgp-signature', 'application/pgp-keys']) || + -1 < inArray(ext, ['asc', 'pem', 'ppk']): result = FileType.Certificate; break; - case -1 < inArray(mimeType, ['application/pkcs7-signature']) || - -1 < inArray(ext, ['p7s']): - + case -1 < inArray(mimeType, ['application/pkcs7-signature']) || -1 < inArray(ext, ['p7s']): result = FileType.CertificateBin; break; - case -1 < inArray(mimeTypeParts[1], [ - 'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document', - 'vnd.openxmlformats-officedocument.wordprocessingml.template', - 'vnd.ms-word.document.macroEnabled.12', - 'vnd.ms-word.template.macroEnabled.12' - ]): + case -1 < + inArray(mimeTypeParts[1], [ + 'rtf', + 'msword', + 'vnd.msword', + 'vnd.openxmlformats-officedocument.wordprocessingml.document', + 'vnd.openxmlformats-officedocument.wordprocessingml.template', + 'vnd.ms-word.document.macroEnabled.12', + 'vnd.ms-word.template.macroEnabled.12' + ]): result = FileType.WordText; break; - case -1 < inArray(mimeTypeParts[1], [ - 'excel', 'ms-excel', 'vnd.ms-excel', - 'vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'vnd.openxmlformats-officedocument.spreadsheetml.template', - 'vnd.ms-excel.sheet.macroEnabled.12', - 'vnd.ms-excel.template.macroEnabled.12', - 'vnd.ms-excel.addin.macroEnabled.12', - 'vnd.ms-excel.sheet.binary.macroEnabled.12' - ]): + case -1 < + inArray(mimeTypeParts[1], [ + 'excel', + 'ms-excel', + 'vnd.ms-excel', + 'vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'vnd.openxmlformats-officedocument.spreadsheetml.template', + 'vnd.ms-excel.sheet.macroEnabled.12', + 'vnd.ms-excel.template.macroEnabled.12', + 'vnd.ms-excel.addin.macroEnabled.12', + 'vnd.ms-excel.sheet.binary.macroEnabled.12' + ]): result = FileType.Sheet; break; - case -1 < inArray(mimeTypeParts[1], [ - 'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint', - 'vnd.openxmlformats-officedocument.presentationml.presentation', - 'vnd.openxmlformats-officedocument.presentationml.template', - 'vnd.openxmlformats-officedocument.presentationml.slideshow', - 'vnd.ms-powerpoint.addin.macroEnabled.12', - 'vnd.ms-powerpoint.presentation.macroEnabled.12', - 'vnd.ms-powerpoint.template.macroEnabled.12', - 'vnd.ms-powerpoint.slideshow.macroEnabled.12' - ]): + case -1 < + inArray(mimeTypeParts[1], [ + 'powerpoint', + 'ms-powerpoint', + 'vnd.ms-powerpoint', + 'vnd.openxmlformats-officedocument.presentationml.presentation', + 'vnd.openxmlformats-officedocument.presentationml.template', + 'vnd.openxmlformats-officedocument.presentationml.slideshow', + 'vnd.ms-powerpoint.addin.macroEnabled.12', + 'vnd.ms-powerpoint.presentation.macroEnabled.12', + 'vnd.ms-powerpoint.template.macroEnabled.12', + 'vnd.ms-powerpoint.slideshow.macroEnabled.12' + ]): result = FileType.Presentation; break; // no default @@ -121,12 +135,10 @@ export const staticFileType = _.memoize((ext, mimeType) => { * @returns {string} */ export const staticIconClass = _.memoize((fileType) => { - let - resultText = '', + let resultText = '', resultClass = 'icon-file'; - switch (fileType) - { + switch (fileType) { case FileType.Text: case FileType.Eml: case FileType.WordText: @@ -174,19 +186,15 @@ export const staticIconClass = _.memoize((fileType) => { * @returns {string} */ export const staticCombinedIconClass = (data) => { - let - result = '', + let result = '', types = []; - if (isNonEmptyArray(data)) - { + if (isNonEmptyArray(data)) { result = 'icon-attachment'; types = _.uniq(_.compact(_.map(data, (item) => (item ? staticFileType(getFileExtension(item[0]), item[1]) : '')))); - if (types && 1 === types.length && types[0]) - { - switch (types[0]) - { + if (types && 1 === types.length && types[0]) { + switch (types[0]) { case FileType.Text: case FileType.WordText: result = 'icon-file-text'; @@ -225,8 +233,7 @@ export const staticCombinedIconClass = (data) => { return result; }; -class AttachmentModel extends AbstractModel -{ +class AttachmentModel extends AbstractModel { constructor() { super('AttachmentModel'); @@ -267,8 +274,7 @@ class AttachmentModel extends AbstractModel */ initByJson(json) { let bResult = false; - if (json && 'Object/Attachment' === json['@Object']) - { + if (json && 'Object/Attachment' === json['@Object']) { this.mimeType = trim((json.MimeType || '').toLowerCase()); this.fileName = trim(json.FileName); this.estimatedSize = pInt(json.EstimatedSize); @@ -335,8 +341,13 @@ class AttachmentModel extends AbstractModel * @returns {boolean} */ isText() { - return FileType.Text === this.fileType || FileType.Eml === this.fileType || - FileType.Certificate === this.fileType || FileType.Html === this.fileType || FileType.Code === this.fileType; + return ( + FileType.Text === this.fileType || + FileType.Eml === this.fileType || + FileType.Certificate === this.fileType || + FileType.Html === this.fileType || + FileType.Code === this.fileType + ); } /** @@ -350,8 +361,13 @@ class AttachmentModel extends AbstractModel * @returns {boolean} */ isFramed() { - return this.framed && (GlobalsData.__APP__ && GlobalsData.__APP__.googlePreviewSupported()) && - !(this.isPdf() && bAllowPdfPreview) && !this.isText() && !this.isImage(); + return ( + this.framed && + (GlobalsData.__APP__ && GlobalsData.__APP__.googlePreviewSupported()) && + !(this.isPdf() && bAllowPdfPreview) && + !this.isText() && + !this.isImage() + ); } /** @@ -365,7 +381,11 @@ class AttachmentModel extends AbstractModel * @returns {boolean} */ hasPreplay() { - return (Audio.supportedMp3 && this.isMp3()) || (Audio.supportedOgg && this.isOgg()) || (Audio.supportedWav && this.isWav()); + return ( + (Audio.supportedMp3 && this.isMp3()) || + (Audio.supportedOgg && this.isOgg()) || + (Audio.supportedWav && this.isWav()) + ); } /** @@ -416,8 +436,7 @@ class AttachmentModel extends AbstractModel */ linkPreviewMain() { let result = ''; - switch (true) - { + switch (true) { case this.isImage(): case this.isPdf() && bAllowPdfPreview: result = this.linkPreview(); @@ -439,8 +458,7 @@ class AttachmentModel extends AbstractModel */ generateTransferDownloadUrl() { let link = this.linkDownload(); - if ('http' !== link.substr(0, 4)) - { + if ('http' !== link.substr(0, 4)) { link = window.location.protocol + '//' + window.location.host + window.location.pathname + link; } @@ -454,8 +472,7 @@ class AttachmentModel extends AbstractModel */ eventDragStart(attachment, event) { const localEvent = event.originalEvent || event; - if (attachment && localEvent && localEvent.dataTransfer && localEvent.dataTransfer.setData) - { + if (attachment && localEvent && localEvent.dataTransfer && localEvent.dataTransfer.setData) { localEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl()); } @@ -477,4 +494,4 @@ class AttachmentModel extends AbstractModel } } -export {AttachmentModel, AttachmentModel as default}; +export { AttachmentModel, AttachmentModel as default }; diff --git a/dev/Model/ComposeAttachment.js b/dev/Model/ComposeAttachment.js index cff7ac021..f6c1342d7 100644 --- a/dev/Model/ComposeAttachment.js +++ b/dev/Model/ComposeAttachment.js @@ -1,12 +1,10 @@ - import ko from 'ko'; -import {isUnd, pInt, friendlySize, mimeContentType, getFileExtension} from 'Common/Utils'; +import { isUnd, pInt, friendlySize, mimeContentType, getFileExtension } from 'Common/Utils'; -import {staticIconClass, staticFileType} from 'Model/Attachment'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { staticIconClass, staticFileType } from 'Model/Attachment'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class ComposeAttachmentModel extends AbstractModel -{ +class ComposeAttachmentModel extends AbstractModel { /** * @param {string} id * @param {string} fileName @@ -16,8 +14,7 @@ class ComposeAttachmentModel extends AbstractModel * @param {string=} CID = '' * @param {string=} contentLocation = '' */ - constructor(id, fileName, size = null, isInline = false, isLinked = false, CID = '', contentLocation = '') - { + constructor(id, fileName, size = null, isInline = false, isLinked = false, CID = '', contentLocation = '') { super('ComposeAttachmentModel'); this.id = id; @@ -61,7 +58,14 @@ class ComposeAttachmentModel extends AbstractModel this.mimeType = ko.computed(() => mimeContentType(this.fileName())); this.fileExt = ko.computed(() => getFileExtension(this.fileName())); - this.regDisposables([this.progressText, this.progressStyle, this.title, this.friendlySize, this.mimeType, this.fileExt]); + this.regDisposables([ + this.progressText, + this.progressStyle, + this.title, + this.friendlySize, + this.mimeType, + this.fileExt + ]); } /** @@ -70,8 +74,7 @@ class ComposeAttachmentModel extends AbstractModel */ initByUploadJson(json) { let bResult = false; - if (json) - { + if (json) { this.fileName(json.Name); this.size(isUnd(json.Size) ? 0 : pInt(json.Size)); this.tempName(isUnd(json.TempName) ? '' : json.TempName); @@ -98,4 +101,4 @@ class ComposeAttachmentModel extends AbstractModel } } -export {ComposeAttachmentModel, ComposeAttachmentModel as default}; +export { ComposeAttachmentModel, ComposeAttachmentModel as default }; diff --git a/dev/Model/Contact.js b/dev/Model/Contact.js index c545f71e2..f3d110ae0 100644 --- a/dev/Model/Contact.js +++ b/dev/Model/Contact.js @@ -1,15 +1,13 @@ - import _ from '_'; import ko from 'ko'; -import {ContactPropertyType} from 'Common/Enums'; -import {trim, isNonEmptyArray, isNormal, pInt, pString} from 'Common/Utils'; -import {emptyContactPic} from 'Common/Links'; +import { ContactPropertyType } from 'Common/Enums'; +import { trim, isNonEmptyArray, isNormal, pInt, pString } from 'Common/Utils'; +import { emptyContactPic } from 'Common/Links'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class ContactModel extends AbstractModel -{ +class ContactModel extends AbstractModel { constructor() { super('ContactModel'); @@ -28,25 +26,17 @@ class ContactModel extends AbstractModel * @returns {Array|null} */ getNameAndEmailHelper() { - let - name = '', + let name = '', email = ''; - if (isNonEmptyArray(this.properties)) - { + if (isNonEmptyArray(this.properties)) { _.each(this.properties, (property) => { - if (property) - { - if (ContactPropertyType.FirstName === property[0]) - { + if (property) { + if (ContactPropertyType.FirstName === property[0]) { name = trim(property[1] + ' ' + name); - } - else if (ContactPropertyType.LastName === property[0]) - { + } else if (ContactPropertyType.LastName === property[0]) { name = trim(name + ' ' + property[1]); - } - else if ('' === email && ContactPropertyType.Email === property[0]) - { + } else if ('' === email && ContactPropertyType.Email === property[0]) { email = property[1]; } } @@ -62,17 +52,14 @@ class ContactModel extends AbstractModel */ parse(json) { let result = false; - if (json && 'Object/Contact' === json['@Object']) - { + if (json && 'Object/Contact' === json['@Object']) { this.idContact = pInt(json.IdContact); this.display = pString(json.Display); this.readOnly = !!json.ReadOnly; - if (isNonEmptyArray(json.Properties)) - { + if (isNonEmptyArray(json.Properties)) { _.each(json.Properties, (property) => { - if (property && property.Type && isNormal(property.Value) && isNormal(property.TypeStr)) - { + if (property && property.Type && isNormal(property.Value) && isNormal(property.TypeStr)) { this.properties.push([pInt(property.Type), pString(property.Value), pString(property.TypeStr)]); } }); @@ -103,20 +90,16 @@ class ContactModel extends AbstractModel */ lineAsCss() { const result = []; - if (this.deleted()) - { + if (this.deleted()) { result.push('deleted'); } - if (this.selected()) - { + if (this.selected()) { result.push('selected'); } - if (this.checked()) - { + if (this.checked()) { result.push('checked'); } - if (this.focused()) - { + if (this.focused()) { result.push('focused'); } @@ -124,4 +107,4 @@ class ContactModel extends AbstractModel } } -export {ContactModel, ContactModel as default}; +export { ContactModel, ContactModel as default }; diff --git a/dev/Model/ContactProperty.js b/dev/Model/ContactProperty.js index e77469338..387453245 100644 --- a/dev/Model/ContactProperty.js +++ b/dev/Model/ContactProperty.js @@ -1,14 +1,12 @@ - import ko from 'ko'; -import {ContactPropertyType} from 'Common/Enums'; -import {pInt, pString} from 'Common/Utils'; -import {i18n} from 'Common/Translator'; +import { ContactPropertyType } from 'Common/Enums'; +import { pInt, pString } from 'Common/Utils'; +import { i18n } from 'Common/Translator'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class ContactPropertyModel extends AbstractModel -{ +class ContactPropertyModel extends AbstractModel { /** * @param {number=} type = Enums.ContactPropertyType.Unknown * @param {string=} typeStr = '' @@ -16,8 +14,7 @@ class ContactPropertyModel extends AbstractModel * @param {boolean=} focused = false * @param {string=} placeholder = '' */ - constructor(type = ContactPropertyType.Unknown, typeStr = '', value = '', focused = false, placeholder = '') - { + constructor(type = ContactPropertyType.Unknown, typeStr = '', value = '', focused = false, placeholder = '') { super('ContactPropertyModel'); this.type = ko.observable(pInt(type)); @@ -38,4 +35,4 @@ class ContactPropertyModel extends AbstractModel } } -export {ContactPropertyModel, ContactPropertyModel as default}; +export { ContactPropertyModel, ContactPropertyModel as default }; diff --git a/dev/Model/Email.js b/dev/Model/Email.js index d273e8484..54946419d 100644 --- a/dev/Model/Email.js +++ b/dev/Model/Email.js @@ -1,10 +1,8 @@ - import _ from '_'; import addressparser from 'emailjs-addressparser'; -import {trim, encodeHtml, isNonEmptyArray} from 'Common/Utils'; +import { trim, encodeHtml, isNonEmptyArray } from 'Common/Utils'; -class EmailModel -{ +class EmailModel { email = ''; name = ''; dkimStatus = ''; @@ -16,8 +14,7 @@ class EmailModel * @param {string=} dkimStatus = 'none' * @param {string=} dkimValue = '' */ - constructor(email = '', name = '', dkimStatus = 'none', dkimValue = '') - { + constructor(email = '', name = '', dkimStatus = 'none', dkimValue = '') { this.email = email; this.name = name; this.dkimStatus = dkimStatus; @@ -66,8 +63,7 @@ class EmailModel * @returns {void} */ clearDuplicateName() { - if (this.name === this.email) - { + if (this.name === this.email) { this.name = ''; } } @@ -86,8 +82,7 @@ class EmailModel */ initByJson(json) { let result = false; - if (json && 'Object/Email' === json['@Object']) - { + if (json && 'Object/Email' === json['@Object']) { this.name = trim(json.Name); this.email = trim(json.Email); this.dkimStatus = trim(json.DkimStatus || ''); @@ -108,24 +103,31 @@ class EmailModel */ toLine(friendlyView, wrapWithLink = false, useEncodeHtml = false) { let result = ''; - if ('' !== this.email) - { - if (friendlyView && '' !== this.name) - { - result = wrapWithLink ? '') + - '" target="_blank" tabindex="-1">' + encodeHtml(this.name) + '' : (useEncodeHtml ? encodeHtml(this.name) : this.name); + if ('' !== this.email) { + if (friendlyView && '' !== this.name) { + result = wrapWithLink + ? '') + + '" target="_blank" tabindex="-1">' + + encodeHtml(this.name) + + '' + : useEncodeHtml + ? encodeHtml(this.name) + : this.name; // result = wrapWithLink ? '') + // '" target="_blank" tabindex="-1">' + encodeHtml(this.name) + '' : (useEncodeHtml ? encodeHtml(this.name) : this.name); - } - else - { + } else { result = this.email; - if ('' !== this.name) - { - if (wrapWithLink) - { - result = encodeHtml('"' + this.name + '" <') + '') + + if ('' !== this.name) { + if (wrapWithLink) { + result = + encodeHtml('"' + this.name + '" <') + + '') + '" target="_blank" tabindex="-1">' + encodeHtml(result) + '' + @@ -136,19 +138,19 @@ class EmailModel // encodeHtml(result) + // '' + // encodeHtml('>'); - } - else - { + } else { result = '"' + this.name + '" <' + result + '>'; - if (useEncodeHtml) - { + if (useEncodeHtml) { result = encodeHtml(result); } } - } - else if (wrapWithLink) - { - result = '' + encodeHtml(this.email) + ''; + } else if (wrapWithLink) { + result = + '' + + encodeHtml(this.email) + + ''; } } } @@ -158,15 +160,13 @@ class EmailModel static splitEmailLine(line) { const parsedResult = addressparser(line); - if (isNonEmptyArray(parsedResult)) - { + if (isNonEmptyArray(parsedResult)) { const result = []; let exists = false; parsedResult.forEach((item) => { - const address = item.address ? new EmailModel( - item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), - item.name || '' - ) : null; + const address = item.address + ? new EmailModel(item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), item.name || '') + : null; if (address && address.email) { exists = true; @@ -183,14 +183,12 @@ class EmailModel static parseEmailLine(line) { const parsedResult = addressparser(line); - if (isNonEmptyArray(parsedResult)) - { - return _.compact(parsedResult.map( - (item) => (item.address ? new EmailModel( - item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), - item.name || '' - ) : null) - )); + if (isNonEmptyArray(parsedResult)) { + return _.compact( + parsedResult.map((item) => + item.address ? new EmailModel(item.address.replace(/^[<]+(.*)[>]+$/g, '$1'), item.name || '') : null + ) + ); } return []; @@ -202,14 +200,12 @@ class EmailModel */ parse(emailAddress) { emailAddress = trim(emailAddress); - if ('' === emailAddress) - { + if ('' === emailAddress) { return false; } const result = addressparser(emailAddress); - if (isNonEmptyArray(result) && result[0]) - { + if (isNonEmptyArray(result) && result[0]) { this.name = result[0].name || ''; this.email = result[0].address || ''; this.clearDuplicateName(); @@ -221,4 +217,4 @@ class EmailModel } } -export {EmailModel, EmailModel as default}; +export { EmailModel, EmailModel as default }; diff --git a/dev/Model/Filter.js b/dev/Model/Filter.js index 079797e0f..9ad5a6757 100644 --- a/dev/Model/Filter.js +++ b/dev/Model/Filter.js @@ -1,19 +1,17 @@ - import _ from '_'; import ko from 'ko'; -import {FilterRulesType, FiltersAction} from 'Common/Enums'; -import {pString, inArray, isNonEmptyArray, fakeMd5, delegateRunOnDestroy, windowResizeCallback} from 'Common/Utils'; -import {i18n} from 'Common/Translator'; -import {getFolderFromCacheList} from 'Common/Cache'; +import { FilterRulesType, FiltersAction } from 'Common/Enums'; +import { pString, inArray, isNonEmptyArray, fakeMd5, delegateRunOnDestroy, windowResizeCallback } from 'Common/Utils'; +import { i18n } from 'Common/Translator'; +import { getFolderFromCacheList } from 'Common/Cache'; import AccountStore from 'Stores/User/Account'; -import {FilterConditionModel} from 'Model/FilterCondition'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { FilterConditionModel } from 'Model/FilterCondition'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class FilterModel extends AbstractModel -{ +class FilterModel extends AbstractModel { constructor() { super('FilterModel'); @@ -56,15 +54,14 @@ class FilterModel extends AbstractModel const fGetRealFolderName = (folderFullNameRaw) => { const folder = getFolderFromCacheList(folderFullNameRaw); - return folder ? folder.fullName.replace('.' === folder.delimiter ? /\./ : /[\\\/]+/, ' / ') : folderFullNameRaw; + return folder ? folder.fullName.replace('.' === folder.delimiter ? /\./ : /[\\/]+/, ' / ') : folderFullNameRaw; }; this.nameSub = ko.computed(() => { let result = ''; const actionValue = this.actionValue(); - switch (this.actionType()) - { + switch (this.actionType()) { case FiltersAction.MoveTo: result = i18n('SETTINGS_FILTERS/SUBNAME_MOVE_TO', { FOLDER: fGetRealFolderName(actionValue) @@ -93,8 +90,7 @@ class FilterModel extends AbstractModel this.actionTemplate = ko.computed(() => { let result = ''; - switch (this.actionType()) - { + switch (this.actionType()) { case FiltersAction.Forward: result = 'SettingsFiltersActionForward'; break; @@ -121,13 +117,17 @@ class FilterModel extends AbstractModel this.regDisposables(this.conditions.subscribe(windowResizeCallback)); - this.regDisposables(this.name.subscribe((sValue) => { - this.name.error('' === sValue); - })); + this.regDisposables( + this.name.subscribe((sValue) => { + this.name.error('' === sValue); + }) + ); - this.regDisposables(this.actionValue.subscribe((sValue) => { - this.actionValue.error('' === sValue); - })); + this.regDisposables( + this.actionValue.subscribe((sValue) => { + this.actionValue.error('' === sValue); + }) + ); this.regDisposables([this.actionNoStop, this.actionTemplate]); @@ -140,42 +140,42 @@ class FilterModel extends AbstractModel } verify() { - if ('' === this.name()) - { + if ('' === this.name()) { this.name.error(true); return false; } - if (0 < this.conditions().length) - { - if (_.find(this.conditions(), (cond) => cond && !cond.verify())) - { + if (0 < this.conditions().length) { + if (_.find(this.conditions(), (cond) => cond && !cond.verify())) { return false; } } - if ('' === this.actionValue()) - { - if (-1 < inArray(this.actionType(), [ - FiltersAction.MoveTo, FiltersAction.Forward, FiltersAction.Reject, FiltersAction.Vacation - ])) - { + if ('' === this.actionValue()) { + if ( + -1 < + inArray(this.actionType(), [ + FiltersAction.MoveTo, + FiltersAction.Forward, + FiltersAction.Reject, + FiltersAction.Vacation + ]) + ) { this.actionValue.error(true); return false; } } - if (FiltersAction.Forward === this.actionType() && - -1 === this.actionValue().indexOf('@')) - { + if (FiltersAction.Forward === this.actionType() && -1 === this.actionValue().indexOf('@')) { this.actionValue.error(true); return false; } - if (FiltersAction.Vacation === this.actionType() && - '' !== this.actionValueFourth() && -1 === this.actionValueFourth().indexOf('@') - ) - { + if ( + FiltersAction.Vacation === this.actionType() && + '' !== this.actionValueFourth() && + -1 === this.actionValueFourth().indexOf('@') + ) { this.actionValueFourth.error(true); return false; } @@ -221,8 +221,7 @@ class FilterModel extends AbstractModel parse(json) { let result = false; - if (json && 'Object/Filter' === json['@Object']) - { + if (json && 'Object/Filter' === json['@Object']) { this.id = pString(json.ID); this.name(pString(json.Name)); this.enabled(!!json.Enabled); @@ -231,12 +230,15 @@ class FilterModel extends AbstractModel this.conditions([]); - if (isNonEmptyArray(json.Conditions)) - { - this.conditions(_.compact(_.map(json.Conditions, (aData) => { - const filterCondition = new FilterConditionModel(); - return filterCondition && filterCondition.parse(aData) ? filterCondition : null; - }))); + if (isNonEmptyArray(json.Conditions)) { + this.conditions( + _.compact( + _.map(json.Conditions, (aData) => { + const filterCondition = new FilterConditionModel(); + return filterCondition && filterCondition.parse(aData) ? filterCondition : null; + }) + ) + ); } this.actionType(pString(json.ActionType)); @@ -257,7 +259,6 @@ class FilterModel extends AbstractModel } cloneSelf() { - const filter = new FilterModel(); filter.id = this.id; @@ -289,4 +290,4 @@ class FilterModel extends AbstractModel } } -export {FilterModel, FilterModel as default}; +export { FilterModel, FilterModel as default }; diff --git a/dev/Model/FilterCondition.js b/dev/Model/FilterCondition.js index 0d5067a07..99f4e707f 100644 --- a/dev/Model/FilterCondition.js +++ b/dev/Model/FilterCondition.js @@ -1,13 +1,11 @@ - import ko from 'ko'; -import {FilterConditionField, FilterConditionType} from 'Common/Enums'; -import {pString} from 'Common/Utils'; +import { FilterConditionField, FilterConditionType } from 'Common/Enums'; +import { pString } from 'Common/Utils'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class FilterConditionModel extends AbstractModel -{ +class FilterConditionModel extends AbstractModel { constructor() { super('FilterConditionModel'); @@ -20,10 +18,8 @@ class FilterConditionModel extends AbstractModel this.valueSecond.error = ko.observable(false); this.template = ko.computed(() => { - let template = ''; - switch (this.field()) - { + switch (this.field()) { case FilterConditionField.Size: template = 'SettingsFiltersConditionSize'; break; @@ -36,7 +32,6 @@ class FilterConditionModel extends AbstractModel } return template; - }, this); this.field.subscribe(() => { @@ -48,14 +43,12 @@ class FilterConditionModel extends AbstractModel } verify() { - if ('' === this.value()) - { + if ('' === this.value()) { this.value.error(true); return false; } - if (FilterConditionField.Header === this.field() && '' === this.valueSecond()) - { + if (FilterConditionField.Header === this.field() && '' === this.valueSecond()) { this.valueSecond.error(true); return false; } @@ -64,8 +57,7 @@ class FilterConditionModel extends AbstractModel } parse(json) { - if (json && json.Field && json.Type) - { + if (json && json.Field && json.Type) { this.field(pString(json.Field)); this.type(pString(json.Type)); this.value(pString(json.Value)); @@ -98,4 +90,4 @@ class FilterConditionModel extends AbstractModel } } -export {FilterConditionModel, FilterConditionModel as default}; +export { FilterConditionModel, FilterConditionModel as default }; diff --git a/dev/Model/Folder.js b/dev/Model/Folder.js index 6fa096c77..87ca16e5f 100644 --- a/dev/Model/Folder.js +++ b/dev/Model/Folder.js @@ -1,17 +1,15 @@ - import _ from '_'; import ko from 'ko'; -import {FolderType} from 'Common/Enums'; -import {isPosNumeric} from 'Common/Utils'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; -import {getFolderInboxName} from 'Common/Cache'; +import { FolderType } from 'Common/Enums'; +import { isPosNumeric } from 'Common/Utils'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; +import { getFolderInboxName } from 'Common/Cache'; import * as Events from 'Common/Events'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class FolderModel extends AbstractModel -{ +class FolderModel extends AbstractModel { constructor() { super('FolderModel'); @@ -36,7 +34,7 @@ class FolderModel extends AbstractModel this.checkable = ko.observable(false); this.subFolders = ko.observableArray([]); this.deleteAccess = ko.observable(false); - this.actionBlink = ko.observable(false).extend({falseTimeout: 1000}); + this.actionBlink = ko.observable(false).extend({ falseTimeout: 1000 }); this.nameForEdit = ko.observable(''); @@ -65,24 +63,26 @@ class FolderModel extends AbstractModel this.isInbox = ko.computed(() => FolderType.Inbox === this.type()); this.hasSubScribedSubfolders = ko.computed( - () => !!_.find(this.subFolders(), (oFolder) => (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder()) + () => + !!_.find( + this.subFolders(), + (oFolder) => (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder() + ) ); this.canBeEdited = ko.computed(() => FolderType.User === this.type() && this.existen && this.selectable); this.visible = ko.computed(() => { - const - isSubScribed = this.subScribed(), + const isSubScribed = this.subScribed(), isSubFolders = this.hasSubScribedSubfolders(); - return (isSubScribed || (isSubFolders && (!this.existen || !this.selectable))); + return isSubScribed || (isSubFolders && (!this.existen || !this.selectable)); }); this.isSystemFolder = ko.computed(() => FolderType.User !== this.type()); this.hidden = ko.computed(() => { - const - isSystem = this.isSystemFolder(), + const isSystem = this.isSystemFolder(), isSubFolders = this.hasSubScribedSubfolders(); return (isSystem && !isSubFolders) || (!this.selectable && !isSubFolders); @@ -90,48 +90,46 @@ class FolderModel extends AbstractModel this.selectableForFolderList = ko.computed(() => !this.isSystemFolder() && this.selectable); - this.messageCountAll = ko.computed({ - read: this.privateMessageCountAll, - write: (iValue) => { - if (isPosNumeric(iValue, true)) - { - this.privateMessageCountAll(iValue); + this.messageCountAll = ko + .computed({ + read: this.privateMessageCountAll, + write: (iValue) => { + if (isPosNumeric(iValue, true)) { + this.privateMessageCountAll(iValue); + } else { + this.privateMessageCountAll.valueHasMutated(); + } } - else - { - this.privateMessageCountAll.valueHasMutated(); - } - } - }).extend({notify: 'always'}); + }) + .extend({ notify: 'always' }); - this.messageCountUnread = ko.computed({ - read: this.privateMessageCountUnread, - write: (value) => { - if (isPosNumeric(value, true)) - { - this.privateMessageCountUnread(value); + this.messageCountUnread = ko + .computed({ + read: this.privateMessageCountUnread, + write: (value) => { + if (isPosNumeric(value, true)) { + this.privateMessageCountUnread(value); + } else { + this.privateMessageCountUnread.valueHasMutated(); + } } - else - { - this.privateMessageCountUnread.valueHasMutated(); - } - } - }).extend({notify: 'always'}); + }) + .extend({ notify: 'always' }); this.printableUnreadCount = ko.computed(() => { - const - count = this.messageCountAll(), + const count = this.messageCountAll(), unread = this.messageCountUnread(), type = this.type(); - if (0 < count) - { - if (FolderType.Draft === type) - { + if (0 < count) { + if (FolderType.Draft === type) { return '' + count; - } - else if (0 < unread && FolderType.Trash !== type && FolderType.Archive !== type && FolderType.SentItems !== type) - { + } else if ( + 0 < unread && + FolderType.Trash !== type && + FolderType.Archive !== type && + FolderType.SentItems !== type + ) { return '' + unread; } } @@ -144,21 +142,20 @@ class FolderModel extends AbstractModel return !bSystem && 0 === this.subFolders().length && inboxFolderName !== this.fullNameRaw; }); - this.canBeSubScribed = ko.computed(() => !this.isSystemFolder() && this.selectable && inboxFolderName !== this.fullNameRaw); + this.canBeSubScribed = ko.computed( + () => !this.isSystemFolder() && this.selectable && inboxFolderName !== this.fullNameRaw + ); this.canBeChecked = this.canBeSubScribed; this.localName = ko.computed(() => { - translatorTrigger(); let name = this.name(); const type = this.type(); - if (this.isSystemFolder()) - { - switch (type) - { + if (this.isSystemFolder()) { + switch (type) { case FolderType.Inbox: name = i18n('FOLDER_LIST/INBOX_NAME'); break; @@ -185,18 +182,14 @@ class FolderModel extends AbstractModel }); this.manageFolderSystemName = ko.computed(() => { - translatorTrigger(); let suffix = ''; - const - type = this.type(), + const type = this.type(), name = this.name(); - if (this.isSystemFolder()) - { - switch (type) - { + if (this.isSystemFolder()) { + switch (type) { case FolderType.Inbox: suffix = '(' + i18n('FOLDER_LIST/INBOX_NAME') + ')'; break; @@ -219,8 +212,7 @@ class FolderModel extends AbstractModel } } - if ('' !== suffix && '(' + name + ')' === suffix || '(inbox)' === suffix.toLowerCase()) - { + if (('' !== suffix && '(' + name + ')' === suffix) || '(inbox)' === suffix.toLowerCase()) { suffix = ''; } @@ -237,7 +229,11 @@ class FolderModel extends AbstractModel this.hasUnreadMessages = ko.computed(() => 0 < this.messageCountUnread() && '' !== this.printableUnreadCount()); this.hasSubScribedUnreadMessagesSubfolders = ko.computed( - () => !!_.find(this.subFolders(), (folder) => folder.hasUnreadMessages() || folder.hasSubScribedUnreadMessagesSubfolders()) + () => + !!_.find( + this.subFolders(), + (folder) => folder.hasUnreadMessages() || folder.hasSubScribedUnreadMessagesSubfolders() + ) ); // subscribe @@ -246,15 +242,13 @@ class FolderModel extends AbstractModel }); this.edited.subscribe((value) => { - if (value) - { + if (value) { this.nameForEdit(this.name()); } }); this.messageCountUnread.subscribe((unread) => { - if (FolderType.Inbox === this.type()) - { + if (FolderType.Inbox === this.type()) { Events.pub('mailbox.inbox-unread-count', [unread]); } }); @@ -266,8 +260,11 @@ class FolderModel extends AbstractModel * @returns {string} */ collapsedCss() { - return this.hasSubScribedSubfolders() ? - (this.collapsed() ? 'icon-right-mini e-collapsed-sign' : 'icon-down-mini e-collapsed-sign') : 'icon-none e-collapsed-sign'; + return this.hasSubScribedSubfolders() + ? this.collapsed() + ? 'icon-right-mini e-collapsed-sign' + : 'icon-down-mini e-collapsed-sign' + : 'icon-none e-collapsed-sign'; } /** @@ -278,8 +275,7 @@ class FolderModel extends AbstractModel let bResult = false; const sInboxFolderName = getFolderInboxName(); - if (json && 'Object/Folder' === json['@Object']) - { + if (json && 'Object/Folder' === json['@Object']) { this.name(json.Name); this.delimiter = json.Delimiter; this.fullName = json.FullName; @@ -308,4 +304,4 @@ class FolderModel extends AbstractModel } } -export {FolderModel, FolderModel as default}; +export { FolderModel, FolderModel as default }; diff --git a/dev/Model/Identity.js b/dev/Model/Identity.js index c2a427917..94b8fe566 100644 --- a/dev/Model/Identity.js +++ b/dev/Model/Identity.js @@ -1,16 +1,13 @@ - import ko from 'ko'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class IdentityModel extends AbstractModel -{ +class IdentityModel extends AbstractModel { /** * @param {string} id * @param {string} email */ - constructor(id, email) - { + constructor(id, email) { super('IdentityModel'); this.id = ko.observable(id || ''); @@ -31,12 +28,11 @@ class IdentityModel extends AbstractModel * @returns {string} */ formattedName() { - const - name = this.name(), + const name = this.name(), email = this.email(); return '' !== name ? name + ' (' + email + ')' : email; } } -export {IdentityModel, IdentityModel as default}; +export { IdentityModel, IdentityModel as default }; diff --git a/dev/Model/Message.js b/dev/Model/Message.js index 6d5741c73..df55b6fb1 100644 --- a/dev/Model/Message.js +++ b/dev/Model/Message.js @@ -1,4 +1,3 @@ - import _ from '_'; import $ from '$'; import ko from 'ko'; @@ -6,28 +5,34 @@ import moment from 'moment'; import classnames from 'classnames'; import lozad from 'lozad'; -import {MessagePriority, SignedVerifyStatus} from 'Common/Enums'; -import {i18n} from 'Common/Translator'; -import {DATA_IMAGE_LAZY_PLACEHOLDER_PIC} from 'Common/Consts'; +import { MessagePriority, SignedVerifyStatus } from 'Common/Enums'; +import { i18n } from 'Common/Translator'; +import { DATA_IMAGE_LAZY_PLACEHOLDER_PIC } from 'Common/Consts'; import { - pInt, inArray, isArray, isUnd, trim, - previewMessage, windowResize, friendlySize, isNonEmptyArray + pInt, + inArray, + isArray, + isUnd, + trim, + previewMessage, + windowResize, + friendlySize, + isNonEmptyArray } from 'Common/Utils'; -import {$win} from 'Common/Globals'; -import {messageViewLink, messageDownloadLink} from 'Common/Links'; +import { $win } from 'Common/Globals'; +import { messageViewLink, messageDownloadLink } from 'Common/Links'; import FolderStore from 'Stores/User/Folder'; import PgpStore from 'Stores/User/Pgp'; -import {emailArrayFromJson, emailArrayToStringClear, emailArrayToString, replyHelper} from 'Helper/Message'; +import { emailArrayFromJson, emailArrayToStringClear, emailArrayToString, replyHelper } from 'Helper/Message'; -import {AttachmentModel, staticCombinedIconClass} from 'Model/Attachment'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AttachmentModel, staticCombinedIconClass } from 'Model/Attachment'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class MessageModel extends AbstractModel -{ +class MessageModel extends AbstractModel { constructor() { super('MessageModel'); @@ -78,7 +83,9 @@ class MessageModel extends AbstractModel this.hasAttachments = ko.observable(false); this.attachmentsSpecData = ko.observableArray([]); - this.attachmentIconClass = ko.computed(() => staticCombinedIconClass(this.hasAttachments() ? this.attachmentsSpecData() : [])); + this.attachmentIconClass = ko.computed(() => + staticCombinedIconClass(this.hasAttachments() ? this.attachmentsSpecData() : []) + ); this.body = null; @@ -194,10 +201,13 @@ class MessageModel extends AbstractModel * @returns {Array} */ getEmails(properties) { - return _.compact(_.uniq(_.map( - _.reduce(properties, (carry, property) => carry.concat(this[property]), []), - (oItem) => (oItem ? oItem.email : '') - ))); + return _.compact( + _.uniq( + _.map(_.reduce(properties, (carry, property) => carry.concat(this[property]), []), (oItem) => + oItem ? oItem.email : '' + ) + ) + ); } /** @@ -215,15 +225,20 @@ class MessageModel extends AbstractModel } computeSenderEmail() { - const - sentFolder = FolderStore.sentFolder(), + const sentFolder = FolderStore.sentFolder(), draftFolder = FolderStore.draftFolder(); - this.senderEmailsString(this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder ? - this.toEmailsString() : this.fromEmailString()); + this.senderEmailsString( + this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder + ? this.toEmailsString() + : this.fromEmailString() + ); - this.senderClearEmailsString(this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder ? - this.toClearEmailsString() : this.fromClearEmailString()); + this.senderClearEmailsString( + this.folderFullNameRaw === sentFolder || this.folderFullNameRaw === draftFolder + ? this.toClearEmailsString() + : this.fromClearEmailString() + ); } /** @@ -231,14 +246,14 @@ class MessageModel extends AbstractModel * @returns {boolean} */ initByJson(json) { - let - result = false, + let result = false, priority = MessagePriority.Normal; - if (json && 'Object/Message' === json['@Object']) - { + if (json && 'Object/Message' === json['@Object']) { priority = pInt(json.Priority); - this.priority(-1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal); + this.priority( + -1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal + ); this.folderFullNameRaw = json.Folder; this.uid = json.Uid; @@ -258,13 +273,10 @@ class MessageModel extends AbstractModel this.unsubsribeLinks = isNonEmptyArray(json.UnsubsribeLinks) ? json.UnsubsribeLinks : []; this.subject(json.Subject); - if (isArray(json.SubjectParts)) - { + if (isArray(json.SubjectParts)) { this.subjectPrefix(json.SubjectParts[0]); this.subjectSuffix(json.SubjectParts[1]); - } - else - { + } else { this.subjectPrefix(''); this.subjectSuffix(this.subject()); } @@ -294,15 +306,14 @@ class MessageModel extends AbstractModel * @returns {boolean} */ initUpdateByMessageJson(json) { - let - result = false, + let result = false, priority = MessagePriority.Normal; - if (json && 'Object/Message' === json['@Object']) - { + if (json && 'Object/Message' === json['@Object']) { priority = pInt(json.Priority); - this.priority(-1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? - priority : MessagePriority.Normal); + this.priority( + -1 < inArray(priority, [MessagePriority.High, MessagePriority.Low]) ? priority : MessagePriority.Normal + ); this.aDraftInfo = json.DraftInfo; @@ -312,8 +323,7 @@ class MessageModel extends AbstractModel this.proxy = !!json.ExternalProxy; - if (PgpStore.capaOpenPGP()) - { + if (PgpStore.capaOpenPGP()) { this.isPgpSigned(!!json.PgpSigned); this.isPgpEncrypted(!!json.PgpEncrypted); } @@ -339,22 +349,20 @@ class MessageModel extends AbstractModel * @returns {Array} */ initAttachmentsFromJson(json) { - let - index = 0, + let index = 0, len = 0, attachment = null; const result = []; - if (json && 'Collection/AttachmentCollection' === json['@Object'] && isNonEmptyArray(json['@Collection'])) - { - for (index = 0, len = json['@Collection'].length; index < len; index++) - { + if (json && 'Collection/AttachmentCollection' === json['@Object'] && isNonEmptyArray(json['@Collection'])) { + for (index = 0, len = json['@Collection'].length; index < len; index++) { attachment = AttachmentModel.newInstanceFromJson(json['@Collection'][index]); - if (attachment) - { - if ('' !== attachment.cidWithOutTags && 0 < this.foundedCIDs.length && - 0 <= inArray(attachment.cidWithOutTags, this.foundedCIDs)) - { + if (attachment) { + if ( + '' !== attachment.cidWithOutTags && + 0 < this.foundedCIDs.length && + 0 <= inArray(attachment.cidWithOutTags, this.foundedCIDs) + ) { attachment.isLinked = true; } @@ -377,7 +385,7 @@ class MessageModel extends AbstractModel * @returns {string} */ getFirstUnsubsribeLink() { - return this.unsubsribeLinks && 0 < this.unsubsribeLinks.length ? (this.unsubsribeLinks[0] || '') : ''; + return this.unsubsribeLinks && 0 < this.unsubsribeLinks.length ? this.unsubsribeLinks[0] || '' : ''; } /** @@ -386,8 +394,7 @@ class MessageModel extends AbstractModel */ initFlagsByJson(json) { let result = false; - if (json && 'Object/Message' === json['@Object']) - { + if (json && 'Object/Message' === json['@Object']) { this.unseen(!json.IsSeen); this.flagged(!!json.IsFlagged); this.answered(!!json.IsAnswered); @@ -415,8 +422,7 @@ class MessageModel extends AbstractModel */ fromDkimData() { let result = ['none', '']; - if (isNonEmptyArray(this.from) && 1 === this.from.length && this.from[0] && this.from[0].dkimStatus) - { + if (isNonEmptyArray(this.from) && 1 === this.from.length && this.from[0] && this.from[0].dkimStatus) { result = [this.from[0].dkimStatus, this.from[0].dkimValue || '']; } @@ -498,8 +504,7 @@ class MessageModel extends AbstractModel let result = null; const attachments = this.attachments(); - if (isNonEmptyArray(attachments)) - { + if (isNonEmptyArray(attachments)) { cid = cid.replace(/^<+/, '').replace(/>+$/, ''); result = _.find(attachments, (item) => cid === item.cidWithOutTags); } @@ -515,8 +520,7 @@ class MessageModel extends AbstractModel let result = null; const attachments = this.attachments(); - if (isNonEmptyArray(attachments)) - { + if (isNonEmptyArray(attachments)) { result = _.find(attachments, (item) => contentLocation === item.contentLocation); } @@ -571,18 +575,15 @@ class MessageModel extends AbstractModel * @returns {Array} */ replyEmails(excludeEmails, last = false) { - const - result = [], + const result = [], unic = isUnd(excludeEmails) ? {} : excludeEmails; replyHelper(this.replyTo, unic, result); - if (0 === result.length) - { + if (0 === result.length) { replyHelper(this.from, unic, result); } - if (0 === result.length && !last) - { + if (0 === result.length && !last) { return this.replyEmails({}, true); } @@ -596,22 +597,19 @@ class MessageModel extends AbstractModel */ replyAllEmails(excludeEmails, last = false) { let data = []; - const - toResult = [], + const toResult = [], ccResult = [], unic = isUnd(excludeEmails) ? {} : excludeEmails; replyHelper(this.replyTo, unic, toResult); - if (0 === toResult.length) - { + if (0 === toResult.length) { replyHelper(this.from, unic, toResult); } replyHelper(this.to, unic, toResult); replyHelper(this.cc, unic, ccResult); - if (0 === toResult.length && !last) - { + if (0 === toResult.length && !last) { data = this.replyAllEmails({}, true); return [data[0], ccResult]; } @@ -640,22 +638,26 @@ class MessageModel extends AbstractModel viewPopupMessage(print = false) { this.showLazyExternalImagesInBody(); - const - timeStampInUTC = this.dateTimeStampInUTC() || 0, + const timeStampInUTC = this.dateTimeStampInUTC() || 0, ccLine = this.ccToLine(false), m = 0 < timeStampInUTC ? moment.unix(timeStampInUTC) : null; - previewMessage({ - title: this.subject(), - subject: this.subject(), - date: m ? m.format('LLL') : '', - fromCreds: this.fromToLine(false), - toLabel: i18n('MESSAGE/LABEL_TO'), - toCreds: this.toToLine(false), - ccClass: ccLine ? '' : 'rl-preview-hide', - ccLabel: i18n('MESSAGE/LABEL_CC'), - ccCreds: ccLine - }, this.body, this.isHtml(), print); + previewMessage( + { + title: this.subject(), + subject: this.subject(), + date: m ? m.format('LLL') : '', + fromCreds: this.fromToLine(false), + toLabel: i18n('MESSAGE/LABEL_TO'), + toCreds: this.toToLine(false), + ccClass: ccLine ? '' : 'rl-preview-hide', + ccLabel: i18n('MESSAGE/LABEL_CC'), + ccCreds: ccLine + }, + this.body, + this.isHtml(), + print + ); } printMessage() { @@ -674,8 +676,7 @@ class MessageModel extends AbstractModel * @returns {MessageModel} */ populateByMessageListItem(message) { - if (message) - { + if (message) { this.folderFullNameRaw = message.folderFullNameRaw; this.uid = message.uid; this.hash = message.hash; @@ -686,8 +687,7 @@ class MessageModel extends AbstractModel this.subjectPrefix(this.subjectPrefix()); this.subjectSuffix(this.subjectSuffix()); - if (message) - { + if (message) { this.size(message.size()); this.dateTimeStampInUTC(message.dateTimeStampInUTC()); this.priority(message.priority()); @@ -731,8 +731,7 @@ class MessageModel extends AbstractModel this.sInReplyTo = ''; this.sReferences = ''; - if (message) - { + if (message) { this.threads(message.threads()); } @@ -742,11 +741,12 @@ class MessageModel extends AbstractModel } showLazyExternalImagesInBody() { - if (this.body) - { + if (this.body) { $('.lazy.lazy-inited[data-original]', this.body).each(function() { - $(this).attr('src', $(this).attr('data-original')) // eslint-disable-line no-invalid-this - .removeAttr('data-original').removeAttr('data-loaded'); + $(this) + .attr('src', $(this).attr('data-original')) // eslint-disable-line no-invalid-this + .removeAttr('data-original') + .removeAttr('data-loaded'); }); } } @@ -762,32 +762,27 @@ class MessageModel extends AbstractModel .attr('src', element.dataset.original) .removeAttr('data-loaded') .removeAttr('data-original') - .css({opacity: 0.3}) - .animate({opacity: 1}, 500); + .css({ opacity: 0.3 }) + .animate({ opacity: 1 }, 500); } }).observe(); } showExternalImages(lazy = false) { - if (this.body && this.body.data('rl-has-images')) - { + if (this.body && this.body.data('rl-has-images')) { this.hasImages(false); this.body.data('rl-has-images', false); let attr = this.proxy ? 'data-x-additional-src' : 'data-x-src'; $('[' + attr + ']', this.body).each(function() { const $this = $(this); // eslint-disable-line no-invalid-this - if (lazy && $this.is('img')) - { + if (lazy && $this.is('img')) { $this .addClass('lazy') .attr('data-original', $this.attr(attr)) .removeAttr('data-loaded'); - } - else - { - $this.attr('src', $this.attr(attr)) - .removeAttr('data-loaded'); + } else { + $this.attr('src', $this.attr(attr)).removeAttr('data-loaded'); } }); @@ -795,12 +790,11 @@ class MessageModel extends AbstractModel $('[' + attr + ']', this.body).each(function() { const $this = $(this); // eslint-disable-line no-invalid-this let style = trim($this.attr('style')); - style = '' === style ? '' : (';' === style.substr(-1) ? style + ' ' : style + '; '); + style = '' === style ? '' : ';' === style.substr(-1) ? style + ' ' : style + '; '; $this.attr('style', style + $this.attr(attr)); }); - if (lazy) - { + if (lazy) { this.lozad(); $win.resize(); } @@ -810,27 +804,19 @@ class MessageModel extends AbstractModel } showInternalImages(lazy = false) { - if (this.body && !this.body.data('rl-init-internal-images')) - { + if (this.body && !this.body.data('rl-init-internal-images')) { this.body.data('rl-init-internal-images', true); const self = this; $('[data-x-src-cid]', this.body).each(function() { - const - $this = $(this), // eslint-disable-line no-invalid-this + const $this = $(this), // eslint-disable-line no-invalid-this attachment = self.findAttachmentByCid($this.attr('data-x-src-cid')); - if (attachment && attachment.download) - { - if (lazy && $this.is('img')) - { - $this - .addClass('lazy') - .attr('data-original', attachment.linkPreview()); - } - else - { + if (attachment && attachment.download) { + if (lazy && $this.is('img')) { + $this.addClass('lazy').attr('data-original', attachment.linkPreview()); + } else { $this.attr('src', attachment.linkPreview()); } } @@ -839,49 +825,37 @@ class MessageModel extends AbstractModel $('[data-x-src-location]', this.body).each(function() { const $this = $(this); // eslint-disable-line no-invalid-this let attachment = self.findAttachmentByContentLocation($this.attr('data-x-src-location')); - if (!attachment) - { + if (!attachment) { attachment = self.findAttachmentByCid($this.attr('data-x-src-location')); } - if (attachment && attachment.download) - { - if (lazy && $this.is('img')) - { - $this - .addClass('lazy') - .attr('data-original', attachment.linkPreview()); - } - else - { + if (attachment && attachment.download) { + if (lazy && $this.is('img')) { + $this.addClass('lazy').attr('data-original', attachment.linkPreview()); + } else { $this.attr('src', attachment.linkPreview()); } } }); $('[data-x-style-cid]', this.body).each(function() { - let - style = '', + let style = '', name = ''; - const - $this = $(this), // eslint-disable-line no-invalid-this + const $this = $(this), // eslint-disable-line no-invalid-this attachment = self.findAttachmentByCid($this.attr('data-x-style-cid')); - if (attachment && attachment.linkPreview) - { + if (attachment && attachment.linkPreview) { name = $this.attr('data-x-style-cid-name'); - if ('' !== name) - { + if ('' !== name) { style = trim($this.attr('style')); - style = '' === style ? '' : (';' === style.substr(-1) ? style + ' ' : style + '; '); - $this.attr('style', style + name + ': url(\'' + attachment.linkPreview() + '\')'); + style = '' === style ? '' : ';' === style.substr(-1) ? style + ' ' : style + '; '; + $this.attr('style', style + name + ": url('" + attachment.linkPreview() + "')"); } } }); - if (lazy) - { + if (lazy) { // $('.RL-MailMessageView .messageView .messageItem .content')[0] _.delay(() => this.lozad(), 300); } @@ -891,24 +865,21 @@ class MessageModel extends AbstractModel } storeDataInDom() { - if (this.body) - { + if (this.body) { this.body.data('rl-is-html', !!this.isHtml()); this.body.data('rl-has-images', !!this.hasImages()); } } fetchDataFromDom() { - if (this.body) - { + if (this.body) { this.isHtml(!!this.body.data('rl-is-html')); this.hasImages(!!this.body.data('rl-has-images')); } } replacePlaneTextBody(plain) { - if (this.body) - { + if (this.body) { this.body.html(plain).addClass('b-text-part plain'); } } @@ -917,8 +888,16 @@ class MessageModel extends AbstractModel * @returns {string} */ flagHash() { - return [this.deleted(), this.deletedMark(), this.unseen(), this.flagged(), this.answered(), this.forwarded(), this.isReadReceipt()].join(','); + return [ + this.deleted(), + this.deletedMark(), + this.unseen(), + this.flagged(), + this.answered(), + this.forwarded(), + this.isReadReceipt() + ].join(','); } } -export {MessageModel, MessageModel as default}; +export { MessageModel, MessageModel as default }; diff --git a/dev/Model/OpenPgpKey.js b/dev/Model/OpenPgpKey.js index b78cb3397..198b2d27d 100644 --- a/dev/Model/OpenPgpKey.js +++ b/dev/Model/OpenPgpKey.js @@ -1,14 +1,12 @@ - import ko from 'ko'; -import {isNonEmptyArray, log} from 'Common/Utils'; +import { isNonEmptyArray, log } from 'Common/Utils'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; import PgpStore from 'Stores/User/Pgp'; -class OpenPgpKeyModel extends AbstractModel -{ +class OpenPgpKeyModel extends AbstractModel { /** * @param {string} index * @param {string} guID @@ -20,8 +18,7 @@ class OpenPgpKeyModel extends AbstractModel * @param {string} armor * @param {string} userID */ - constructor(index, guID, ID, IDs, userIDs, emails, isPrivate, armor, userID) - { + constructor(index, guID, ID, IDs, userIDs, emails, isPrivate, armor, userID) { super('OpenPgpKeyModel'); this.index = index; @@ -42,16 +39,12 @@ class OpenPgpKeyModel extends AbstractModel getNativeKey() { let key = null; - try - { + try { key = PgpStore.openpgp.key.readArmored(this.armor); - if (key && !key.err && key.keys && key.keys[0]) - { + if (key && !key.err && key.keys && key.keys[0]) { return key; } - } - catch (e) - { + } catch (e) { log(e); } @@ -64,11 +57,9 @@ class OpenPgpKeyModel extends AbstractModel } select(pattern, property) { - if (this[property]) - { + if (this[property]) { const index = this[property].indexOf(pattern); - if (-1 !== index) - { + if (-1 !== index) { this.user = this.users[index]; this.email = this.emails[index]; } @@ -84,4 +75,4 @@ class OpenPgpKeyModel extends AbstractModel } } -export {OpenPgpKeyModel, OpenPgpKeyModel as default}; +export { OpenPgpKeyModel, OpenPgpKeyModel as default }; diff --git a/dev/Model/Template.js b/dev/Model/Template.js index 6a3f06be8..b190f2443 100644 --- a/dev/Model/Template.js +++ b/dev/Model/Template.js @@ -1,19 +1,16 @@ - import ko from 'ko'; -import {pString} from 'Common/Utils'; +import { pString } from 'Common/Utils'; -import {AbstractModel} from 'Knoin/AbstractModel'; +import { AbstractModel } from 'Knoin/AbstractModel'; -class TemplateModel extends AbstractModel -{ +class TemplateModel extends AbstractModel { /** * @param {string} id * @param {string} name * @param {string} body */ - constructor(id, name, body) - { + constructor(id, name, body) { super('TemplateModel'); this.id = id; @@ -29,8 +26,7 @@ class TemplateModel extends AbstractModel */ parse(json) { let result = false; - if (json && 'Object/Template' === json['@Object']) - { + if (json && 'Object/Template' === json['@Object']) { this.id = pString(json.ID); this.name = pString(json.Name); this.body = pString(json.Body); @@ -43,4 +39,4 @@ class TemplateModel extends AbstractModel } } -export {TemplateModel, TemplateModel as default}; +export { TemplateModel, TemplateModel as default }; diff --git a/dev/Promises/AbstractAjax.js b/dev/Promises/AbstractAjax.js index 7e274f823..7942047a2 100644 --- a/dev/Promises/AbstractAjax.js +++ b/dev/Promises/AbstractAjax.js @@ -1,19 +1,17 @@ - import window from 'window'; import $ from '$'; -import {ajax} from 'Common/Links'; -import {microtime, isUnd, isNormal, pString, pInt, inArray} from 'Common/Utils'; -import {DEFAULT_AJAX_TIMEOUT, TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT} from 'Common/Consts'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {data as GlobalsData} from 'Common/Globals'; +import { ajax } from 'Common/Links'; +import { microtime, isUnd, isNormal, pString, pInt, inArray } from 'Common/Utils'; +import { DEFAULT_AJAX_TIMEOUT, TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT } from 'Common/Consts'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { data as GlobalsData } from 'Common/Globals'; import * as Plugins from 'Common/Plugins'; import * as Settings from 'Storage/Settings'; -import {AbstractBasicPromises} from 'Promises/AbstractBasic'; +import { AbstractBasicPromises } from 'Promises/AbstractBasic'; -class AbstractAjaxPromises extends AbstractBasicPromises -{ +class AbstractAjaxPromises extends AbstractBasicPromises { oRequests = {}; constructor() { @@ -27,10 +25,8 @@ class AbstractAjaxPromises extends AbstractBasicPromises } abort(sAction, bClearOnly) { - if (this.oRequests[sAction]) - { - if (!bClearOnly && this.oRequests[sAction].abort) - { + if (this.oRequests[sAction]) { + if (!bClearOnly && this.oRequests[sAction].abort) { this.oRequests[sAction].__aborted__ = true; this.oRequests[sAction].abort(); } @@ -43,16 +39,13 @@ class AbstractAjaxPromises extends AbstractBasicPromises } ajaxRequest(action, isPost, timeOut, params, additionalGetString, fTrigger) { - return new window.Promise((resolve, reject) => { - const start = microtime(); timeOut = isNormal(timeOut) ? timeOut : DEFAULT_AJAX_TIMEOUT; additionalGetString = isUnd(additionalGetString) ? '' : pString(additionalGetString); - if (isPost) - { + if (isPost) { params.XToken = Settings.appSettingsGet('token'); } @@ -65,24 +58,20 @@ class AbstractAjaxPromises extends AbstractBasicPromises url: ajax(additionalGetString), async: true, dataType: 'json', - data: isPost ? (params || {}) : {}, + data: isPost ? params || {} : {}, timeout: timeOut, global: true }).always((data, textStatus) => { - - let - isCached = false, + let isCached = false, errorData = null; - if (data && data.Time) - { + if (data && data.Time) { isCached = pInt(data.Time) > microtime() - start; } // backward capability let type = ''; - switch (true) - { + switch (true) { case 'success' === textStatus && data && data.Result && action === data.Action: type = StorageResultType.Success; break; @@ -95,97 +84,84 @@ class AbstractAjaxPromises extends AbstractBasicPromises } Plugins.runHook('ajax-default-response', [ - action, StorageResultType.Success === type ? data : null, type, isCached, params + action, + StorageResultType.Success === type ? data : null, + type, + isCached, + params ]); - if ('success' === textStatus) - { - if (data && data.Result && action === data.Action) - { + if ('success' === textStatus) { + if (data && data.Result && action === data.Action) { data.__cached__ = isCached; resolve(data); - } - else if (data && data.Action) - { + } else if (data && data.Action) { errorData = data; reject(data.ErrorCode ? data.ErrorCode : Notification.AjaxFalse); - } - else - { + } else { errorData = data; reject(Notification.AjaxParse); } - } - else if ('timeout' === textStatus) - { + } else if ('timeout' === textStatus) { errorData = data; reject(Notification.AjaxTimeout); - } - else if ('abort' === textStatus) - { - if (!data || !data.__aborted__) - { + } else if ('abort' === textStatus) { + if (!data || !data.__aborted__) { reject(Notification.AjaxAbort); } - } - else - { + } else { errorData = data; reject(Notification.AjaxParse); } - if (this.oRequests[action]) - { + if (this.oRequests[action]) { this.oRequests[action] = null; delete this.oRequests[action]; } this.setTrigger(fTrigger, false); - if (errorData) - { - if (-1 < inArray(errorData.ErrorCode, [ - Notification.AuthError, Notification.AccessError, - Notification.ConnectionError, Notification.DomainNotAllowed, Notification.AccountNotAllowed, - Notification.MailServerError, Notification.UnknownNotification, Notification.UnknownError - ])) - { + if (errorData) { + if ( + -1 < + inArray(errorData.ErrorCode, [ + Notification.AuthError, + Notification.AccessError, + Notification.ConnectionError, + Notification.DomainNotAllowed, + Notification.AccountNotAllowed, + Notification.MailServerError, + Notification.UnknownNotification, + Notification.UnknownError + ]) + ) { GlobalsData.iAjaxErrorCount += 1; } - if (Notification.InvalidToken === errorData.ErrorCode) - { + if (Notification.InvalidToken === errorData.ErrorCode) { GlobalsData.iTokenErrorCount += 1; } - if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) - { - if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) - { + if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) { + if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) { GlobalsData.__APP__.loginAndLogoutReload(false, true); } } - if (errorData.ClearAuth || errorData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) - { - if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) - { + if (errorData.ClearAuth || errorData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) { + if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) { GlobalsData.__APP__.clearClientSideToken(); } - if (GlobalsData.__APP__ && !errorData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) - { + if (GlobalsData.__APP__ && !errorData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) { GlobalsData.__APP__.loginAndLogoutReload(false, true); } } } - }); - if (oH) - { - if (this.oRequests[action]) - { + if (oH) { + if (this.oRequests[action]) { this.oRequests[action] = null; delete this.oRequests[action]; } @@ -196,7 +172,6 @@ class AbstractAjaxPromises extends AbstractBasicPromises } getRequest(sAction, fTrigger, sAdditionalGetString, iTimeOut) { - sAdditionalGetString = isUnd(sAdditionalGetString) ? '' : pString(sAdditionalGetString); sAdditionalGetString = sAction + '/' + sAdditionalGetString; @@ -204,7 +179,6 @@ class AbstractAjaxPromises extends AbstractBasicPromises } postRequest(action, fTrigger, params, timeOut) { - params = params || {}; params.Action = action; @@ -212,4 +186,4 @@ class AbstractAjaxPromises extends AbstractBasicPromises } } -export {AbstractAjaxPromises, AbstractAjaxPromises as default}; +export { AbstractAjaxPromises, AbstractAjaxPromises as default }; diff --git a/dev/Promises/AbstractBasic.js b/dev/Promises/AbstractBasic.js index 4ab08794d..d70869aa9 100644 --- a/dev/Promises/AbstractBasic.js +++ b/dev/Promises/AbstractBasic.js @@ -1,9 +1,7 @@ - import window from 'window'; -import {isArray} from 'Common/Utils'; +import { isArray } from 'Common/Utils'; -export class AbstractBasicPromises -{ +export class AbstractBasicPromises { oPromisesStack = {}; func(fFunc) { @@ -20,12 +18,10 @@ export class AbstractBasicPromises } setTrigger(trigger, value) { - if (trigger) - { + if (trigger) { value = !!value; (isArray(trigger) ? trigger : [trigger]).forEach((fTrigger) => { - if (fTrigger) - { + if (fTrigger) { fTrigger(value); } }); diff --git a/dev/Promises/User/Ajax.js b/dev/Promises/User/Ajax.js index c90c159f9..1f62825b9 100644 --- a/dev/Promises/User/Ajax.js +++ b/dev/Promises/User/Ajax.js @@ -1,11 +1,9 @@ - import window from 'window'; import PromisesPopulator from 'Promises/User/Populator'; -import {AbstractAjaxPromises} from 'Promises/AbstractAjax'; +import { AbstractAjaxPromises } from 'Promises/AbstractAjax'; -class UserAjaxUserPromises extends AbstractAjaxPromises -{ +class UserAjaxUserPromises extends AbstractAjaxPromises { constructor() { super(); @@ -13,11 +11,13 @@ class UserAjaxUserPromises extends AbstractAjaxPromises } foldersReload(fTrigger) { - return this.abort('Folders').postRequest('Folders', fTrigger).then((data) => { - PromisesPopulator.foldersList(data.Result); - PromisesPopulator.foldersAdditionalParameters(data.Result); - return true; - }); + return this.abort('Folders') + .postRequest('Folders', fTrigger) + .then((data) => { + PromisesPopulator.foldersList(data.Result); + PromisesPopulator.foldersAdditionalParameters(data.Result); + return true; + }); } foldersReloadWithTimeout(fTrigger) { diff --git a/dev/Promises/User/Populator.js b/dev/Promises/User/Populator.js index 7bc2f402a..8602ab670 100644 --- a/dev/Promises/User/Populator.js +++ b/dev/Promises/User/Populator.js @@ -1,9 +1,8 @@ - import _ from '_'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {isArray, isNormal, pInt, isUnd, noop} from 'Common/Utils'; -import {ClientSideKeyName, ServerFolderType} from 'Common/Enums'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { isArray, isNormal, pInt, isUnd, noop } from 'Common/Utils'; +import { ClientSideKeyName, ServerFolderType } from 'Common/Enums'; import * as Cache from 'Common/Cache'; import * as Settings from 'Storage/Settings'; @@ -14,11 +13,10 @@ import FolderStore from 'Stores/User/Folder'; import Remote from 'Remote/User/Ajax'; -import {FolderModel} from 'Model/Folder'; -import {AbstractBasicPromises} from 'Promises/AbstractBasic'; +import { FolderModel } from 'Model/Folder'; +import { AbstractBasicPromises } from 'Promises/AbstractBasic'; -class PromisesUserPopulator extends AbstractBasicPromises -{ +class PromisesUserPopulator extends AbstractBasicPromises { /** * @param {string} sFullNameHash * @param {Array?} expandedFolders @@ -33,8 +31,11 @@ class PromisesUserPopulator extends AbstractBasicPromises * @returns {string} */ normalizeFolder(sFolderFullNameRaw) { - return ('' === sFolderFullNameRaw || UNUSED_OPTION_VALUE === sFolderFullNameRaw || - null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : ''; + return '' === sFolderFullNameRaw || + UNUSED_OPTION_VALUE === sFolderFullNameRaw || + null !== Cache.getFolderFromCacheList(sFolderFullNameRaw) + ? sFolderFullNameRaw + : ''; } /** @@ -44,61 +45,52 @@ class PromisesUserPopulator extends AbstractBasicPromises * @returns {Array} */ folderResponseParseRec(sNamespace, aFolders, expandedFolders) { - - const - bDisplaySpecSetting = FolderStore.displaySpecSetting(), + const bDisplaySpecSetting = FolderStore.displaySpecSetting(), aList = []; _.each(aFolders, (oFolder) => { - if (oFolder) - { + if (oFolder) { let oCacheFolder = Cache.getFolderFromCacheList(oFolder.FullNameRaw); - if (!oCacheFolder) - { + if (!oCacheFolder) { oCacheFolder = FolderModel.newInstanceFromJson(oFolder); - if (oCacheFolder) - { + if (oCacheFolder) { Cache.setFolderToCacheList(oFolder.FullNameRaw, oCacheFolder); Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, oFolder.FullNameRaw, oCacheFolder); } } - if (oCacheFolder) - { - if (bDisplaySpecSetting) - { + if (oCacheFolder) { + if (bDisplaySpecSetting) { oCacheFolder.checkable(!!oFolder.Checkable); - } - else - { + } else { oCacheFolder.checkable(true); } oCacheFolder.collapsed(!this.isFolderExpanded(oCacheFolder.fullNameHash, expandedFolders)); - if (oFolder.Extended) - { - if (oFolder.Extended.Hash) - { + if (oFolder.Extended) { + if (oFolder.Extended.Hash) { Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash); } - if (isNormal(oFolder.Extended.MessageCount)) - { + if (isNormal(oFolder.Extended.MessageCount)) { oCacheFolder.messageCountAll(oFolder.Extended.MessageCount); } - if (isNormal(oFolder.Extended.MessageUnseenCount)) - { + if (isNormal(oFolder.Extended.MessageUnseenCount)) { oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount); } } - if (oFolder.SubFolders && 'Collection/FolderCollection' === oFolder.SubFolders['@Object'] && - oFolder.SubFolders['@Collection'] && isArray(oFolder.SubFolders['@Collection'])) - { + if ( + oFolder.SubFolders && + 'Collection/FolderCollection' === oFolder.SubFolders['@Object'] && + oFolder.SubFolders['@Collection'] && + isArray(oFolder.SubFolders['@Collection']) + ) { oCacheFolder.subFolders( - this.folderResponseParseRec(sNamespace, oFolder.SubFolders['@Collection'], expandedFolders)); + this.folderResponseParseRec(sNamespace, oFolder.SubFolders['@Collection'], expandedFolders) + ); } aList.push(oCacheFolder); @@ -110,29 +102,39 @@ class PromisesUserPopulator extends AbstractBasicPromises } foldersList(oData) { - if (oData && 'Collection/FolderCollection' === oData['@Object'] && - oData['@Collection'] && isArray(oData['@Collection'])) - { - const - expandedFolders = Local.get(ClientSideKeyName.ExpandedFolders), + if ( + oData && + 'Collection/FolderCollection' === oData['@Object'] && + oData['@Collection'] && + isArray(oData['@Collection']) + ) { + const expandedFolders = Local.get(ClientSideKeyName.ExpandedFolders), cnt = pInt(oData.CountRec); let limit = pInt(Settings.appSettingsGet('folderSpecLimit')); - limit = 100 < limit ? 100 : (10 > limit ? 10 : limit); + limit = 100 < limit ? 100 : 10 > limit ? 10 : limit; FolderStore.displaySpecSetting(0 >= cnt || limit < cnt); - FolderStore.folderList(this.folderResponseParseRec( - isUnd(oData.Namespace) ? '' : oData.Namespace, oData['@Collection'], expandedFolders)); // @todo optimization required + FolderStore.folderList( + this.folderResponseParseRec( + isUnd(oData.Namespace) ? '' : oData.Namespace, + oData['@Collection'], + expandedFolders + ) + ); // @todo optimization required } } foldersAdditionalParameters(oData) { - if (oData && oData && 'Collection/FolderCollection' === oData['@Object'] && - oData['@Collection'] && isArray(oData['@Collection'])) - { - if (!isUnd(oData.Namespace)) - { + if ( + oData && + oData && + 'Collection/FolderCollection' === oData['@Object'] && + oData['@Collection'] && + isArray(oData['@Collection']) + ) { + if (!isUnd(oData.Namespace)) { FolderStore.namespace = oData.Namespace; } @@ -142,14 +144,17 @@ class PromisesUserPopulator extends AbstractBasicPromises let update = false; - if (oData.SystemFolders && '' === '' + - Settings.settingsGet('SentFolder') + - Settings.settingsGet('DraftFolder') + - Settings.settingsGet('SpamFolder') + - Settings.settingsGet('TrashFolder') + - Settings.settingsGet('ArchiveFolder') + - Settings.settingsGet('NullFolder')) - { + if ( + oData.SystemFolders && + '' === + '' + + Settings.settingsGet('SentFolder') + + Settings.settingsGet('DraftFolder') + + Settings.settingsGet('SpamFolder') + + Settings.settingsGet('TrashFolder') + + Settings.settingsGet('ArchiveFolder') + + Settings.settingsGet('NullFolder') + ) { Settings.settingsSet('SentFolder', oData.SystemFolders[ServerFolderType.SENT] || null); Settings.settingsSet('DraftFolder', oData.SystemFolders[ServerFolderType.DRAFTS] || null); Settings.settingsSet('SpamFolder', oData.SystemFolders[ServerFolderType.JUNK] || null); @@ -165,8 +170,7 @@ class PromisesUserPopulator extends AbstractBasicPromises FolderStore.trashFolder(this.normalizeFolder(Settings.settingsGet('TrashFolder'))); FolderStore.archiveFolder(this.normalizeFolder(Settings.settingsGet('ArchiveFolder'))); - if (update) - { + if (update) { Remote.saveSystemFolders(noop, { SentFolder: FolderStore.sentFolder(), DraftFolder: FolderStore.draftFolder(), diff --git a/dev/Remote/AbstractAjax.js b/dev/Remote/AbstractAjax.js index c41b5f78b..31100108d 100644 --- a/dev/Remote/AbstractAjax.js +++ b/dev/Remote/AbstractAjax.js @@ -1,19 +1,17 @@ - import window from 'window'; import _ from '_'; import $ from '$'; -import {TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT, DEFAULT_AJAX_TIMEOUT} from 'Common/Consts'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {inArray, pInt, pString, isUnd} from 'Common/Utils'; -import {data as GlobalsData} from 'Common/Globals'; -import {ajax} from 'Common/Links'; -import {runHook} from 'Common/Plugins'; +import { TOKEN_ERROR_LIMIT, AJAX_ERROR_LIMIT, DEFAULT_AJAX_TIMEOUT } from 'Common/Consts'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { inArray, pInt, pString, isUnd } from 'Common/Utils'; +import { data as GlobalsData } from 'Common/Globals'; +import { ajax } from 'Common/Links'; +import { runHook } from 'Common/Plugins'; import * as Settings from 'Storage/Settings'; -class AbstractAjaxRemote -{ +class AbstractAjaxRemote { constructor() { this.oRequests = {}; } @@ -27,72 +25,73 @@ class AbstractAjaxRemote * @param {*=} oRequestParameters */ defaultResponse(fCallback, sRequestAction, sType, oData, bCached, oRequestParameters) { - const - fCall = () => { - if (StorageResultType.Success !== sType && GlobalsData.bUnload) - { - sType = StorageResultType.Unload; + const fCall = () => { + if (StorageResultType.Success !== sType && GlobalsData.bUnload) { + sType = StorageResultType.Unload; + } + + if (StorageResultType.Success === sType && oData && !oData.Result) { + if ( + oData && + -1 < + inArray(oData.ErrorCode, [ + Notification.AuthError, + Notification.AccessError, + Notification.ConnectionError, + Notification.DomainNotAllowed, + Notification.AccountNotAllowed, + Notification.MailServerError, + Notification.UnknownNotification, + Notification.UnknownError + ]) + ) { + GlobalsData.iAjaxErrorCount += 1; } - if (StorageResultType.Success === sType && oData && !oData.Result) - { - if (oData && -1 < inArray(oData.ErrorCode, [ - Notification.AuthError, Notification.AccessError, - Notification.ConnectionError, Notification.DomainNotAllowed, Notification.AccountNotAllowed, - Notification.MailServerError, Notification.UnknownNotification, Notification.UnknownError - ])) - { - GlobalsData.iAjaxErrorCount += 1; - } + if (oData && Notification.InvalidToken === oData.ErrorCode) { + GlobalsData.iTokenErrorCount += 1; + } - if (oData && Notification.InvalidToken === oData.ErrorCode) - { - GlobalsData.iTokenErrorCount += 1; + if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) { + if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) { + GlobalsData.__APP__.loginAndLogoutReload(false, true); } + } - if (TOKEN_ERROR_LIMIT < GlobalsData.iTokenErrorCount) - { - if (GlobalsData.__APP__ && GlobalsData.__APP__.loginAndLogoutReload) - { + if (oData.ClearAuth || oData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) { + if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) { + GlobalsData.__APP__.clearClientSideToken(); + + if (!oData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) { GlobalsData.__APP__.loginAndLogoutReload(false, true); } } - - if (oData.ClearAuth || oData.Logout || AJAX_ERROR_LIMIT < GlobalsData.iAjaxErrorCount) - { - if (GlobalsData.__APP__ && GlobalsData.__APP__.clearClientSideToken) - { - GlobalsData.__APP__.clearClientSideToken(); - - if (!oData.ClearAuth && GlobalsData.__APP__.loginAndLogoutReload) - { - GlobalsData.__APP__.loginAndLogoutReload(false, true); - } - } - } - } - else if (StorageResultType.Success === sType && oData && oData.Result) - { - GlobalsData.iAjaxErrorCount = 0; - GlobalsData.iTokenErrorCount = 0; } + } else if (StorageResultType.Success === sType && oData && oData.Result) { + GlobalsData.iAjaxErrorCount = 0; + GlobalsData.iTokenErrorCount = 0; + } - runHook('ajax-default-response', [sRequestAction, StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]); + runHook('ajax-default-response', [ + sRequestAction, + StorageResultType.Success === sType ? oData : null, + sType, + bCached, + oRequestParameters + ]); - if (fCallback) - { - fCallback( - sType, - StorageResultType.Success === sType ? oData : null, - bCached, - sRequestAction, - oRequestParameters - ); - } - }; + if (fCallback) { + fCallback( + sType, + StorageResultType.Success === sType ? oData : null, + bCached, + sRequestAction, + oRequestParameters + ); + } + }; - switch (sType) - { + switch (sType) { case 'success': sType = StorageResultType.Success; break; @@ -104,12 +103,9 @@ class AbstractAjaxRemote break; } - if (StorageResultType.Error === sType) - { + if (StorageResultType.Error === sType) { _.delay(fCall, 300); - } - else - { + } else { fCall(); } } @@ -123,25 +119,20 @@ class AbstractAjaxRemote * @returns {jQuery.jqXHR} */ ajaxRequest(fResultCallback, params, iTimeOut = 20000, sGetAdd = '', abortActions = []) { - const - isPost = '' === sGetAdd, + const isPost = '' === sGetAdd, headers = {}, - start = (new window.Date()).getTime(); + start = new window.Date().getTime(); - let - action = ''; + let action = ''; params = params || {}; action = params.Action || ''; - if (action && 0 < abortActions.length) - { + if (action && 0 < abortActions.length) { _.each(abortActions, (actionToAbort) => { - if (this.oRequests[actionToAbort]) - { + if (this.oRequests[actionToAbort]) { this.oRequests[actionToAbort].__aborted = true; - if (this.oRequests[actionToAbort].abort) - { + if (this.oRequests[actionToAbort].abort) { this.oRequests[actionToAbort].abort(); } this.oRequests[actionToAbort] = null; @@ -149,8 +140,7 @@ class AbstractAjaxRemote }); } - if (isPost) - { + if (isPost) { params.XToken = Settings.appSettingsGet('token'); } @@ -166,17 +156,13 @@ class AbstractAjaxRemote }); oDefAjax.always((oData, sType) => { - let cached = false; - if (oData && oData.Time) - { - cached = pInt(oData.Time) > (new window.Date()).getTime() - start; + if (oData && oData.Time) { + cached = pInt(oData.Time) > new window.Date().getTime() - start; } - if (action && this.oRequests[action]) - { - if (this.oRequests[action].__aborted) - { + if (action && this.oRequests[action]) { + if (this.oRequests[action].__aborted) { sType = 'abort'; } @@ -186,13 +172,10 @@ class AbstractAjaxRemote this.defaultResponse(fResultCallback, action, sType, oData, cached, params); }); - if (action && 0 < abortActions.length && -1 < inArray(action, abortActions)) - { - if (this.oRequests[action]) - { + if (action && 0 < abortActions.length && -1 < inArray(action, abortActions)) { + if (this.oRequests[action]) { this.oRequests[action].__aborted = true; - if (this.oRequests[action].abort) - { + if (this.oRequests[action].abort) { this.oRequests[action].abort(); } this.oRequests[action] = null; @@ -201,6 +184,7 @@ class AbstractAjaxRemote this.oRequests[action] = oDefAjax; } + // eslint-disable-next-line no-console oDefAjax.catch(console.log); return oDefAjax; } @@ -221,8 +205,13 @@ class AbstractAjaxRemote runHook('ajax-default-request', [sAction, oParameters, sGetAdd]); - return this.ajaxRequest(fCallback, oParameters, - isUnd(iTimeout) ? DEFAULT_AJAX_TIMEOUT : pInt(iTimeout), sGetAdd, aAbortActions); + return this.ajaxRequest( + fCallback, + oParameters, + isUnd(iTimeout) ? DEFAULT_AJAX_TIMEOUT : pInt(iTimeout), + sGetAdd, + aAbortActions + ); } /** @@ -284,4 +273,4 @@ class AbstractAjaxRemote } } -export {AbstractAjaxRemote, AbstractAjaxRemote as default}; +export { AbstractAjaxRemote, AbstractAjaxRemote as default }; diff --git a/dev/Remote/Admin/Ajax.js b/dev/Remote/Admin/Ajax.js index b9b92a8f6..8fd685366 100644 --- a/dev/Remote/Admin/Ajax.js +++ b/dev/Remote/Admin/Ajax.js @@ -1,8 +1,6 @@ +import { AbstractAjaxRemote } from 'Remote/AbstractAjax'; -import {AbstractAjaxRemote} from 'Remote/AbstractAjax'; - -class RemoteAdminAjax extends AbstractAjaxRemote -{ +class RemoteAdminAjax extends AbstractAjaxRemote { constructor() { super(); @@ -92,11 +90,16 @@ class RemoteAdminAjax extends AbstractAjaxRemote * @param {Object} oPackage */ packageInstall(fCallback, oPackage) { - this.defaultRequest(fCallback, 'AdminPackageInstall', { - 'Id': oPackage.id, - 'Type': oPackage.type, - 'File': oPackage.file - }, 60000); + this.defaultRequest( + fCallback, + 'AdminPackageInstall', + { + 'Id': oPackage.id, + 'Type': oPackage.type, + 'File': oPackage.file + }, + 60000 + ); } /** @@ -200,11 +203,25 @@ class RemoteAdminAjax extends AbstractAjaxRemote }); } - createOrUpdateDomain(fCallback, - bCreate, sName, - sIncHost, iIncPort, sIncSecure, bIncShortLogin, - bUseSieve, sSieveAllowRaw, sSieveHost, iSievePort, sSieveSecure, - sOutHost, iOutPort, sOutSecure, bOutShortLogin, bOutAuth, bOutPhpMail, + createOrUpdateDomain( + fCallback, + bCreate, + sName, + sIncHost, + iIncPort, + sIncSecure, + bIncShortLogin, + bUseSieve, + sSieveAllowRaw, + sSieveHost, + iSievePort, + sSieveSecure, + sOutHost, + iOutPort, + sOutSecure, + bOutShortLogin, + bOutAuth, + bOutPhpMail, sWhiteList ) { this.defaultRequest(fCallback, 'AdminDomainSave', { @@ -233,10 +250,21 @@ class RemoteAdminAjax extends AbstractAjaxRemote }); } - testConnectionForDomain(fCallback, sName, - sIncHost, iIncPort, sIncSecure, - bUseSieve, sSieveHost, iSievePort, sSieveSecure, - sOutHost, iOutPort, sOutSecure, bOutAuth, bOutPhpMail + testConnectionForDomain( + fCallback, + sName, + sIncHost, + iIncPort, + sIncSecure, + bUseSieve, + sSieveHost, + iSievePort, + sSieveSecure, + sOutHost, + iOutPort, + sOutSecure, + bOutAuth, + bOutPhpMail ) { this.defaultRequest(fCallback, 'AdminDomainTest', { 'Name': sName, diff --git a/dev/Remote/User/Ajax.js b/dev/Remote/User/Ajax.js index 63bd4ae8b..4234976bc 100644 --- a/dev/Remote/User/Ajax.js +++ b/dev/Remote/User/Ajax.js @@ -1,7 +1,6 @@ - import _ from '_'; -import {pString, pInt, isArray, trim, boolToAjax} from 'Common/Utils'; +import { pString, pInt, isArray, trim, boolToAjax } from 'Common/Utils'; import { CONTACTS_SYNC_AJAX_TIMEOUT, @@ -19,19 +18,18 @@ import { getMessageFlagsFromCache } from 'Common/Cache'; -import {subQueryPrefix} from 'Common/Links'; +import { subQueryPrefix } from 'Common/Links'; import * as Base64 from 'Common/Base64'; import * as Settings from 'Storage/Settings'; import AppStore from 'Stores/User/App'; import SettingsStore from 'Stores/User/Settings'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {AbstractAjaxRemote} from 'Remote/AbstractAjax'; +import { AbstractAjaxRemote } from 'Remote/AbstractAjax'; -class RemoteUserAjax extends AbstractAjaxRemote -{ +class RemoteUserAjax extends AbstractAjaxRemote { constructor() { super(); this.oRequests = {}; @@ -41,13 +39,20 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {?Function} fCallback */ folders(fCallback) { - this.defaultRequest(fCallback, 'Folders', { - 'SentFolder': Settings.settingsGet('SentFolder'), - 'DraftFolder': Settings.settingsGet('DraftFolder'), - 'SpamFolder': Settings.settingsGet('SpamFolder'), - 'TrashFolder': Settings.settingsGet('TrashFolder'), - 'ArchiveFolder': Settings.settingsGet('ArchiveFolder') - }, null, '', ['Folders']); + this.defaultRequest( + fCallback, + 'Folders', + { + 'SentFolder': Settings.settingsGet('SentFolder'), + 'DraftFolder': Settings.settingsGet('DraftFolder'), + 'SpamFolder': Settings.settingsGet('SpamFolder'), + 'TrashFolder': Settings.settingsGet('TrashFolder'), + 'ArchiveFolder': Settings.settingsGet('ArchiveFolder') + }, + null, + '', + ['Folders'] + ); } /** @@ -304,40 +309,54 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {boolean=} bSilent = false */ messageList(fCallback, sFolderFullNameRaw, iOffset = 0, iLimit = 20, sSearch = '', sThreadUid = '', bSilent = false) { - sFolderFullNameRaw = pString(sFolderFullNameRaw); - const - folderHash = getFolderHash(sFolderFullNameRaw), + const folderHash = getFolderHash(sFolderFullNameRaw), useThreads = AppStore.threadsAllowed() && SettingsStore.useThreads(), inboxUidNext = getFolderInboxName() === sFolderFullNameRaw ? getFolderUidNext(sFolderFullNameRaw) : ''; - if ('' !== folderHash && ('' === sSearch || -1 === sSearch.indexOf('is:'))) - { - return this.defaultRequest(fCallback, 'MessageList', {}, + if ('' !== folderHash && ('' === sSearch || -1 === sSearch.indexOf('is:'))) { + return this.defaultRequest( + fCallback, + 'MessageList', + {}, '' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT, - 'MessageList/' + subQueryPrefix() + '/' + Base64.urlsafe_encode([ - sFolderFullNameRaw, - iOffset, - iLimit, - sSearch, - AppStore.projectHash(), - folderHash, - inboxUidNext, - useThreads ? '1' : '0', - useThreads ? sThreadUid : '' - ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']); + 'MessageList/' + + subQueryPrefix() + + '/' + + Base64.urlsafe_encode( + [ + sFolderFullNameRaw, + iOffset, + iLimit, + sSearch, + AppStore.projectHash(), + folderHash, + inboxUidNext, + useThreads ? '1' : '0', + useThreads ? sThreadUid : '' + ].join(String.fromCharCode(0)) + ), + bSilent ? [] : ['MessageList'] + ); } - return this.defaultRequest(fCallback, 'MessageList', { - Folder: sFolderFullNameRaw, - Offset: iOffset, - Limit: iLimit, - Search: sSearch, - UidNext: inboxUidNext, - UseThreads: useThreads ? '1' : '0', - ThreadUid: useThreads ? sThreadUid : '' - }, '' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT, '', bSilent ? [] : ['MessageList']); + return this.defaultRequest( + fCallback, + 'MessageList', + { + Folder: sFolderFullNameRaw, + Offset: iOffset, + Limit: iLimit, + Search: sSearch, + UidNext: inboxUidNext, + UseThreads: useThreads ? '1' : '0', + ThreadUid: useThreads ? sThreadUid : '' + }, + '' === sSearch ? DEFAULT_AJAX_TIMEOUT : SEARCH_AJAX_TIMEOUT, + '', + bSilent ? [] : ['MessageList'] + ); } /** @@ -345,9 +364,14 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {Array} aDownloads */ messageUploadAttachments(fCallback, aDownloads) { - this.defaultRequest(fCallback, 'MessageUploadAttachments', { - 'Attachments': aDownloads - }, 999000); + this.defaultRequest( + fCallback, + 'MessageUploadAttachments', + { + 'Attachments': aDownloads + }, + 999000 + ); } /** @@ -357,19 +381,28 @@ class RemoteUserAjax extends AbstractAjaxRemote * @returns {boolean} */ message(fCallback, sFolderFullNameRaw, iUid) { - sFolderFullNameRaw = pString(sFolderFullNameRaw); iUid = pInt(iUid); - if (getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid) - { - this.defaultRequest(fCallback, 'Message', {}, null, - 'Message/' + subQueryPrefix() + '/' + Base64.urlsafe_encode([ - sFolderFullNameRaw, - iUid, - AppStore.projectHash(), - AppStore.threadsAllowed() && SettingsStore.useThreads() ? '1' : '0' - ].join(String.fromCharCode(0))), ['Message']); + if (getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid) { + this.defaultRequest( + fCallback, + 'Message', + {}, + null, + 'Message/' + + subQueryPrefix() + + '/' + + Base64.urlsafe_encode( + [ + sFolderFullNameRaw, + iUid, + AppStore.projectHash(), + AppStore.threadsAllowed() && SettingsStore.useThreads() ? '1' : '0' + ].join(String.fromCharCode(0)) + ), + ['Message'] + ); return true; } @@ -382,9 +415,14 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {Array} aExternals */ composeUploadExternals(fCallback, aExternals) { - this.defaultRequest(fCallback, 'ComposeUploadExternals', { - 'Externals': aExternals - }, 999000); + this.defaultRequest( + fCallback, + 'ComposeUploadExternals', + { + 'Externals': aExternals + }, + 999000 + ); } /** @@ -393,10 +431,15 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {string} sAccessToken */ composeUploadDrive(fCallback, sUrl, sAccessToken) { - this.defaultRequest(fCallback, 'ComposeUploadDrive', { - 'AccessToken': sAccessToken, - 'Url': sUrl - }, 999000); + this.defaultRequest( + fCallback, + 'ComposeUploadDrive', + { + 'AccessToken': sAccessToken, + 'Url': sUrl + }, + 999000 + ); } /** @@ -405,46 +448,37 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {Array=} list = [] */ folderInformation(fCallback, folder, list = []) { - let request = true; const uids = []; - if (isArray(list) && 0 < list.length) - { + if (isArray(list) && 0 < list.length) { request = false; _.each(list, (messageListItem) => { - if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, messageListItem.uid)) - { + if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, messageListItem.uid)) { uids.push(messageListItem.uid); } - if (0 < messageListItem.threads().length) - { + if (0 < messageListItem.threads().length) { _.each(messageListItem.threads(), (uid) => { - if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, uid)) - { + if (!getMessageFlagsFromCache(messageListItem.folderFullNameRaw, uid)) { uids.push(uid); } }); } }); - if (0 < uids.length) - { + if (0 < uids.length) { request = true; } } - if (request) - { + if (request) { this.defaultRequest(fCallback, 'FolderInformation', { 'Folder': folder, 'FlagsUids': isArray(uids) ? uids.join(',') : '', 'UidNext': getFolderInboxName() === folder ? getFolderUidNext(folder) : '' }); - } - else if (SettingsStore.useThreads()) - { + } else if (SettingsStore.useThreads()) { getApp().reloadFlagsCurrentMessageListAndMessageFromCache(); } } @@ -527,27 +561,48 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {string} sReferences * @param {boolean} bMarkAsImportant */ - saveMessage(fCallback, sIdentityID, sMessageFolder, sMessageUid, sDraftFolder, - sTo, sCc, sBcc, sReplyTo, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bMarkAsImportant) { - - this.defaultRequest(fCallback, 'SaveMessage', { - 'IdentityID': sIdentityID, - 'MessageFolder': sMessageFolder, - 'MessageUid': sMessageUid, - 'DraftFolder': sDraftFolder, - 'To': sTo, - 'Cc': sCc, - 'Bcc': sBcc, - 'ReplyTo': sReplyTo, - 'Subject': sSubject, - 'TextIsHtml': bTextIsHtml ? '1' : '0', - 'Text': sText, - 'DraftInfo': aDraftInfo, - 'InReplyTo': sInReplyTo, - 'References': sReferences, - 'MarkAsImportant': bMarkAsImportant ? '1' : '0', - 'Attachments': aAttachments - }, SAVE_MESSAGE_AJAX_TIMEOUT); + saveMessage( + fCallback, + sIdentityID, + sMessageFolder, + sMessageUid, + sDraftFolder, + sTo, + sCc, + sBcc, + sReplyTo, + sSubject, + bTextIsHtml, + sText, + aAttachments, + aDraftInfo, + sInReplyTo, + sReferences, + bMarkAsImportant + ) { + this.defaultRequest( + fCallback, + 'SaveMessage', + { + 'IdentityID': sIdentityID, + 'MessageFolder': sMessageFolder, + 'MessageUid': sMessageUid, + 'DraftFolder': sDraftFolder, + 'To': sTo, + 'Cc': sCc, + 'Bcc': sBcc, + 'ReplyTo': sReplyTo, + 'Subject': sSubject, + 'TextIsHtml': bTextIsHtml ? '1' : '0', + 'Text': sText, + 'DraftInfo': aDraftInfo, + 'InReplyTo': sInReplyTo, + 'References': sReferences, + 'MarkAsImportant': bMarkAsImportant ? '1' : '0', + 'Attachments': aAttachments + }, + SAVE_MESSAGE_AJAX_TIMEOUT + ); } /** @@ -589,30 +644,52 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {boolean} bRequestReadReceipt * @param {boolean} bMarkAsImportant */ - sendMessage(fCallback, sIdentityID, sMessageFolder, sMessageUid, sSentFolder, - sTo, sCc, sBcc, sReplyTo, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, - bRequestDsn, bRequestReadReceipt, bMarkAsImportant) { - - this.defaultRequest(fCallback, 'SendMessage', { - 'IdentityID': sIdentityID, - 'MessageFolder': sMessageFolder, - 'MessageUid': sMessageUid, - 'SentFolder': sSentFolder, - 'To': sTo, - 'Cc': sCc, - 'Bcc': sBcc, - 'ReplyTo': sReplyTo, - 'Subject': sSubject, - 'TextIsHtml': bTextIsHtml ? '1' : '0', - 'Text': sText, - 'DraftInfo': aDraftInfo, - 'InReplyTo': sInReplyTo, - 'References': sReferences, - 'Dsn': bRequestDsn ? '1' : '0', - 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0', - 'MarkAsImportant': bMarkAsImportant ? '1' : '0', - 'Attachments': aAttachments - }, SEND_MESSAGE_AJAX_TIMEOUT); + sendMessage( + fCallback, + sIdentityID, + sMessageFolder, + sMessageUid, + sSentFolder, + sTo, + sCc, + sBcc, + sReplyTo, + sSubject, + bTextIsHtml, + sText, + aAttachments, + aDraftInfo, + sInReplyTo, + sReferences, + bRequestDsn, + bRequestReadReceipt, + bMarkAsImportant + ) { + this.defaultRequest( + fCallback, + 'SendMessage', + { + 'IdentityID': sIdentityID, + 'MessageFolder': sMessageFolder, + 'MessageUid': sMessageUid, + 'SentFolder': sSentFolder, + 'To': sTo, + 'Cc': sCc, + 'Bcc': sBcc, + 'ReplyTo': sReplyTo, + 'Subject': sSubject, + 'TextIsHtml': bTextIsHtml ? '1' : '0', + 'Text': sText, + 'DraftInfo': aDraftInfo, + 'InReplyTo': sInReplyTo, + 'References': sReferences, + 'Dsn': bRequestDsn ? '1' : '0', + 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0', + 'MarkAsImportant': bMarkAsImportant ? '1' : '0', + 'Attachments': aAttachments + }, + SEND_MESSAGE_AJAX_TIMEOUT + ); } /** @@ -699,13 +776,20 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {boolean=} bMarkAsRead */ messagesMove(fCallback, sFolder, sToFolder, aUids, sLearning, bMarkAsRead) { - this.defaultRequest(fCallback, 'MessageMove', { - 'FromFolder': sFolder, - 'ToFolder': sToFolder, - 'Uids': aUids.join(','), - 'MarkAsRead': bMarkAsRead ? '1' : '0', - 'Learning': sLearning || '' - }, null, '', ['MessageList']); + this.defaultRequest( + fCallback, + 'MessageMove', + { + 'FromFolder': sFolder, + 'ToFolder': sToFolder, + 'Uids': aUids.join(','), + 'MarkAsRead': bMarkAsRead ? '1' : '0', + 'Learning': sLearning || '' + }, + null, + '', + ['MessageList'] + ); } /** @@ -728,10 +812,17 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {Array} aUids */ messagesDelete(fCallback, sFolder, aUids) { - this.defaultRequest(fCallback, 'MessageDelete', { - 'Folder': sFolder, - 'Uids': aUids.join(',') - }, null, '', ['MessageList']); + this.defaultRequest( + fCallback, + 'MessageDelete', + { + 'Folder': sFolder, + 'Uids': aUids.join(',') + }, + null, + '', + ['MessageList'] + ); } /** @@ -755,11 +846,18 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {string} sSearch */ contacts(fCallback, iOffset, iLimit, sSearch) { - this.defaultRequest(fCallback, 'Contacts', { - 'Offset': iOffset, - 'Limit': iLimit, - 'Search': sSearch - }, null, '', ['Contacts']); + this.defaultRequest( + fCallback, + 'Contacts', + { + 'Offset': iOffset, + 'Limit': iLimit, + 'Search': sSearch + }, + null, + '', + ['Contacts'] + ); } /** @@ -792,10 +890,17 @@ class RemoteUserAjax extends AbstractAjaxRemote * @param {number} iPage */ suggestions(fCallback, sQuery, iPage) { - this.defaultRequest(fCallback, 'Suggestions', { - 'Query': sQuery, - 'Page': iPage - }, null, '', ['Suggestions']); + this.defaultRequest( + fCallback, + 'Suggestions', + { + 'Query': sQuery, + 'Page': iPage + }, + null, + '', + ['Suggestions'] + ); } /** diff --git a/dev/Screen/AbstractSettings.js b/dev/Screen/AbstractSettings.js index 479cd233e..28ecb87f9 100644 --- a/dev/Screen/AbstractSettings.js +++ b/dev/Screen/AbstractSettings.js @@ -1,22 +1,19 @@ - import _ from '_'; import $ from '$'; import ko from 'ko'; -import {VIEW_MODELS} from 'Common/Globals'; -import {delegateRun, windowResize, log, isUnd, pString} from 'Common/Utils'; -import {settings} from 'Common/Links'; +import { VIEW_MODELS } from 'Common/Globals'; +import { delegateRun, windowResize, log, isUnd, pString } from 'Common/Utils'; +import { settings } from 'Common/Links'; -import {setHash} from 'Knoin/Knoin'; -import {AbstractScreen} from 'Knoin/AbstractScreen'; +import { setHash } from 'Knoin/Knoin'; +import { AbstractScreen } from 'Knoin/AbstractScreen'; -class AbstractSettingsScreen extends AbstractScreen -{ +class AbstractSettingsScreen extends AbstractScreen { /** * @param {Array} viewModels */ - constructor(viewModels) - { + constructor(viewModels) { super('settings', viewModels); this.menu = ko.observableArray([]); @@ -31,51 +28,57 @@ class AbstractSettingsScreen extends AbstractScreen * @param {Function=} fCallback */ setupSettings(fCallback = null) { - if (fCallback) - { + if (fCallback) { fCallback(); } } onRoute(subName) { - let - settingsScreen = null, + let settingsScreen = null, RoutedSettingsViewModel = null, viewModelPlace = null, viewModelDom = null; - RoutedSettingsViewModel = _.find(VIEW_MODELS.settings, - (SettingsViewModel) => SettingsViewModel && SettingsViewModel.__rlSettingsData && subName === SettingsViewModel.__rlSettingsData.Route + RoutedSettingsViewModel = _.find( + VIEW_MODELS.settings, + (SettingsViewModel) => + SettingsViewModel && SettingsViewModel.__rlSettingsData && subName === SettingsViewModel.__rlSettingsData.Route ); - if (RoutedSettingsViewModel) - { - if (_.find(VIEW_MODELS['settings-removed'], (DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel)) - { + if (RoutedSettingsViewModel) { + if ( + _.find( + VIEW_MODELS['settings-removed'], + (DisabledSettingsViewModel) => + DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel + ) + ) { RoutedSettingsViewModel = null; } - if (RoutedSettingsViewModel && _.find(VIEW_MODELS['settings-disabled'], - (DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel)) - { + if ( + RoutedSettingsViewModel && + _.find( + VIEW_MODELS['settings-disabled'], + (DisabledSettingsViewModel) => + DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel + ) + ) { RoutedSettingsViewModel = null; } } - if (RoutedSettingsViewModel) - { - if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm) - { + if (RoutedSettingsViewModel) { + if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm) { settingsScreen = RoutedSettingsViewModel.__vm; - } - else - { + } else { viewModelPlace = this.oViewModelPlace; - if (viewModelPlace && 1 === viewModelPlace.length) - { + if (viewModelPlace && 1 === viewModelPlace.length) { settingsScreen = new RoutedSettingsViewModel(); - viewModelDom = $('').addClass('rl-settings-view-model').hide(); + viewModelDom = $('') + .addClass('rl-settings-view-model') + .hide(); viewModelDom.appendTo(viewModelPlace); settingsScreen.viewModelDom = viewModelDom; @@ -86,26 +89,26 @@ class AbstractSettingsScreen extends AbstractScreen RoutedSettingsViewModel.__builded = true; RoutedSettingsViewModel.__vm = settingsScreen; - const tmpl = {name: RoutedSettingsViewModel.__rlSettingsData.Template}; - ko.applyBindingAccessorsToNode(viewModelDom[0], { - translatorInit: true, - template: () => tmpl - }, settingsScreen); + const tmpl = { name: RoutedSettingsViewModel.__rlSettingsData.Template }; + ko.applyBindingAccessorsToNode( + viewModelDom[0], + { + translatorInit: true, + template: () => tmpl + }, + settingsScreen + ); delegateRun(settingsScreen, 'onBuild', [viewModelDom]); - } - else - { + } else { log('Cannot find sub settings view model position: SettingsSubScreen'); } } - if (settingsScreen) - { + if (settingsScreen) { _.defer(() => { // hide - if (this.oCurrentSubScreen) - { + if (this.oCurrentSubScreen) { delegateRun(this.oCurrentSubScreen, 'onHide'); this.oCurrentSubScreen.viewModelDom.hide(); } @@ -114,15 +117,18 @@ class AbstractSettingsScreen extends AbstractScreen this.oCurrentSubScreen = settingsScreen; // show - if (this.oCurrentSubScreen) - { + if (this.oCurrentSubScreen) { delegateRun(this.oCurrentSubScreen, 'onBeforeShow'); this.oCurrentSubScreen.viewModelDom.show(); delegateRun(this.oCurrentSubScreen, 'onShow'); delegateRun(this.oCurrentSubScreen, 'onShowWithDelay', [], 200); _.each(this.menu(), (item) => { - item.selected(settingsScreen && settingsScreen.__rlSettingsData && item.route === settingsScreen.__rlSettingsData.Route); + item.selected( + settingsScreen && + settingsScreen.__rlSettingsData && + item.route === settingsScreen.__rlSettingsData.Route + ); }); $('#rl-content .b-settings .b-content .content').scrollTop(0); @@ -132,16 +138,13 @@ class AbstractSettingsScreen extends AbstractScreen windowResize(); }); } - } - else - { + } else { setHash(settings(), false, true); } } onHide() { - if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom) - { + if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom) { delegateRun(this.oCurrentSubScreen, 'onHide'); this.oCurrentSubScreen.viewModelDom.hide(); } @@ -149,15 +152,22 @@ class AbstractSettingsScreen extends AbstractScreen onBuild() { _.each(VIEW_MODELS.settings, (SettingsViewModel) => { - if (SettingsViewModel && SettingsViewModel.__rlSettingsData && !_.find(VIEW_MODELS['settings-removed'], - (RemoveSettingsViewModel) => RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel)) - { + if ( + SettingsViewModel && + SettingsViewModel.__rlSettingsData && + !_.find( + VIEW_MODELS['settings-removed'], + (RemoveSettingsViewModel) => RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel + ) + ) { this.menu.push({ route: SettingsViewModel.__rlSettingsData.Route, label: SettingsViewModel.__rlSettingsData.Label, selected: ko.observable(false), - disabled: !!_.find(VIEW_MODELS['settings-disabled'], - (DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel) + disabled: !!_.find( + VIEW_MODELS['settings-disabled'], + (DisabledSettingsViewModel) => DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel + ) }); } }); @@ -166,12 +176,13 @@ class AbstractSettingsScreen extends AbstractScreen } routes() { - const - DefaultViewModel = _.find( + const DefaultViewModel = _.find( VIEW_MODELS.settings, - (SettingsViewModel) => SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault + (SettingsViewModel) => + SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault ), - defaultRoute = DefaultViewModel && DefaultViewModel.__rlSettingsData ? DefaultViewModel.__rlSettingsData.Route : 'general', + defaultRoute = + DefaultViewModel && DefaultViewModel.__rlSettingsData ? DefaultViewModel.__rlSettingsData.Route : 'general', rules = { subname: /^(.*)$/, normalize_: (rquest, vals) => { @@ -180,12 +191,8 @@ class AbstractSettingsScreen extends AbstractScreen } }; - return [ - ['{subname}/', rules], - ['{subname}', rules], - ['', rules] - ]; + return [['{subname}/', rules], ['{subname}', rules], ['', rules]]; } } -export {AbstractSettingsScreen, AbstractSettingsScreen as default}; +export { AbstractSettingsScreen, AbstractSettingsScreen as default }; diff --git a/dev/Screen/Admin/Login.js b/dev/Screen/Admin/Login.js index b7b836b3a..4e9b6123b 100644 --- a/dev/Screen/Admin/Login.js +++ b/dev/Screen/Admin/Login.js @@ -1,16 +1,12 @@ +import { AbstractScreen } from 'Knoin/AbstractScreen'; -import {AbstractScreen} from 'Knoin/AbstractScreen'; +import { getApp } from 'Helper/Apps/Admin'; -import {getApp} from 'Helper/Apps/Admin'; +import { LoginAdminView } from 'View/Admin/Login'; -import {LoginAdminView} from 'View/Admin/Login'; - -class LoginAdminScreen extends AbstractScreen -{ +class LoginAdminScreen extends AbstractScreen { constructor() { - super('login', [ - LoginAdminView - ]); + super('login', [LoginAdminView]); } onShow() { @@ -18,4 +14,4 @@ class LoginAdminScreen extends AbstractScreen } } -export {LoginAdminScreen, LoginAdminScreen as default}; +export { LoginAdminScreen, LoginAdminScreen as default }; diff --git a/dev/Screen/Admin/Settings.js b/dev/Screen/Admin/Settings.js index f6671bb01..4ee1489d2 100644 --- a/dev/Screen/Admin/Settings.js +++ b/dev/Screen/Admin/Settings.js @@ -1,93 +1,82 @@ -import {addSettingsViewModel} from 'Knoin/Knoin'; -import {runSettingsViewModelHooks} from 'Common/Plugins'; +import { addSettingsViewModel } from 'Knoin/Knoin'; +import { runSettingsViewModelHooks } from 'Common/Plugins'; -import {AbstractSettingsScreen} from 'Screen/AbstractSettings'; +import { AbstractSettingsScreen } from 'Screen/AbstractSettings'; -import {GeneralAdminSettings} from 'Settings/Admin/General'; -import {DomainsAdminSettings} from 'Settings/Admin/Domains'; -import {LoginAdminSettings} from 'Settings/Admin/Login'; -import {ContactsAdminSettings} from 'Settings/Admin/Contacts'; -import {SecurityAdminSettings} from 'Settings/Admin/Security'; -import {SocialAdminSettings} from 'Settings/Admin/Social'; -import {PluginsAdminSettings} from 'Settings/Admin/Plugins'; -import {PackagesAdminSettings} from 'Settings/Admin/Packages'; -import {AboutAdminSettings} from 'Settings/Admin/About'; +import { GeneralAdminSettings } from 'Settings/Admin/General'; +import { DomainsAdminSettings } from 'Settings/Admin/Domains'; +import { LoginAdminSettings } from 'Settings/Admin/Login'; +import { ContactsAdminSettings } from 'Settings/Admin/Contacts'; +import { SecurityAdminSettings } from 'Settings/Admin/Security'; +import { SocialAdminSettings } from 'Settings/Admin/Social'; +import { PluginsAdminSettings } from 'Settings/Admin/Plugins'; +import { PackagesAdminSettings } from 'Settings/Admin/Packages'; +import { AboutAdminSettings } from 'Settings/Admin/About'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -import {MenuSettingsAdminView} from 'View/Admin/Settings/Menu'; -import {PaneSettingsAdminView} from 'View/Admin/Settings/Pane'; +import { MenuSettingsAdminView } from 'View/Admin/Settings/Menu'; +import { PaneSettingsAdminView } from 'View/Admin/Settings/Pane'; -class SettingsAdminScreen extends AbstractSettingsScreen -{ +class SettingsAdminScreen extends AbstractSettingsScreen { constructor() { - super([ - MenuSettingsAdminView, - PaneSettingsAdminView - ]); + super([MenuSettingsAdminView, PaneSettingsAdminView]); } /** * @param {Function=} fCallback = null */ setupSettings(fCallback = null) { - let branding = null, licensing = null; - if (RL_COMMUNITY) - { + if (RL_COMMUNITY) { branding = require('Settings/Admin/Branding').default; - } - else - { + } else { branding = require('Settings/Admin/Prem/Branding').default; licensing = require('Settings/Admin/Prem/Licensing').default; } - addSettingsViewModel(GeneralAdminSettings, - 'AdminSettingsGeneral', 'TABS_LABELS/LABEL_GENERAL_NAME', 'general', true); + addSettingsViewModel( + GeneralAdminSettings, + 'AdminSettingsGeneral', + 'TABS_LABELS/LABEL_GENERAL_NAME', + 'general', + true + ); - addSettingsViewModel(DomainsAdminSettings, - 'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains'); + addSettingsViewModel(DomainsAdminSettings, 'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains'); - addSettingsViewModel(LoginAdminSettings, - 'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login'); + addSettingsViewModel(LoginAdminSettings, 'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login'); - if (branding) - { - addSettingsViewModel(branding, - 'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding'); + if (branding) { + addSettingsViewModel(branding, 'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding'); } - addSettingsViewModel(ContactsAdminSettings, - 'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); + addSettingsViewModel(ContactsAdminSettings, 'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); - addSettingsViewModel(SecurityAdminSettings, - 'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security'); + addSettingsViewModel(SecurityAdminSettings, 'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security'); - addSettingsViewModel(SocialAdminSettings, - 'AdminSettingsSocial', 'TABS_LABELS/LABEL_INTEGRATION_NAME', 'integrations'); + addSettingsViewModel( + SocialAdminSettings, + 'AdminSettingsSocial', + 'TABS_LABELS/LABEL_INTEGRATION_NAME', + 'integrations' + ); - addSettingsViewModel(PluginsAdminSettings, - 'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins'); + addSettingsViewModel(PluginsAdminSettings, 'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins'); - addSettingsViewModel(PackagesAdminSettings, - 'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages'); + addSettingsViewModel(PackagesAdminSettings, 'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages'); - if (licensing) - { - addSettingsViewModel(licensing, - 'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing'); + if (licensing) { + addSettingsViewModel(licensing, 'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing'); } - addSettingsViewModel(AboutAdminSettings, - 'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about'); + addSettingsViewModel(AboutAdminSettings, 'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about'); runSettingsViewModelHooks(true); - if (fCallback) - { + if (fCallback) { fCallback(); } } @@ -97,4 +86,4 @@ class SettingsAdminScreen extends AbstractSettingsScreen } } -export {SettingsAdminScreen, SettingsAdminScreen as default}; +export { SettingsAdminScreen, SettingsAdminScreen as default }; diff --git a/dev/Screen/User/About.js b/dev/Screen/User/About.js index b46672048..0a7330d29 100644 --- a/dev/Screen/User/About.js +++ b/dev/Screen/User/About.js @@ -1,12 +1,10 @@ +import { AbstractScreen } from 'Knoin/AbstractScreen'; -import {AbstractScreen} from 'Knoin/AbstractScreen'; +import { AboutUserView } from 'View/User/About'; -import {AboutUserView} from 'View/User/About'; +import { getApp } from 'Helper/Apps/User'; -import {getApp} from 'Helper/Apps/User'; - -class AboutUserScreen extends AbstractScreen -{ +class AboutUserScreen extends AbstractScreen { constructor() { super('about', [AboutUserView]); } @@ -16,4 +14,4 @@ class AboutUserScreen extends AbstractScreen } } -export {AboutUserScreen, AboutUserScreen as default}; +export { AboutUserScreen, AboutUserScreen as default }; diff --git a/dev/Screen/User/Login.js b/dev/Screen/User/Login.js index 3091865f1..71599447d 100644 --- a/dev/Screen/User/Login.js +++ b/dev/Screen/User/Login.js @@ -1,12 +1,10 @@ +import { AbstractScreen } from 'Knoin/AbstractScreen'; -import {AbstractScreen} from 'Knoin/AbstractScreen'; +import { LoginUserView } from 'View/User/Login'; -import {LoginUserView} from 'View/User/Login'; +import { getApp } from 'Helper/Apps/User'; -import {getApp} from 'Helper/Apps/User'; - -class LoginUserScreen extends AbstractScreen -{ +class LoginUserScreen extends AbstractScreen { constructor() { super('login', [LoginUserView]); } @@ -16,4 +14,4 @@ class LoginUserScreen extends AbstractScreen } } -export {LoginUserScreen, LoginUserScreen as default}; +export { LoginUserScreen, LoginUserScreen as default }; diff --git a/dev/Screen/User/MailBox.js b/dev/Screen/User/MailBox.js index 39792c83b..e9adb5fe3 100644 --- a/dev/Screen/User/MailBox.js +++ b/dev/Screen/User/MailBox.js @@ -1,11 +1,10 @@ - import _ from '_'; -import {Focused, Capa, ClientSideKeyName, Magics} from 'Common/Enums'; -import {$html, leftPanelDisabled, leftPanelType, moveAction, bMobileDevice} from 'Common/Globals'; -import {pString, pInt, decodeURI, windowResizeCallback} from 'Common/Utils'; -import {getFolderFromCacheList, getFolderFullNameRaw, getFolderInboxName} from 'Common/Cache'; -import {i18n} from 'Common/Translator'; +import { Focused, Capa, ClientSideKeyName, Magics } from 'Common/Enums'; +import { $html, leftPanelDisabled, leftPanelType, moveAction, bMobileDevice } from 'Common/Globals'; +import { pString, pInt, decodeURI, windowResizeCallback } from 'Common/Utils'; +import { getFolderFromCacheList, getFolderFullNameRaw, getFolderInboxName } from 'Common/Cache'; +import { i18n } from 'Common/Translator'; import * as Events from 'Common/Events'; import * as Settings from 'Storage/Settings'; @@ -16,19 +15,18 @@ import SettingsStore from 'Stores/User/Settings'; import FolderStore from 'Stores/User/Folder'; import MessageStore from 'Stores/User/Message'; -import {SystemDropDownMailBoxUserView} from 'View/User/MailBox/SystemDropDown'; -import {FolderListMailBoxUserView} from 'View/User/MailBox/FolderList'; -import {MessageListMailBoxUserView} from 'View/User/MailBox/MessageList'; -import {MessageViewMailBoxUserView} from 'View/User/MailBox/MessageView'; +import { SystemDropDownMailBoxUserView } from 'View/User/MailBox/SystemDropDown'; +import { FolderListMailBoxUserView } from 'View/User/MailBox/FolderList'; +import { MessageListMailBoxUserView } from 'View/User/MailBox/MessageList'; +import { MessageViewMailBoxUserView } from 'View/User/MailBox/MessageView'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {warmUpScreenPopup} from 'Knoin/Knoin'; +import { warmUpScreenPopup } from 'Knoin/Knoin'; -import {AbstractScreen} from 'Knoin/AbstractScreen'; +import { AbstractScreen } from 'Knoin/AbstractScreen'; -class MailBoxUserScreen extends AbstractScreen -{ +class MailBoxUserScreen extends AbstractScreen { constructor() { super('mailbox', [ SystemDropDownMailBoxUserView, @@ -45,12 +43,16 @@ class MailBoxUserScreen extends AbstractScreen let foldersInboxUnreadCount = FolderStore.foldersInboxUnreadCount(); const email = AccountStore.email(); - if (Settings.appSettingsGet('listPermanentFiltered')) - { + if (Settings.appSettingsGet('listPermanentFiltered')) { foldersInboxUnreadCount = 0; } - getApp().setWindowTitle(('' === email ? '' : '' + (0 < foldersInboxUnreadCount ? '(' + foldersInboxUnreadCount + ') ' : ' ') + email + ' - ') + i18n('TITLES/MAILBOX')); + getApp().setWindowTitle( + ('' === email + ? '' + : '' + (0 < foldersInboxUnreadCount ? '(' + foldersInboxUnreadCount + ') ' : ' ') + email + ' - ') + + i18n('TITLES/MAILBOX') + ); } /** @@ -62,17 +64,13 @@ class MailBoxUserScreen extends AbstractScreen AppStore.focusedState(Focused.None); AppStore.focusedState(Focused.MessageList); - if (Settings.appSettingsGet('mobile')) - { + if (Settings.appSettingsGet('mobile')) { leftPanelDisabled(true); } - if (!Settings.capa(Capa.Folders)) - { + if (!Settings.capa(Capa.Folders)) { leftPanelType(Settings.capa(Capa.Composer) || Settings.capa(Capa.Contacts) ? 'short' : 'none'); - } - else - { + } else { leftPanelType(''); } } @@ -87,10 +85,8 @@ class MailBoxUserScreen extends AbstractScreen let threadUid = folderHash.replace(/^(.+)~([\d]+)$/, '$2'); const folder = getFolderFromCacheList(getFolderFullNameRaw(folderHash.replace(/~([\d]+)$/, ''))); - if (folder) - { - if (folderHash === threadUid) - { + if (folder) { + if (folderHash === threadUid) { threadUid = ''; } @@ -121,8 +117,7 @@ class MailBoxUserScreen extends AbstractScreen const email = AccountStore.email(); _.each(AccountStore.accounts(), (item) => { - if (item && email === item.email) - { + if (item && email === item.email) { item.count(count); } }); @@ -135,8 +130,7 @@ class MailBoxUserScreen extends AbstractScreen * @returns {void} */ onBuild() { - if (!bMobileDevice && !Settings.appSettingsGet('mobile')) - { + if (!bMobileDevice && !Settings.appSettingsGet('mobile')) { _.defer(() => { getApp().initHorizontalLayoutResizer(ClientSideKeyName.MessageListSize); }); @@ -151,16 +145,14 @@ class MailBoxUserScreen extends AbstractScreen * @returns {Array} */ routes() { - const - inboxFolderName = getFolderInboxName(), + const inboxFolderName = getFolderInboxName(), fNormS = (request, vals) => { vals[0] = pString(vals[0]); vals[1] = pInt(vals[1]); vals[1] = 0 >= vals[1] ? 1 : vals[1]; vals[2] = pString(vals[2]); - if ('' === request) - { + if ('' === request) { vals[0] = inboxFolderName; vals[1] = 1; } @@ -171,8 +163,7 @@ class MailBoxUserScreen extends AbstractScreen vals[0] = pString(vals[0]); vals[1] = pString(vals[1]); - if ('' === request) - { + if ('' === request) { vals[0] = inboxFolderName; } @@ -180,12 +171,12 @@ class MailBoxUserScreen extends AbstractScreen }; return [ - [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)\/(.+)\/?$/, {'normalize_': fNormS}], - [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)$/, {'normalize_': fNormS}], - [/^([a-zA-Z0-9~]+)\/(.+)\/?$/, {'normalize_': fNormD}], - [/^([^\/]*)$/, {'normalize_': fNormS}] + [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)\/(.+)\/?$/, { 'normalize_': fNormS }], + [/^([a-zA-Z0-9~]+)\/p([1-9][0-9]*)$/, { 'normalize_': fNormS }], + [/^([a-zA-Z0-9~]+)\/(.+)\/?$/, { 'normalize_': fNormD }], + [/^([^/]*)$/, { 'normalize_': fNormS }] ]; } } -export {MailBoxUserScreen, MailBoxUserScreen as default}; +export { MailBoxUserScreen, MailBoxUserScreen as default }; diff --git a/dev/Screen/User/Settings.js b/dev/Screen/User/Settings.js index 046a555fc..18700cf38 100644 --- a/dev/Screen/User/Settings.js +++ b/dev/Screen/User/Settings.js @@ -1,135 +1,127 @@ - -import {Capa, KeyState} from 'Common/Enums'; -import {keyScope, leftPanelType, leftPanelDisabled} from 'Common/Globals'; -import {runSettingsViewModelHooks} from 'Common/Plugins'; -import {initOnStartOrLangChange, i18n} from 'Common/Translator'; +import { Capa, KeyState } from 'Common/Enums'; +import { keyScope, leftPanelType, leftPanelDisabled } from 'Common/Globals'; +import { runSettingsViewModelHooks } from 'Common/Plugins'; +import { initOnStartOrLangChange, i18n } from 'Common/Translator'; import AppStore from 'Stores/User/App'; import AccountStore from 'Stores/User/Account'; import * as Settings from 'Storage/Settings'; -import {addSettingsViewModel} from 'Knoin/Knoin'; +import { addSettingsViewModel } from 'Knoin/Knoin'; -import {AbstractSettingsScreen} from 'Screen/AbstractSettings'; +import { AbstractSettingsScreen } from 'Screen/AbstractSettings'; -import {GeneralUserSettings} from 'Settings/User/General'; -import {ContactsUserSettings} from 'Settings/User/Contacts'; -import {AccountsUserSettings} from 'Settings/User/Accounts'; -import {FiltersUserSettings} from 'Settings/User/Filters'; -import {SecurityUserSettings} from 'Settings/User/Security'; -import {SocialUserSettings} from 'Settings/User/Social'; -import {ChangePasswordUserSettings} from 'Settings/User/ChangePassword'; -import {TemplatesUserSettings} from 'Settings/User/Templates'; -import {FoldersUserSettings} from 'Settings/User/Folders'; -import {ThemesUserSettings} from 'Settings/User/Themes'; -import {OpenPgpUserSettings} from 'Settings/User/OpenPgp'; +import { GeneralUserSettings } from 'Settings/User/General'; +import { ContactsUserSettings } from 'Settings/User/Contacts'; +import { AccountsUserSettings } from 'Settings/User/Accounts'; +import { FiltersUserSettings } from 'Settings/User/Filters'; +import { SecurityUserSettings } from 'Settings/User/Security'; +import { SocialUserSettings } from 'Settings/User/Social'; +import { ChangePasswordUserSettings } from 'Settings/User/ChangePassword'; +import { TemplatesUserSettings } from 'Settings/User/Templates'; +import { FoldersUserSettings } from 'Settings/User/Folders'; +import { ThemesUserSettings } from 'Settings/User/Themes'; +import { OpenPgpUserSettings } from 'Settings/User/OpenPgp'; -import {SystemDropDownSettingsUserView} from 'View/User/Settings/SystemDropDown'; -import {MenuSettingsUserView} from 'View/User/Settings/Menu'; -import {PaneSettingsUserView} from 'View/User/Settings/Pane'; +import { SystemDropDownSettingsUserView } from 'View/User/Settings/SystemDropDown'; +import { MenuSettingsUserView } from 'View/User/Settings/Menu'; +import { PaneSettingsUserView } from 'View/User/Settings/Pane'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -class SettingsUserScreen extends AbstractSettingsScreen -{ +class SettingsUserScreen extends AbstractSettingsScreen { constructor() { - super([ - SystemDropDownSettingsUserView, - MenuSettingsUserView, - PaneSettingsUserView - ]); + super([SystemDropDownSettingsUserView, MenuSettingsUserView, PaneSettingsUserView]); - initOnStartOrLangChange(() => { - this.sSettingsTitle = i18n('TITLES/SETTINGS'); - }, () => { - this.setSettingsTitle(); - }); + initOnStartOrLangChange( + () => { + this.sSettingsTitle = i18n('TITLES/SETTINGS'); + }, + () => { + this.setSettingsTitle(); + } + ); } /** * @param {Function=} fCallback */ setupSettings(fCallback = null) { - if (!Settings.capa(Capa.Settings)) - { - if (fCallback) - { + if (!Settings.capa(Capa.Settings)) { + if (fCallback) { fCallback(); } return false; } - addSettingsViewModel(GeneralUserSettings, - 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true); + addSettingsViewModel(GeneralUserSettings, 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true); - if (AppStore.contactsIsAllowed()) - { - addSettingsViewModel(ContactsUserSettings, - 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); + if (AppStore.contactsIsAllowed()) { + addSettingsViewModel(ContactsUserSettings, 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); } - if (Settings.capa(Capa.AdditionalAccounts) || Settings.capa(Capa.Identities)) - { - addSettingsViewModel(AccountsUserSettings, 'SettingsAccounts', - Settings.capa(Capa.AdditionalAccounts) ? 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME' : 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'accounts'); + if (Settings.capa(Capa.AdditionalAccounts) || Settings.capa(Capa.Identities)) { + addSettingsViewModel( + AccountsUserSettings, + 'SettingsAccounts', + Settings.capa(Capa.AdditionalAccounts) + ? 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME' + : 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', + 'accounts' + ); } - if (Settings.capa(Capa.Sieve)) - { - addSettingsViewModel(FiltersUserSettings, - 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters'); + if (Settings.capa(Capa.Sieve)) { + addSettingsViewModel(FiltersUserSettings, 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters'); } - if (Settings.capa(Capa.AutoLogout) || Settings.capa(Capa.TwoFactor)) - { - addSettingsViewModel(SecurityUserSettings, - 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security'); + if (Settings.capa(Capa.AutoLogout) || Settings.capa(Capa.TwoFactor)) { + addSettingsViewModel(SecurityUserSettings, 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security'); } - if (AccountStore.isRootAccount() && ( - (Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) || - Settings.settingsGet('AllowFacebookSocial') || - Settings.settingsGet('AllowTwitterSocial'))) - { - addSettingsViewModel(SocialUserSettings, - 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social'); + if ( + AccountStore.isRootAccount() && + ((Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) || + Settings.settingsGet('AllowFacebookSocial') || + Settings.settingsGet('AllowTwitterSocial')) + ) { + addSettingsViewModel(SocialUserSettings, 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social'); } - if (Settings.settingsGet('ChangePasswordIsAllowed')) - { - addSettingsViewModel(ChangePasswordUserSettings, - 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password'); + if (Settings.settingsGet('ChangePasswordIsAllowed')) { + addSettingsViewModel( + ChangePasswordUserSettings, + 'SettingsChangePassword', + 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', + 'change-password' + ); } - if (Settings.capa(Capa.Templates)) - { - addSettingsViewModel(TemplatesUserSettings, - 'SettingsTemplates', 'SETTINGS_LABELS/LABEL_TEMPLATES_NAME', 'templates'); + if (Settings.capa(Capa.Templates)) { + addSettingsViewModel( + TemplatesUserSettings, + 'SettingsTemplates', + 'SETTINGS_LABELS/LABEL_TEMPLATES_NAME', + 'templates' + ); } - if (Settings.capa(Capa.Folders)) - { - addSettingsViewModel(FoldersUserSettings, - 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders'); + if (Settings.capa(Capa.Folders)) { + addSettingsViewModel(FoldersUserSettings, 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders'); } - if (Settings.capa(Capa.Themes)) - { - addSettingsViewModel(ThemesUserSettings, - 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes'); + if (Settings.capa(Capa.Themes)) { + addSettingsViewModel(ThemesUserSettings, 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes'); } - if (Settings.capa(Capa.OpenPGP)) - { - addSettingsViewModel(OpenPgpUserSettings, - 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp'); + if (Settings.capa(Capa.OpenPGP)) { + addSettingsViewModel(OpenPgpUserSettings, 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp'); } runSettingsViewModelHooks(false); - if (fCallback) - { + if (fCallback) { fCallback(); } @@ -141,8 +133,7 @@ class SettingsUserScreen extends AbstractSettingsScreen keyScope(KeyState.Settings); leftPanelType(''); - if (Settings.appSettingsGet('mobile')) - { + if (Settings.appSettingsGet('mobile')) { leftPanelDisabled(true); } } @@ -153,4 +144,4 @@ class SettingsUserScreen extends AbstractSettingsScreen } } -export {SettingsUserScreen, SettingsUserScreen as default}; +export { SettingsUserScreen, SettingsUserScreen as default }; diff --git a/dev/Settings/Admin/About.js b/dev/Settings/Admin/About.js index 5dacd5ae9..f12fa3828 100644 --- a/dev/Settings/Admin/About.js +++ b/dev/Settings/Admin/About.js @@ -1,15 +1,14 @@ import ko from 'ko'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; -import {appSettingsGet, settingsGet} from 'Storage/Settings'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; +import { appSettingsGet, settingsGet } from 'Storage/Settings'; import AppStore from 'Stores/Admin/App'; import CoreStore from 'Stores/Admin/Core'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -class AboutAdminSettings -{ +class AboutAdminSettings { constructor() { this.version = ko.observable(appSettingsGet('version')); this.access = ko.observable(!!settingsGet('CoreAccess')); @@ -32,35 +31,25 @@ class AboutAdminSettings this.coreRemoteVersionHtmlDesc = ko.computed(() => { translatorTrigger(); - return i18n('TAB_ABOUT/HTML_NEW_VERSION', {'VERSION': this.coreRemoteVersion()}); + return i18n('TAB_ABOUT/HTML_NEW_VERSION', { 'VERSION': this.coreRemoteVersion() }); }); this.statusType = ko.computed(() => { let type = ''; - const - versionToCompare = this.coreVersionCompare(), + const versionToCompare = this.coreVersionCompare(), isChecking = this.coreChecking(), isUpdating = this.coreUpdating(), isReal = this.coreReal(); - if (isChecking) - { + if (isChecking) { type = 'checking'; - } - else if (isUpdating) - { + } else if (isUpdating) { type = 'updating'; - } - else if (isReal && 0 === versionToCompare) - { + } else if (isReal && 0 === versionToCompare) { type = 'up-to-date'; - } - else if (isReal && -1 === versionToCompare) - { + } else if (isReal && -1 === versionToCompare) { type = 'available'; - } - else if (!isReal) - { + } else if (!isReal) { type = 'error'; this.errorDesc('Cannot access the repository at the moment.'); } @@ -70,18 +59,16 @@ class AboutAdminSettings } onBuild() { - if (this.access() && !this.community) - { + if (this.access() && !this.community) { getApp().reloadCoreData(); } } updateCoreData() { - if (!this.coreUpdating() && !this.community) - { + if (!this.coreUpdating() && !this.community) { getApp().updateCoreData(); } } } -export {AboutAdminSettings, AboutAdminSettings as default}; +export { AboutAdminSettings, AboutAdminSettings as default }; diff --git a/dev/Settings/Admin/Branding.js b/dev/Settings/Admin/Branding.js index f350eb8d2..a42ab5f6c 100644 --- a/dev/Settings/Admin/Branding.js +++ b/dev/Settings/Admin/Branding.js @@ -1,18 +1,16 @@ - import _ from '_'; import ko from 'ko'; -import {Magics} from 'Common/Enums'; -import {settingsSaveHelperSimpleFunction, trim} from 'Common/Utils'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; +import { Magics } from 'Common/Enums'; +import { settingsSaveHelperSimpleFunction, trim } from 'Common/Utils'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; import Remote from 'Remote/Admin/Ajax'; import AppStore from 'Stores/Admin/App'; -import {settingsGet} from 'Storage/Settings'; +import { settingsGet } from 'Storage/Settings'; -class BrandingAdminSettings -{ +class BrandingAdminSettings { constructor() { this.capa = AppStore.prem; @@ -33,9 +31,9 @@ class BrandingAdminSettings this.welcomePageDisplay.options = ko.computed(() => { translatorTrigger(); return [ - {optValue: 'none', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE')}, - {optValue: 'once', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE')}, - {optValue: 'always', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS')} + { optValue: 'none', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE') }, + { optValue: 'once', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE') }, + { optValue: 'always', optText: i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS') } ]; }); @@ -45,8 +43,7 @@ class BrandingAdminSettings onBuild() { _.delay(() => { - const - f1 = settingsSaveHelperSimpleFunction(this.title.trigger, this), + const f1 = settingsSaveHelperSimpleFunction(this.title.trigger, this), f2 = settingsSaveHelperSimpleFunction(this.loadingDesc.trigger, this), f3 = settingsSaveHelperSimpleFunction(this.faviconUrl.trigger, this); @@ -71,4 +68,4 @@ class BrandingAdminSettings } } -export {BrandingAdminSettings, BrandingAdminSettings as default}; +export { BrandingAdminSettings, BrandingAdminSettings as default }; diff --git a/dev/Settings/Admin/Contacts.js b/dev/Settings/Admin/Contacts.js index 8cc94b63a..9e9beef35 100644 --- a/dev/Settings/Admin/Contacts.js +++ b/dev/Settings/Admin/Contacts.js @@ -1,32 +1,24 @@ - import _ from '_'; import ko from 'ko'; -import { - settingsSaveHelperSimpleFunction, - defautOptionsAfterRender, - inArray, trim, boolToAjax -} from 'Common/Utils'; +import { settingsSaveHelperSimpleFunction, defautOptionsAfterRender, inArray, trim, boolToAjax } from 'Common/Utils'; -import {SaveSettingsStep, StorageResultType, Magics} from 'Common/Enums'; -import {i18n} from 'Common/Translator'; -import {settingsGet} from 'Storage/Settings'; +import { SaveSettingsStep, StorageResultType, Magics } from 'Common/Enums'; +import { i18n } from 'Common/Translator'; +import { settingsGet } from 'Storage/Settings'; import Remote from 'Remote/Admin/Ajax'; -import {command} from 'Knoin/Knoin'; +import { command } from 'Knoin/Knoin'; -class ContactsAdminSettings -{ +class ContactsAdminSettings { constructor() { this.defautOptionsAfterRender = defautOptionsAfterRender; this.enableContacts = ko.observable(!!settingsGet('ContactsEnable')); this.contactsSync = ko.observable(!!settingsGet('ContactsSync')); - const - supportedTypes = [], + const supportedTypes = [], types = ['sqlite', 'mysql', 'pgsql'], getTypeName = (name) => { - switch (name) - { + switch (name) { case 'sqlite': name = 'SQLite'; break; @@ -42,16 +34,13 @@ class ContactsAdminSettings return name; }; - if (settingsGet('SQLiteIsSupported')) - { + if (settingsGet('SQLiteIsSupported')) { supportedTypes.push('sqlite'); } - if (settingsGet('MySqlIsSupported')) - { + if (settingsGet('MySqlIsSupported')) { supportedTypes.push('mysql'); } - if (settingsGet('PostgreSqlIsSupported')) - { + if (settingsGet('PostgreSqlIsSupported')) { supportedTypes.push('pgsql'); } @@ -70,26 +59,22 @@ class ContactsAdminSettings this.contactsTypes(types); this.contactsType = ko.observable(''); - this.mainContactsType = ko.computed({ - read: this.contactsType, - write: (value) => { - if (value !== this.contactsType()) - { - if (-1 < inArray(value, supportedTypes)) - { - this.contactsType(value); - } - else if (0 < supportedTypes.length) - { - this.contactsType(''); + this.mainContactsType = ko + .computed({ + read: this.contactsType, + write: (value) => { + if (value !== this.contactsType()) { + if (-1 < inArray(value, supportedTypes)) { + this.contactsType(value); + } else if (0 < supportedTypes.length) { + this.contactsType(''); + } + } else { + this.contactsType.valueHasMutated(); } } - else - { - this.contactsType.valueHasMutated(); - } - } - }).extend({notify: 'always'}); + }) + .extend({ notify: 'always' }); this.contactsType.subscribe(() => { this.testContactsSuccess(false); @@ -136,19 +121,13 @@ class ContactsAdminSettings this.testContactsError(false); this.testContactsErrorMessage(''); - if (StorageResultType.Success === result && data && data.Result && data.Result.Result) - { + if (StorageResultType.Success === result && data && data.Result && data.Result.Result) { this.testContactsSuccess(true); - } - else - { + } else { this.testContactsError(true); - if (data && data.Result) - { + if (data && data.Result) { this.testContactsErrorMessage(data.Result.Message || ''); - } - else - { + } else { this.testContactsErrorMessage(''); } } @@ -164,8 +143,7 @@ class ContactsAdminSettings onBuild() { _.delay(() => { - const - f1 = settingsSaveHelperSimpleFunction(this.pdoDsnTrigger, this), + const f1 = settingsSaveHelperSimpleFunction(this.pdoDsnTrigger, this), f3 = settingsSaveHelperSimpleFunction(this.pdoUserTrigger, this), f4 = settingsSaveHelperSimpleFunction(this.pdoPasswordTrigger, this), f5 = settingsSaveHelperSimpleFunction(this.contactsTypeTrigger, this); @@ -211,4 +189,4 @@ class ContactsAdminSettings } } -export {ContactsAdminSettings, ContactsAdminSettings as default}; +export { ContactsAdminSettings, ContactsAdminSettings as default }; diff --git a/dev/Settings/Admin/Domains.js b/dev/Settings/Admin/Domains.js index 0238e07bb..782a0b68d 100644 --- a/dev/Settings/Admin/Domains.js +++ b/dev/Settings/Admin/Domains.js @@ -1,17 +1,15 @@ - import _ from '_'; import ko from 'ko'; -import {StorageResultType} from 'Common/Enums'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { StorageResultType } from 'Common/Enums'; +import { showScreenPopup } from 'Knoin/Knoin'; import DomainStore from 'Stores/Admin/Domain'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -class DomainsAdminSettings -{ +class DomainsAdminSettings { constructor() { this.domains = DomainStore.domains; @@ -43,21 +41,19 @@ class DomainsAdminSettings onBuild(oDom) { const self = this; - oDom - .on('click', '.b-admin-domains-list-table .e-item .e-action', function() { // eslint-disable-line prefer-arrow-callback - const domainItem = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (domainItem) - { - Remote.domain(self.onDomainLoadRequest, domainItem.name); - } - }); + oDom.on('click', '.b-admin-domains-list-table .e-item .e-action', function() { + // eslint-disable-line prefer-arrow-callback + const domainItem = ko.dataFor(this); // eslint-disable-line no-invalid-this + if (domainItem) { + Remote.domain(self.onDomainLoadRequest, domainItem.name); + } + }); getApp().reloadDomainList(); } onDomainLoadRequest(sResult, oData) { - if (StorageResultType.Success === sResult && oData && oData.Result) - { + if (StorageResultType.Success === sResult && oData && oData.Result) { showScreenPopup(require('View/Popup/Domain'), [oData.Result]); } } @@ -67,4 +63,4 @@ class DomainsAdminSettings } } -export {DomainsAdminSettings, DomainsAdminSettings as default}; +export { DomainsAdminSettings, DomainsAdminSettings as default }; diff --git a/dev/Settings/Admin/General.js b/dev/Settings/Admin/General.js index 988c6abb2..58149538c 100644 --- a/dev/Settings/Admin/General.js +++ b/dev/Settings/Admin/General.js @@ -1,18 +1,22 @@ - import _ from '_'; import ko from 'ko'; import { - trim, pInt, boolToAjax, settingsSaveHelperSimpleFunction, - changeTheme, convertThemeName, convertLangName + trim, + pInt, + boolToAjax, + settingsSaveHelperSimpleFunction, + changeTheme, + convertThemeName, + convertLangName } from 'Common/Utils'; -import {SaveSettingsStep, Magics} from 'Common/Enums'; -import {reload as translatorReload} from 'Common/Translator'; -import {phpInfo} from 'Common/Links'; +import { SaveSettingsStep, Magics } from 'Common/Enums'; +import { reload as translatorReload } from 'Common/Translator'; +import { phpInfo } from 'Common/Links'; -import {settingsGet} from 'Storage/Settings'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { settingsGet } from 'Storage/Settings'; +import { showScreenPopup } from 'Knoin/Knoin'; import Remote from 'Remote/Admin/Ajax'; @@ -21,8 +25,7 @@ import LanguageStore from 'Stores/Language'; import AppAdminStore from 'Stores/Admin/App'; import CapaAdminStore from 'Stores/Admin/Capa'; -class GeneralAdminSettings -{ +class GeneralAdminSettings { constructor() { this.language = LanguageStore.language; this.languages = LanguageStore.languages; @@ -46,29 +49,37 @@ class GeneralAdminSettings this.dataFolderAccess = AppAdminStore.dataFolderAccess; - this.mainAttachmentLimit = ko.observable(pInt(settingsGet('AttachmentLimit')) / (Magics.BitLength1024 * Magics.BitLength1024)).extend({posInterer: 25}); + this.mainAttachmentLimit = ko + .observable(pInt(settingsGet('AttachmentLimit')) / (Magics.BitLength1024 * Magics.BitLength1024)) + .extend({ posInterer: 25 }); this.uploadData = settingsGet('PhpUploadSizes'); - this.uploadDataDesc = this.uploadData && (this.uploadData.upload_max_filesize || this.uploadData.post_max_size) ? [ - this.uploadData.upload_max_filesize ? 'upload_max_filesize = ' + this.uploadData.upload_max_filesize + '; ' : '', - this.uploadData.post_max_size ? 'post_max_size = ' + this.uploadData.post_max_size : '' - ].join('') : ''; + this.uploadDataDesc = + this.uploadData && (this.uploadData.upload_max_filesize || this.uploadData.post_max_size) + ? [ + this.uploadData.upload_max_filesize + ? 'upload_max_filesize = ' + this.uploadData.upload_max_filesize + '; ' + : '', + this.uploadData.post_max_size ? 'post_max_size = ' + this.uploadData.post_max_size : '' + ].join('') + : ''; - this.themesOptions = ko.computed(() => _.map(this.themes(), (theme) => ({optValue: theme, optText: convertThemeName(theme)}))); + this.themesOptions = ko.computed(() => + _.map(this.themes(), (theme) => ({ optValue: theme, optText: convertThemeName(theme) })) + ); this.languageFullName = ko.computed(() => convertLangName(this.language())); this.languageAdminFullName = ko.computed(() => convertLangName(this.languageAdmin())); this.attachmentLimitTrigger = ko.observable(SaveSettingsStep.Idle); this.languageTrigger = ko.observable(SaveSettingsStep.Idle); - this.languageAdminTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); + this.languageAdminTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms }); this.themeTrigger = ko.observable(SaveSettingsStep.Idle); } onBuild() { _.delay(() => { - const - f1 = settingsSaveHelperSimpleFunction(this.attachmentLimitTrigger, this), + const f1 = settingsSaveHelperSimpleFunction(this.attachmentLimitTrigger, this), f2 = settingsSaveHelperSimpleFunction(this.languageTrigger, this), f3 = settingsSaveHelperSimpleFunction(this.themeTrigger, this), fReloadLanguageHelper = (saveSettingsStep) => () => { @@ -90,14 +101,13 @@ class GeneralAdminSettings this.languageAdmin.subscribe((value) => { this.languageAdminTrigger(SaveSettingsStep.Animate); - translatorReload(true, value).then( - fReloadLanguageHelper(SaveSettingsStep.TrueResult), - fReloadLanguageHelper(SaveSettingsStep.FalseResult) - ).then(() => { - Remote.saveAdminConfig(null, { - 'LanguageAdmin': trim(value) + translatorReload(true, value) + .then(fReloadLanguageHelper(SaveSettingsStep.TrueResult), fReloadLanguageHelper(SaveSettingsStep.FalseResult)) + .then(() => { + Remote.saveAdminConfig(null, { + 'LanguageAdmin': trim(value) + }); }); - }); }); this.theme.subscribe((value) => { @@ -164,14 +174,14 @@ class GeneralAdminSettings } selectLanguage() { - showScreenPopup(require('View/Popup/Languages'), [ - this.language, this.languages(), LanguageStore.userLanguage() - ]); + showScreenPopup(require('View/Popup/Languages'), [this.language, this.languages(), LanguageStore.userLanguage()]); } selectLanguageAdmin() { showScreenPopup(require('View/Popup/Languages'), [ - this.languageAdmin, this.languagesAdmin(), LanguageStore.userLanguageAdmin() + this.languageAdmin, + this.languagesAdmin(), + LanguageStore.userLanguageAdmin() ]); } @@ -183,4 +193,4 @@ class GeneralAdminSettings } } -export {GeneralAdminSettings, GeneralAdminSettings as default}; +export { GeneralAdminSettings, GeneralAdminSettings as default }; diff --git a/dev/Settings/Admin/Login.js b/dev/Settings/Admin/Login.js index 2d7836cf8..b06b2be50 100644 --- a/dev/Settings/Admin/Login.js +++ b/dev/Settings/Admin/Login.js @@ -1,16 +1,14 @@ - import _ from '_'; import ko from 'ko'; -import {settingsSaveHelperSimpleFunction, boolToAjax, trim} from 'Common/Utils'; -import {settingsGet} from 'Storage/Settings'; +import { settingsSaveHelperSimpleFunction, boolToAjax, trim } from 'Common/Utils'; +import { settingsGet } from 'Storage/Settings'; import AppStore from 'Stores/Admin/App'; import Remote from 'Remote/Admin/Ajax'; -class LoginAdminSettings -{ +class LoginAdminSettings { constructor() { this.determineUserLanguage = AppStore.determineUserLanguage; this.determineUserDomain = AppStore.determineUserDomain; @@ -52,4 +50,4 @@ class LoginAdminSettings } } -export {LoginAdminSettings, LoginAdminSettings as default}; +export { LoginAdminSettings, LoginAdminSettings as default }; diff --git a/dev/Settings/Admin/Packages.js b/dev/Settings/Admin/Packages.js index 044f15c8e..7ce46c076 100644 --- a/dev/Settings/Admin/Packages.js +++ b/dev/Settings/Admin/Packages.js @@ -1,18 +1,16 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {getNotification} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { getNotification } from 'Common/Translator'; import PackageStore from 'Stores/Admin/Package'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -class PackagesAdminSettings -{ +class PackagesAdminSettings { constructor() { this.packagesError = ko.observable(''); @@ -37,54 +35,44 @@ class PackagesAdminSettings requestHelper(packageToRequest, install) { return (result, data) => { - - if (StorageResultType.Success !== result || !data || !data.Result) - { - if (data && data.ErrorCode) - { + if (StorageResultType.Success !== result || !data || !data.Result) { + if (data && data.ErrorCode) { this.packagesError(getNotification(data.ErrorCode)); - } - else - { - this.packagesError(getNotification( - install ? Notification.CantInstallPackage : Notification.CantDeletePackage)); + } else { + this.packagesError( + getNotification(install ? Notification.CantInstallPackage : Notification.CantDeletePackage) + ); } } _.each(this.packages(), (item) => { - if (item && packageToRequest && item.loading && item.loading() && packageToRequest.file === item.file) - { + if (item && packageToRequest && item.loading && item.loading() && packageToRequest.file === item.file) { packageToRequest.loading(false); item.loading(false); } }); - if (StorageResultType.Success === result && data && data.Result && data.Result.Reload) - { + if (StorageResultType.Success === result && data && data.Result && data.Result.Reload) { window.location.reload(); - } - else - { + } else { getApp().reloadPackagesList(); } }; } deletePackage(packageToDelete) { - if (packageToDelete) - { + if (packageToDelete) { packageToDelete.loading(true); Remote.packageDelete(this.requestHelper(packageToDelete, false), packageToDelete); } } installPackage(packageToInstall) { - if (packageToInstall) - { + if (packageToInstall) { packageToInstall.loading(true); Remote.packageInstall(this.requestHelper(packageToInstall, true), packageToInstall); } } } -export {PackagesAdminSettings, PackagesAdminSettings as default}; +export { PackagesAdminSettings, PackagesAdminSettings as default }; diff --git a/dev/Settings/Admin/Plugins.js b/dev/Settings/Admin/Plugins.js index 449c40cec..2729be672 100644 --- a/dev/Settings/Admin/Plugins.js +++ b/dev/Settings/Admin/Plugins.js @@ -1,22 +1,21 @@ import _ from '_'; import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {getNotification} from 'Common/Translator'; -import {boolToAjax} from 'Common/Utils'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { getNotification } from 'Common/Translator'; +import { boolToAjax } from 'Common/Utils'; -import {settingsGet} from 'Storage/Settings'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { settingsGet } from 'Storage/Settings'; +import { showScreenPopup } from 'Knoin/Knoin'; import AppStore from 'Stores/Admin/App'; import PluginStore from 'Stores/Admin/Plugin'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -class PluginsAdminSettings -{ +class PluginsAdminSettings { constructor() { this.enabledPlugins = ko.observable(!!settingsGet('EnabledPlugins')); @@ -41,21 +40,20 @@ class PluginsAdminSettings } onBuild(oDom) { - const self = this; oDom - .on('click', '.e-item .configure-plugin-action', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.e-item .configure-plugin-action', function() { + // eslint-disable-line prefer-arrow-callback const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (plugin) - { + if (plugin) { self.configurePlugin(plugin); } }) - .on('click', '.e-item .disabled-plugin', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.e-item .disabled-plugin', function() { + // eslint-disable-line prefer-arrow-callback const plugin = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (plugin) - { + if (plugin) { self.disablePlugin(plugin); } }); @@ -73,23 +71,17 @@ class PluginsAdminSettings } onPluginLoadRequest(result, data) { - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { showScreenPopup(require('View/Popup/Plugin'), [data.Result]); } } onPluginDisableRequest(result, data) { - if (StorageResultType.Success === result && data) - { - if (!data.Result && data.ErrorCode) - { - if (Notification.UnsupportedPluginPackage === data.ErrorCode && data.ErrorMessage && '' !== data.ErrorMessage) - { + if (StorageResultType.Success === result && data) { + if (!data.Result && data.ErrorCode) { + if (Notification.UnsupportedPluginPackage === data.ErrorCode && data.ErrorMessage && '' !== data.ErrorMessage) { PluginStore.plugins.error(data.ErrorMessage); - } - else - { + } else { PluginStore.plugins.error(getNotification(data.ErrorCode)); } } @@ -99,4 +91,4 @@ class PluginsAdminSettings } } -export {PluginsAdminSettings, PluginsAdminSettings as default}; +export { PluginsAdminSettings, PluginsAdminSettings as default }; diff --git a/dev/Settings/Admin/Prem/Branding.js b/dev/Settings/Admin/Prem/Branding.js index 681f3cfb5..50b30110b 100644 --- a/dev/Settings/Admin/Prem/Branding.js +++ b/dev/Settings/Admin/Prem/Branding.js @@ -1,23 +1,18 @@ - import _ from '_'; -import {settingsSaveHelperSimpleFunction, trim, boolToAjax} from 'Common/Utils'; -import {Magics} from 'Common/Enums'; +import { settingsSaveHelperSimpleFunction, trim, boolToAjax } from 'Common/Utils'; +import { Magics } from 'Common/Enums'; import Remote from 'Remote/Admin/Ajax'; -import {BrandingAdminSettings} from 'Settings/Admin/Branding'; +import { BrandingAdminSettings } from 'Settings/Admin/Branding'; -class BrandingPremAdminSettings extends BrandingAdminSettings -{ +class BrandingPremAdminSettings extends BrandingAdminSettings { onBuild(dom) { super.onBuild(dom); - if (this.capa && this.capa() && !this.community) - { + if (this.capa && this.capa() && !this.community) { _.delay(() => { - - const - f1 = settingsSaveHelperSimpleFunction(this.loginLogo.trigger, this), + const f1 = settingsSaveHelperSimpleFunction(this.loginLogo.trigger, this), f2 = settingsSaveHelperSimpleFunction(this.loginDescription.trigger, this), f3 = settingsSaveHelperSimpleFunction(this.loginCss.trigger, this), f4 = settingsSaveHelperSimpleFunction(this.userLogo.trigger, this), @@ -100,10 +95,9 @@ class BrandingPremAdminSettings extends BrandingAdminSettings 'LoginPowered': boolToAjax(value) }); }); - }, Magics.Time50ms); } } } -export {BrandingPremAdminSettings, BrandingPremAdminSettings as default}; +export { BrandingPremAdminSettings, BrandingPremAdminSettings as default }; diff --git a/dev/Settings/Admin/Prem/Licensing.js b/dev/Settings/Admin/Prem/Licensing.js index ee7d4ad85..b1224baa6 100644 --- a/dev/Settings/Admin/Prem/Licensing.js +++ b/dev/Settings/Admin/Prem/Licensing.js @@ -1,16 +1,14 @@ - import ko from 'ko'; import moment from 'moment'; -import {settingsGet} from 'Storage/Settings'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { settingsGet } from 'Storage/Settings'; +import { showScreenPopup } from 'Knoin/Knoin'; import LicenseStore from 'Stores/Admin/License'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -class LicensingPremAdminSettings -{ +class LicensingPremAdminSettings { constructor() { this.licensing = LicenseStore.licensing; this.licensingProcess = LicenseStore.licensingProcess; @@ -23,16 +21,14 @@ class LicensingPremAdminSettings this.subscriptionEnabled = ko.observable(!!settingsGet('SubscriptionEnabled')); this.licenseTrigger.subscribe(() => { - if (this.subscriptionEnabled()) - { + if (this.subscriptionEnabled()) { getApp().reloadLicensing(true); } }); } onBuild() { - if (this.subscriptionEnabled()) - { + if (this.subscriptionEnabled()) { getApp().reloadLicensing(false); } } @@ -60,12 +56,11 @@ class LicensingPremAdminSettings * @returns {string} */ licenseExpiredMomentValue() { - const - time = this.licenseExpired(), + const time = this.licenseExpired(), momentUnix = moment.unix(time); - return this.licenseIsUnlim() ? 'Never' : (time && (momentUnix.format('LL') + ' (' + momentUnix.from(moment()) + ')')); + return this.licenseIsUnlim() ? 'Never' : time && momentUnix.format('LL') + ' (' + momentUnix.from(moment()) + ')'; } } -export {LicensingPremAdminSettings, LicensingPremAdminSettings as default}; +export { LicensingPremAdminSettings, LicensingPremAdminSettings as default }; diff --git a/dev/Settings/Admin/Security.js b/dev/Settings/Admin/Security.js index 560b2a1c8..ea515162e 100644 --- a/dev/Settings/Admin/Security.js +++ b/dev/Settings/Admin/Security.js @@ -1,22 +1,20 @@ - import _ from '_'; import ko from 'ko'; -import {trim, boolToAjax} from 'Common/Utils'; -import {phpInfo} from 'Common/Links'; -import {StorageResultType, Magics} from 'Common/Enums'; +import { trim, boolToAjax } from 'Common/Utils'; +import { phpInfo } from 'Common/Links'; +import { StorageResultType, Magics } from 'Common/Enums'; -import {settingsGet} from 'Storage/Settings'; +import { settingsGet } from 'Storage/Settings'; import AppAdminStore from 'Stores/Admin/App'; import CapaAdminStore from 'Stores/Admin/Capa'; import Remote from 'Remote/Admin/Ajax'; -import {command} from 'Knoin/Knoin'; +import { command } from 'Knoin/Knoin'; -class SecurityAdminSettings -{ +class SecurityAdminSettings { constructor() { this.useLocalProxyForExternalImages = AppAdminStore.useLocalProxyForExternalImages; @@ -28,8 +26,7 @@ class SecurityAdminSettings this.capaTwoFactorAuthForce = CapaAdminStore.twoFactorAuthForce; this.capaTwoFactorAuth.subscribe((value) => { - if (!value) - { + if (!value) { this.capaTwoFactorAuthForce(false); } }); @@ -38,8 +35,7 @@ class SecurityAdminSettings this.allowSelfSigned = ko.observable(!!settingsGet('AllowSelfSigned')); this.verifySslCertificate.subscribe((value) => { - if (!value) - { + if (!value) { this.allowSelfSigned(true); } }); @@ -84,15 +80,12 @@ class SecurityAdminSettings @command((self) => '' !== trim(self.adminLogin()) && '' !== self.adminPassword()) saveNewAdminPasswordCommand() { - - if ('' === trim(this.adminLogin())) - { + if ('' === trim(this.adminLogin())) { this.adminLoginError(true); return false; } - if (this.adminPasswordNew() !== this.adminPasswordNew2()) - { + if (this.adminPasswordNew() !== this.adminPasswordNew2()) { this.adminPasswordNewError(true); return false; } @@ -119,8 +112,7 @@ class SecurityAdminSettings } onNewAdminPasswordResponse(result, data) { - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { this.adminPassword(''); this.adminPasswordNew(''); this.adminPasswordNew2(''); @@ -128,9 +120,7 @@ class SecurityAdminSettings this.adminPasswordUpdateSuccess(true); this.weakPassword(!!data.Result.Weak); - } - else - { + } else { this.adminPasswordUpdateError(true); } } @@ -191,4 +181,4 @@ class SecurityAdminSettings } } -export {SecurityAdminSettings, SecurityAdminSettings as default}; +export { SecurityAdminSettings, SecurityAdminSettings as default }; diff --git a/dev/Settings/Admin/Social.js b/dev/Settings/Admin/Social.js index 9931d68e9..9c526859d 100644 --- a/dev/Settings/Admin/Social.js +++ b/dev/Settings/Admin/Social.js @@ -1,16 +1,14 @@ - import _ from '_'; import ko from 'ko'; -import {SaveSettingsStep, Magics} from 'Common/Enums'; -import {settingsSaveHelperSimpleFunction, trim, boolToAjax} from 'Common/Utils'; +import { SaveSettingsStep, Magics } from 'Common/Enums'; +import { settingsSaveHelperSimpleFunction, trim, boolToAjax } from 'Common/Utils'; import SocialStore from 'Stores/Social'; import Remote from 'Remote/Admin/Ajax'; -class SocialAdminSettings -{ +class SocialAdminSettings { constructor() { this.googleEnable = SocialStore.google.enabled; this.googleEnableAuth = SocialStore.google.capa.auth; @@ -52,8 +50,7 @@ class SocialAdminSettings onBuild() { _.delay(() => { - const - f1 = settingsSaveHelperSimpleFunction(this.facebookTrigger1, this), + const f1 = settingsSaveHelperSimpleFunction(this.facebookTrigger1, this), f2 = settingsSaveHelperSimpleFunction(this.facebookTrigger2, this), f3 = settingsSaveHelperSimpleFunction(this.twitterTrigger1, this), f4 = settingsSaveHelperSimpleFunction(this.twitterTrigger2, this), @@ -63,8 +60,7 @@ class SocialAdminSettings f8 = settingsSaveHelperSimpleFunction(this.dropboxTrigger1, this); this.facebookEnable.subscribe((value) => { - if (this.facebookSupported()) - { + if (this.facebookSupported()) { Remote.saveAdminConfig(null, { 'FacebookEnable': boolToAjax(value) }); @@ -72,8 +68,7 @@ class SocialAdminSettings }); this.facebookAppID.subscribe((value) => { - if (this.facebookSupported()) - { + if (this.facebookSupported()) { Remote.saveAdminConfig(f1, { 'FacebookAppID': trim(value) }); @@ -81,8 +76,7 @@ class SocialAdminSettings }); this.facebookAppSecret.subscribe((value) => { - if (this.facebookSupported()) - { + if (this.facebookSupported()) { Remote.saveAdminConfig(f2, { 'FacebookAppSecret': trim(value) }); @@ -107,4 +101,4 @@ class SocialAdminSettings } } -export {SocialAdminSettings, SocialAdminSettings as default}; +export { SocialAdminSettings, SocialAdminSettings as default }; diff --git a/dev/Settings/User/Accounts.js b/dev/Settings/User/Accounts.js index ff19e8f18..febd8a3e7 100644 --- a/dev/Settings/User/Accounts.js +++ b/dev/Settings/User/Accounts.js @@ -1,23 +1,21 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; -import {Capa, StorageResultType} from 'Common/Enums'; -import {root} from 'Common/Links'; +import { Capa, StorageResultType } from 'Common/Enums'; +import { root } from 'Common/Links'; -import {capa} from 'Storage/Settings'; +import { capa } from 'Storage/Settings'; import AccountStore from 'Stores/User/Account'; import IdentityStore from 'Stores/User/Identity'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {showScreenPopup, routeOff, setHash} from 'Knoin/Knoin'; +import { showScreenPopup, routeOff, setHash } from 'Knoin/Knoin'; -class AccountsUserSettings -{ +class AccountsUserSettings { constructor() { this.allowAdditionalAccount = capa(Capa.AdditionalAccounts); this.allowIdentities = capa(Capa.Identities); @@ -42,8 +40,7 @@ class AccountsUserSettings } editAccount(account) { - if (account && account.canBeEdit()) - { + if (account && account.canBeEdit()) { showScreenPopup(require('View/Popup/Account'), [account]); } } @@ -61,28 +58,21 @@ class AccountsUserSettings * @returns {void} */ deleteAccount(accountToRemove) { - if (accountToRemove && accountToRemove.deleteAccess()) - { + if (accountToRemove && accountToRemove.deleteAccess()) { this.accountForDeletion(null); - if (accountToRemove) - { + if (accountToRemove) { this.accounts.remove((account) => accountToRemove === account); Remote.accountDelete((result, data) => { - - if (StorageResultType.Success === result && data && data.Result && data.Reload) - { + if (StorageResultType.Success === result && data && data.Result && data.Reload) { routeOff(); setHash(root(), true); routeOff(); _.defer(() => window.location.reload()); - } - else - { + } else { getApp().accountsAndIdentities(); } - }, accountToRemove.email); } } @@ -93,12 +83,10 @@ class AccountsUserSettings * @returns {void} */ deleteIdentity(identityToRemove) { - if (identityToRemove && identityToRemove.deleteAccess()) - { + if (identityToRemove && identityToRemove.deleteAccess()) { this.identityForDeletion(null); - if (identityToRemove) - { + if (identityToRemove) { IdentityStore.identities.remove((oIdentity) => identityToRemove === oIdentity); Remote.identityDelete(() => { @@ -109,30 +97,28 @@ class AccountsUserSettings } accountsAndIdentitiesAfterMove() { - Remote.accountsAndIdentitiesSortOrder(null, - AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek()); + Remote.accountsAndIdentitiesSortOrder(null, AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek()); } onBuild(oDom) { - const self = this; oDom - .on('click', '.accounts-list .account-item .e-action', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.accounts-list .account-item .e-action', function() { + // eslint-disable-line prefer-arrow-callback const account = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (account) - { + if (account) { self.editAccount(account); } }) - .on('click', '.identities-list .identity-item .e-action', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.identities-list .identity-item .e-action', function() { + // eslint-disable-line prefer-arrow-callback const identity = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (identity) - { + if (identity) { self.editIdentity(identity); } }); } } -export {AccountsUserSettings, AccountsUserSettings as default}; +export { AccountsUserSettings, AccountsUserSettings as default }; diff --git a/dev/Settings/User/ChangePassword.js b/dev/Settings/User/ChangePassword.js index 3b9db0841..e737ffe85 100644 --- a/dev/Settings/User/ChangePassword.js +++ b/dev/Settings/User/ChangePassword.js @@ -1,17 +1,15 @@ - import _ from '_'; import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {getNotificationFromResponse, i18n} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { getNotificationFromResponse, i18n } from 'Common/Translator'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; -import {command} from 'Knoin/Knoin'; +import { getApp } from 'Helper/Apps/User'; +import { command } from 'Knoin/Knoin'; -class ChangePasswordUserSettings -{ +class ChangePasswordUserSettings { constructor() { this.changeProcess = ko.observable(false); @@ -46,15 +44,15 @@ class ChangePasswordUserSettings this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this); } - @command((self) => !self.changeProcess() && '' !== self.currentPassword() && '' !== self.newPassword() && '' !== self.newPassword2()) + @command( + (self) => + !self.changeProcess() && '' !== self.currentPassword() && '' !== self.newPassword() && '' !== self.newPassword2() + ) saveNewPasswordCommand() { - if (this.newPassword() !== this.newPassword2()) - { + if (this.newPassword() !== this.newPassword2()) { this.passwordMismatch(true); this.errorDescription(i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH')); - } - else - { + } else { this.changeProcess(true); this.passwordUpdateError(false); @@ -83,8 +81,7 @@ class ChangePasswordUserSettings this.errorDescription(''); this.currentPassword.error(false); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { this.currentPassword(''); this.newPassword(''); this.newPassword2(''); @@ -93,11 +90,8 @@ class ChangePasswordUserSettings this.currentPassword.error(false); getApp().setClientSideToken(data.Result); - } - else - { - if (data && Notification.CurrentPasswordIncorrect === data.ErrorCode) - { + } else { + if (data && Notification.CurrentPasswordIncorrect === data.ErrorCode) { this.currentPassword.error(true); } @@ -107,4 +101,4 @@ class ChangePasswordUserSettings } } -export {ChangePasswordUserSettings, ChangePasswordUserSettings as default}; +export { ChangePasswordUserSettings, ChangePasswordUserSettings as default }; diff --git a/dev/Settings/User/Contacts.js b/dev/Settings/User/Contacts.js index 5cce76aab..c5d4cd566 100644 --- a/dev/Settings/User/Contacts.js +++ b/dev/Settings/User/Contacts.js @@ -1,15 +1,13 @@ - import ko from 'ko'; -import {Magics} from 'Common/Enums'; -import {boolToAjax} from 'Common/Utils'; +import { Magics } from 'Common/Enums'; +import { boolToAjax } from 'Common/Utils'; import AppStore from 'Stores/User/App'; import ContactStore from 'Stores/User/Contact'; import Remote from 'Remote/User/Ajax'; -class ContactsUserSettings -{ +class ContactsUserSettings { constructor() { this.contactsAutosave = AppStore.contactsAutosave; @@ -19,12 +17,16 @@ class ContactsUserSettings this.contactsSyncUser = ContactStore.contactsSyncUser; this.contactsSyncPass = ContactStore.contactsSyncPass; - this.saveTrigger = ko.computed(() => [ - this.enableContactsSync() ? '1' : '0', - this.contactsSyncUrl(), - this.contactsSyncUser(), - this.contactsSyncPass() - ].join('|')).extend({throttle: Magics.Time500ms}); + this.saveTrigger = ko + .computed(() => + [ + this.enableContactsSync() ? '1' : '0', + this.contactsSyncUrl(), + this.contactsSyncUser(), + this.contactsSyncPass() + ].join('|') + ) + .extend({ throttle: Magics.Time500ms }); } onBuild() { @@ -35,7 +37,8 @@ class ContactsUserSettings }); this.saveTrigger.subscribe(() => { - Remote.saveContactsSyncData(null, + Remote.saveContactsSyncData( + null, this.enableContactsSync(), this.contactsSyncUrl(), this.contactsSyncUser(), @@ -45,4 +48,4 @@ class ContactsUserSettings } } -export {ContactsUserSettings, ContactsUserSettings as default}; +export { ContactsUserSettings, ContactsUserSettings as default }; diff --git a/dev/Settings/User/Filters.js b/dev/Settings/User/Filters.js index da05af366..f633e455c 100644 --- a/dev/Settings/User/Filters.js +++ b/dev/Settings/User/Filters.js @@ -1,20 +1,18 @@ - import _ from '_'; import ko from 'ko'; -import {windowResizeCallback, isArray, trim, delegateRunOnDestroy} from 'Common/Utils'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {getNotification} from 'Common/Translator'; +import { windowResizeCallback, isArray, trim, delegateRunOnDestroy } from 'Common/Utils'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { getNotification } from 'Common/Translator'; import FilterStore from 'Stores/User/Filter'; import Remote from 'Remote/User/Ajax'; -import {FilterModel} from 'Model/Filter'; +import { FilterModel } from 'Model/Filter'; -import {showScreenPopup, command} from 'Knoin/Knoin'; +import { showScreenPopup, command } from 'Knoin/Knoin'; -class FiltersUserSettings -{ +class FiltersUserSettings { constructor() { this.modules = FilterStore.modules; this.filters = FilterStore.filters; @@ -29,8 +27,7 @@ class FiltersUserSettings this.filters.subscribe(windowResizeCallback); this.serverError.subscribe((value) => { - if (!value) - { + if (!value) { this.serverErrorDesc(''); } }, this); @@ -64,10 +61,8 @@ class FiltersUserSettings @command((self) => self.haveChanges()) saveChangesCommand() { - if (!this.filters.saving()) - { - if (this.filterRaw.active() && '' === trim(this.filterRaw())) - { + if (!this.filters.saving()) { + if (this.filterRaw.active() && '' === trim(this.filterRaw())) { this.filterRaw.error(true); return false; } @@ -75,24 +70,23 @@ class FiltersUserSettings this.filters.saving(true); this.saveErrorText(''); - Remote.filtersSave((result, data) => { - this.filters.saving(false); + Remote.filtersSave( + (result, data) => { + this.filters.saving(false); - if (StorageResultType.Success === result && data && data.Result) - { - this.haveChanges(false); - this.updateList(); - } - else if (data && data.ErrorCode) - { - this.saveErrorText(data.ErrorMessageAdditional || getNotification(data.ErrorCode)); - } - else - { - this.saveErrorText(getNotification(Notification.CantSaveFilters)); - } - - }, this.filters(), this.filterRaw(), this.filterRaw.active()); + if (StorageResultType.Success === result && data && data.Result) { + this.haveChanges(false); + this.updateList(); + } else if (data && data.ErrorCode) { + this.saveErrorText(data.ErrorMessageAdditional || getNotification(data.ErrorCode)); + } else { + this.saveErrorText(getNotification(Notification.CantSaveFilters)); + } + }, + this.filters(), + this.filterRaw(), + this.filterRaw.active() + ); } return true; @@ -107,24 +101,25 @@ class FiltersUserSettings } updateList() { - if (!this.filters.loading()) - { + if (!this.filters.loading()) { this.filters.loading(true); Remote.filtersGet((result, data) => { - this.filters.loading(false); this.serverError(false); - if (StorageResultType.Success === result && data && data.Result && isArray(data.Result.Filters)) - { + if (StorageResultType.Success === result && data && data.Result && isArray(data.Result.Filters)) { this.inited(true); this.serverError(false); - this.filters(_.compact(_.map(data.Result.Filters, (aItem) => { - const filter = new FilterModel(); - return (filter && filter.parse(aItem)) ? filter : null; - }))); + this.filters( + _.compact( + _.map(data.Result.Filters, (aItem) => { + const filter = new FilterModel(); + return filter && filter.parse(aItem) ? filter : null; + }) + ) + ); this.modules(data.Result.Modules ? data.Result.Modules : {}); @@ -132,16 +127,16 @@ class FiltersUserSettings this.filterRaw.capa(isArray(data.Result.Capa) ? data.Result.Capa.join(' ') : ''); this.filterRaw.active(!!data.Result.RawIsActive); this.filterRaw.allow(!!data.Result.RawIsAllow); - } - else - { + } else { this.filters([]); this.modules({}); this.filterRaw(''); this.filterRaw.capa({}); this.serverError(true); - this.serverErrorDesc(data && data.ErrorCode ? getNotification(data.ErrorCode) : getNotification(Notification.CantGetFilters)); + this.serverErrorDesc( + data && data.ErrorCode ? getNotification(data.ErrorCode) : getNotification(Notification.CantGetFilters) + ); } this.haveChanges(false); @@ -158,43 +153,47 @@ class FiltersUserSettings const filter = new FilterModel(); filter.generateID(); - showScreenPopup(require('View/Popup/Filter'), [filter, () => { - this.filters.push(filter); - this.filterRaw.active(false); - }, false]); + showScreenPopup(require('View/Popup/Filter'), [ + filter, + () => { + this.filters.push(filter); + this.filterRaw.active(false); + }, + false + ]); } editFilter(filter) { const clonedFilter = filter.cloneSelf(); - showScreenPopup(require('View/Popup/Filter'), [clonedFilter, () => { - const - filters = this.filters(), - index = filters.indexOf(filter); + showScreenPopup(require('View/Popup/Filter'), [ + clonedFilter, + () => { + const filters = this.filters(), + index = filters.indexOf(filter); - if (-1 < index && filters[index]) - { - delegateRunOnDestroy(filters[index]); - filters[index] = clonedFilter; + if (-1 < index && filters[index]) { + delegateRunOnDestroy(filters[index]); + filters[index] = clonedFilter; - this.filters(filters); - this.haveChanges(true); - } - }, true]); + this.filters(filters); + this.haveChanges(true); + } + }, + true + ]); } onBuild(oDom) { - const self = this; - oDom - .on('click', '.filter-item .e-action', function() { // eslint-disable-line prefer-arrow-callback - const filter = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (filter) - { - self.editFilter(filter); - } - }); + oDom.on('click', '.filter-item .e-action', function() { + // eslint-disable-line prefer-arrow-callback + const filter = ko.dataFor(this); // eslint-disable-line no-invalid-this + if (filter) { + self.editFilter(filter); + } + }); } onShow() { @@ -202,4 +201,4 @@ class FiltersUserSettings } } -export {FiltersUserSettings, FiltersUserSettings as default}; +export { FiltersUserSettings, FiltersUserSettings as default }; diff --git a/dev/Settings/User/Folders.js b/dev/Settings/User/Folders.js index 3851a75ce..39f477dbb 100644 --- a/dev/Settings/User/Folders.js +++ b/dev/Settings/User/Folders.js @@ -1,13 +1,12 @@ - import ko from 'ko'; -import {ClientSideKeyName, Notification, Magics} from 'Common/Enums'; -import {trim, noop} from 'Common/Utils'; -import {getNotification, i18n} from 'Common/Translator'; +import { ClientSideKeyName, Notification, Magics } from 'Common/Enums'; +import { trim, noop } from 'Common/Utils'; +import { getNotification, i18n } from 'Common/Translator'; -import {removeFolderFromCacheList} from 'Common/Cache'; +import { removeFolderFromCacheList } from 'Common/Cache'; -import {appSettingsGet} from 'Storage/Settings'; +import { appSettingsGet } from 'Storage/Settings'; import * as Local from 'Storage/Client'; import FolderStore from 'Stores/User/Folder'; @@ -15,21 +14,19 @@ import FolderStore from 'Stores/User/Folder'; import Promises from 'Promises/User/Ajax'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; -class FoldersUserSettings -{ +class FoldersUserSettings { constructor() { this.displaySpecSetting = FolderStore.displaySpecSetting; this.folderList = FolderStore.folderList; - this.folderListHelp = ko.observable('').extend({throttle: Magics.Time100ms}); + this.folderListHelp = ko.observable('').extend({ throttle: Magics.Time100ms }); this.loading = ko.computed(() => { - const - loading = FolderStore.foldersLoading(), + const loading = FolderStore.foldersLoading(), creating = FolderStore.foldersCreating(), deleting = FolderStore.foldersDeleting(), renaming = FolderStore.foldersRenaming(); @@ -39,7 +36,7 @@ class FoldersUserSettings this.folderForDeletion = ko.observable(null).deleteAccessHelper(); - this.folderForEdit = ko.observable(null).extend({toggleSubscribeProperty: [this, 'edited']}); + this.folderForEdit = ko.observable(null).extend({ toggleSubscribeProperty: [this, 'edited'] }); this.useImapSubscribe = !!appSettingsGet('useImapSubscribe'); } @@ -47,8 +44,7 @@ class FoldersUserSettings folderEditOnEnter(folder) { const nameToEdit = folder ? trim(folder.nameForEdit()) : ''; - if ('' !== nameToEdit && folder.name() !== nameToEdit) - { + if ('' !== nameToEdit && folder.name() !== nameToEdit) { Local.set(ClientSideKeyName.FoldersLashHash, ''); getApp().foldersPromisesActionHelper( @@ -65,8 +61,7 @@ class FoldersUserSettings } folderEditOnEsc(folder) { - if (folder) - { + if (folder) { folder.edited(false); } } @@ -100,22 +95,22 @@ class FoldersUserSettings } deleteFolder(folderToRemove) { - if (folderToRemove && folderToRemove.canBeDeleted() && folderToRemove.deleteAccess() && - 0 === folderToRemove.privateMessageCountAll()) - { + if ( + folderToRemove && + folderToRemove.canBeDeleted() && + folderToRemove.deleteAccess() && + 0 === folderToRemove.privateMessageCountAll() + ) { this.folderForDeletion(null); - if (folderToRemove) - { - const - fRemoveFolder = function(folder) { - if (folderToRemove === folder) - { - return true; - } - folder.subFolders.remove(fRemoveFolder); - return false; - }; + if (folderToRemove) { + const fRemoveFolder = function(folder) { + if (folderToRemove === folder) { + return true; + } + folder.subFolders.remove(fRemoveFolder); + return false; + }; Local.set(ClientSideKeyName.FoldersLashHash, ''); @@ -128,9 +123,7 @@ class FoldersUserSettings removeFolderFromCacheList(folderToRemove.fullNameRaw); } - } - else if (0 < folderToRemove.privateMessageCountAll()) - { + } else if (0 < folderToRemove.privateMessageCountAll()) { FolderStore.folderList.error(getNotification(Notification.CantDeleteNonEmptyFolder)); } } @@ -158,4 +151,4 @@ class FoldersUserSettings } } -export {FoldersUserSettings, FoldersUserSettings as default}; +export { FoldersUserSettings, FoldersUserSettings as default }; diff --git a/dev/Settings/User/General.js b/dev/Settings/User/General.js index 9130bed3c..303a4c421 100644 --- a/dev/Settings/User/General.js +++ b/dev/Settings/User/General.js @@ -1,20 +1,16 @@ - import _ from '_'; import ko from 'ko'; -import {MESSAGES_PER_PAGE_VALUES} from 'Common/Consts'; -import {bAnimationSupported} from 'Common/Globals'; +import { MESSAGES_PER_PAGE_VALUES } from 'Common/Consts'; +import { bAnimationSupported } from 'Common/Globals'; -import {SaveSettingsStep, Magics, EditorDefaultType, Layout} from 'Common/Enums'; +import { SaveSettingsStep, Magics, EditorDefaultType, Layout } from 'Common/Enums'; -import { - settingsSaveHelperSimpleFunction, - convertLangName, isArray, timeOutAction, boolToAjax -} from 'Common/Utils'; +import { settingsSaveHelperSimpleFunction, convertLangName, isArray, timeOutAction, boolToAjax } from 'Common/Utils'; -import {i18n, trigger as translatorTrigger, reload as translatorReload} from 'Common/Translator'; +import { i18n, trigger as translatorTrigger, reload as translatorReload } from 'Common/Translator'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; import AppStore from 'Stores/User/App'; import LanguageStore from 'Stores/Language'; @@ -25,8 +21,7 @@ import MessageStore from 'Stores/User/Message'; import Remote from 'Remote/User/Ajax'; -class GeneralUserSettings -{ +class GeneralUserSettings { constructor() { this.language = LanguageStore.language; this.languages = LanguageStore.languages; @@ -52,7 +47,7 @@ class GeneralUserSettings this.allowLanguagesOnSettings = AppStore.allowLanguagesOnSettings; this.languageFullName = ko.computed(() => convertLangName(this.language())); - this.languageTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); + this.languageTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms }); this.mppTrigger = ko.observable(SaveSettingsStep.Idle); this.editorDefaultTypeTrigger = ko.observable(SaveSettingsStep.Idle); @@ -75,27 +70,26 @@ class GeneralUserSettings this.editorDefaultTypes = ko.computed(() => { translatorTrigger(); return [ - {'id': EditorDefaultType.Html, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML')}, - {'id': EditorDefaultType.Plain, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN')}, - {'id': EditorDefaultType.HtmlForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED')}, - {'id': EditorDefaultType.PlainForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED')} + { 'id': EditorDefaultType.Html, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML') }, + { 'id': EditorDefaultType.Plain, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN') }, + { 'id': EditorDefaultType.HtmlForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED') }, + { 'id': EditorDefaultType.PlainForced, 'name': i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED') } ]; }); this.layoutTypes = ko.computed(() => { translatorTrigger(); return [ - {'id': Layout.NoPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT')}, - {'id': Layout.SidePreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT')}, - {'id': Layout.BottomPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT')} + { 'id': Layout.NoPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT') }, + { 'id': Layout.SidePreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT') }, + { 'id': Layout.BottomPreview, 'name': i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT') } ]; }); } editMainIdentity() { const identity = this.identityMain(); - if (identity) - { + if (identity) { showScreenPopup(require('View/Popup/Identity'), [identity]); } } @@ -106,8 +100,7 @@ class GeneralUserSettings onBuild() { _.delay(() => { - const - f0 = settingsSaveHelperSimpleFunction(this.editorDefaultTypeTrigger, this), + const f0 = settingsSaveHelperSimpleFunction(this.editorDefaultTypeTrigger, this), f1 = settingsSaveHelperSimpleFunction(this.mppTrigger, this), f2 = settingsSaveHelperSimpleFunction(this.layoutTrigger, this), fReloadLanguageHelper = (saveSettingsStep) => () => { @@ -117,15 +110,13 @@ class GeneralUserSettings this.language.subscribe((value) => { this.languageTrigger(SaveSettingsStep.Animate); - translatorReload(false, value).then( - fReloadLanguageHelper(SaveSettingsStep.TrueResult), - fReloadLanguageHelper(SaveSettingsStep.FalseResult) - ).then(() => { - Remote.saveSettings(null, { - 'Language': value + translatorReload(false, value) + .then(fReloadLanguageHelper(SaveSettingsStep.TrueResult), fReloadLanguageHelper(SaveSettingsStep.FalseResult)) + .then(() => { + Remote.saveSettings(null, { + 'Language': value + }); }); - }); - }); this.editorDefaultType.subscribe(Remote.saveSettingsHelper('EditorDefaultType', null, f0)); @@ -135,27 +126,39 @@ class GeneralUserSettings this.useCheckboxesInList.subscribe(Remote.saveSettingsHelper('UseCheckboxesInList', boolToAjax)); this.enableDesktopNotification.subscribe((value) => { - timeOutAction('SaveDesktopNotifications', () => { - Remote.saveSettings(null, { - 'DesktopNotifications': boolToAjax(value) - }); - }, Magics.Time3s); + timeOutAction( + 'SaveDesktopNotifications', + () => { + Remote.saveSettings(null, { + 'DesktopNotifications': boolToAjax(value) + }); + }, + Magics.Time3s + ); }); this.enableSoundNotification.subscribe((value) => { - timeOutAction('SaveSoundNotification', () => { - Remote.saveSettings(null, { - 'SoundNotification': boolToAjax(value) - }); - }, Magics.Time3s); + timeOutAction( + 'SaveSoundNotification', + () => { + Remote.saveSettings(null, { + 'SoundNotification': boolToAjax(value) + }); + }, + Magics.Time3s + ); }); this.replySameFolder.subscribe((value) => { - timeOutAction('SaveReplySameFolder', () => { - Remote.saveSettings(null, { - 'ReplySameFolder': boolToAjax(value) - }); - }, Magics.Time3s); + timeOutAction( + 'SaveReplySameFolder', + () => { + Remote.saveSettings(null, { + 'ReplySameFolder': boolToAjax(value) + }); + }, + Magics.Time3s + ); }); this.useThreads.subscribe((value) => { @@ -179,10 +182,8 @@ class GeneralUserSettings } selectLanguage() { - showScreenPopup(require('View/Popup/Languages'), [ - this.language, this.languages(), LanguageStore.userLanguage() - ]); + showScreenPopup(require('View/Popup/Languages'), [this.language, this.languages(), LanguageStore.userLanguage()]); } } -export {GeneralUserSettings, GeneralUserSettings as default}; +export { GeneralUserSettings, GeneralUserSettings as default }; diff --git a/dev/Settings/User/OpenPgp.js b/dev/Settings/User/OpenPgp.js index e834c022a..8a2b7824f 100644 --- a/dev/Settings/User/OpenPgp.js +++ b/dev/Settings/User/OpenPgp.js @@ -1,22 +1,20 @@ - import _ from '_'; import ko from 'ko'; -import {delegateRunOnDestroy, boolToAjax} from 'Common/Utils'; -import {Magics} from 'Common/Enums'; -import {bIsHttps} from 'Common/Globals'; +import { delegateRunOnDestroy, boolToAjax } from 'Common/Utils'; +import { Magics } from 'Common/Enums'; +import { bIsHttps } from 'Common/Globals'; import PgpStore from 'Stores/User/Pgp'; import SettingsStore from 'Stores/User/Settings'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; -class OpenPgpUserSettings -{ +class OpenPgpUserSettings { constructor() { this.openpgpkeys = PgpStore.openpgpkeys; this.openpgpkeysPublic = PgpStore.openpgpkeysPublic; @@ -38,8 +36,7 @@ class OpenPgpUserSettings } viewOpenPgpKey(openPgpKey) { - if (openPgpKey) - { + if (openPgpKey) { showScreenPopup(require('View/Popup/ViewOpenPgpKey'), [openPgpKey]); } } @@ -49,21 +46,16 @@ class OpenPgpUserSettings * @returns {void} */ deleteOpenPgpKey(openPgpKeyToRemove) { - if (openPgpKeyToRemove && openPgpKeyToRemove.deleteAccess()) - { + if (openPgpKeyToRemove && openPgpKeyToRemove.deleteAccess()) { this.openPgpKeyForDeletion(null); - if (openPgpKeyToRemove && PgpStore.openpgpKeyring) - { + if (openPgpKeyToRemove && PgpStore.openpgpKeyring) { const findedItem = _.find(PgpStore.openpgpkeys(), (key) => openPgpKeyToRemove === key); - if (findedItem) - { + if (findedItem) { PgpStore.openpgpkeys.remove(findedItem); delegateRunOnDestroy(findedItem); - PgpStore - .openpgpKeyring[findedItem.isPrivate ? 'privateKeys' : 'publicKeys'] - .removeForId(findedItem.guid); + PgpStore.openpgpKeyring[findedItem.isPrivate ? 'privateKeys' : 'publicKeys'].removeForId(findedItem.guid); PgpStore.openpgpKeyring.store(); } @@ -75,13 +67,9 @@ class OpenPgpUserSettings onBuild() { _.delay(() => { - - this.allowDraftAutosave.subscribe( - Remote.saveSettingsHelper('AllowDraftAutosave', boolToAjax) - ); - + this.allowDraftAutosave.subscribe(Remote.saveSettingsHelper('AllowDraftAutosave', boolToAjax)); }, Magics.Time50ms); } } -export {OpenPgpUserSettings, OpenPgpUserSettings as default}; +export { OpenPgpUserSettings, OpenPgpUserSettings as default }; diff --git a/dev/Settings/User/Security.js b/dev/Settings/User/Security.js index 9d8c95e93..21b2d58ff 100644 --- a/dev/Settings/User/Security.js +++ b/dev/Settings/User/Security.js @@ -1,21 +1,19 @@ - import _ from '_'; import ko from 'ko'; -import {pInt, settingsSaveHelperSimpleFunction} from 'Common/Utils'; -import {Capa, SaveSettingsStep} from 'Common/Enums'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; +import { pInt, settingsSaveHelperSimpleFunction } from 'Common/Utils'; +import { Capa, SaveSettingsStep } from 'Common/Enums'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; -import {capa} from 'Storage/Settings'; +import { capa } from 'Storage/Settings'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; import SettinsStore from 'Stores/User/Settings'; import Remote from 'Remote/User/Ajax'; -class SecurityUserSettings -{ +class SecurityUserSettings { constructor() { this.capaAutoLogout = capa(Capa.AutoLogout); this.capaTwoFactor = capa(Capa.TwoFactor); @@ -26,14 +24,14 @@ class SecurityUserSettings this.autoLogoutOptions = ko.computed(() => { translatorTrigger(); return [ - {'id': 0, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME')}, - {'id': 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 5})}, - {'id': 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 10})}, - {'id': 30, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 30})}, - {'id': 60, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 60})}, - {'id': 60 * 2, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 2})}, - {'id': 60 * 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 5})}, - {'id': 60 * 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 10})} + { 'id': 0, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME') }, + { 'id': 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 5 }) }, + { 'id': 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 10 }) }, + { 'id': 30, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 30 }) }, + { 'id': 60, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', { 'MINUTES': 60 }) }, + { 'id': 60 * 2, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 2 }) }, + { 'id': 60 * 5, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 5 }) }, + { 'id': 60 * 10, 'name': i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', { 'HOURS': 10 }) } ]; }); } @@ -43,8 +41,7 @@ class SecurityUserSettings } onBuild() { - if (this.capaAutoLogout) - { + if (this.capaAutoLogout) { _.delay(() => { const f0 = settingsSaveHelperSimpleFunction(this.autoLogout.trigger, this); @@ -54,4 +51,4 @@ class SecurityUserSettings } } -export {SecurityUserSettings, SecurityUserSettings as default}; +export { SecurityUserSettings, SecurityUserSettings as default }; diff --git a/dev/Settings/User/Social.js b/dev/Settings/User/Social.js index a2a7b4977..465ae8ff1 100644 --- a/dev/Settings/User/Social.js +++ b/dev/Settings/User/Social.js @@ -1,12 +1,10 @@ - import SocialStore from 'Stores/Social'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {command} from 'Knoin/Knoin'; +import { command } from 'Knoin/Knoin'; -class SocialUserSettings -{ +class SocialUserSettings { constructor() { this.googleEnable = SocialStore.google.enabled; this.googleEnableAuth = SocialStore.google.capa.auth; @@ -33,8 +31,7 @@ class SocialUserSettings @command((self) => !self.googleLoggined() && !self.googleActions()) connectGoogleCommand() { - if (!this.googleLoggined()) - { + if (!this.googleLoggined()) { getApp().googleConnect(); } } @@ -46,8 +43,7 @@ class SocialUserSettings @command((self) => !self.facebookLoggined() && !self.facebookActions()) connectFacebookCommand() { - if (!this.facebookLoggined()) - { + if (!this.facebookLoggined()) { getApp().facebookConnect(); } } @@ -59,8 +55,7 @@ class SocialUserSettings @command((self) => !self.twitterLoggined() && !self.twitterActions()) connectTwitterCommand() { - if (!this.twitterLoggined()) - { + if (!this.twitterLoggined()) { getApp().twitterConnect(); } } @@ -71,4 +66,4 @@ class SocialUserSettings } } -export {SocialUserSettings, SocialUserSettings as default}; +export { SocialUserSettings, SocialUserSettings as default }; diff --git a/dev/Settings/User/Templates.js b/dev/Settings/User/Templates.js index e5c5ae582..9e8aa118d 100644 --- a/dev/Settings/User/Templates.js +++ b/dev/Settings/User/Templates.js @@ -1,21 +1,21 @@ - import ko from 'ko'; -import {i18n} from 'Common/Translator'; +import { i18n } from 'Common/Translator'; import TemplateStore from 'Stores/User/Template'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; -class TemplatesUserSettings -{ +class TemplatesUserSettings { constructor() { this.templates = TemplateStore.templates; - this.processText = ko.computed(() => (TemplateStore.templates.loading() ? i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : '')); + this.processText = ko.computed(() => + TemplateStore.templates.loading() ? i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : '' + ); this.visibility = ko.computed(() => ('' === this.processText() ? 'hidden' : 'visible')); this.templateForDeletion = ko.observable(null).deleteAccessHelper(); @@ -34,19 +34,16 @@ class TemplatesUserSettings } editTemplate(oTemplateItem) { - if (oTemplateItem) - { + if (oTemplateItem) { showScreenPopup(require('View/Popup/Template'), [oTemplateItem]); } } deleteTemplate(templateToRemove) { - if (templateToRemove && templateToRemove.deleteAccess()) - { + if (templateToRemove && templateToRemove.deleteAccess()) { this.templateForDeletion(null); - if (templateToRemove) - { + if (templateToRemove) { this.templates.remove((template) => templateToRemove === template); Remote.templateDelete(() => { @@ -61,20 +58,18 @@ class TemplatesUserSettings } onBuild(oDom) { - const self = this; - oDom - .on('click', '.templates-list .template-item .e-action', function() { // eslint-disable-line prefer-arrow-callback - const template = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (template) - { - self.editTemplate(template); - } - }); + oDom.on('click', '.templates-list .template-item .e-action', function() { + // eslint-disable-line prefer-arrow-callback + const template = ko.dataFor(this); // eslint-disable-line no-invalid-this + if (template) { + self.editTemplate(template); + } + }); this.reloadTemplates(); } } -export {TemplatesUserSettings, TemplatesUserSettings as default}; +export { TemplatesUserSettings, TemplatesUserSettings as default }; diff --git a/dev/Settings/User/Themes.js b/dev/Settings/User/Themes.js index c24aa6cd1..d20230634 100644 --- a/dev/Settings/User/Themes.js +++ b/dev/Settings/User/Themes.js @@ -1,23 +1,21 @@ - import _ from '_'; import $ from '$'; import ko from 'ko'; import Jua from 'Jua'; -import {SaveSettingsStep, UploadErrorCode, Capa, Magics} from 'Common/Enums'; -import {changeTheme, convertThemeName} from 'Common/Utils'; -import {userBackground, themePreviewLink, uploadBackground} from 'Common/Links'; -import {i18n} from 'Common/Translator'; +import { SaveSettingsStep, UploadErrorCode, Capa, Magics } from 'Common/Enums'; +import { changeTheme, convertThemeName } from 'Common/Utils'; +import { userBackground, themePreviewLink, uploadBackground } from 'Common/Links'; +import { i18n } from 'Common/Translator'; -import {capa} from 'Storage/Settings'; +import { capa } from 'Storage/Settings'; import ThemeStore from 'Stores/Theme'; import Remote from 'Remote/User/Ajax'; -class ThemesUserSettings -{ +class ThemesUserSettings { constructor() { this.theme = ThemeStore.theme; this.themes = ThemeStore.themes; @@ -32,7 +30,7 @@ class ThemesUserSettings this.capaUserBackground = ko.observable(capa(Capa.UserBackground)); - this.themeTrigger = ko.observable(SaveSettingsStep.Idle).extend({throttle: Magics.Time100ms}); + this.themeTrigger = ko.observable(SaveSettingsStep.Idle).extend({ throttle: Magics.Time100ms }); this.iTimer = 0; this.oThemeAjaxRequest = null; @@ -51,18 +49,19 @@ class ThemesUserSettings this.background.hash.subscribe((value) => { const $bg = $('#rl-bg'); - if (!value) - { - if ($bg.data('backstretch')) - { + if (!value) { + if ($bg.data('backstretch')) { $bg.backstretch('destroy').attr('style', ''); } - } - else - { - $bg.attr('style', 'background-image: none !important;').backstretch(userBackground(value), { - fade: Magics.Time1s, centeredX: true, centeredY: true - }).removeAttr('style'); + } else { + $bg + .attr('style', 'background-image: none !important;') + .backstretch(userBackground(value), { + fade: Magics.Time1s, + centeredX: true, + centeredY: true + }) + .removeAttr('style'); } }); } @@ -70,12 +69,14 @@ class ThemesUserSettings onBuild() { const currentTheme = this.theme(); - this.themesObjects(_.map(this.themes(), (theme) => ({ - name: theme, - nameDisplay: convertThemeName(theme), - selected: ko.observable(theme === currentTheme), - themePreviewSrc: themePreviewLink(theme) - }))); + this.themesObjects( + _.map(this.themes(), (theme) => ({ + name: theme, + nameDisplay: convertThemeName(theme), + selected: ko.observable(theme === currentTheme), + themePreviewSrc: themePreviewLink(theme) + })) + ); this.initUploader(); } @@ -85,8 +86,7 @@ class ThemesUserSettings } clearBackground() { - if (this.capaUserBackground()) - { + if (this.capaUserBackground()) { Remote.clearUserBackground(() => { this.background.name(''); this.background.hash(''); @@ -95,18 +95,16 @@ class ThemesUserSettings } initUploader() { - if (this.background.uploaderButton() && this.capaUserBackground()) - { - const - oJua = new Jua({ - 'action': uploadBackground(), - 'name': 'uploader', - 'queueSize': 1, - 'multipleSizeLimit': 1, - 'disableDragAndDrop': true, - 'disableMultiple': true, - 'clickElement': this.background.uploaderButton() - }); + if (this.background.uploaderButton() && this.capaUserBackground()) { + const oJua = new Jua({ + 'action': uploadBackground(), + 'name': 'uploader', + 'queueSize': 1, + 'multipleSizeLimit': 1, + 'disableDragAndDrop': true, + 'disableMultiple': true, + 'clickElement': this.background.uploaderButton() + }); oJua .on('onStart', () => { @@ -117,21 +115,16 @@ class ThemesUserSettings .on('onComplete', (id, result, data) => { this.background.loading(false); - if (result && id && data && data.Result && data.Result.Name && data.Result.Hash) - { + if (result && id && data && data.Result && data.Result.Name && data.Result.Hash) { this.background.name(data.Result.Name); this.background.hash(data.Result.Hash); - } - else - { + } else { this.background.name(''); this.background.hash(''); let errorMsg = ''; - if (data.ErrorCode) - { - switch (data.ErrorCode) - { + if (data.ErrorCode) { + switch (data.ErrorCode) { case UploadErrorCode.FileIsTooBig: errorMsg = i18n('SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG'); break; @@ -142,8 +135,7 @@ class ThemesUserSettings } } - if (!errorMsg && data.ErrorMessage) - { + if (!errorMsg && data.ErrorMessage) { errorMsg = data.ErrorMessage; } @@ -156,4 +148,4 @@ class ThemesUserSettings } } -export {ThemesUserSettings, ThemesUserSettings as default}; +export { ThemesUserSettings, ThemesUserSettings as default }; diff --git a/dev/Storage/Client.js b/dev/Storage/Client.js index 47d629630..285ba8898 100644 --- a/dev/Storage/Client.js +++ b/dev/Storage/Client.js @@ -1,10 +1,10 @@ - import _ from '_'; -import {CookieDriver} from 'Common/ClientStorageDriver/Cookie'; -import {LocalStorageDriver} from 'Common/ClientStorageDriver/LocalStorage'; +import { CookieDriver } from 'Common/ClientStorageDriver/Cookie'; +import { LocalStorageDriver } from 'Common/ClientStorageDriver/LocalStorage'; const SupportedStorageDriver = _.find( - [LocalStorageDriver, CookieDriver], (StorageDriver) => StorageDriver && StorageDriver.supported() + [LocalStorageDriver, CookieDriver], + (StorageDriver) => StorageDriver && StorageDriver.supported() ); const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null; @@ -14,8 +14,7 @@ const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null; * @param {*} data * @returns {boolean} */ -export function set(key, data) -{ +export function set(key, data) { return driver ? driver.set('p' + key, data) : false; } @@ -23,7 +22,6 @@ export function set(key, data) * @param {number} key * @returns {*} */ -export function get(key) -{ +export function get(key) { return driver ? driver.get('p' + key) : null; } diff --git a/dev/Storage/RainLoop.js b/dev/Storage/RainLoop.js index e71018891..ea95afd85 100644 --- a/dev/Storage/RainLoop.js +++ b/dev/Storage/RainLoop.js @@ -1,4 +1,3 @@ - import window from 'window'; const STORAGE_KEY = '__rlA'; @@ -8,65 +7,55 @@ const TIME_KEY = '__rlT'; * @param {string} storageName * @returns {boolean} */ -export function isStorageSupported(storageName) -{ +export function isStorageSupported(storageName) { let storageIsAvailable = false; - try - { + try { // at: window[storageName] firefox throws SecurityError: The operation is insecure. when in iframe storageIsAvailable = storageName in window && window[storageName] && window[storageName].setItem; - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty - if (storageIsAvailable) - { - const - s = window[storageName], + if (storageIsAvailable) { + const s = window[storageName], key = 'testLocalStorage_' + window.Math.random(); - try - { + try { s.setItem(key, key); - if (key === s.getItem(key)) - { + if (key === s.getItem(key)) { s.removeItem(key); return true; } - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty } return false; } -const SESS_STORAGE = isStorageSupported('sessionStorage') ? (window.sessionStorage || null) : null; +const SESS_STORAGE = isStorageSupported('sessionStorage') ? window.sessionStorage || null : null; const WIN_STORAGE = window.top || window || null; const __get = (key) => { - let result = null; - if (SESS_STORAGE) - { + if (SESS_STORAGE) { result = SESS_STORAGE.getItem(key) || null; - } - else if (WIN_STORAGE && window.JSON) - { - const data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? window.JSON.parse(WIN_STORAGE.name.toString()) : null; - result = data ? (data[key] || null) : null; + } else if (WIN_STORAGE && window.JSON) { + const data = + WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) + ? window.JSON.parse(WIN_STORAGE.name.toString()) + : null; + result = data ? data[key] || null : null; } return result; }; const __set = (key, value) => { - - if (SESS_STORAGE) - { + if (SESS_STORAGE) { SESS_STORAGE.setItem(key, value); - } - else if (WIN_STORAGE && window.JSON) - { - let data = WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) ? window.JSON.parse(WIN_STORAGE.name.toString()) : null; + } else if (WIN_STORAGE && window.JSON) { + let data = + WIN_STORAGE.name && '{' === WIN_STORAGE.name.toString().substr(0, 1) + ? window.JSON.parse(WIN_STORAGE.name.toString()) + : null; data = data || {}; data[key] = value; @@ -74,30 +63,27 @@ const __set = (key, value) => { } }; -const timestamp = () => window.Math.round((new window.Date()).getTime() / 1000); +const timestamp = () => window.Math.round(new window.Date().getTime() / 1000); const setTimestamp = () => __set(TIME_KEY, timestamp()); const getTimestamp = () => { const time = __get(TIME_KEY, 0); - return time ? (window.parseInt(time, 10) || 0) : 0; + return time ? window.parseInt(time, 10) || 0 : 0; }; /** * @returns {string} */ -export function getHash() -{ +export function getHash() { return __get(STORAGE_KEY); } /** * @returns {void} */ -export function setHash() -{ - const - key = 'AuthAccountHash', +export function setHash() { + const key = 'AuthAccountHash', appData = window.__rlah_data(); __set(STORAGE_KEY, appData && appData[key] ? appData[key] : ''); @@ -107,8 +93,7 @@ export function setHash() /** * @returns {void} */ -export function clearHash() -{ +export function clearHash() { __set(STORAGE_KEY, ''); setTimestamp(); } @@ -116,10 +101,9 @@ export function clearHash() /** * @returns {boolean} */ -export function checkTimestamp() -{ - if (timestamp() > getTimestamp() + 1000 * 60 * 60) // 60m - { +export function checkTimestamp() { + if (timestamp() > getTimestamp() + 1000 * 60 * 60) { + // 60m clearHash(); return true; } diff --git a/dev/Storage/Settings.js b/dev/Storage/Settings.js index b80b315dc..e4ecbabea 100644 --- a/dev/Storage/Settings.js +++ b/dev/Storage/Settings.js @@ -1,6 +1,5 @@ - import window from 'window'; -import {isUnd, isNormal, isArray, inArray} from 'Common/Utils'; +import { isUnd, isNormal, isArray, inArray } from 'Common/Utils'; let SETTINGS = window.__rlah_data() || null; SETTINGS = isNormal(SETTINGS) ? SETTINGS : {}; @@ -12,8 +11,7 @@ APP_SETTINGS = isNormal(APP_SETTINGS) ? APP_SETTINGS : {}; * @param {string} name * @returns {*} */ -export function settingsGet(name) -{ +export function settingsGet(name) { return isUnd(SETTINGS[name]) ? null : SETTINGS[name]; } @@ -21,8 +19,7 @@ export function settingsGet(name) * @param {string} name * @param {*} value */ -export function settingsSet(name, value) -{ +export function settingsSet(name, value) { SETTINGS[name] = value; } @@ -30,8 +27,7 @@ export function settingsSet(name, value) * @param {string} name * @returns {*} */ -export function appSettingsGet(name) -{ +export function appSettingsGet(name) { return isUnd(APP_SETTINGS[name]) ? null : APP_SETTINGS[name]; } @@ -39,8 +35,7 @@ export function appSettingsGet(name) * @param {string} name * @returns {boolean} */ -export function capa(name) -{ +export function capa(name) { const values = settingsGet('Capa'); return isArray(values) && isNormal(name) && -1 < inArray(name, values); } diff --git a/dev/Stores/AbstractApp.js b/dev/Stores/AbstractApp.js index ddfe81dc4..f4e2e8ee6 100644 --- a/dev/Stores/AbstractApp.js +++ b/dev/Stores/AbstractApp.js @@ -1,10 +1,8 @@ - import ko from 'ko'; -import {$html, bMobileDevice} from 'Common/Globals'; +import { $html, bMobileDevice } from 'Common/Globals'; import * as Settings from 'Storage/Settings'; -class AbstractAppStore -{ +class AbstractAppStore { constructor() { this.allowLanguagesOnSettings = ko.observable(true); this.allowLanguagesOnLogin = ko.observable(true); @@ -35,4 +33,4 @@ class AbstractAppStore } } -export {AbstractAppStore, AbstractAppStore as default}; +export { AbstractAppStore, AbstractAppStore as default }; diff --git a/dev/Stores/Admin/App.js b/dev/Stores/Admin/App.js index 99630604e..1195edd05 100644 --- a/dev/Stores/Admin/App.js +++ b/dev/Stores/Admin/App.js @@ -1,12 +1,10 @@ - import window from 'window'; import $ from '$'; import ko from 'ko'; -import {settingsGet} from 'Storage/Settings'; -import {AbstractAppStore} from 'Stores/AbstractApp'; +import { settingsGet } from 'Storage/Settings'; +import { AbstractAppStore } from 'Stores/AbstractApp'; -class AppAdminStore extends AbstractAppStore -{ +class AppAdminStore extends AbstractAppStore { constructor() { super(); diff --git a/dev/Stores/Admin/Capa.js b/dev/Stores/Admin/Capa.js index 4c7c3375b..46e852b7c 100644 --- a/dev/Stores/Admin/Capa.js +++ b/dev/Stores/Admin/Capa.js @@ -1,10 +1,8 @@ - import ko from 'ko'; -import {Capa} from 'Common/Enums'; +import { Capa } from 'Common/Enums'; import * as Settings from 'Storage/Settings'; -class CapaAdminStore -{ +class CapaAdminStore { constructor() { this.additionalAccounts = ko.observable(false); this.identities = ko.observable(false); diff --git a/dev/Stores/Admin/Core.js b/dev/Stores/Admin/Core.js index 086eff923..3d76f584d 100644 --- a/dev/Stores/Admin/Core.js +++ b/dev/Stores/Admin/Core.js @@ -1,8 +1,6 @@ - import ko from 'ko'; -class CoreAdminStore -{ +class CoreAdminStore { constructor() { this.coreReal = ko.observable(true); this.coreChannel = ko.observable('stable'); @@ -10,8 +8,8 @@ class CoreAdminStore this.coreUpdatable = ko.observable(true); this.coreAccess = ko.observable(true); this.coreWarning = ko.observable(false); - this.coreChecking = ko.observable(false).extend({throttle: 100}); - this.coreUpdating = ko.observable(false).extend({throttle: 100}); + this.coreChecking = ko.observable(false).extend({ throttle: 100 }); + this.coreUpdating = ko.observable(false).extend({ throttle: 100 }); this.coreVersion = ko.observable(''); this.coreRemoteVersion = ko.observable(''); this.coreRemoteRelease = ko.observable(''); diff --git a/dev/Stores/Admin/Domain.js b/dev/Stores/Admin/Domain.js index c6731fc90..b5f4710cc 100644 --- a/dev/Stores/Admin/Domain.js +++ b/dev/Stores/Admin/Domain.js @@ -1,11 +1,9 @@ - import ko from 'ko'; -class DomainAdminStore -{ +class DomainAdminStore { constructor() { this.domains = ko.observableArray([]); - this.domains.loading = ko.observable(false).extend({'throttle': 100}); + this.domains.loading = ko.observable(false).extend({ 'throttle': 100 }); this.domainsWithoutAliases = this.domains.filter((item) => item && !item.alias); } } diff --git a/dev/Stores/Admin/License.js b/dev/Stores/Admin/License.js index 2e47e7f54..d86abde2d 100644 --- a/dev/Stores/Admin/License.js +++ b/dev/Stores/Admin/License.js @@ -1,8 +1,6 @@ - import ko from 'ko'; -class LicenseAdminStore -{ +class LicenseAdminStore { constructor() { this.licensing = ko.observable(false); this.licensingProcess = ko.observable(false); diff --git a/dev/Stores/Admin/Package.js b/dev/Stores/Admin/Package.js index fd4005648..e7b888128 100644 --- a/dev/Stores/Admin/Package.js +++ b/dev/Stores/Admin/Package.js @@ -1,11 +1,9 @@ - import ko from 'ko'; -class PackageAdminStore -{ +class PackageAdminStore { constructor() { this.packages = ko.observableArray([]); - this.packages.loading = ko.observable(false).extend({throttle: 100}); + this.packages.loading = ko.observable(false).extend({ throttle: 100 }); this.packagesReal = ko.observable(true); this.packagesMainUpdatable = ko.observable(true); diff --git a/dev/Stores/Admin/Plugin.js b/dev/Stores/Admin/Plugin.js index 10455c846..3dc4d8bc8 100644 --- a/dev/Stores/Admin/Plugin.js +++ b/dev/Stores/Admin/Plugin.js @@ -1,11 +1,9 @@ - import ko from 'ko'; -class PluginAdminStore -{ +class PluginAdminStore { constructor() { this.plugins = ko.observableArray([]); - this.plugins.loading = ko.observable(false).extend({throttle: 100}); + this.plugins.loading = ko.observable(false).extend({ throttle: 100 }); this.plugins.error = ko.observable(''); } } diff --git a/dev/Stores/Language.js b/dev/Stores/Language.js index 3d0e93ef8..ded5f537d 100644 --- a/dev/Stores/Language.js +++ b/dev/Stores/Language.js @@ -1,29 +1,28 @@ - import ko from 'ko'; -import {isArray} from 'Common/Utils'; +import { isArray } from 'Common/Utils'; import * as Settings from 'Storage/Settings'; -class LanguageStore -{ +class LanguageStore { constructor() { this.languages = ko.observableArray([]); this.languagesAdmin = ko.observableArray([]); - this.language = ko.observable('') - .extend({limitedList: this.languages}) - .extend({reversible: true}); + this.language = ko + .observable('') + .extend({ limitedList: this.languages }) + .extend({ reversible: true }); - this.languageAdmin = ko.observable('') - .extend({limitedList: this.languagesAdmin}) - .extend({reversible: true}); + this.languageAdmin = ko + .observable('') + .extend({ limitedList: this.languagesAdmin }) + .extend({ reversible: true }); this.userLanguage = ko.observable(''); this.userLanguageAdmin = ko.observable(''); } populate() { - const - aLanguages = Settings.appSettingsGet('languages'), + const aLanguages = Settings.appSettingsGet('languages'), aLanguagesAdmin = Settings.appSettingsGet('languagesAdmin'); this.languages(isArray(aLanguages) ? aLanguages : []); diff --git a/dev/Stores/Social.js b/dev/Stores/Social.js index c323a630c..93291b2e0 100644 --- a/dev/Stores/Social.js +++ b/dev/Stores/Social.js @@ -1,11 +1,9 @@ - import window from 'window'; import ko from 'ko'; import $ from '$'; import * as Settings from 'Storage/Settings'; -class SocialStore -{ +class SocialStore { constructor() { this.google = {}; this.twitter = {}; @@ -32,7 +30,8 @@ class SocialStore this.google.require = {}; this.google.require.clientSettings = ko.computed( - () => this.google.enabled() && (this.google.capa.auth() || this.google.capa.drive())); + () => this.google.enabled() && (this.google.capa.auth() || this.google.capa.drive()) + ); this.google.require.apiKeySettings = ko.computed(() => this.google.enabled() && this.google.capa.drive()); @@ -85,14 +84,14 @@ class SocialStore } appendDropbox() { - if (!window.Dropbox && this.dropbox.enabled() && this.dropbox.apiKey()) - { - if (!window.document.getElementById('dropboxjs')) - { + if (!window.Dropbox && this.dropbox.enabled() && this.dropbox.apiKey()) { + if (!window.document.getElementById('dropboxjs')) { const script = window.document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://www.dropbox.com/static/api/2/dropins.js'; - $(script).attr('id', 'dropboxjs').attr('data-app-key', this.dropbox.apiKey()); + $(script) + .attr('id', 'dropboxjs') + .attr('data-app-key', this.dropbox.apiKey()); window.document.body.appendChild(script); } diff --git a/dev/Stores/Theme.js b/dev/Stores/Theme.js index 9e8acebe9..717bbcd07 100644 --- a/dev/Stores/Theme.js +++ b/dev/Stores/Theme.js @@ -1,16 +1,14 @@ - import ko from 'ko'; -import {isArray} from 'Common/Utils'; +import { isArray } from 'Common/Utils'; import * as Settings from 'Storage/Settings'; -class ThemeStore -{ +class ThemeStore { constructor() { this.themes = ko.observableArray([]); this.themeBackgroundName = ko.observable(''); this.themeBackgroundHash = ko.observable(''); - this.theme = ko.observable('').extend({limitedList: this.themes}); + this.theme = ko.observable('').extend({ limitedList: this.themes }); } populate() { diff --git a/dev/Stores/User/Account.js b/dev/Stores/User/Account.js index 51c119002..b23109004 100644 --- a/dev/Stores/User/Account.js +++ b/dev/Stores/User/Account.js @@ -1,11 +1,9 @@ - import ko from 'ko'; import _ from '_'; -import {Magics} from 'Common/Enums'; +import { Magics } from 'Common/Enums'; import * as Settings from 'Storage/Settings'; -class AccountUserStore -{ +class AccountUserStore { constructor() { this.email = ko.observable(''); this.parentEmail = ko.observable(''); @@ -13,14 +11,13 @@ class AccountUserStore this.signature = ko.observable(''); this.accounts = ko.observableArray([]); - this.accounts.loading = ko.observable(false).extend({throttle: Magics.Time100ms}); + this.accounts.loading = ko.observable(false).extend({ throttle: Magics.Time100ms }); this.computers(); } computers() { - this.accountsEmails = ko.computed( - () => _.compact(_.map(this.accounts(), (item) => (item ? item.email : null)))); + this.accountsEmails = ko.computed(() => _.compact(_.map(this.accounts(), (item) => (item ? item.email : null)))); this.accountsUnreadCount = ko.computed(() => 0); // this.accountsUnreadCount = ko.computed(() => { diff --git a/dev/Stores/User/App.js b/dev/Stores/User/App.js index 524e9dfdf..67ab37cdb 100644 --- a/dev/Stores/User/App.js +++ b/dev/Stores/User/App.js @@ -1,16 +1,14 @@ - import ko from 'ko'; -import {Focused, KeyState} from 'Common/Enums'; +import { Focused, KeyState } from 'Common/Enums'; -import {keyScope, leftPanelDisabled} from 'Common/Globals'; -import {isNonEmptyArray} from 'Common/Utils'; +import { keyScope, leftPanelDisabled } from 'Common/Globals'; +import { isNonEmptyArray } from 'Common/Utils'; import * as Settings from 'Storage/Settings'; -import {AbstractAppStore} from 'Stores/AbstractApp'; +import { AbstractAppStore } from 'Stores/AbstractApp'; -class AppUserStore extends AbstractAppStore -{ +class AppUserStore extends AbstractAppStore { constructor() { super(); @@ -21,8 +19,7 @@ class AppUserStore extends AbstractAppStore const isMobile = Settings.appSettingsGet('mobile'); this.focusedState.subscribe((value) => { - switch (value) - { + switch (value) { case Focused.MessageList: keyScope(KeyState.MessageList); if (isMobile) { @@ -63,7 +60,6 @@ class AppUserStore extends AbstractAppStore } populate() { - super.populate(); this.projectHash(Settings.settingsGet('ProjectHash')); diff --git a/dev/Stores/User/Contact.js b/dev/Stores/User/Contact.js index c1f157832..d3a8ef6d9 100644 --- a/dev/Stores/User/Contact.js +++ b/dev/Stores/User/Contact.js @@ -1,17 +1,15 @@ - import ko from 'ko'; -import {Magics} from 'Common/Enums'; +import { Magics } from 'Common/Enums'; import * as Settings from 'Storage/Settings'; -class ContactUserStore -{ +class ContactUserStore { constructor() { this.contacts = ko.observableArray([]); - this.contacts.loading = ko.observable(false).extend({throttle: Magics.Time200ms}); - this.contacts.importing = ko.observable(false).extend({throttle: Magics.Time200ms}); - this.contacts.syncing = ko.observable(false).extend({throttle: Magics.Time200ms}); - this.contacts.exportingVcf = ko.observable(false).extend({throttle: Magics.Time200ms}); - this.contacts.exportingCsv = ko.observable(false).extend({throttle: Magics.Time200ms}); + this.contacts.loading = ko.observable(false).extend({ throttle: Magics.Time200ms }); + this.contacts.importing = ko.observable(false).extend({ throttle: Magics.Time200ms }); + this.contacts.syncing = ko.observable(false).extend({ throttle: Magics.Time200ms }); + this.contacts.exportingVcf = ko.observable(false).extend({ throttle: Magics.Time200ms }); + this.contacts.exportingCsv = ko.observable(false).extend({ throttle: Magics.Time200ms }); this.allowContactsSync = ko.observable(false); this.enableContactsSync = ko.observable(false); diff --git a/dev/Stores/User/Filter.js b/dev/Stores/User/Filter.js index 4ced2c348..49e4ebda0 100644 --- a/dev/Stores/User/Filter.js +++ b/dev/Stores/User/Filter.js @@ -1,17 +1,15 @@ - import ko from 'ko'; -import {Magics} from 'Common/Enums'; +import { Magics } from 'Common/Enums'; -class FilterUserStore -{ +class FilterUserStore { constructor() { this.capa = ko.observable(''); this.modules = ko.observable({}); this.filters = ko.observableArray([]); - this.filters.loading = ko.observable(false).extend({throttle: Magics.Time200ms}); - this.filters.saving = ko.observable(false).extend({throttle: Magics.Time200ms}); + this.filters.loading = ko.observable(false).extend({ throttle: Magics.Time200ms }); + this.filters.saving = ko.observable(false).extend({ throttle: Magics.Time200ms }); this.raw = ko.observable(''); } diff --git a/dev/Stores/User/Folder.js b/dev/Stores/User/Folder.js index 1ed15acc9..159d9a04a 100644 --- a/dev/Stores/User/Folder.js +++ b/dev/Stores/User/Folder.js @@ -1,18 +1,16 @@ - import ko from 'ko'; import _ from '_'; -import {settingsGet} from 'Storage/Settings'; +import { settingsGet } from 'Storage/Settings'; -import {FolderType} from 'Common/Enums'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {isArray, folderListOptionsBuilder} from 'Common/Utils'; -import {getFolderInboxName, getFolderFromCacheList} from 'Common/Cache'; +import { FolderType } from 'Common/Enums'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { isArray, folderListOptionsBuilder } from 'Common/Utils'; +import { getFolderInboxName, getFolderFromCacheList } from 'Common/Cache'; -import {momentNowUnix} from 'Common/Momentor'; +import { momentNowUnix } from 'Common/Momentor'; -class FolderUserStore -{ +class FolderUserStore { constructor() { this.displaySpecSetting = ko.observable(true); @@ -35,7 +33,7 @@ class FolderUserStore this.foldersInboxUnreadCount = ko.observable(0); - this.currentFolder = ko.observable(null).extend({toggleSubscribeProperty: [this, 'selected']}); + this.currentFolder = ko.observable(null).extend({ toggleSubscribeProperty: [this, 'selected'] }); this.sieveAllowFileintoInbox = !!settingsGet('SieveAllowFileintoInbox'); @@ -44,25 +42,21 @@ class FolderUserStore } computers() { - this.draftFolderNotEnabled = ko.computed( - () => ('' === this.draftFolder() || UNUSED_OPTION_VALUE === this.draftFolder()) + () => '' === this.draftFolder() || UNUSED_OPTION_VALUE === this.draftFolder() ); this.foldersListWithSingleInboxRootFolder = ko.computed( - () => !_.find(this.folderList(), (folder) => (folder && !folder.isSystemFolder() && folder.visible())) + () => !_.find(this.folderList(), (folder) => folder && !folder.isSystemFolder() && folder.visible()) ); - this.currentFolderFullNameRaw = ko.computed( - () => (this.currentFolder() ? this.currentFolder().fullNameRaw : '') - ); + this.currentFolderFullNameRaw = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullNameRaw : '')); this.currentFolderFullName = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullName : '')); this.currentFolderFullNameHash = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullNameHash : '')); this.foldersChanging = ko.computed(() => { - const - loading = this.foldersLoading(), + const loading = this.foldersLoading(), creating = this.foldersCreating(), deleting = this.foldersDeleting(), renaming = this.foldersRenaming(); @@ -71,9 +65,7 @@ class FolderUserStore }); this.folderListSystemNames = ko.computed(() => { - - const - list = [getFolderInboxName()], + const list = [getFolderInboxName()], folders = this.folderList(), sentFolder = this.sentFolder(), draftFolder = this.draftFolder(), @@ -81,26 +73,20 @@ class FolderUserStore trashFolder = this.trashFolder(), archiveFolder = this.archiveFolder(); - if (isArray(folders) && 0 < folders.length) - { - if ('' !== sentFolder && UNUSED_OPTION_VALUE !== sentFolder) - { + if (isArray(folders) && 0 < folders.length) { + if ('' !== sentFolder && UNUSED_OPTION_VALUE !== sentFolder) { list.push(sentFolder); } - if ('' !== draftFolder && UNUSED_OPTION_VALUE !== draftFolder) - { + if ('' !== draftFolder && UNUSED_OPTION_VALUE !== draftFolder) { list.push(draftFolder); } - if ('' !== spamFolder && UNUSED_OPTION_VALUE !== spamFolder) - { + if ('' !== spamFolder && UNUSED_OPTION_VALUE !== spamFolder) { list.push(spamFolder); } - if ('' !== trashFolder && UNUSED_OPTION_VALUE !== trashFolder) - { + if ('' !== trashFolder && UNUSED_OPTION_VALUE !== trashFolder) { list.push(trashFolder); } - if ('' !== archiveFolder && UNUSED_OPTION_VALUE !== archiveFolder) - { + if ('' !== archiveFolder && UNUSED_OPTION_VALUE !== archiveFolder) { list.push(archiveFolder); } } @@ -108,40 +94,50 @@ class FolderUserStore return list; }); - this.folderListSystem = ko.computed( - () => _.compact(_.map(this.folderListSystemNames(), (name) => getFolderFromCacheList(name))) + this.folderListSystem = ko.computed(() => + _.compact(_.map(this.folderListSystemNames(), (name) => getFolderFromCacheList(name))) ); - this.folderMenuForMove = ko.computed( - () => folderListOptionsBuilder( - this.folderListSystem(), this.folderList(), - [this.currentFolderFullNameRaw()], null, null, null, null, (item) => (item ? item.localName() : '')) + this.folderMenuForMove = ko.computed(() => + folderListOptionsBuilder( + this.folderListSystem(), + this.folderList(), + [this.currentFolderFullNameRaw()], + null, + null, + null, + null, + (item) => (item ? item.localName() : '') + ) ); - this.folderMenuForFilters = ko.computed( - () => folderListOptionsBuilder( - this.folderListSystem(), this.folderList(), - [(this.sieveAllowFileintoInbox ? '' : 'INBOX')], [['', '']], null, null, null, (item) => (item ? item.localName() : '')) + this.folderMenuForFilters = ko.computed(() => + folderListOptionsBuilder( + this.folderListSystem(), + this.folderList(), + [this.sieveAllowFileintoInbox ? '' : 'INBOX'], + [['', '']], + null, + null, + null, + (item) => (item ? item.localName() : '') + ) ); } subscribers() { - const - fRemoveSystemFolderType = (observable) => () => { - const folder = getFolderFromCacheList(observable()); - if (folder) - { - folder.type(FolderType.User); - } - }; - const - fSetSystemFolderType = (type) => (value) => { - const folder = getFolderFromCacheList(value); - if (folder) - { - folder.type(type); - } - }; + const fRemoveSystemFolderType = (observable) => () => { + const folder = getFolderFromCacheList(observable()); + if (folder) { + folder.type(FolderType.User); + } + }; + const fSetSystemFolderType = (type) => (value) => { + const folder = getFolderFromCacheList(value); + if (folder) { + folder.type(type); + } + }; this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange'); this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange'); @@ -160,9 +156,7 @@ class FolderUserStore * @returns {Array} */ getNextFolderNames() { - - const - result = [], + const result = [], limit = 5, utc = momentNowUnix(), timeout = utc - 60 * 5, @@ -170,16 +164,18 @@ class FolderUserStore inboxFolderName = getFolderInboxName(), fSearchFunction = (list) => { _.each(list, (folder) => { - if (folder && inboxFolderName !== folder.fullNameRaw && - folder.selectable && folder.existen && timeout > folder.interval && + if ( + folder && + inboxFolderName !== folder.fullNameRaw && + folder.selectable && + folder.existen && + timeout > folder.interval && (folder.isSystemFolder() || (folder.subScribed() && folder.checkable())) - ) - { + ) { timeouts.push([folder.interval, folder.fullNameRaw]); } - if (folder && 0 < folder.subFolders().length) - { + if (folder && 0 < folder.subFolders().length) { fSearchFunction(folder.subFolders()); } }); @@ -188,12 +184,9 @@ class FolderUserStore fSearchFunction(this.folderList()); timeouts.sort((a, b) => { - if (a[0] < b[0]) - { + if (a[0] < b[0]) { return -1; - } - else if (a[0] > b[0]) - { + } else if (a[0] > b[0]) { return 1; } @@ -202,8 +195,7 @@ class FolderUserStore _.find(timeouts, (aItem) => { const folder = getFolderFromCacheList(aItem[1]); - if (folder) - { + if (folder) { folder.interval = utc; result.push(aItem[1]); } diff --git a/dev/Stores/User/Identity.js b/dev/Stores/User/Identity.js index fd4085531..cc80b8573 100644 --- a/dev/Stores/User/Identity.js +++ b/dev/Stores/User/Identity.js @@ -1,15 +1,12 @@ - import _ from '_'; import ko from 'ko'; -class IdentityUserStore -{ +class IdentityUserStore { constructor() { this.identities = ko.observableArray([]); - this.identities.loading = ko.observable(false).extend({throttle: 100}); + this.identities.loading = ko.observable(false).extend({ throttle: 100 }); - this.identitiesIDS = ko.computed( - () => _.compact(_.map(this.identities(), (item) => (item ? item.id : null)))); + this.identitiesIDS = ko.computed(() => _.compact(_.map(this.identities(), (item) => (item ? item.id : null)))); } } diff --git a/dev/Stores/User/Message.js b/dev/Stores/User/Message.js index e12d1c302..eed66f84a 100644 --- a/dev/Stores/User/Message.js +++ b/dev/Stores/User/Message.js @@ -1,20 +1,20 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; import $ from '$'; -import { - Magics, Layout, Focused, - MessageSetAction, - StorageResultType, - Notification -} from 'Common/Enums'; +import { Magics, Layout, Focused, MessageSetAction, StorageResultType, Notification } from 'Common/Enums'; import { - trim, isNormal, isArray, inArray, - pInt, pString, plainToHtml, - windowResize, findEmailAndLinks, + trim, + isNormal, + isArray, + inArray, + pInt, + pString, + plainToHtml, + windowResize, + findEmailAndLinks, getRealHeight } from 'Common/Utils'; @@ -32,16 +32,16 @@ import { clearNewMessageCache } from 'Common/Cache'; -import {MESSAGE_BODY_CACHE_LIMIT} from 'Common/Consts'; -import {data as GlobalsData, $div} from 'Common/Globals'; -import {mailBox, notificationMailIcon} from 'Common/Links'; -import {i18n, getNotification} from 'Common/Translator'; -import {momentNowUnix} from 'Common/Momentor'; +import { MESSAGE_BODY_CACHE_LIMIT } from 'Common/Consts'; +import { data as GlobalsData, $div } from 'Common/Globals'; +import { mailBox, notificationMailIcon } from 'Common/Links'; +import { i18n, getNotification } from 'Common/Translator'; +import { momentNowUnix } from 'Common/Momentor'; import * as MessageHelper from 'Helper/Message'; -import {MessageModel} from 'Model/Message'; +import { MessageModel } from 'Model/Message'; -import {setHash} from 'Knoin/Knoin'; +import { setHash } from 'Knoin/Knoin'; import AppStore from 'Stores/User/App'; import AccountStore from 'Stores/User/Account'; @@ -50,17 +50,15 @@ import PgpStore from 'Stores/User/Pgp'; import SettingsStore from 'Stores/User/Settings'; import NotificationStore from 'Stores/User/Notification'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; import Remote from 'Remote/User/Ajax'; -class MessageUserStore -{ - constructor() - { +class MessageUserStore { + constructor() { this.staticMessage = new MessageModel(); - this.messageList = ko.observableArray([]).extend({rateLimit: 0}); + this.messageList = ko.observableArray([]).extend({ rateLimit: 0 }); this.messageListCount = ko.observable(0); this.messageListSearch = ko.observable(''); @@ -76,10 +74,10 @@ class MessageUserStore this.messageListLoading = ko.observable(false); this.messageListIsNotCompleted = ko.observable(false); - this.messageListCompleteLoadingThrottle = ko.observable(false).extend({throttle: 200}); - this.messageListCompleteLoadingThrottleForAnimation = ko.observable(false).extend({specialThrottle: 700}); + this.messageListCompleteLoadingThrottle = ko.observable(false).extend({ throttle: 200 }); + this.messageListCompleteLoadingThrottleForAnimation = ko.observable(false).extend({ specialThrottle: 700 }); - this.messageListDisableAutoSelect = ko.observable(false).extend({falseTimeout: 500}); + this.messageListDisableAutoSelect = ko.observable(false).extend({ falseTimeout: 500 }); this.selectorMessageSelected = ko.observable(null); this.selectorMessageFocused = ko.observable(null); @@ -93,7 +91,7 @@ class MessageUserStore this.messageCurrentLoading = ko.observable(false); - this.messageLoadingThrottle = ko.observable(false).extend({throttle: Magics.Time50ms}); + this.messageLoadingThrottle = ko.observable(false).extend({ throttle: Magics.Time50ms }); this.messageFullScreenMode = ko.observable(false); @@ -109,12 +107,17 @@ class MessageUserStore } computers() { - this.messageLoading = ko.computed(() => this.messageCurrentLoading()); this.messageListEndHash = ko.computed( - () => this.messageListEndFolder() + '|' + this.messageListEndSearch() + - '|' + this.messageListEndThreadUid() + '|' + this.messageListEndPage() + () => + this.messageListEndFolder() + + '|' + + this.messageListEndSearch() + + '|' + + this.messageListEndThreadUid() + + '|' + + this.messageListEndPage() ); this.messageListPageCount = ko.computed(() => { @@ -132,23 +135,21 @@ class MessageUserStore }); this.messageListCompleteLoading = ko.computed(() => { - const - one = this.messageListLoading(), + const one = this.messageListLoading(), two = this.messageListIsNotCompleted(); return one || two; }); this.isMessageSelected = ko.computed(() => null !== this.message()); - this.messageListChecked = ko.computed( - () => _.filter(this.messageList(), (item) => item.checked()) - ).extend({rateLimit: 0}); + this.messageListChecked = ko + .computed(() => _.filter(this.messageList(), (item) => item.checked())) + .extend({ rateLimit: 0 }); - this.hasCheckedMessages = ko.computed(() => 0 < this.messageListChecked().length).extend({rateLimit: 0}); + this.hasCheckedMessages = ko.computed(() => 0 < this.messageListChecked().length).extend({ rateLimit: 0 }); this.messageListCheckedOrSelected = ko.computed(() => { - const - checked = this.messageListChecked(), + const checked = this.messageListChecked(), selectedMessage = this.selectorMessageSelected(), focusedMessage = this.selectorMessageFocused(); @@ -164,11 +165,9 @@ class MessageUserStore this.messageListCheckedOrSelectedUidsWithSubMails = ko.computed(() => { let result = []; _.each(this.messageListCheckedOrSelected(), (message) => { - if (message) - { + if (message) { result.push(message.uid); - if (1 < message.threadsLen()) - { + if (1 < message.threadsLen()) { result = _.union(result, message.threads()); } } @@ -178,39 +177,33 @@ class MessageUserStore } subscribers() { - this.messageListCompleteLoading.subscribe((value) => { value = !!value; this.messageListCompleteLoadingThrottle(value); this.messageListCompleteLoadingThrottleForAnimation(value); }); - this.messageList.subscribe(_.debounce((list) => { - _.each(list, (item) => { - if (item && item.newForAnimation()) - { - item.newForAnimation(false); - } - }); - }, Magics.Time500ms)); + this.messageList.subscribe( + _.debounce((list) => { + _.each(list, (item) => { + if (item && item.newForAnimation()) { + item.newForAnimation(false); + } + }); + }, Magics.Time500ms) + ); this.message.subscribe((message) => { - - if (message) - { - if (Layout.NoPreview === SettingsStore.layout()) - { + if (message) { + if (Layout.NoPreview === SettingsStore.layout()) { AppStore.focusedState(Focused.MessageView); } - } - else - { + } else { AppStore.focusedState(Focused.MessageList); this.messageFullScreenMode(false); this.hideMessageBodies(); } - }); this.messageLoading.subscribe((value) => { @@ -218,42 +211,35 @@ class MessageUserStore }); this.messagesBodiesDom.subscribe((dom) => { - if (dom && !(dom instanceof $)) - { + if (dom && !(dom instanceof $)) { this.messagesBodiesDom($(dom)); } }); this.messageListEndFolder.subscribe((folder) => { const message = this.message(); - if (message && folder && folder !== message.folderFullNameRaw) - { + if (message && folder && folder !== message.folderFullNameRaw) { this.message(null); } }); } purgeMessageBodyCache() { - let count = 0; const end = GlobalsData.iMessageBodyCacheCount - MESSAGE_BODY_CACHE_LIMIT; - if (0 < end) - { + if (0 < end) { const messagesDom = this.messagesBodiesDom(); - if (messagesDom) - { + if (messagesDom) { messagesDom.find('.rl-cache-class').each(function() { const item = $(this); // eslint-disable-line no-invalid-this - if (end > item.data('rl-cache-count')) - { + if (end > item.data('rl-cache-count')) { item.addClass('rl-cache-purge'); count += 1; } }); - if (0 < count) - { + if (0 < count) { _.delay(() => messagesDom.find('.rl-cache-purge').remove(), Magics.Time350ms); } } @@ -261,10 +247,8 @@ class MessageUserStore } initUidNextAndNewMessages(folder, uidNext, newMessages) { - if (getFolderInboxName() === folder && isNormal(uidNext) && '' !== uidNext) - { - if (isArray(newMessages) && 0 < newMessages.length) - { + if (getFolderInboxName() === folder && isNormal(uidNext) && '' !== uidNext) { + if (isArray(newMessages) && 0 < newMessages.length) { _.each(newMessages, (item) => { addNewMessageCache(folder, item.Uid); }); @@ -272,25 +256,22 @@ class MessageUserStore NotificationStore.playSoundNotification(); const len = newMessages.length; - if (3 < len) - { + if (3 < len) { NotificationStore.displayDesktopNotification( notificationMailIcon(), AccountStore.email(), i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', { 'COUNT': len }), - {'Folder': '', 'Uid': ''} + { 'Folder': '', 'Uid': '' } ); - } - else - { + } else { _.each(newMessages, (item) => { NotificationStore.displayDesktopNotification( notificationMailIcon(), MessageHelper.emailArrayToString(MessageHelper.emailArrayFromJson(item.From), false), item.Subject, - {'Folder': item.Folder, 'Uid': item.Uid} + { 'Folder': item.Folder, 'Uid': item.Uid } ); }); } @@ -302,8 +283,7 @@ class MessageUserStore hideMessageBodies() { const messagesDom = this.messagesBodiesDom(); - if (messagesDom) - { + if (messagesDom) { messagesDom.find('.b-text-part').hide(); } } @@ -315,73 +295,63 @@ class MessageUserStore * @param {boolean=} copy = false */ removeMessagesFromList(fromFolderFullNameRaw, uidForRemove, toFolderFullNameRaw = '', copy = false) { - uidForRemove = _.map(uidForRemove, (mValue) => pInt(mValue)); - let - unseenCount = 0, + let unseenCount = 0, messageList = this.messageList(), currentMessage = this.message(); - const - trashFolder = FolderStore.trashFolder(), + const trashFolder = FolderStore.trashFolder(), spamFolder = FolderStore.spamFolder(), fromFolder = getFolderFromCacheList(fromFolderFullNameRaw), toFolder = '' === toFolderFullNameRaw ? null : getFolderFromCacheList(toFolderFullNameRaw || ''), currentFolderFullNameRaw = FolderStore.currentFolderFullNameRaw(), - messages = currentFolderFullNameRaw === fromFolderFullNameRaw ? - _.filter(messageList, (item) => (item && -1 < inArray(pInt(item.uid), uidForRemove))) : []; + messages = + currentFolderFullNameRaw === fromFolderFullNameRaw + ? _.filter(messageList, (item) => item && -1 < inArray(pInt(item.uid), uidForRemove)) + : []; _.each(messages, (item) => { - if (item && item.unseen()) - { + if (item && item.unseen()) { unseenCount += 1; } }); - if (fromFolder && !copy) - { - fromFolder.messageCountAll(0 <= fromFolder.messageCountAll() - uidForRemove.length ? - fromFolder.messageCountAll() - uidForRemove.length : 0); + if (fromFolder && !copy) { + fromFolder.messageCountAll( + 0 <= fromFolder.messageCountAll() - uidForRemove.length ? fromFolder.messageCountAll() - uidForRemove.length : 0 + ); - if (0 < unseenCount) - { - fromFolder.messageCountUnread(0 <= fromFolder.messageCountUnread() - unseenCount ? - fromFolder.messageCountUnread() - unseenCount : 0); + if (0 < unseenCount) { + fromFolder.messageCountUnread( + 0 <= fromFolder.messageCountUnread() - unseenCount ? fromFolder.messageCountUnread() - unseenCount : 0 + ); } } - if (toFolder) - { - if (trashFolder === toFolder.fullNameRaw || spamFolder === toFolder.fullNameRaw) - { + if (toFolder) { + if (trashFolder === toFolder.fullNameRaw || spamFolder === toFolder.fullNameRaw) { unseenCount = 0; } toFolder.messageCountAll(toFolder.messageCountAll() + uidForRemove.length); - if (0 < unseenCount) - { + if (0 < unseenCount) { toFolder.messageCountUnread(toFolder.messageCountUnread() + unseenCount); } toFolder.actionBlink(true); } - if (0 < messages.length) - { - if (copy) - { + if (0 < messages.length) { + if (copy) { _.each(messages, (item) => { item.checked(false); }); - } - else - { + } else { this.messageListIsNotCompleted(true); _.each(messages, (item) => { - if (currentMessage && currentMessage.hash === item.hash) - { + if (currentMessage && currentMessage.hash === item.hash) { currentMessage = null; this.message(null); } @@ -397,57 +367,62 @@ class MessageUserStore } } - if ('' !== fromFolderFullNameRaw) - { + if ('' !== fromFolderFullNameRaw) { setFolderHash(fromFolderFullNameRaw, ''); } - if ('' !== toFolderFullNameRaw) - { + if ('' !== toFolderFullNameRaw) { setFolderHash(toFolderFullNameRaw, ''); } - if ('' !== this.messageListThreadUid()) - { + if ('' !== this.messageListThreadUid()) { messageList = this.messageList(); - if (messageList && 0 < messageList.length && - !!_.find(messageList, (item) => !!(item && item.deleted() && item.uid === this.messageListThreadUid()))) - { + if ( + messageList && + 0 < messageList.length && + !!_.find(messageList, (item) => !!(item && item.deleted() && item.uid === this.messageListThreadUid())) + ) { const message = _.find(messageList, (item) => item && !item.deleted()); - if (message && this.messageListThreadUid() !== pString(message.uid)) - { + if (message && this.messageListThreadUid() !== pString(message.uid)) { this.messageListThreadUid(pString(message.uid)); - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - this.messageListPage(), - this.messageListSearch(), - this.messageListThreadUid() - ), true, true); - } - else if (!message) - { - if (1 < this.messageListPage()) - { - this.messageListPage(this.messageListPage() - 1); - - setHash(mailBox( + setHash( + mailBox( FolderStore.currentFolderFullNameHash(), this.messageListPage(), this.messageListSearch(), this.messageListThreadUid() - ), true, true); - } - else - { + ), + true, + true + ); + } else if (!message) { + if (1 < this.messageListPage()) { + this.messageListPage(this.messageListPage() - 1); + + setHash( + mailBox( + FolderStore.currentFolderFullNameHash(), + this.messageListPage(), + this.messageListSearch(), + this.messageListThreadUid() + ), + true, + true + ); + } else { this.messageListThreadUid(''); - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - this.messageListPageBeforeThread(), - this.messageListSearch() - ), true, true); + setHash( + mailBox( + FolderStore.currentFolderFullNameHash(), + this.messageListPageBeforeThread(), + this.messageListSearch() + ), + true, + true + ); } } } @@ -458,25 +433,26 @@ class MessageUserStore * @param {Object} messageTextBody */ initBlockquoteSwitcher(messageTextBody) { - if (messageTextBody) - { + if (messageTextBody) { const $oList = $('blockquote:not(.rl-bq-switcher)', messageTextBody).filter(function() { - return 0 === $(this).parent().closest('blockquote', messageTextBody).length; // eslint-disable-line no-invalid-this + return ( + 0 === + $(this) + .parent() + .closest('blockquote', messageTextBody).length + ); // eslint-disable-line no-invalid-this }); - if ($oList && 0 < $oList.length) - { + if ($oList && 0 < $oList.length) { $oList.each(function() { const $this = $(this); // eslint-disable-line no-invalid-this let h = $this.height(); - if (0 === h) - { + if (0 === h) { h = getRealHeight($this); } - if ('' !== trim($this.text()) && (0 === h || 100 < h)) - { + if ('' !== trim($this.text()) && (0 === h || 100 < h)) { $this.addClass('rl-bq-switcher hidden-bq'); $('') .insertBefore($this) @@ -497,8 +473,7 @@ class MessageUserStore * @param {Object} message */ initOpenPgpControls(messageTextBody, message) { - if (messageTextBody && messageTextBody.find) - { + if (messageTextBody && messageTextBody.find) { messageTextBody.find('.b-plain-openpgp:not(.inited)').each(function() { PgpStore.initMessageBodyControls($(this), message); // eslint-disable-line no-invalid-this }); @@ -506,9 +481,7 @@ class MessageUserStore } setMessage(data, cached) { - - let - isNew = false, + let isNew = false, body = null, id = '', plain = '', @@ -518,15 +491,17 @@ class MessageUserStore selectedMessage = this.selectorMessageSelected(), message = this.message(); - if (data && message && data.Result && 'Object/Message' === data.Result['@Object'] && - message.folderFullNameRaw === data.Result.Folder) - { + if ( + data && + message && + data.Result && + 'Object/Message' === data.Result['@Object'] && + message.folderFullNameRaw === data.Result.Folder + ) { const threads = message.threads(); - if (message.uid !== data.Result.Uid && 1 < threads.length && -1 < inArray(data.Result.Uid, threads)) - { + if (message.uid !== data.Result.Uid && 1 < threads.length && -1 < inArray(data.Result.Uid, threads)) { message = MessageModel.newInstanceFromJson(data.Result); - if (message) - { + if (message) { message.threads(threads); initMessageFlagsFromCache(message); @@ -537,63 +512,45 @@ class MessageUserStore } } - if (message && message.uid === data.Result.Uid) - { + if (message && message.uid === data.Result.Uid) { this.messageError(''); message.initUpdateByMessageJson(data.Result); addRequestedMessage(message.folderFullNameRaw, message.uid); - if (!cached) - { + if (!cached) { message.initFlagsByJson(data.Result); } messagesDom = messagesDom && messagesDom[0] ? messagesDom : null; - if (messagesDom) - { + if (messagesDom) { id = 'rl-mgs-' + message.hash.replace(/[^a-zA-Z0-9]/g, ''); const textBody = messagesDom.find('#' + id); - if (!textBody || !textBody[0]) - { + if (!textBody || !textBody[0]) { let isHtml = false; - if (isNormal(data.Result.Html) && '' !== data.Result.Html) - { + if (isNormal(data.Result.Html) && '' !== data.Result.Html) { isHtml = true; resultHtml = data.Result.Html.toString(); - } - else if (isNormal(data.Result.Plain) && '' !== data.Result.Plain) - { + } else if (isNormal(data.Result.Plain) && '' !== data.Result.Plain) { isHtml = false; resultHtml = plainToHtml(data.Result.Plain.toString(), false); - if ((message.isPgpSigned() || message.isPgpEncrypted()) && PgpStore.capaOpenPGP()) - { + if ((message.isPgpSigned() || message.isPgpEncrypted()) && PgpStore.capaOpenPGP()) { plain = pString(data.Result.Plain); - const isPgpEncrypted = (/---BEGIN PGP MESSAGE---/).test(plain); - if (!isPgpEncrypted) - { - pgpSigned = (/-----BEGIN PGP SIGNED MESSAGE-----/).test(plain) && - (/-----BEGIN PGP SIGNATURE-----/).test(plain); + const isPgpEncrypted = /---BEGIN PGP MESSAGE---/.test(plain); + if (!isPgpEncrypted) { + pgpSigned = + /-----BEGIN PGP SIGNED MESSAGE-----/.test(plain) && /-----BEGIN PGP SIGNATURE-----/.test(plain); } $div.empty(); - if (pgpSigned && message.isPgpSigned()) - { - resultHtml = $div.append( - $('').text(plain) - ).html(); - } - else if (isPgpEncrypted && message.isPgpEncrypted()) - { - resultHtml = $div.append( - $('').text(plain) - ).html(); - } - else - { + if (pgpSigned && message.isPgpSigned()) { + resultHtml = $div.append($('').text(plain)).html(); + } else if (isPgpEncrypted && message.isPgpEncrypted()) { + resultHtml = $div.append($('').text(plain)).html(); + } else { resultHtml = ' ' + resultHtml + ''; } @@ -601,55 +558,45 @@ class MessageUserStore message.isPgpSigned(pgpSigned); message.isPgpEncrypted(isPgpEncrypted); - } - else - { + } else { resultHtml = '' + resultHtml + ''; } - } - else - { + } else { isHtml = false; resultHtml = '' + resultHtml + ''; } GlobalsData.iMessageBodyCacheCount += 1; - body = $('').hide().addClass('rl-cache-class'); + body = $('') + .hide() + .addClass('rl-cache-class'); body.data('rl-cache-count', GlobalsData.iMessageBodyCacheCount); - body - .html(findEmailAndLinks(resultHtml)) - .addClass('b-text-part ' + (isHtml ? 'html' : 'plain')); + body.html(findEmailAndLinks(resultHtml)).addClass('b-text-part ' + (isHtml ? 'html' : 'plain')); message.isHtml(!!isHtml); message.hasImages(!!data.Result.HasExternals); message.body = body; - if (message.body) - { + if (message.body) { messagesDom.append(message.body); } message.storeDataInDom(); - if (data.Result.HasInternals) - { + if (data.Result.HasInternals) { message.showInternalImages(true); } - if (message.hasImages() && SettingsStore.showImages()) - { + if (message.hasImages() && SettingsStore.showImages()) { message.showExternalImages(true); } this.purgeMessageBodyCacheThrottle(); - } - else - { + } else { message.body = textBody; - if (message.body) - { + if (message.body) { GlobalsData.iMessageBodyCacheCount += 1; message.body.data('rl-cache-count', GlobalsData.iMessageBodyCacheCount); message.fetchDataFromDom(); @@ -660,8 +607,7 @@ class MessageUserStore this.hideMessageBodies(); - if (body) - { + if (body) { this.initOpenPgpControls(body, message); this.initBlockquoteSwitcher(body); @@ -671,42 +617,36 @@ class MessageUserStore } initMessageFlagsFromCache(message); - if (message.unseen() || message.hasUnseenSubMessage()) - { - getApp().messageListAction( - message.folderFullNameRaw, MessageSetAction.SetSeen, [message]); + if (message.unseen() || message.hasUnseenSubMessage()) { + getApp().messageListAction(message.folderFullNameRaw, MessageSetAction.SetSeen, [message]); } - if (isNew) - { + if (isNew) { message = this.message(); - if (selectedMessage && message && ( - message.folderFullNameRaw !== selectedMessage.folderFullNameRaw || - message.uid !== selectedMessage.uid - )) - { + if ( + selectedMessage && + message && + (message.folderFullNameRaw !== selectedMessage.folderFullNameRaw || message.uid !== selectedMessage.uid) + ) { this.selectorMessageSelected(null); - if (1 === this.messageList().length) - { + if (1 === this.messageList().length) { this.selectorMessageFocused(null); } - } - else if (!selectedMessage && message) - { - selectedMessage = _.find(this.messageList(), - (subMessage) => subMessage && + } else if (!selectedMessage && message) { + selectedMessage = _.find( + this.messageList(), + (subMessage) => + subMessage && subMessage.folderFullNameRaw === message.folderFullNameRaw && subMessage.uid === message.uid ); - if (selectedMessage) - { + if (selectedMessage) { this.selectorMessageSelected(selectedMessage); this.selectorMessageFocused(selectedMessage); } } - } windowResize(); @@ -715,37 +655,29 @@ class MessageUserStore } selectMessage(oMessage) { - if (oMessage) - { + if (oMessage) { this.message(this.staticMessage.populateByMessageListItem(oMessage)); this.populateMessageBody(this.message()); - } - else - { + } else { this.message(null); } } selectMessageByFolderAndUid(sFolder, sUid) { - if (sFolder && sUid) - { + if (sFolder && sUid) { this.message(this.staticMessage.populateByMessageListItem(null)); this.message().folderFullNameRaw = sFolder; this.message().uid = sUid; this.populateMessageBody(this.message()); - } - else - { + } else { this.message(null); } } populateMessageBody(oMessage) { - if (oMessage) - { - if (Remote.message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid)) - { + if (oMessage) { + if (Remote.message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid)) { this.messageCurrentLoading(true); } } @@ -757,25 +689,20 @@ class MessageUserStore * @param {boolean} bCached */ onMessageResponse(sResult, oData, bCached) { - this.hideMessageBodies(); this.messageCurrentLoading(false); - if (StorageResultType.Success === sResult && oData && oData.Result) - { + if (StorageResultType.Success === sResult && oData && oData.Result) { this.setMessage(oData, bCached); - } - else if (StorageResultType.Unload === sResult) - { + } else if (StorageResultType.Unload === sResult) { this.message(null); this.messageError(''); - } - else if (StorageResultType.Abort !== sResult) - { + } else if (StorageResultType.Abort !== sResult) { this.message(null); - this.messageError((oData && oData.ErrorCode ? - getNotification(oData.ErrorCode) : getNotification(Notification.UnknownError))); + this.messageError( + oData && oData.ErrorCode ? getNotification(oData.ErrorCode) : getNotification(Notification.UnknownError) + ); } } @@ -784,40 +711,40 @@ class MessageUserStore * @returns {string} */ calculateMessageListHash(list) { - return _.map(list, (message) => '' + message.hash + '_' + message.threadsLen() + '_' + message.flagHash()).join('|'); + return _.map(list, (message) => '' + message.hash + '_' + message.threadsLen() + '_' + message.flagHash()).join( + '|' + ); } setMessageList(data, cached) { - if (data && data.Result && 'Collection/MessageCollection' === data.Result['@Object'] && - data.Result['@Collection'] && isArray(data.Result['@Collection'])) - { - let - newCount = 0, + if ( + data && + data.Result && + 'Collection/MessageCollection' === data.Result['@Object'] && + data.Result['@Collection'] && + isArray(data.Result['@Collection']) + ) { + let newCount = 0, unreadCountChange = false; - const - list = [], + const list = [], utc = momentNowUnix(), iCount = pInt(data.Result.MessageResultCount), iOffset = pInt(data.Result.Offset); const folder = getFolderFromCacheList(isNormal(data.Result.Folder) ? data.Result.Folder : ''); - if (folder && !cached) - { + if (folder && !cached) { folder.interval = utc; setFolderHash(data.Result.Folder, data.Result.FolderHash); - if (isNormal(data.Result.MessageCount)) - { + if (isNormal(data.Result.MessageCount)) { folder.messageCountAll(data.Result.MessageCount); } - if (isNormal(data.Result.MessageUnseenCount)) - { - if (pInt(folder.messageCountUnread()) !== pInt(data.Result.MessageUnseenCount)) - { + if (isNormal(data.Result.MessageUnseenCount)) { + if (pInt(folder.messageCountUnread()) !== pInt(data.Result.MessageUnseenCount)) { unreadCountChange = true; } @@ -827,31 +754,24 @@ class MessageUserStore this.initUidNextAndNewMessages(folder.fullNameRaw, data.Result.UidNext, data.Result.NewMessages); } - if (unreadCountChange && folder) - { + if (unreadCountChange && folder) { clearMessageFlagsFromCacheByFolder(folder.fullNameRaw); } _.each(data.Result['@Collection'], (jsonMessage) => { - if (jsonMessage && 'Object/Message' === jsonMessage['@Object']) - { + if (jsonMessage && 'Object/Message' === jsonMessage['@Object']) { const message = MessageModel.newInstanceFromJson(jsonMessage); - if (message) - { - if (hasNewMessageAndRemoveFromCache(message.folderFullNameRaw, message.uid) && 5 >= newCount) - { + if (message) { + if (hasNewMessageAndRemoveFromCache(message.folderFullNameRaw, message.uid) && 5 >= newCount) { newCount += 1; message.newForAnimation(true); } message.deleted(false); - if (cached) - { + if (cached) { initMessageFlagsFromCache(message); - } - else - { + } else { storeMessageFlagsToCache(message); } @@ -862,7 +782,7 @@ class MessageUserStore this.messageListCount(iCount); this.messageListSearch(isNormal(data.Result.Search) ? data.Result.Search : ''); - this.messageListPage(window.Math.ceil((iOffset / SettingsStore.messagesPerPage()) + 1)); + this.messageListPage(window.Math.ceil(iOffset / SettingsStore.messagesPerPage() + 1)); this.messageListThreadUid(isNormal(data.Result.ThreadUid) ? pString(data.Result.ThreadUid) : ''); this.messageListEndFolder(isNormal(data.Result.Folder) ? data.Result.Folder : ''); @@ -877,18 +797,13 @@ class MessageUserStore clearNewMessageCache(); - if (folder && (cached || unreadCountChange || SettingsStore.useThreads())) - { + if (folder && (cached || unreadCountChange || SettingsStore.useThreads())) { getApp().folderInformation(folder.fullNameRaw, list); } - } - else - { + } else { this.messageListCount(0); this.messageList([]); - this.messageListError(getNotification( - data && data.ErrorCode ? data.ErrorCode : Notification.CantGetMessageList - )); + this.messageListError(getNotification(data && data.ErrorCode ? data.ErrorCode : Notification.CantGetMessageList)); } } } diff --git a/dev/Stores/User/Notification.js b/dev/Stores/User/Notification.js index b4cc048f7..2baeffaa9 100644 --- a/dev/Stores/User/Notification.js +++ b/dev/Stores/User/Notification.js @@ -1,110 +1,87 @@ - import window from 'window'; import ko from 'ko'; -import {DesktopNotification, Magics} from 'Common/Enums'; +import { DesktopNotification, Magics } from 'Common/Enums'; import * as Events from 'Common/Events'; import Audio from 'Common/Audio'; import * as Settings from 'Storage/Settings'; -class NotificationUserStore -{ +class NotificationUserStore { constructor() { this.enableSoundNotification = ko.observable(false); this.soundNotificationIsSupported = ko.observable(false); this.allowDesktopNotification = ko.observable(false); - this.desktopNotificationPermissions = ko.computed(() => { + this.desktopNotificationPermissions = ko + .computed(() => { + this.allowDesktopNotification(); - this.allowDesktopNotification(); + let result = DesktopNotification.NotSupported; - let result = DesktopNotification.NotSupported; - - const NotificationClass = this.notificationClass(); - if (NotificationClass && NotificationClass.permission) - { - switch (NotificationClass.permission.toLowerCase()) - { - case 'granted': - result = DesktopNotification.Allowed; - break; - case 'denied': - result = DesktopNotification.Denied; - break; - case 'default': - result = DesktopNotification.NotAllowed; - break; - // no default + const NotificationClass = this.notificationClass(); + if (NotificationClass && NotificationClass.permission) { + switch (NotificationClass.permission.toLowerCase()) { + case 'granted': + result = DesktopNotification.Allowed; + break; + case 'denied': + result = DesktopNotification.Denied; + break; + case 'default': + result = DesktopNotification.NotAllowed; + break; + // no default + } + } else if (window.webkitNotifications && window.webkitNotifications.checkPermission) { + result = window.webkitNotifications.checkPermission(); } - } - else if (window.webkitNotifications && window.webkitNotifications.checkPermission) - { - result = window.webkitNotifications.checkPermission(); - } - return result; + return result; + }) + .extend({ notify: 'always' }); - }).extend({notify: 'always'}); + this.enableDesktopNotification = ko + .computed({ + read: () => + this.allowDesktopNotification() && DesktopNotification.Allowed === this.desktopNotificationPermissions(), + write: (value) => { + if (value) { + const NotificationClass = this.notificationClass(), + permission = this.desktopNotificationPermissions(); - this.enableDesktopNotification = ko.computed({ - read: () => this.allowDesktopNotification() && DesktopNotification.Allowed === this.desktopNotificationPermissions(), - write: (value) => { - if (value) - { - const - NotificationClass = this.notificationClass(), - permission = this.desktopNotificationPermissions(); + if (NotificationClass && DesktopNotification.Allowed === permission) { + this.allowDesktopNotification(true); + } else if (NotificationClass && DesktopNotification.NotAllowed === permission) { + NotificationClass.requestPermission(() => { + this.allowDesktopNotification.valueHasMutated(); - if (NotificationClass && DesktopNotification.Allowed === permission) - { - this.allowDesktopNotification(true); - } - else if (NotificationClass && DesktopNotification.NotAllowed === permission) - { - NotificationClass.requestPermission(() => { - - this.allowDesktopNotification.valueHasMutated(); - - if (DesktopNotification.Allowed === this.desktopNotificationPermissions()) - { - if (this.allowDesktopNotification()) - { - this.allowDesktopNotification.valueHasMutated(); + if (DesktopNotification.Allowed === this.desktopNotificationPermissions()) { + if (this.allowDesktopNotification()) { + this.allowDesktopNotification.valueHasMutated(); + } else { + this.allowDesktopNotification(true); + } + } else { + if (this.allowDesktopNotification()) { + this.allowDesktopNotification(false); + } else { + this.allowDesktopNotification.valueHasMutated(); + } } - else - { - this.allowDesktopNotification(true); - } - } - else - { - if (this.allowDesktopNotification()) - { - this.allowDesktopNotification(false); - } - else - { - this.allowDesktopNotification.valueHasMutated(); - } - } - }); - } - else - { + }); + } else { + this.allowDesktopNotification(false); + } + } else { this.allowDesktopNotification(false); } } - else - { - this.allowDesktopNotification(false); - } - } - }).extend({notify: 'always'}); + }) + .extend({ notify: 'always' }); - if (!this.enableDesktopNotification.valueHasMutated) - { + if (!this.enableDesktopNotification.valueHasMutated) { this.enableDesktopNotification.valueHasMutated = () => { this.allowDesktopNotification.valueHasMutated(); }; @@ -121,72 +98,64 @@ class NotificationUserStore ); this.isDesktopNotificationDenied = ko.computed( - () => DesktopNotification.NotSupported === this.desktopNotificationPermissions() || + () => + DesktopNotification.NotSupported === this.desktopNotificationPermissions() || DesktopNotification.Denied === this.desktopNotificationPermissions() ); } initNotificationPlayer() { - if (Audio && Audio.supportedNotification) - { + if (Audio && Audio.supportedNotification) { this.soundNotificationIsSupported(true); - } - else - { + } else { this.enableSoundNotification(false); this.soundNotificationIsSupported(false); } } playSoundNotification(skipSetting) { - if (Audio && Audio.supportedNotification && (skipSetting ? true : this.enableSoundNotification())) - { + if (Audio && Audio.supportedNotification && (skipSetting ? true : this.enableSoundNotification())) { Audio.playNotification(); } } displayDesktopNotification(imageSrc, title, text, nessageData) { - if (this.enableDesktopNotification()) - { - const - NotificationClass = this.notificationClass(), - notification = NotificationClass ? new NotificationClass(title, { - body: text, - icon: imageSrc - }) : null; + if (this.enableDesktopNotification()) { + const NotificationClass = this.notificationClass(), + notification = NotificationClass + ? new NotificationClass(title, { + body: text, + icon: imageSrc + }) + : null; - if (notification) - { - if (notification.show) - { + if (notification) { + if (notification.show) { notification.show(); } - if (nessageData) - { + if (nessageData) { notification.onclick = () => { - window.focus(); - if (nessageData.Folder && nessageData.Uid) - { + if (nessageData.Folder && nessageData.Uid) { Events.pub('mailbox.message.show', [nessageData.Folder, nessageData.Uid]); } }; } - window.setTimeout((function(localNotifications) { - return () => { - if (localNotifications.cancel) - { - localNotifications.cancel(); - } - else if (localNotifications.close) - { - localNotifications.close(); - } - }; - }(notification)), Magics.Time7s); + window.setTimeout( + (function(localNotifications) { + return () => { + if (localNotifications.cancel) { + localNotifications.cancel(); + } else if (localNotifications.close) { + localNotifications.close(); + } + }; + })(notification), + Magics.Time7s + ); } } } diff --git a/dev/Stores/User/Pgp.js b/dev/Stores/User/Pgp.js index f80eda564..9d48a75d7 100644 --- a/dev/Stores/User/Pgp.js +++ b/dev/Stores/User/Pgp.js @@ -1,17 +1,15 @@ - import ko from 'ko'; import _ from '_'; import $ from '$'; -import {i18n} from 'Common/Translator'; -import {log, isArray, isNonEmptyArray, pString, isUnd, trim} from 'Common/Utils'; +import { i18n } from 'Common/Translator'; +import { log, isArray, isNonEmptyArray, pString, isUnd, trim } from 'Common/Utils'; import AccountStore from 'Stores/User/Account'; -import {showScreenPopup} from 'Knoin/Knoin'; +import { showScreenPopup } from 'Knoin/Knoin'; -class PgpUserStore -{ +class PgpUserStore { constructor() { this.capaOpenPGP = ko.observable(false); @@ -32,7 +30,7 @@ class PgpUserStore } findKeyByHex(keys, hash) { - return _.find(keys, (item) => (hash && item && (hash === item.id || -1 < item.ids.indexOf(hash)))); + return _.find(keys, (item) => hash && item && (hash === item.id || -1 < item.ids.indexOf(hash))); } findPublicKeyByHex(hash) { @@ -44,32 +42,59 @@ class PgpUserStore } findPublicKeysByEmail(email) { - return _.compact(_.flatten(_.map(this.openpgpkeysPublic(), (item) => { - const key = item && -1 < item.emails.indexOf(email) ? item : null; - return key ? key.getNativeKeys() : [null]; - }), true)); + return _.compact( + _.flatten( + _.map(this.openpgpkeysPublic(), (item) => { + const key = item && -1 < item.emails.indexOf(email) ? item : null; + return key ? key.getNativeKeys() : [null]; + }), + true + ) + ); } findPublicKeysBySigningKeyIds(signingKeyIds) { - return _.compact(_.flatten(_.map(signingKeyIds, (id) => { - const key = id && id.toHex ? this.findPublicKeyByHex(id.toHex()) : null; - return key ? key.getNativeKeys() : [null]; - }), true)); + return _.compact( + _.flatten( + _.map(signingKeyIds, (id) => { + const key = id && id.toHex ? this.findPublicKeyByHex(id.toHex()) : null; + return key ? key.getNativeKeys() : [null]; + }), + true + ) + ); } findPrivateKeysByEncryptionKeyIds(encryptionKeyIds, recipients, returnWrapKeys) { - let - result = isArray(encryptionKeyIds) ? _.compact(_.flatten(_.map(encryptionKeyIds, (id) => { - const key = id && id.toHex ? this.findPrivateKeyByHex(id.toHex()) : null; - return key ? (returnWrapKeys ? [key] : key.getNativeKeys()) : [null]; - }), true)) : []; + let result = isArray(encryptionKeyIds) + ? _.compact( + _.flatten( + _.map(encryptionKeyIds, (id) => { + const key = id && id.toHex ? this.findPrivateKeyByHex(id.toHex()) : null; + return key ? (returnWrapKeys ? [key] : key.getNativeKeys()) : [null]; + }), + true + ) + ) + : []; - if (0 === result.length && isNonEmptyArray(recipients)) - { - result = _.uniq(_.compact(_.flatten(_.map(recipients, (sEmail) => { - const keys = sEmail ? this.findAllPrivateKeysByEmailNotNative(sEmail) : null; - return keys ? (returnWrapKeys ? keys : _.flatten(_.map(keys, (key) => key.getNativeKeys()), true)) : [null]; - }), true)), (key) => key.id); + if (0 === result.length && isNonEmptyArray(recipients)) { + result = _.uniq( + _.compact( + _.flatten( + _.map(recipients, (sEmail) => { + const keys = sEmail ? this.findAllPrivateKeysByEmailNotNative(sEmail) : null; + return keys + ? returnWrapKeys + ? keys + : _.flatten(_.map(keys, (key) => key.getNativeKeys()), true) + : [null]; + }), + true + ) + ), + (key) => key.id + ); } return result; @@ -80,7 +105,7 @@ class PgpUserStore * @returns {?} */ findPublicKeyByEmailNotNative(email) { - return _.find(this.openpgpkeysPublic(), (item) => (item && -1 < item.emails.indexOf(email))) || null; + return _.find(this.openpgpkeysPublic(), (item) => item && -1 < item.emails.indexOf(email)) || null; } /** @@ -88,7 +113,7 @@ class PgpUserStore * @returns {?} */ findPrivateKeyByEmailNotNative(email) { - return _.find(this.openpgpkeysPrivate(), (item) => (item && -1 < item.emails.indexOf(email))) || null; + return _.find(this.openpgpkeysPrivate(), (item) => item && -1 < item.emails.indexOf(email)) || null; } /** @@ -96,7 +121,7 @@ class PgpUserStore * @returns {?} */ findAllPublicKeysByEmailNotNative(email) { - return _.filter(this.openpgpkeysPublic(), (item) => (item && -1 < item.emails.indexOf(email))) || null; + return _.filter(this.openpgpkeysPublic(), (item) => item && -1 < item.emails.indexOf(email)) || null; } /** @@ -104,7 +129,7 @@ class PgpUserStore * @returns {?} */ findAllPrivateKeysByEmailNotNative(email) { - return _.filter(this.openpgpkeysPrivate(), (item) => (item && -1 < item.emails.indexOf(email))) || null; + return _.filter(this.openpgpkeysPrivate(), (item) => item && -1 < item.emails.indexOf(email)) || null; } /** @@ -113,22 +138,16 @@ class PgpUserStore * @returns {?} */ findPrivateKeyByEmail(email, password) { - let privateKey = null; - const key = _.find(this.openpgpkeysPrivate(), (item) => (item && -1 < item.emails.indexOf(email))); + const key = _.find(this.openpgpkeysPrivate(), (item) => item && -1 < item.emails.indexOf(email)); - if (key) - { - try - { + if (key) { + try { privateKey = key.getNativeKeys()[0] || null; - if (privateKey) - { + if (privateKey) { privateKey.decrypt(pString(password)); } - } - catch (e) - { + } catch (e) { privateKey = null; } } @@ -145,46 +164,38 @@ class PgpUserStore } decryptMessage(message, recipients, fCallback) { - if (message && message.getEncryptionKeyIds) - { + if (message && message.getEncryptionKeyIds) { const privateKeys = this.findPrivateKeysByEncryptionKeyIds(message.getEncryptionKeyIds(), recipients, true); - if (privateKeys && 0 < privateKeys.length) - { - showScreenPopup(require('View/Popup/MessageOpenPgp'), [(decryptedKey) => { - - if (decryptedKey) - { - message.decrypt(decryptedKey).then((decryptedMessage) => { - let privateKey = null; - if (decryptedMessage) - { - privateKey = this.findPrivateKeyByHex(decryptedKey.primaryKey.keyid.toHex()); - if (privateKey) - { - this.verifyMessage(decryptedMessage, (oValidKey, aSigningKeyIds) => { - fCallback(privateKey, decryptedMessage, oValidKey || null, aSigningKeyIds || null); - }); + if (privateKeys && 0 < privateKeys.length) { + showScreenPopup(require('View/Popup/MessageOpenPgp'), [ + (decryptedKey) => { + if (decryptedKey) { + message.decrypt(decryptedKey).then( + (decryptedMessage) => { + let privateKey = null; + if (decryptedMessage) { + privateKey = this.findPrivateKeyByHex(decryptedKey.primaryKey.keyid.toHex()); + if (privateKey) { + this.verifyMessage(decryptedMessage, (oValidKey, aSigningKeyIds) => { + fCallback(privateKey, decryptedMessage, oValidKey || null, aSigningKeyIds || null); + }); + } else { + fCallback(privateKey, decryptedMessage); + } + } else { + fCallback(privateKey, decryptedMessage); + } + }, + () => { + fCallback(null, null); } - else - { - fCallback(privateKey, decryptedMessage); - } - } - else - { - fCallback(privateKey, decryptedMessage); - } - - }, () => { + ); + } else { fCallback(null, null); - }); - } - else - { - fCallback(null, null); - } - - }, privateKeys]); + } + }, + privateKeys + ]); return false; } @@ -196,28 +207,20 @@ class PgpUserStore } verifyMessage(message, fCallback) { - if (message && message.getSigningKeyIds) - { + if (message && message.getSigningKeyIds) { const signingKeyIds = message.getSigningKeyIds(); - if (signingKeyIds && 0 < signingKeyIds.length) - { + if (signingKeyIds && 0 < signingKeyIds.length) { const publicKeys = this.findPublicKeysBySigningKeyIds(signingKeyIds); - if (publicKeys && 0 < publicKeys.length) - { - try - { - const - result = message.verify(publicKeys), - valid = _.find(_.isArray(result) ? result : [], (item) => (item && item.valid && item.keyid)); + if (publicKeys && 0 < publicKeys.length) { + try { + const result = message.verify(publicKeys), + valid = _.find(_.isArray(result) ? result : [], (item) => item && item.valid && item.keyid); - if (valid && valid.keyid && valid.keyid && valid.keyid.toHex) - { + if (valid && valid.keyid && valid.keyid && valid.keyid.toHex) { fCallback(this.findPublicKeyByHex(valid.keyid.toHex())); return true; } - } - catch (e) - { + } catch (e) { log(e); } } @@ -232,75 +235,83 @@ class PgpUserStore } controlsHelper(dom, verControl, success, title, text) { - if (success) - { - dom.removeClass('error').addClass('success').attr('title', title); - verControl.removeClass('error').addClass('success').attr('title', title); - } - else - { - dom.removeClass('success').addClass('error').attr('title', title); - verControl.removeClass('success').addClass('error').attr('title', title); + if (success) { + dom + .removeClass('error') + .addClass('success') + .attr('title', title); + verControl + .removeClass('error') + .addClass('success') + .attr('title', title); + } else { + dom + .removeClass('success') + .addClass('error') + .attr('title', title); + verControl + .removeClass('success') + .addClass('error') + .attr('title', title); } - if (!isUnd(text)) - { + if (!isUnd(text)) { dom.text(trim(text)); } } static domControlEncryptedClickHelper(store, dom, armoredMessage, recipients) { - return function() { - let message = null; const $this = $(this); // eslint-disable-line no-invalid-this - if ($this.hasClass('success')) - { + if ($this.hasClass('success')) { return false; } - try - { + try { message = store.openpgp.message.readArmored(armoredMessage); - } - catch (e) - { + } catch (e) { log(e); } - if (message && message.getText && message.verify && message.decrypt) - { - store.decryptMessage(message, recipients, (validPrivateKey, decryptedMessage, validPublicKey, signingKeyIds) => { - if (decryptedMessage) - { - if (validPublicKey) - { - store.controlsHelper(dom, $this, true, i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', { - 'USER': validPublicKey.user + ' (' + validPublicKey.id + ')' - }), decryptedMessage.getText()); - } - else if (validPrivateKey) - { - const - keyIds = isNonEmptyArray(signingKeyIds) ? signingKeyIds : null, - additional = keyIds ? _.compact(_.map(keyIds, - (item) => (item && item.toHex ? item.toHex() : null))).join(', ') : ''; + if (message && message.getText && message.verify && message.decrypt) { + store.decryptMessage( + message, + recipients, + (validPrivateKey, decryptedMessage, validPublicKey, signingKeyIds) => { + if (decryptedMessage) { + if (validPublicKey) { + store.controlsHelper( + dom, + $this, + true, + i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', { + 'USER': validPublicKey.user + ' (' + validPublicKey.id + ')' + }), + decryptedMessage.getText() + ); + } else if (validPrivateKey) { + const keyIds = isNonEmptyArray(signingKeyIds) ? signingKeyIds : null, + additional = keyIds + ? _.compact(_.map(keyIds, (item) => (item && item.toHex ? item.toHex() : null))).join(', ') + : ''; - store.controlsHelper(dom, $this, false, i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE') + - (additional ? ' (' + additional + ')' : ''), decryptedMessage.getText()); - } - else - { + store.controlsHelper( + dom, + $this, + false, + i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE') + (additional ? ' (' + additional + ')' : ''), + decryptedMessage.getText() + ); + } else { + store.controlsHelper(dom, $this, false, i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR')); + } + } else { store.controlsHelper(dom, $this, false, i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR')); } } - else - { - store.controlsHelper(dom, $this, false, i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR')); - } - }); + ); return false; } @@ -311,43 +322,44 @@ class PgpUserStore } static domControlSignedClickHelper(store, dom, armoredMessage) { - return function() { - let message = null; const $this = $(this); // eslint-disable-line no-invalid-this - if ($this.hasClass('success') || $this.hasClass('error')) - { + if ($this.hasClass('success') || $this.hasClass('error')) { return false; } - try - { + try { message = store.openpgp.cleartext.readArmored(armoredMessage); - } - catch (e) - { + } catch (e) { log(e); } - if (message && message.getText && message.verify) - { + if (message && message.getText && message.verify) { store.verifyMessage(message, (validKey, signingKeyIds) => { - if (validKey) - { - store.controlsHelper(dom, $this, true, i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', { - 'USER': validKey.user + ' (' + validKey.id + ')' - }), message.getText()); - } - else - { - const - keyIds = isNonEmptyArray(signingKeyIds) ? signingKeyIds : null, - additional = keyIds ? _.compact(_.map(keyIds, (item) => (item && item.toHex ? item.toHex() : null))).join(', ') : ''; + if (validKey) { + store.controlsHelper( + dom, + $this, + true, + i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', { + 'USER': validKey.user + ' (' + validKey.id + ')' + }), + message.getText() + ); + } else { + const keyIds = isNonEmptyArray(signingKeyIds) ? signingKeyIds : null, + additional = keyIds + ? _.compact(_.map(keyIds, (item) => (item && item.toHex ? item.toHex() : null))).join(', ') + : ''; - store.controlsHelper(dom, $this, false, - i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE') + (additional ? ' (' + additional + ')' : '')); + store.controlsHelper( + dom, + $this, + false, + i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE') + (additional ? ' (' + additional + ')' : '') + ); } }); @@ -364,37 +376,30 @@ class PgpUserStore * @param {MessageModel} rainLoopMessage */ initMessageBodyControls(dom, rainLoopMessage) { - if (dom && !dom.hasClass('inited')) - { + if (dom && !dom.hasClass('inited')) { dom.addClass('inited'); - const - encrypted = dom.hasClass('encrypted'), + const encrypted = dom.hasClass('encrypted'), signed = dom.hasClass('signed'), recipients = rainLoopMessage ? rainLoopMessage.getEmails(['from', 'to', 'cc']) : []; let verControl = null; - if (encrypted || signed) - { + if (encrypted || signed) { const domText = dom.text(); dom.data('openpgp-original', domText); - if (encrypted) - { + if (encrypted) { verControl = $('') .attr('title', i18n('MESSAGE/PGP_ENCRYPTED_MESSAGE_DESC')) .on('click', PgpUserStore.domControlEncryptedClickHelper(this, dom, domText, recipients)); - } - else if (signed) - { + } else if (signed) { verControl = $('') .attr('title', i18n('MESSAGE/PGP_SIGNED_MESSAGE_DESC')) .on('click', PgpUserStore.domControlSignedClickHelper(this, dom, domText)); } - if (verControl) - { + if (verControl) { dom.before(verControl).before(''); } } diff --git a/dev/Stores/User/Quota.js b/dev/Stores/User/Quota.js index 700b46e20..21c6ffb62 100644 --- a/dev/Stores/User/Quota.js +++ b/dev/Stores/User/Quota.js @@ -1,23 +1,18 @@ - import window from 'window'; import ko from 'ko'; -import {Magics} from 'Common/Enums'; +import { Magics } from 'Common/Enums'; -class QuotaUserStore -{ +class QuotaUserStore { constructor() { this.quota = ko.observable(0); this.usage = ko.observable(0); this.percentage = ko.computed(() => { - - const - quota = this.quota(), + const quota = this.quota(), usage = this.usage(); return 0 < quota ? window.Math.ceil((usage / quota) * 100) : 0; - }); } diff --git a/dev/Stores/User/Settings.js b/dev/Stores/User/Settings.js index aa2e0a908..03f60ddd5 100644 --- a/dev/Stores/User/Settings.js +++ b/dev/Stores/User/Settings.js @@ -1,32 +1,32 @@ - import window from 'window'; import ko from 'ko'; -import {MESSAGES_PER_PAGE, MESSAGES_PER_PAGE_VALUES} from 'Common/Consts'; -import {Layout, EditorDefaultType, Magics} from 'Common/Enums'; -import {$html} from 'Common/Globals'; -import {pInt} from 'Common/Utils'; +import { MESSAGES_PER_PAGE, MESSAGES_PER_PAGE_VALUES } from 'Common/Consts'; +import { Layout, EditorDefaultType, Magics } from 'Common/Enums'; +import { $html } from 'Common/Globals'; +import { pInt } from 'Common/Utils'; import * as Events from 'Common/Events'; import * as Settings from 'Storage/Settings'; -class SettingsUserStore -{ +class SettingsUserStore { constructor() { - this.iAutoLogoutTimer = 0; - this.layout = ko.observable(Layout.SidePreview) - .extend({limitedList: [Layout.SidePreview, Layout.BottomPreview, Layout.NoPreview]}); + this.layout = ko + .observable(Layout.SidePreview) + .extend({ limitedList: [Layout.SidePreview, Layout.BottomPreview, Layout.NoPreview] }); - this.editorDefaultType = ko.observable(EditorDefaultType.Html) - .extend({limitedList: [ - EditorDefaultType.Html, EditorDefaultType.Plain, - EditorDefaultType.HtmlForced, EditorDefaultType.PlainForced - ]}); + this.editorDefaultType = ko.observable(EditorDefaultType.Html).extend({ + limitedList: [ + EditorDefaultType.Html, + EditorDefaultType.Plain, + EditorDefaultType.HtmlForced, + EditorDefaultType.PlainForced + ] + }); - this.messagesPerPage = ko.observable(MESSAGES_PER_PAGE) - .extend({limitedList: MESSAGES_PER_PAGE_VALUES}); + this.messagesPerPage = ko.observable(MESSAGES_PER_PAGE).extend({ limitedList: MESSAGES_PER_PAGE_VALUES }); this.showImages = ko.observable(false); this.useCheckboxesInList = ko.observable(true); @@ -68,8 +68,7 @@ class SettingsUserStore Events.sub('rl.auto-logout-refresh', () => { window.clearTimeout(this.iAutoLogoutTimer); - if (0 < this.autoLogout() && !Settings.settingsGet('AccountSignMe')) - { + if (0 < this.autoLogout() && !Settings.settingsGet('AccountSignMe')) { this.iAutoLogoutTimer = window.setTimeout(() => { Events.pub('rl.auto-logout'); }, this.autoLogout() * Magics.Time1m); diff --git a/dev/Stores/User/Template.js b/dev/Stores/User/Template.js index 3f556b387..d5791ae00 100644 --- a/dev/Stores/User/Template.js +++ b/dev/Stores/User/Template.js @@ -1,23 +1,20 @@ - import ko from 'ko'; import _ from '_'; // import Remote from 'Remote/User/Ajax'; -class TemplateUserStore -{ +class TemplateUserStore { constructor() { this.templates = ko.observableArray([]); - this.templates.loading = ko.observable(false).extend({throttle: 100}); + this.templates.loading = ko.observable(false).extend({ throttle: 100 }); - this.templatesNames = ko.observableArray([]).extend({throttle: 1000}); + this.templatesNames = ko.observableArray([]).extend({ throttle: 1000 }); this.templatesNames.skipFirst = true; this.subscribers(); } subscribers() { - this.templates.subscribe((list) => { this.templatesNames(_.compact(_.map(list, (item) => (item ? item.name : null)))); }); diff --git a/dev/View/Admin/Login.js b/dev/View/Admin/Login.js index 10a634266..98523c993 100644 --- a/dev/View/Admin/Login.js +++ b/dev/View/Admin/Login.js @@ -1,31 +1,27 @@ - import ko from 'ko'; import _ from '_'; -import { - trim, triggerAutocompleteInputChange -} from 'Common/Utils'; +import { trim, triggerAutocompleteInputChange } from 'Common/Utils'; -import {StorageResultType, Notification, Magics} from 'Common/Enums'; -import {getNotification} from 'Common/Translator'; -import {$win} from 'Common/Globals'; +import { StorageResultType, Notification, Magics } from 'Common/Enums'; +import { getNotification } from 'Common/Translator'; +import { $win } from 'Common/Globals'; import * as Settings from 'Storage/Settings'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -import {view, command, ViewType, routeOff} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, command, ViewType, routeOff } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/Admin/Login', type: ViewType.Center, templateID: 'AdminLogin' }) -class LoginAdminView extends AbstractViewNext -{ +class LoginAdminView extends AbstractViewNext { constructor() { super(); @@ -42,8 +38,8 @@ class LoginAdminView extends AbstractViewNext this.loginError = ko.observable(false); this.passwordError = ko.observable(false); - this.loginErrorAnimation = ko.observable(false).extend({'falseTimeout': 500}); - this.passwordErrorAnimation = ko.observable(false).extend({'falseTimeout': 500}); + this.loginErrorAnimation = ko.observable(false).extend({ 'falseTimeout': 500 }); + this.passwordErrorAnimation = ko.observable(false).extend({ 'falseTimeout': 500 }); this.loginFocus = ko.observable(false); @@ -67,7 +63,6 @@ class LoginAdminView extends AbstractViewNext @command((self) => !self.submitRequest()) submitCommand() { - triggerAutocompleteInputChange(); this.loginError(false); @@ -76,38 +71,33 @@ class LoginAdminView extends AbstractViewNext this.loginError('' === trim(this.login())); this.passwordError('' === trim(this.password())); - if (this.loginError() || this.passwordError()) - { + if (this.loginError() || this.passwordError()) { return false; } this.submitRequest(true); $win.trigger('rl.tooltips.diactivate'); - Remote.adminLogin((sResult, oData) => { + Remote.adminLogin( + (sResult, oData) => { + $win.trigger('rl.tooltips.diactivate'); + $win.trigger('rl.tooltips.activate'); - $win.trigger('rl.tooltips.diactivate'); - $win.trigger('rl.tooltips.activate'); - - if (StorageResultType.Success === sResult && oData && 'AdminLogin' === oData.Action) - { - if (oData.Result) - { - getApp().loginAndLogoutReload(true); - } - else if (oData.ErrorCode) - { + if (StorageResultType.Success === sResult && oData && 'AdminLogin' === oData.Action) { + if (oData.Result) { + getApp().loginAndLogoutReload(true); + } else if (oData.ErrorCode) { + this.submitRequest(false); + this.submitError(getNotification(oData.ErrorCode)); + } + } else { this.submitRequest(false); - this.submitError(getNotification(oData.ErrorCode)); + this.submitError(getNotification(Notification.UnknownError)); } - } - else - { - this.submitRequest(false); - this.submitError(getNotification(Notification.UnknownError)); - } - - }, this.login(), this.password()); + }, + this.login(), + this.password() + ); return true; } @@ -133,4 +123,4 @@ class LoginAdminView extends AbstractViewNext } } -export {LoginAdminView, LoginAdminView as default}; +export { LoginAdminView, LoginAdminView as default }; diff --git a/dev/View/Admin/Settings/Menu.js b/dev/View/Admin/Settings/Menu.js index ebd09fb0e..b6ebc91a2 100644 --- a/dev/View/Admin/Settings/Menu.js +++ b/dev/View/Admin/Settings/Menu.js @@ -1,25 +1,22 @@ - import $ from '$'; import key from 'key'; -import {leftPanelDisabled} from 'Common/Globals'; -import {KeyState} from 'Common/Enums'; +import { leftPanelDisabled } from 'Common/Globals'; +import { KeyState } from 'Common/Enums'; -import {view, ViewType, settingsMenuKeysHandler} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType, settingsMenuKeysHandler } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/Admin/Settings/Menu', type: ViewType.Left, templateID: 'AdminMenu' }) -class MenuSettingsAdminView extends AbstractViewNext -{ +class MenuSettingsAdminView extends AbstractViewNext { /** * @param {?} screen */ constructor(screen) { - super(); this.leftPanelDisabled = leftPanelDisabled; @@ -36,4 +33,4 @@ class MenuSettingsAdminView extends AbstractViewNext } } -export {MenuSettingsAdminView, MenuSettingsAdminView as default}; +export { MenuSettingsAdminView, MenuSettingsAdminView as default }; diff --git a/dev/View/Admin/Settings/Pane.js b/dev/View/Admin/Settings/Pane.js index 21e295131..2c8b853d8 100644 --- a/dev/View/Admin/Settings/Pane.js +++ b/dev/View/Admin/Settings/Pane.js @@ -1,4 +1,3 @@ - import ko from 'ko'; import * as Settings from 'Storage/Settings'; @@ -9,18 +8,17 @@ import DomainStore from 'Stores/Admin/Domain'; import PluginStore from 'Stores/Admin/Plugin'; import PackageStore from 'Stores/Admin/Package'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -import {view, ViewType} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/Admin/Settings/Pane', type: ViewType.Right, templateID: 'AdminPane' }) -class PaneSettingsAdminView extends AbstractViewNext -{ +class PaneSettingsAdminView extends AbstractViewNext { constructor() { super(); @@ -31,16 +29,18 @@ class PaneSettingsAdminView extends AbstractViewNext this.community = RL_COMMUNITY; this.adminManLoading = ko.computed( - () => '000' !== [ - DomainStore.domains.loading() ? '1' : '0', - PluginStore.plugins.loading() ? '1' : '0', - PackageStore.packages.loading() ? '1' : '0' - ].join('') + () => + '000' !== + [ + DomainStore.domains.loading() ? '1' : '0', + PluginStore.plugins.loading() ? '1' : '0', + PackageStore.packages.loading() ? '1' : '0' + ].join('') ); - this.adminManLoadingVisibility = ko.computed( - () => (this.adminManLoading() ? 'visible' : 'hidden') - ).extend({rateLimit: 300}); + this.adminManLoadingVisibility = ko + .computed(() => (this.adminManLoading() ? 'visible' : 'hidden')) + .extend({ rateLimit: 300 }); } logoutClick() { @@ -50,4 +50,4 @@ class PaneSettingsAdminView extends AbstractViewNext } } -export {PaneSettingsAdminView, PaneSettingsAdminView as default}; +export { PaneSettingsAdminView, PaneSettingsAdminView as default }; diff --git a/dev/View/Popup/Account.js b/dev/View/Popup/Account.js index 9dc4dc16a..a48eedc40 100644 --- a/dev/View/Popup/Account.js +++ b/dev/View/Popup/Account.js @@ -1,23 +1,21 @@ - import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {trim} from 'Common/Utils'; -import {getNotification} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { trim } from 'Common/Utils'; +import { getNotification } from 'Common/Translator'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Account', templateID: 'PopupsAccount' }) -class AccountPopupView extends AbstractViewNext -{ +class AccountPopupView extends AbstractViewNext { constructor() { super(); @@ -46,45 +44,40 @@ class AccountPopupView extends AbstractViewNext @command((self) => !self.submitRequest()) addAccountCommand() { - this.emailError('' === trim(this.email())); this.passwordError('' === trim(this.password())); - if (this.emailError() || this.passwordError()) - { + if (this.emailError() || this.passwordError()) { return false; } this.submitRequest(true); - Remote.accountSetup((result, data) => { + Remote.accountSetup( + (result, data) => { + this.submitRequest(false); + if (StorageResultType.Success === result && data) { + if (data.Result) { + getApp().accountsAndIdentities(); + this.cancelCommand(); + } else { + this.submitError( + data.ErrorCode ? getNotification(data.ErrorCode) : getNotification(Notification.UnknownError) + ); - this.submitRequest(false); - if (StorageResultType.Success === result && data) - { - if (data.Result) - { - getApp().accountsAndIdentities(); - this.cancelCommand(); - } - else - { - this.submitError(data.ErrorCode ? getNotification(data.ErrorCode) : - getNotification(Notification.UnknownError)); - - if (data.ErrorMessageAdditional) - { - this.submitErrorAdditional(data.ErrorMessageAdditional); + if (data.ErrorMessageAdditional) { + this.submitErrorAdditional(data.ErrorMessageAdditional); + } } + } else { + this.submitError(getNotification(Notification.UnknownError)); + this.submitErrorAdditional(''); } - } - else - { - this.submitError(getNotification(Notification.UnknownError)); - this.submitErrorAdditional(''); - } - - }, this.email(), this.password(), this.isNew()); + }, + this.email(), + this.password(), + this.isNew() + ); return true; } @@ -105,8 +98,7 @@ class AccountPopupView extends AbstractViewNext onShow(account) { this.clearPopup(); - if (account && account.canBeEdit()) - { + if (account && account.canBeEdit()) { this.isNew(false); this.email(account.email); } @@ -117,4 +109,4 @@ class AccountPopupView extends AbstractViewNext } } -export {AccountPopupView, AccountPopupView as default}; +export { AccountPopupView, AccountPopupView as default }; diff --git a/dev/View/Popup/Activate.js b/dev/View/Popup/Activate.js index 08cfe4332..fbaee33ea 100644 --- a/dev/View/Popup/Activate.js +++ b/dev/View/Popup/Activate.js @@ -1,25 +1,23 @@ - import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {trim, isUnd} from 'Common/Utils'; -import {RAINLOOP_TRIAL_KEY} from 'Common/Consts'; -import {i18n, getNotification} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { trim, isUnd } from 'Common/Utils'; +import { RAINLOOP_TRIAL_KEY } from 'Common/Consts'; +import { i18n, getNotification } from 'Common/Translator'; import * as Settings from 'Storage/Settings'; import Remote from 'Remote/Admin/Ajax'; import LicenseStore from 'Stores/Admin/License'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Activate', templateID: 'PopupsActivate' }) -class ActivatePopupView extends AbstractViewNext -{ +class ActivatePopupView extends AbstractViewNext { constructor() { super(); @@ -34,7 +32,7 @@ class ActivatePopupView extends AbstractViewNext this.activateText = ko.observable(''); this.activateText.isError = ko.observable(false); - this.htmlDescription = ko.computed(() => i18n('POPUPS_ACTIVATE/HTML_DESC', {'DOMAIN': this.domain()})); + this.htmlDescription = ko.computed(() => i18n('POPUPS_ACTIVATE/HTML_DESC', { 'DOMAIN': this.domain() })); this.key.subscribe(() => { this.activateText(''); @@ -42,54 +40,45 @@ class ActivatePopupView extends AbstractViewNext }); this.activationSuccessed.subscribe((value) => { - if (value) - { + if (value) { this.licenseTrigger(!this.licenseTrigger()); } }); } - @command((self) => !self.activateProcess() && '' !== self.domain() && '' !== self.key() && !self.activationSuccessed()) + @command( + (self) => !self.activateProcess() && '' !== self.domain() && '' !== self.key() && !self.activationSuccessed() + ) activateCommand() { - this.activateProcess(true); - if (this.validateSubscriptionKey()) - { - Remote.licensingActivate((sResult, oData) => { - - this.activateProcess(false); - if (StorageResultType.Success === sResult && oData.Result) - { - if (true === oData.Result) - { - this.activationSuccessed(true); - this.activateText(i18n('POPUPS_ACTIVATE/SUBS_KEY_ACTIVATED')); - this.activateText.isError(false); - } - else - { - this.activateText(oData.Result); + if (this.validateSubscriptionKey()) { + Remote.licensingActivate( + (sResult, oData) => { + this.activateProcess(false); + if (StorageResultType.Success === sResult && oData.Result) { + if (true === oData.Result) { + this.activationSuccessed(true); + this.activateText(i18n('POPUPS_ACTIVATE/SUBS_KEY_ACTIVATED')); + this.activateText.isError(false); + } else { + this.activateText(oData.Result); + this.activateText.isError(true); + this.key.focus(true); + } + } else if (oData.ErrorCode) { + this.activateText(getNotification(oData.ErrorCode)); + this.activateText.isError(true); + this.key.focus(true); + } else { + this.activateText(getNotification(Notification.UnknownError)); this.activateText.isError(true); this.key.focus(true); } - } - else if (oData.ErrorCode) - { - this.activateText(getNotification(oData.ErrorCode)); - this.activateText.isError(true); - this.key.focus(true); - } - else - { - this.activateText(getNotification(Notification.UnknownError)); - this.activateText.isError(true); - this.key.focus(true); - } - - }, this.domain(), this.key().replace(/[^A-Z0-9\-]/gi, '')); - } - else - { + }, + this.domain(), + this.key().replace(/[^A-Z0-9-]/gi, '') + ); + } else { this.activateProcess(false); this.activateText(i18n('POPUPS_ACTIVATE/ERROR_INVALID_SUBS_KEY')); this.activateText.isError(true); @@ -99,8 +88,7 @@ class ActivatePopupView extends AbstractViewNext onShow(isTrial) { this.domain(Settings.settingsGet('AdminDomain')); - if (!this.activateProcess()) - { + if (!this.activateProcess()) { isTrial = isUnd(isTrial) ? false : !!isTrial; this.key(isTrial ? RAINLOOP_TRIAL_KEY : ''); @@ -111,8 +99,7 @@ class ActivatePopupView extends AbstractViewNext } onShowWithDelay() { - if (!this.activateProcess()) - { + if (!this.activateProcess()) { this.key.focus(true); } } @@ -122,8 +109,12 @@ class ActivatePopupView extends AbstractViewNext */ validateSubscriptionKey() { const value = this.key(); - return '' === value || RAINLOOP_TRIAL_KEY === value || !!(/^RL[\d]+-[A-Z0-9\-]+Z$/).test(trim(value).replace(/[^A-Z0-9\-]/gi, '')); + return ( + '' === value || + RAINLOOP_TRIAL_KEY === value || + !!/^RL[\d]+-[A-Z0-9-]+Z$/.test(trim(value).replace(/[^A-Z0-9-]/gi, '')) + ); } } -export {ActivatePopupView, ActivatePopupView as default}; +export { ActivatePopupView, ActivatePopupView as default }; diff --git a/dev/View/Popup/AddOpenPgpKey.js b/dev/View/Popup/AddOpenPgpKey.js index 3bd094ac1..074302a89 100644 --- a/dev/View/Popup/AddOpenPgpKey.js +++ b/dev/View/Popup/AddOpenPgpKey.js @@ -1,20 +1,18 @@ - import ko from 'ko'; -import {trim, delegateRun, log} from 'Common/Utils'; +import { trim, delegateRun, log } from 'Common/Utils'; import PgpStore from 'Stores/User/Pgp'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/AddOpenPgpKey', templateID: 'PopupsAddOpenPgpKey' }) -class AddOpenPgpKeyPopupView extends AbstractViewNext -{ +class AddOpenPgpKeyPopupView extends AbstractViewNext { constructor() { super(); @@ -31,50 +29,39 @@ class AddOpenPgpKeyPopupView extends AbstractViewNext @command() addOpenPgpKeyCommand() { - - const - reg = /[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi, + // eslint-disable-next-line max-len + const reg = /[-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[-]{3,6}[\s\S]+?[-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[-]{3,6}/gi, openpgpKeyring = PgpStore.openpgpKeyring; let keyTrimmed = trim(this.key()); - if ((/[\n]/).test(keyTrimmed)) - { + if (/[\n]/.test(keyTrimmed)) { keyTrimmed = keyTrimmed.replace(/[\r]+/g, '').replace(/[\n]{2,}/g, '\n\n'); } this.key.error('' === keyTrimmed); this.key.errorMessage(''); - if (!openpgpKeyring || this.key.error()) - { + if (!openpgpKeyring || this.key.error()) { return false; } - let - match = null, + let match = null, count = 30, done = false; - do - { + do { match = reg.exec(keyTrimmed); - if (match && 0 < count) - { - if (match[0] && match[1] && match[2] && match[1] === match[2]) - { + if (match && 0 < count) { + if (match[0] && match[1] && match[2] && match[1] === match[2]) { let err = null; - if ('PRIVATE' === match[1]) - { + if ('PRIVATE' === match[1]) { err = openpgpKeyring.privateKeys.importKey(match[0]); - } - else if ('PUBLIC' === match[1]) - { + } else if ('PUBLIC' === match[1]) { err = openpgpKeyring.publicKeys.importKey(match[0]); } - if (err) - { + if (err) { this.key.error(true); this.key.errorMessage(err && err[0] ? '' + err[0] : ''); log(err); @@ -83,20 +70,16 @@ class AddOpenPgpKeyPopupView extends AbstractViewNext count -= 1; done = false; - } - else - { + } else { done = true; } - } - while (!done); + } while (!done); openpgpKeyring.store(); getApp().reloadOpenPgpKeys(); - if (this.key.error()) - { + if (this.key.error()) { return false; } @@ -119,4 +102,4 @@ class AddOpenPgpKeyPopupView extends AbstractViewNext } } -export {AddOpenPgpKeyPopupView, AddOpenPgpKeyPopupView as default}; +export { AddOpenPgpKeyPopupView, AddOpenPgpKeyPopupView as default }; diff --git a/dev/View/Popup/AdvancedSearch.js b/dev/View/Popup/AdvancedSearch.js index 0437a1784..08aed0eba 100644 --- a/dev/View/Popup/AdvancedSearch.js +++ b/dev/View/Popup/AdvancedSearch.js @@ -1,22 +1,20 @@ - import _ from '_'; import ko from 'ko'; -import {trim} from 'Common/Utils'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; -import {searchSubtractFormatDateHelper} from 'Common/Momentor'; +import { trim } from 'Common/Utils'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; +import { searchSubtractFormatDateHelper } from 'Common/Momentor'; import MessageStore from 'Stores/User/Message'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/AdvancedSearch', templateID: 'PopupsAdvancedSearch' }) -class AdvancedSearchPopupView extends AbstractViewNext -{ +class AdvancedSearchPopupView extends AbstractViewNext { constructor() { super(); @@ -35,13 +33,13 @@ class AdvancedSearchPopupView extends AbstractViewNext this.selectedDates = ko.computed(() => { translatorTrigger(); return [ - {id: -1, name: i18n('SEARCH/LABEL_ADV_DATE_ALL')}, - {id: 3, name: i18n('SEARCH/LABEL_ADV_DATE_3_DAYS')}, - {id: 7, name: i18n('SEARCH/LABEL_ADV_DATE_7_DAYS')}, - {id: 30, name: i18n('SEARCH/LABEL_ADV_DATE_MONTH')}, - {id: 90, name: i18n('SEARCH/LABEL_ADV_DATE_3_MONTHS')}, - {id: 180, name: i18n('SEARCH/LABEL_ADV_DATE_6_MONTHS')}, - {id: 365, name: i18n('SEARCH/LABEL_ADV_DATE_YEAR')} + { id: -1, name: i18n('SEARCH/LABEL_ADV_DATE_ALL') }, + { id: 3, name: i18n('SEARCH/LABEL_ADV_DATE_3_DAYS') }, + { id: 7, name: i18n('SEARCH/LABEL_ADV_DATE_7_DAYS') }, + { id: 30, name: i18n('SEARCH/LABEL_ADV_DATE_MONTH') }, + { id: 90, name: i18n('SEARCH/LABEL_ADV_DATE_3_MONTHS') }, + { id: 180, name: i18n('SEARCH/LABEL_ADV_DATE_6_MONTHS') }, + { id: 365, name: i18n('SEARCH/LABEL_ADV_DATE_YEAR') } ]; }); } @@ -49,8 +47,7 @@ class AdvancedSearchPopupView extends AbstractViewNext @command() searchCommand() { const search = this.buildSearchString(); - if ('' !== search) - { + if ('' !== search) { MessageStore.mainMessageListSearch(search); } @@ -60,14 +57,13 @@ class AdvancedSearchPopupView extends AbstractViewNext parseSearchStringValue(search) { const parts = (search || '').split(/[\s]+/g); _.each(parts, (part) => { - switch (part) - { + switch (part) { case 'has:attachment': this.hasAttachment(true); break; case 'is:unseen,flagged': this.starred(true); - /* falls through */ + /* falls through */ case 'is:unseen': this.unseen(true); break; @@ -77,16 +73,14 @@ class AdvancedSearchPopupView extends AbstractViewNext } buildSearchStringValue(value) { - if (-1 < value.indexOf(' ')) - { + if (-1 < value.indexOf(' ')) { value = '"' + value + '"'; } return value; } buildSearchString() { - const - result = [], + const result = [], from_ = trim(this.from()), to = trim(this.to()), subject = trim(this.subject()), @@ -94,53 +88,43 @@ class AdvancedSearchPopupView extends AbstractViewNext isPart = [], hasPart = []; - if (from_ && '' !== from_) - { + if (from_ && '' !== from_) { result.push('from:' + this.buildSearchStringValue(from_)); } - if (to && '' !== to) - { + if (to && '' !== to) { result.push('to:' + this.buildSearchStringValue(to)); } - if (subject && '' !== subject) - { + if (subject && '' !== subject) { result.push('subject:' + this.buildSearchStringValue(subject)); } - if (this.hasAttachment()) - { + if (this.hasAttachment()) { hasPart.push('attachment'); } - if (this.unseen()) - { + if (this.unseen()) { isPart.push('unseen'); } - if (this.starred()) - { + if (this.starred()) { isPart.push('flagged'); } - if (0 < hasPart.length) - { + if (0 < hasPart.length) { result.push('has:' + hasPart.join(',')); } - if (0 < isPart.length) - { + if (0 < isPart.length) { result.push('is:' + isPart.join(',')); } - if (-1 < this.selectedDateValue()) - { + if (-1 < this.selectedDateValue()) { result.push('date:' + searchSubtractFormatDateHelper(this.selectedDateValue()) + '/'); } - if (text && '' !== text) - { + if (text && '' !== text) { result.push('text:' + this.buildSearchStringValue(text)); } @@ -171,4 +155,4 @@ class AdvancedSearchPopupView extends AbstractViewNext } } -export {AdvancedSearchPopupView, AdvancedSearchPopupView as default}; +export { AdvancedSearchPopupView, AdvancedSearchPopupView as default }; diff --git a/dev/View/Popup/Ask.js b/dev/View/Popup/Ask.js index 04818a3fb..243598690 100644 --- a/dev/View/Popup/Ask.js +++ b/dev/View/Popup/Ask.js @@ -1,20 +1,18 @@ - import ko from 'ko'; import key from 'key'; -import {KeyState} from 'Common/Enums'; -import {isFunc} from 'Common/Utils'; -import {i18n} from 'Common/Translator'; +import { KeyState } from 'Common/Enums'; +import { isFunc } from 'Common/Utils'; +import { i18n } from 'Common/Translator'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Ask', templateID: 'PopupsAsk' }) -class AskPopupView extends AbstractViewNext -{ +class AskPopupView extends AbstractViewNext { constructor() { super(); @@ -48,8 +46,7 @@ class AskPopupView extends AbstractViewNext yesClick() { this.cancelCommand(); - if (isFunc(this.fYesAction)) - { + if (isFunc(this.fYesAction)) { this.fYesAction.call(null); } } @@ -57,8 +54,7 @@ class AskPopupView extends AbstractViewNext noClick() { this.cancelCommand(); - if (isFunc(this.fNoAction)) - { + if (isFunc(this.fNoAction)) { this.fNoAction.call(null); } } @@ -73,7 +69,6 @@ class AskPopupView extends AbstractViewNext * @returns {void} */ onShow(askDesc, fYesFunc = null, fNoFunc = null, yesButton = '', noButton = '', isFocusYesOnShow = true) { - this.clearPopup(); this.fYesAction = fYesFunc || null; @@ -81,13 +76,11 @@ class AskPopupView extends AbstractViewNext this.askDesc(askDesc || ''); - if (yesButton) - { + if (yesButton) { this.yesButton(yesButton); } - if (noButton) - { + if (noButton) { this.noButton(noButton); } @@ -95,20 +88,16 @@ class AskPopupView extends AbstractViewNext } onShowWithDelay() { - if (this.bFocusYesOnShow) - { + if (this.bFocusYesOnShow) { this.yesFocus(true); } } onBuild() { key('tab, shift+tab, right, left', KeyState.PopupAsk, () => { - if (this.yesFocus()) - { + if (this.yesFocus()) { this.noFocus(true); - } - else - { + } else { this.yesFocus(true); } return false; @@ -121,4 +110,4 @@ class AskPopupView extends AbstractViewNext } } -export {AskPopupView, AskPopupView as default}; +export { AskPopupView, AskPopupView as default }; diff --git a/dev/View/Popup/Compose.js b/dev/View/Popup/Compose.js index 1ff83d327..a2f3fba5a 100644 --- a/dev/View/Popup/Compose.js +++ b/dev/View/Popup/Compose.js @@ -1,4 +1,3 @@ - import window from 'window'; import _ from '_'; import $ from '$'; @@ -7,26 +6,41 @@ import key from 'key'; import Jua from 'Jua'; import { - Capa, Magics, KeyState, ComposeType, StorageResultType, - EditorDefaultType, Notification, SetSystemFoldersNotification, + Capa, + Magics, + KeyState, + ComposeType, + StorageResultType, + EditorDefaultType, + Notification, + SetSystemFoldersNotification, UploadErrorCode } from 'Common/Enums'; import { - trim, isArray, isNormal, delegateRun, - isNonEmptyArray, clearBqSwitcher, replySubjectAdd, - encodeHtml, noopFalse, inFocus, delegateRunOnDestroy, - pInt, isUnd + trim, + isArray, + isNormal, + delegateRun, + isNonEmptyArray, + clearBqSwitcher, + replySubjectAdd, + encodeHtml, + noopFalse, + inFocus, + delegateRunOnDestroy, + pInt, + isUnd } from 'Common/Utils'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {bXMLHttpRequestSupported, bMobileDevice} from 'Common/Globals'; -import {upload} from 'Common/Links'; -import {i18n, getNotification, getUploadErrorDescByCode} from 'Common/Translator'; -import {format as momentorFormat} from 'Common/Momentor'; -import {getMessageFlagsFromCache, setMessageFlagsToCache, setFolderHash} from 'Common/Cache'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { bXMLHttpRequestSupported, bMobileDevice } from 'Common/Globals'; +import { upload } from 'Common/Links'; +import { i18n, getNotification, getUploadErrorDescByCode } from 'Common/Translator'; +import { format as momentorFormat } from 'Common/Momentor'; +import { getMessageFlagsFromCache, setMessageFlagsToCache, setFolderHash } from 'Common/Cache'; -import {HtmlEditor} from 'Common/HtmlEditor'; +import { HtmlEditor } from 'Common/HtmlEditor'; import AppStore from 'Stores/User/App'; import SettingsStore from 'Stores/User/Settings'; @@ -42,42 +56,38 @@ import Remote from 'Remote/User/Ajax'; import * as Settings from 'Storage/Settings'; import * as Events from 'Common/Events'; -import {ComposeAttachmentModel} from 'Model/ComposeAttachment'; +import { ComposeAttachmentModel } from 'Model/ComposeAttachment'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command, isPopupVisible, showScreenPopup, hideScreenPopup, routeOn, routeOff} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command, isPopupVisible, showScreenPopup, hideScreenPopup, routeOn, routeOff } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Compose', templateID: 'PopupsCompose' }) -class ComposePopupView extends AbstractViewNext -{ +class ComposePopupView extends AbstractViewNext { constructor() { super(); - const - fEmailOutInHelper = (context, identity, name, isIn) => { - if (identity && context && identity[name]() && (isIn ? true : context[name]())) - { - const identityEmail = identity[name](); - let list = trim(context[name]()).split(/[,]/); + const fEmailOutInHelper = (context, identity, name, isIn) => { + if (identity && context && identity[name]() && (isIn ? true : context[name]())) { + const identityEmail = identity[name](); + let list = trim(context[name]()).split(/[,]/); - list = _.filter(list, (email) => { - email = trim(email); - return email && trim(identityEmail) !== email; - }); + list = _.filter(list, (email) => { + email = trim(email); + return email && trim(identityEmail) !== email; + }); - if (isIn) - { - list.push(identityEmail); - } - - context[name](list.join(',')); + if (isIn) { + list.push(identityEmail); } - }; + + context[name](list.join(',')); + } + }; this.oLastMessage = null; this.oEditor = null; @@ -113,8 +123,7 @@ class ComposePopupView extends AbstractViewNext // this.to.subscribe((v) => console.log(v)); ko.computed(() => { - switch (true) - { + switch (true) { case this.to.focused(): this.sLastFocusedField = 'to'; break; @@ -126,7 +135,7 @@ class ComposePopupView extends AbstractViewNext break; // no default } - }).extend({notify: 'always'}); + }).extend({ notify: 'always' }); this.subject = ko.observable(''); this.subject.focused = ko.observable(false); @@ -141,51 +150,43 @@ class ComposePopupView extends AbstractViewNext this.sendSuccessButSaveError = ko.observable(false); this.savedError = ko.observable(false); - this.sendButtonSuccess = ko.computed( - () => !this.sendError() && !this.sendSuccessButSaveError() - ); + this.sendButtonSuccess = ko.computed(() => !this.sendError() && !this.sendSuccessButSaveError()); this.sendErrorDesc = ko.observable(''); this.savedErrorDesc = ko.observable(''); this.sendError.subscribe((value) => { - if (!value) - { + if (!value) { this.sendErrorDesc(''); } }); this.savedError.subscribe((value) => { - if (!value) - { + if (!value) { this.savedErrorDesc(''); } }); this.sendSuccessButSaveError.subscribe((value) => { - if (!value) - { + if (!value) { this.savedErrorDesc(''); } }); this.savedTime = ko.observable(0); - this.savedTimeText = ko.computed( - () => (0 < this.savedTime() ? i18n('COMPOSE/SAVED_TIME', {'TIME': momentorFormat(this.savedTime() - 1, 'LT')}) : '') + this.savedTimeText = ko.computed(() => + 0 < this.savedTime() ? i18n('COMPOSE/SAVED_TIME', { 'TIME': momentorFormat(this.savedTime() - 1, 'LT') }) : '' ); this.emptyToError = ko.observable(false); - this.emptyToErrorTooltip = ko.computed( - () => (this.emptyToError() ? i18n('COMPOSE/EMPTY_TO_ERROR_DESC') : '') - ); + this.emptyToErrorTooltip = ko.computed(() => (this.emptyToError() ? i18n('COMPOSE/EMPTY_TO_ERROR_DESC') : '')); this.attachmentsInProcessError = ko.observable(false); this.attachmentsInErrorError = ko.observable(false); this.attachmentsErrorTooltip = ko.computed(() => { let result = ''; - switch (true) - { + switch (true) { case this.attachmentsInProcessError(): result = i18n('COMPOSE/ATTACHMENTS_UPLOAD_ERROR_DESC'); break; @@ -202,22 +203,19 @@ class ComposePopupView extends AbstractViewNext this.showReplyTo = ko.observable(false); this.cc.subscribe((value) => { - if (false === this.showCc() && 0 < value.length) - { + if (false === this.showCc() && 0 < value.length) { this.showCc(true); } }); this.bcc.subscribe((value) => { - if (false === this.showBcc() && 0 < value.length) - { + if (false === this.showBcc() && 0 < value.length) { this.showBcc(true); } }); this.replyTo.subscribe((value) => { - if (false === this.showReplyTo() && 0 < value.length) - { + if (false === this.showReplyTo() && 0 < value.length) { this.showReplyTo(true); } }); @@ -243,8 +241,7 @@ class ComposePopupView extends AbstractViewNext this.attachmentsPlace.subscribe(this.resizerTrigger); this.attachmentsInErrorCount.subscribe((value) => { - if (0 === value) - { + if (0 === value) { this.attachmentsInErrorError(false); } }); @@ -252,36 +249,37 @@ class ComposePopupView extends AbstractViewNext this.composeUploaderButton = ko.observable(null); this.composeUploaderDropPlace = ko.observable(null); this.dragAndDropEnabled = ko.observable(false); - this.dragAndDropOver = ko.observable(false).extend({throttle: 1}); - this.dragAndDropVisible = ko.observable(false).extend({throttle: 1}); + this.dragAndDropOver = ko.observable(false).extend({ throttle: 1 }); + this.dragAndDropVisible = ko.observable(false).extend({ throttle: 1 }); this.attacheMultipleAllowed = ko.observable(false); this.addAttachmentEnabled = ko.observable(false); this.composeEditorArea = ko.observable(null); this.identities = IdentityStore.identities; - this.identitiesOptions = ko.computed( - () => _.map(IdentityStore.identities(), (item) => ({ + this.identitiesOptions = ko.computed(() => + _.map(IdentityStore.identities(), (item) => ({ 'item': item, 'optValue': item.id(), 'optText': item.formattedName() })) ); - this.currentIdentity = ko.observable( - this.identities()[0] ? this.identities()[0] : null); + this.currentIdentity = ko.observable(this.identities()[0] ? this.identities()[0] : null); - this.currentIdentity.extend({toggleSubscribe: [ - this, - (identity) => { - fEmailOutInHelper(this, identity, 'bcc'); - fEmailOutInHelper(this, identity, 'replyTo'); - }, - (identity) => { - fEmailOutInHelper(this, identity, 'bcc', true); - fEmailOutInHelper(this, identity, 'replyTo', true); - } - ]}); + this.currentIdentity.extend({ + toggleSubscribe: [ + this, + (identity) => { + fEmailOutInHelper(this, identity, 'bcc'); + fEmailOutInHelper(this, identity, 'replyTo'); + }, + (identity) => { + fEmailOutInHelper(this, identity, 'bcc', true); + fEmailOutInHelper(this, identity, 'replyTo', true); + } + ] + }); this.currentIdentityView = ko.computed(() => { const item = this.currentIdentity(); @@ -289,20 +287,18 @@ class ComposePopupView extends AbstractViewNext }); this.to.subscribe((value) => { - if (this.emptyToError() && 0 < value.length) - { + if (this.emptyToError() && 0 < value.length) { this.emptyToError(false); } }); this.attachmentsInProcess.subscribe((value) => { - if (this.attachmentsInProcessError() && isArray(value) && 0 === value.length) - { + if (this.attachmentsInProcessError() && isArray(value) && 0 === value.length) { this.attachmentsInProcessError(false); } }); - this.resizer = ko.observable(false).extend({throttle: 50}); + this.resizer = ko.observable(false).extend({ throttle: 50 }); this.resizer.subscribe(() => { if (this.oEditor) { @@ -316,9 +312,15 @@ class ComposePopupView extends AbstractViewNext this.saveMessageResponse = _.bind(this.saveMessageResponse, this); Events.sub('interval.2m', () => { - if (this.modalVisibility() && !FolderStore.draftFolderNotEnabled() && SettingsStore.allowDraftAutosave() && - !this.isEmptyForm(false) && !this.saving() && !this.sending() && !this.savedError()) - { + if ( + this.modalVisibility() && + !FolderStore.draftFolderNotEnabled() && + SettingsStore.allowDraftAutosave() && + !this.isEmptyForm(false) && + !this.saving() && + !this.sending() && + !this.savedError() + ) { this.saveCommand(); } }); @@ -330,9 +332,13 @@ class ComposePopupView extends AbstractViewNext this.dropboxEnabled = SocialStore.dropbox.enabled; this.dropboxApiKey = SocialStore.dropbox.apiKey; - this.driveEnabled = ko.observable(bXMLHttpRequestSupported && - !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialDrive') && - !!Settings.settingsGet('GoogleClientID') && !!Settings.settingsGet('GoogleApiKey')); + this.driveEnabled = ko.observable( + bXMLHttpRequestSupported && + !!Settings.settingsGet('AllowGoogleSocial') && + !!Settings.settingsGet('AllowGoogleSocialDrive') && + !!Settings.settingsGet('GoogleClientID') && + !!Settings.settingsGet('GoogleApiKey') + ); this.driveVisible = ko.observable(false); @@ -353,69 +359,55 @@ class ComposePopupView extends AbstractViewNext @command((self) => self.canBeSentOrSaved()) sendCommand() { - - const - sTo = trim(this.to()), + const sTo = trim(this.to()), sCc = trim(this.cc()), sBcc = trim(this.bcc()); - let - sSentFolder = FolderStore.sentFolder(); + let sSentFolder = FolderStore.sentFolder(); this.attachmentsInProcessError(false); this.attachmentsInErrorError(false); this.emptyToError(false); - if (0 < this.attachmentsInProcess().length) - { + if (0 < this.attachmentsInProcess().length) { this.attachmentsInProcessError(true); this.attachmentsPlace(true); - } - else if (0 < this.attachmentsInError().length) - { + } else if (0 < this.attachmentsInError().length) { this.attachmentsInErrorError(true); this.attachmentsPlace(true); } - if ('' === sTo && '' === sCc && '' === sBcc) - { + if ('' === sTo && '' === sCc && '' === sBcc) { this.emptyToError(true); } - if (!this.emptyToError() && !this.attachmentsInErrorError() && !this.attachmentsInProcessError()) - { - if (SettingsStore.replySameFolder()) - { - if (isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length && isNormal(this.aDraftInfo[2]) && 0 < this.aDraftInfo[2].length) - { + if (!this.emptyToError() && !this.attachmentsInErrorError() && !this.attachmentsInProcessError()) { + if (SettingsStore.replySameFolder()) { + if ( + isArray(this.aDraftInfo) && + 3 === this.aDraftInfo.length && + isNormal(this.aDraftInfo[2]) && + 0 < this.aDraftInfo[2].length + ) { sSentFolder = this.aDraftInfo[2]; } } - if (!this.allowFolders) - { + if (!this.allowFolders) { sSentFolder = UNUSED_OPTION_VALUE; } - if ('' === sSentFolder) - { + if ('' === sSentFolder) { showScreenPopup(require('View/Popup/FolderSystem'), [SetSystemFoldersNotification.Sent]); - } - else - { + } else { this.sendError(false); this.sending(true); - if (isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length) - { + if (isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length) { const flagsCache = getMessageFlagsFromCache(this.aDraftInfo[2], this.aDraftInfo[1]); - if (flagsCache) - { - if ('forward' === this.aDraftInfo[0]) - { + if (flagsCache) { + if ('forward' === this.aDraftInfo[0]) { flagsCache[3] = true; - } - else - { + } else { flagsCache[2] = true; } @@ -457,18 +449,13 @@ class ComposePopupView extends AbstractViewNext @command((self) => self.canBeSentOrSaved()) saveCommand() { - - if (!this.allowFolders) - { + if (!this.allowFolders) { return false; } - if (FolderStore.draftFolderNotEnabled()) - { + if (FolderStore.draftFolderNotEnabled()) { showScreenPopup(require('View/Popup/FolderSystem'), [SetSystemFoldersNotification.Draft]); - } - else - { + } else { this.savedError(false); this.saving(true); @@ -503,26 +490,30 @@ class ComposePopupView extends AbstractViewNext @command((self) => self.isDraftFolderMessage()) deleteCommand() { const PopupsAskViewModel = require('View/Popup/Ask'); - if (!isPopupVisible(PopupsAskViewModel) && this.modalVisibility()) - { - showScreenPopup(PopupsAskViewModel, [i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => { - if (this.modalVisibility()) - { - getApp().deleteMessagesFromFolderWithoutCheck(this.draftFolder(), [this.draftUid()]); - hideScreenPopup(ComposePopupView); + if (!isPopupVisible(PopupsAskViewModel) && this.modalVisibility()) { + showScreenPopup(PopupsAskViewModel, [ + i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), + () => { + if (this.modalVisibility()) { + getApp().deleteMessagesFromFolderWithoutCheck(this.draftFolder(), [this.draftUid()]); + hideScreenPopup(ComposePopupView); + } } - }]); + ]); } } @command((self) => self.canBeSentOrSaved()) skipCommand() { - this.bSkipNextHide = true; - if (this.modalVisibility() && !this.saving() && !this.sending() && - !FolderStore.draftFolderNotEnabled() && SettingsStore.allowDraftAutosave()) - { + if ( + this.modalVisibility() && + !this.saving() && + !this.sending() && + !FolderStore.draftFolderNotEnabled() && + SettingsStore.allowDraftAutosave() + ) { this.saveCommand(); } @@ -531,8 +522,7 @@ class ComposePopupView extends AbstractViewNext @command((self) => self.allowContacts) contactsCommand() { - if (this.allowContacts) - { + if (this.allowContacts) { this.skipCommand(); _.delay(() => { showScreenPopup(require('View/Popup/Contacts'), [true, this.sLastFocusedField]); @@ -542,12 +532,10 @@ class ComposePopupView extends AbstractViewNext @command((self) => self.dropboxEnabled()) dropboxCommand() { - if (window.Dropbox) - { + if (window.Dropbox) { window.Dropbox.choose({ success: (files) => { - if (files && files[0] && files[0].link) - { + if (files && files[0] && files[0].link) { this.addDropboxAttachment(files[0]); } }, @@ -565,9 +553,15 @@ class ComposePopupView extends AbstractViewNext } autosaveFunction() { - if (this.modalVisibility() && !FolderStore.draftFolderNotEnabled() && SettingsStore.allowDraftAutosave() && - !this.isEmptyForm(false) && !this.saving() && !this.sending() && !this.savedError()) - { + if ( + this.modalVisibility() && + !FolderStore.draftFolderNotEnabled() && + SettingsStore.allowDraftAutosave() && + !this.isEmptyForm(false) && + !this.saving() && + !this.sending() && + !this.savedError() + ) { this.saveCommand(); } @@ -590,8 +584,7 @@ class ComposePopupView extends AbstractViewNext } openOpenPgpPopup() { - if (PgpStore.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml()) - { + if (PgpStore.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml()) { showScreenPopup(require('View/Popup/ComposeOpenPgp'), [ (result) => { this.editor((editor) => { @@ -609,33 +602,24 @@ class ComposePopupView extends AbstractViewNext reloadDraftFolder() { const draftFolder = FolderStore.draftFolder(); - if ('' !== draftFolder && UNUSED_OPTION_VALUE !== draftFolder) - { + if ('' !== draftFolder && UNUSED_OPTION_VALUE !== draftFolder) { setFolderHash(draftFolder, ''); - if (FolderStore.currentFolderFullNameRaw() === draftFolder) - { + if (FolderStore.currentFolderFullNameRaw() === draftFolder) { getApp().reloadMessageList(true); - } - else - { + } else { getApp().folderInformation(draftFolder); } } } findIdentityByMessage(composeType, message) { - - let - resultIndex = 1000, + let resultIndex = 1000, resultIdentity = null; - const - identities = IdentityStore.identities(), + const identities = IdentityStore.identities(), identitiesCache = {}, fEachHelper = (item) => { - if (item && item.email && identitiesCache[item.email]) - { - if (!resultIdentity || resultIndex > identitiesCache[item.email][1]) - { + if (item && item.email && identitiesCache[item.email]) { + if (!resultIdentity || resultIndex > identitiesCache[item.email][1]) { resultIdentity = identitiesCache[item.email][0]; resultIndex = identitiesCache[item.email][1]; } @@ -646,10 +630,8 @@ class ComposePopupView extends AbstractViewNext identitiesCache[item.email()] = [item, index]; }); - if (message) - { - switch (composeType) - { + if (message) { + switch (composeType) { case ComposeType.Empty: break; case ComposeType.Reply: @@ -672,40 +654,34 @@ class ComposePopupView extends AbstractViewNext } selectIdentity(identity) { - if (identity && identity.item) - { + if (identity && identity.item) { this.currentIdentity(identity.item); this.setSignatureFromIdentity(identity.item); } } sendMessageResponse(statusResult, data) { - let - result = false, + let result = false, message = ''; this.sending(false); - if (StorageResultType.Success === statusResult && data && data.Result) - { + if (StorageResultType.Success === statusResult && data && data.Result) { result = true; - if (this.modalVisibility()) - { + if (this.modalVisibility()) { delegateRun(this, 'closeCommand'); } } - if (this.modalVisibility() && !result) - { - if (data && Notification.CantSaveMessage === data.ErrorCode) - { + if (this.modalVisibility() && !result) { + if (data && Notification.CantSaveMessage === data.ErrorCode) { this.sendSuccessButSaveError(true); this.savedErrorDesc(trim(i18n('COMPOSE/SAVED_ERROR_ON_SEND'))); - } - else - { - message = getNotification(data && data.ErrorCode ? data.ErrorCode : Notification.CantSendMessage, - data && data.ErrorMessage ? data.ErrorMessage : ''); + } else { + message = getNotification( + data && data.ErrorCode ? data.ErrorCode : Notification.CantSendMessage, + data && data.ErrorMessage ? data.ErrorMessage : '' + ); this.sendError(true); this.sendErrorDesc(message || getNotification(Notification.CantSendMessage)); @@ -716,22 +692,17 @@ class ComposePopupView extends AbstractViewNext } saveMessageResponse(statusResult, oData) { - let result = false; this.saving(false); - if (StorageResultType.Success === statusResult && oData && oData.Result) - { - if (oData.Result.NewFolder && oData.Result.NewUid) - { + if (StorageResultType.Success === statusResult && oData && oData.Result) { + if (oData.Result.NewFolder && oData.Result.NewUid) { result = true; - if (this.bFromDraft) - { + if (this.bFromDraft) { const message = MessageStore.message(); - if (message && this.draftFolder() === message.folderFullNameRaw && this.draftUid() === message.uid) - { + if (message && this.draftFolder() === message.folderFullNameRaw && this.draftUid() === message.uid) { MessageStore.message(null); } } @@ -739,17 +710,15 @@ class ComposePopupView extends AbstractViewNext this.draftFolder(oData.Result.NewFolder); this.draftUid(oData.Result.NewUid); - this.savedTime(window.Math.round((new window.Date()).getTime() / 1000)); + this.savedTime(window.Math.round(new window.Date().getTime() / 1000)); - if (this.bFromDraft) - { + if (this.bFromDraft) { setFolderHash(this.draftFolder(), ''); } } } - if (!result) - { + if (!result) { this.savedError(true); this.savedErrorDesc(getNotification(Notification.CantSaveMessage)); } @@ -760,8 +729,7 @@ class ComposePopupView extends AbstractViewNext onHide() { this.autosaveStop(); - if (!this.bSkipNextHide) - { + if (!this.bSkipNextHide) { AppStore.composeInEdit(false); this.reset(); } @@ -774,21 +742,22 @@ class ComposePopupView extends AbstractViewNext } editor(fOnInit) { - if (fOnInit) - { - if (!this.oEditor && this.composeEditorArea()) - { + if (fOnInit) { + if (!this.oEditor && this.composeEditorArea()) { // _.delay(() => { - this.oEditor = new HtmlEditor(this.composeEditorArea(), null, () => { - fOnInit(this.oEditor); - this.resizerTrigger(); - }, (bHtml) => { - this.isHtml(!!bHtml); - }); + this.oEditor = new HtmlEditor( + this.composeEditorArea(), + null, + () => { + fOnInit(this.oEditor); + this.resizerTrigger(); + }, + (bHtml) => { + this.isHtml(!!bHtml); + } + ); // }, 1000); - } - else if (this.oEditor) - { + } else if (this.oEditor) { fOnInit(this.oEditor); this.resizerTrigger(); } @@ -796,23 +765,19 @@ class ComposePopupView extends AbstractViewNext } converSignature(signature) { - let - limit = 10, + let limit = 10, fromLine = ''; - const - moments = [], + const moments = [], momentRegx = /{{MOMENT:([^}]+)}}/g; signature = signature.replace(/[\r]/g, ''); fromLine = this.oLastMessage ? this.emailArrayToStringLineHelper(this.oLastMessage.from, true) : ''; - if ('' !== fromLine) - { + if ('' !== fromLine) { signature = signature.replace(/{{FROM-FULL}}/g, fromLine); - if (-1 === fromLine.indexOf(' ') && 0 < fromLine.indexOf('@')) - { + if (-1 === fromLine.indexOf(' ') && 0 < fromLine.indexOf('@')) { fromLine = fromLine.replace(/@[\S]+/, ''); } @@ -825,61 +790,49 @@ class ComposePopupView extends AbstractViewNext signature = signature.replace(/{{FROM}}/g, ''); signature = signature.replace(/{{FROM-FULL}}/g, ''); - if (-1 < signature.indexOf('{{DATE}}')) - { + if (-1 < signature.indexOf('{{DATE}}')) { signature = signature.replace(/{{DATE}}/g, momentorFormat(0, 'llll')); } - if (-1 < signature.indexOf('{{TIME}}')) - { + if (-1 < signature.indexOf('{{TIME}}')) { signature = signature.replace(/{{TIME}}/g, momentorFormat(0, 'LT')); } - if (-1 < signature.indexOf('{{MOMENT:')) - { - try - { + if (-1 < signature.indexOf('{{MOMENT:')) { + try { let match = null; - while (null !== (match = momentRegx.exec(signature))) // eslint-disable-line no-cond-assign - { - if (match && match[0] && match[1]) - { + while (null !== (match = momentRegx.exec(signature))) { + // eslint-disable-line no-cond-assign + if (match && match[0] && match[1]) { moments.push([match[0], match[1]]); } limit -= 1; - if (0 === limit) - { + if (0 === limit) { break; } } - if (moments && 0 < moments.length) - { + if (moments && 0 < moments.length) { _.each(moments, (data) => { signature = signature.replace(data[0], momentorFormat(0, data[1])); }); } signature = signature.replace(/{{MOMENT:[^}]+}}/g, ''); - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty } return signature; } setSignatureFromIdentity(identity) { - if (identity) - { + if (identity) { this.editor((editor) => { - let - isHtml = false, + let isHtml = false, signature = identity.signature(); - if ('' !== signature) - { - if (':HTML:' === signature.substr(0, 6)) - { + if ('' !== signature) { + if (':HTML:' === signature.substr(0, 6)) { isHtml = true; signature = signature.substr(6); } @@ -900,41 +853,39 @@ class ComposePopupView extends AbstractViewNext * @param {string=} sCustomPlainText = null */ onShow(type, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText) { - routeOff(); this.autosaveStart(); - if (AppStore.composeInEdit()) - { + if (AppStore.composeInEdit()) { type = type || ComposeType.Empty; - if (ComposeType.Empty !== type) - { - showScreenPopup(require('View/Popup/Ask'), [i18n('COMPOSE/DISCARD_UNSAVED_DATA'), () => { - this.initOnShow(type, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText); - }, null, null, null, false]); - } - else - { + if (ComposeType.Empty !== type) { + showScreenPopup(require('View/Popup/Ask'), [ + i18n('COMPOSE/DISCARD_UNSAVED_DATA'), + () => { + this.initOnShow(type, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText); + }, + null, + null, + null, + false + ]); + } else { this.addEmailsTo(this.to, aToEmails); this.addEmailsTo(this.cc, aCcEmails); this.addEmailsTo(this.bcc, aBccEmails); - if (isNormal(sCustomSubject) && '' !== sCustomSubject && '' === this.subject()) - { + if (isNormal(sCustomSubject) && '' !== sCustomSubject && '' === this.subject()) { this.subject(sCustomSubject); } } - } - else - { + } else { this.initOnShow(type, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText); } } onWarmUp() { - if (this.modalVisibility && !this.modalVisibility()) - { + if (this.modalVisibility && !this.modalVisibility()) { this.editor((editor) => editor.modeToggle(false)); } } @@ -944,10 +895,8 @@ class ComposePopupView extends AbstractViewNext * @param {Array} emails */ addEmailsTo(fKoValue, emails) { - if (isNonEmptyArray(emails)) - { - const - value = trim(fKoValue()), + if (isNonEmptyArray(emails)) { + const value = trim(fKoValue()), values = _.uniq(_.compact(_.map(emails, (item) => (item ? item.toLine(false) : null)))); fKoValue(value + ('' === value ? '' : ', ') + trim(values.join(', '))); @@ -974,12 +923,10 @@ class ComposePopupView extends AbstractViewNext * @param {string=} sCustomSubject = null * @param {string=} sCustomPlainText = null */ - initOnShow(sType, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText) - { + initOnShow(sType, oMessageOrArray, aToEmails, aCcEmails, aBccEmails, sCustomSubject, sCustomPlainText) { AppStore.composeInEdit(true); - let - sFrom = '', + let sFrom = '', sTo = '', sCc = '', sDate = '', @@ -990,65 +937,59 @@ class ComposePopupView extends AbstractViewNext aDraftInfo = null, message = null; - const - excludeEmail = {}, + const excludeEmail = {}, mEmail = AccountStore.email(), lineComposeType = sType || ComposeType.Empty; oMessageOrArray = oMessageOrArray || null; - if (oMessageOrArray && isNormal(oMessageOrArray)) - { - message = isArray(oMessageOrArray) && 1 === oMessageOrArray.length ? oMessageOrArray[0] : - (!isArray(oMessageOrArray) ? oMessageOrArray : null); + if (oMessageOrArray && isNormal(oMessageOrArray)) { + message = + isArray(oMessageOrArray) && 1 === oMessageOrArray.length + ? oMessageOrArray[0] + : !isArray(oMessageOrArray) + ? oMessageOrArray + : null; } this.oLastMessage = message; - if (null !== mEmail) - { + if (null !== mEmail) { excludeEmail[mEmail] = true; } this.reset(); identity = this.findIdentityByMessage(lineComposeType, message); - if (identity) - { + if (identity) { excludeEmail[identity.email()] = true; } - if (isNonEmptyArray(aToEmails)) - { + if (isNonEmptyArray(aToEmails)) { this.to(this.emailArrayToStringLineHelper(aToEmails)); } - if (isNonEmptyArray(aCcEmails)) - { + if (isNonEmptyArray(aCcEmails)) { this.cc(this.emailArrayToStringLineHelper(aCcEmails)); } - if (isNonEmptyArray(aBccEmails)) - { + if (isNonEmptyArray(aBccEmails)) { this.bcc(this.emailArrayToStringLineHelper(aBccEmails)); } - if ('' !== lineComposeType && message) - { + if ('' !== lineComposeType && message) { sDate = momentorFormat(message.dateTimeStampInUTC(), 'FULL'); sSubject = message.subject(); aDraftInfo = message.aDraftInfo; const clonedText = $(message.body).clone(); - if (clonedText) - { + if (clonedText) { clearBqSwitcher(clonedText); sText = clonedText.html(); } let resplyAllParts = null; - switch (lineComposeType) - { + switch (lineComposeType) { case ComposeType.Empty: break; @@ -1123,8 +1064,7 @@ class ComposePopupView extends AbstractViewNext // no default } - switch (lineComposeType) - { + switch (lineComposeType) { case ComposeType.Reply: case ComposeType.ReplyAll: sFrom = message.fromToLine(false, true); @@ -1133,9 +1073,7 @@ class ComposePopupView extends AbstractViewNext 'EMAIL': sFrom }); - sText = '
' + sReplyTitle + ':' + - '
' + - '' + trim(sText) + ''; + sText = '
' + sReplyTitle + ':' + '
' + '' + trim(sText) + ''; break; @@ -1143,13 +1081,29 @@ class ComposePopupView extends AbstractViewNext sFrom = message.fromToLine(false, true); sTo = message.toToLine(false, true); sCc = message.ccToLine(false, true); - sText = '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') + - '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + ': ' + sFrom + - '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + ': ' + sTo + - (0 < sCc.length ? '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') + - '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + ': ' + encodeHtml(sDate) + - '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + ': ' + encodeHtml(sSubject) + - '
' + trim(sText) + '
'; + sText = + '
' + + i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') + + '
' + + i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + + ': ' + + sFrom + + '
' + + i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + + ': ' + + sTo + + (0 < sCc.length ? '
' + i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') + + '
' + + i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + + ': ' + + encodeHtml(sDate) + + '
' + + i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + + ': ' + + encodeHtml(sSubject) + + '
' + + trim(sText) + + '
'; break; case ComposeType.ForwardAsAttachment: @@ -1159,84 +1113,73 @@ class ComposePopupView extends AbstractViewNext } this.editor((editor) => { - editor.setHtml(sText, false); - if (EditorDefaultType.PlainForced === this.editorDefaultType() || - (!message.isHtml() && EditorDefaultType.HtmlForced !== this.editorDefaultType())) - { + if ( + EditorDefaultType.PlainForced === this.editorDefaultType() || + (!message.isHtml() && EditorDefaultType.HtmlForced !== this.editorDefaultType()) + ) { editor.modeToggle(false); } - if (identity && ComposeType.Draft !== lineComposeType && ComposeType.EditAsNew !== lineComposeType) - { + if (identity && ComposeType.Draft !== lineComposeType && ComposeType.EditAsNew !== lineComposeType) { this.setSignatureFromIdentity(identity); } this.setFocusInPopup(); }); - } - else if (ComposeType.Empty === lineComposeType) - { + } else if (ComposeType.Empty === lineComposeType) { this.subject(isNormal(sCustomSubject) ? '' + sCustomSubject : ''); sText = isNormal(sCustomPlainText) ? '' + sCustomPlainText : ''; this.editor((editor) => { - editor.setHtml(sText, false); - if (EditorDefaultType.Html !== this.editorDefaultType() && - EditorDefaultType.HtmlForced !== this.editorDefaultType()) - { + if ( + EditorDefaultType.Html !== this.editorDefaultType() && + EditorDefaultType.HtmlForced !== this.editorDefaultType() + ) { editor.modeToggle(false); } - if (identity) - { + if (identity) { this.setSignatureFromIdentity(identity); } this.setFocusInPopup(); }); - } - else if (isNonEmptyArray(oMessageOrArray)) - { + } else if (isNonEmptyArray(oMessageOrArray)) { _.each(oMessageOrArray, (item) => { this.addMessageAsAttachment(item); }); this.editor((editor) => { - editor.setHtml('', false); - if (EditorDefaultType.Html !== this.editorDefaultType() && - EditorDefaultType.HtmlForced !== this.editorDefaultType()) - { + if ( + EditorDefaultType.Html !== this.editorDefaultType() && + EditorDefaultType.HtmlForced !== this.editorDefaultType() + ) { editor.modeToggle(false); } - if (identity && ComposeType.Draft !== lineComposeType && ComposeType.EditAsNew !== lineComposeType) - { + if (identity && ComposeType.Draft !== lineComposeType && ComposeType.EditAsNew !== lineComposeType) { this.setSignatureFromIdentity(identity); } this.setFocusInPopup(); }); - } - else - { + } else { this.setFocusInPopup(); } const downloads = this.getAttachmentsDownloadsForUpload(); - if (isNonEmptyArray(downloads)) - { + if (isNonEmptyArray(downloads)) { Remote.messageUploadAttachments(this.onMessageUploadAttachments, downloads); } - if (identity) - { + if (identity) { this.currentIdentity(identity); } @@ -1244,43 +1187,34 @@ class ComposePopupView extends AbstractViewNext } onMessageUploadAttachments(sResult, oData) { - if (StorageResultType.Success === sResult && oData && oData.Result) - { - if (!this.viewModelVisibility()) - { + if (StorageResultType.Success === sResult && oData && oData.Result) { + if (!this.viewModelVisibility()) { _.each(oData.Result, (id, tempName) => { const attachment = this.getAttachmentById(id); - if (attachment) - { + if (attachment) { attachment.tempName(tempName); - attachment.waiting(false).uploading(false).complete(true); + attachment + .waiting(false) + .uploading(false) + .complete(true); } }); } - } - else - { + } else { this.setMessageAttachmentFailedDownloadText(); } } setFocusInPopup() { - if (!bMobileDevice) - { + if (!bMobileDevice) { _.delay(() => { - - if ('' === this.to()) - { + if ('' === this.to()) { this.to.focused(true); - } - else if (this.oEditor) - { - if (!this.to.focused()) - { + } else if (this.oEditor) { + if (!this.to.focused()) { this.oEditor.focus(); } } - }, Magics.Time100ms); } } @@ -1291,20 +1225,18 @@ class ComposePopupView extends AbstractViewNext tryToClosePopup() { const PopupsAskViewModel = require('View/Popup/Ask'); - if (!isPopupVisible(PopupsAskViewModel) && this.modalVisibility()) - { - if (this.bSkipNextHide || (this.isEmptyForm() && !this.draftUid())) - { + if (!isPopupVisible(PopupsAskViewModel) && this.modalVisibility()) { + if (this.bSkipNextHide || (this.isEmptyForm() && !this.draftUid())) { delegateRun(this, 'closeCommand'); - } - else - { - showScreenPopup(PopupsAskViewModel, [i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), () => { - if (this.modalVisibility()) - { - delegateRun(this, 'closeCommand'); + } else { + showScreenPopup(PopupsAskViewModel, [ + i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), + () => { + if (this.modalVisibility()) { + delegateRun(this, 'closeCommand'); + } } - }]); + ]); } } } @@ -1315,8 +1247,7 @@ class ComposePopupView extends AbstractViewNext key('ctrl+q, command+q, ctrl+w, command+w', KeyState.Compose, noopFalse); key('`', KeyState.Compose, () => { - if (this.oEditor && !this.oEditor.hasFocus() && !inFocus()) - { + if (this.oEditor && !this.oEditor.hasFocus() && !inFocus()) { this.identitiesDropdownTrigger(true); return false; } @@ -1334,16 +1265,14 @@ class ComposePopupView extends AbstractViewNext return false; }); - if (this.allowFolders) - { + if (this.allowFolders) { key('ctrl+s, command+s', KeyState.Compose, () => { this.saveCommand(); return false; }); } - if (Settings.appSettingsGet('allowCtrlEnterOnCompose')) - { + if (Settings.appSettingsGet('allowCtrlEnterOnCompose')) { key('ctrl+enter, command+enter', KeyState.Compose, () => { this.sendCommand(); return false; @@ -1351,8 +1280,7 @@ class ComposePopupView extends AbstractViewNext } key('shift+esc', KeyState.Compose, () => { - if (this.modalVisibility()) - { + if (this.modalVisibility()) { this.tryToClosePopup(); } return false; @@ -1363,49 +1291,47 @@ class ComposePopupView extends AbstractViewNext SocialStore.appendDropbox(); - if (this.driveEnabled()) - { + if (this.driveEnabled()) { $.getScript('https://apis.google.com/js/api.js', () => { - if (window.gapi) - { + if (window.gapi) { this.driveVisible(true); } }); } window.setInterval(() => { - if (this.modalVisibility() && this.oEditor) - { + if (this.modalVisibility() && this.oEditor) { this.oEditor.resize(); } }, Magics.Time5s); } driveCallback(accessToken, data) { - if (data && window.XMLHttpRequest && window.google && + if ( + data && + window.XMLHttpRequest && + window.google && data[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED && - data[window.google.picker.Response.DOCUMENTS] && data[window.google.picker.Response.DOCUMENTS][0] && - data[window.google.picker.Response.DOCUMENTS][0].id) - { + data[window.google.picker.Response.DOCUMENTS] && + data[window.google.picker.Response.DOCUMENTS][0] && + data[window.google.picker.Response.DOCUMENTS][0].id + ) { const request = new window.XMLHttpRequest(); - request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + data[window.google.picker.Response.DOCUMENTS][0].id); + request.open( + 'GET', + 'https://www.googleapis.com/drive/v2/files/' + data[window.google.picker.Response.DOCUMENTS][0].id + ); request.setRequestHeader('Authorization', 'Bearer ' + accessToken); request.addEventListener('load', () => { - if (request && request.responseText) - { - const - response = window.JSON.parse(request.responseText), + if (request && request.responseText) { + const response = window.JSON.parse(request.responseText), fExport = (item, mimeType, ext) => { - if (item && item.exportLinks) - { - if (item.exportLinks[mimeType]) - { + if (item && item.exportLinks) { + if (item.exportLinks[mimeType]) { response.downloadUrl = item.exportLinks[mimeType]; response.title = item.title + '.' + ext; response.mimeType = mimeType; - } - else if (item.exportLinks['application/pdf']) - { + } else if (item.exportLinks['application/pdf']) { response.downloadUrl = item.exportLinks['application/pdf']; response.title = item.title + '.pdf'; response.mimeType = 'application/pdf'; @@ -1413,10 +1339,8 @@ class ComposePopupView extends AbstractViewNext } }; - if (response && !response.downloadUrl && response.mimeType && response.exportLinks) - { - switch (response.mimeType.toString().toLowerCase()) - { + if (response && !response.downloadUrl && response.mimeType && response.exportLinks) { + switch (response.mimeType.toString().toLowerCase()) { case 'application/vnd.google-apps.document': fExport(response, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx'); break; @@ -1435,8 +1359,7 @@ class ComposePopupView extends AbstractViewNext } } - if (response && response.downloadUrl) - { + if (response && response.downloadUrl) { this.addDriveAttachment(response, accessToken); } } @@ -1447,12 +1370,10 @@ class ComposePopupView extends AbstractViewNext } driveCreatePiker(authToken) { - if (window.gapi && authToken && authToken.access_token) - { + if (window.gapi && authToken && authToken.access_token) { window.gapi.load('picker', { callback: () => { - if (window.google && window.google.picker) - { + if (window.google && window.google.picker) { const drivePicker = new window.google.picker.PickerBuilder() // .addView(window.google.picker.ViewId.FOLDERS) .addView(window.google.picker.ViewId.DOCS) @@ -1471,18 +1392,14 @@ class ComposePopupView extends AbstractViewNext } driveOpenPopup() { - if (window.gapi) - { + if (window.gapi) { window.gapi.load('auth', { callback: () => { - const - authToken = window.gapi.auth.getToken(), + const authToken = window.gapi.auth.getToken(), fResult = (authResult) => { - if (authResult && !authResult.error) - { + if (authResult && !authResult.error) { const token = window.gapi.auth.getToken(); - if (token) - { + if (token) { this.driveCreatePiker(token); } @@ -1492,25 +1409,27 @@ class ComposePopupView extends AbstractViewNext return false; }; - if (!authToken) - { - window.gapi.auth.authorize({ - 'client_id': Settings.settingsGet('GoogleClientID'), - 'scope': 'https://www.googleapis.com/auth/drive.readonly', - 'immediate': true - }, (authResult) => { - if (!fResult(authResult)) + if (!authToken) { + window.gapi.auth.authorize( { - window.gapi.auth.authorize({ - 'client_id': Settings.settingsGet('GoogleClientID'), - 'scope': 'https://www.googleapis.com/auth/drive.readonly', - 'immediate': false - }, fResult); + 'client_id': Settings.settingsGet('GoogleClientID'), + 'scope': 'https://www.googleapis.com/auth/drive.readonly', + 'immediate': true + }, + (authResult) => { + if (!fResult(authResult)) { + window.gapi.auth.authorize( + { + 'client_id': Settings.settingsGet('GoogleClientID'), + 'scope': 'https://www.googleapis.com/auth/drive.readonly', + 'immediate': false + }, + fResult + ); + } } - }); - } - else - { + ); + } else { this.driveCreatePiker(authToken); } } @@ -1529,13 +1448,11 @@ class ComposePopupView extends AbstractViewNext cancelAttachmentHelper(id, oJua) { return () => { const attachment = _.find(this.attachments(), (item) => item && item.id === id); - if (attachment) - { + if (attachment) { this.attachments.remove(attachment); delegateRunOnDestroy(attachment); - if (oJua) - { + if (oJua) { oJua.cancel(id); } } @@ -1543,10 +1460,8 @@ class ComposePopupView extends AbstractViewNext } initUploader() { - if (this.composeUploaderButton()) - { - const - uploadCache = {}, + if (this.composeUploaderButton()) { + const uploadCache = {}, attachmentSizeLimit = pInt(Settings.settingsGet('AttachmentLimit')), oJua = new Jua({ 'action': upload(), @@ -1557,8 +1472,7 @@ class ComposePopupView extends AbstractViewNext 'dragAndDropElement': this.composeUploaderDropPlace() }); - if (oJua) - { + if (oJua) { oJua // .on('onLimitReached', (limit) => { // alert(limit); @@ -1577,29 +1491,22 @@ class ComposePopupView extends AbstractViewNext this.dragAndDropVisible(false); }) .on('onProgress', (id, loaded, total) => { - let item = uploadCache[id]; - if (!item) - { + if (!item) { item = this.getAttachmentById(id); - if (item) - { + if (item) { uploadCache[id] = item; } } - if (item) - { - item.progress(window.Math.floor(loaded / total * 100)); + if (item) { + item.progress(window.Math.floor((loaded / total) * 100)); } - }) .on('onSelect', (sId, oData) => { - this.dragAndDropOver(false); - const - fileName = isUnd(oData.FileName) ? '' : oData.FileName.toString(), + const fileName = isUnd(oData.FileName) ? '' : oData.FileName.toString(), size = isNormal(oData.Size) ? pInt(oData.Size) : null, attachment = new ComposeAttachmentModel(sId, fileName, size); @@ -1609,10 +1516,11 @@ class ComposePopupView extends AbstractViewNext this.attachmentsPlace(true); - if (0 < size && 0 < attachmentSizeLimit && attachmentSizeLimit < size) - { + if (0 < size && 0 < attachmentSizeLimit && attachmentSizeLimit < size) { attachment - .waiting(false).uploading(true).complete(true) + .waiting(false) + .uploading(true) + .complete(true) .error(i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG')); return false; @@ -1621,51 +1529,41 @@ class ComposePopupView extends AbstractViewNext return true; }) .on('onStart', (id) => { - let item = uploadCache[id]; - if (!item) - { + if (!item) { item = this.getAttachmentById(id); - if (item) - { + if (item) { uploadCache[id] = item; } } - if (item) - { - item.waiting(false).uploading(true).complete(false); + if (item) { + item + .waiting(false) + .uploading(true) + .complete(false); } }) .on('onComplete', (id, result, data) => { - - const - attachment = this.getAttachmentById(id), + const attachment = this.getAttachmentById(id), errorCode = data && data.Result && data.Result.ErrorCode ? data.Result.ErrorCode : null, attachmentJson = result && data && data.Result && data.Result.Attachment ? data.Result.Attachment : null; let error = ''; - if (null !== errorCode) - { + if (null !== errorCode) { error = getUploadErrorDescByCode(errorCode); - } - else if (!attachmentJson) - { + } else if (!attachmentJson) { error = i18n('UPLOAD/ERROR_UNKNOWN'); } - if (attachment) - { - if ('' !== error && 0 < error.length) - { + if (attachment) { + if ('' !== error && 0 < error.length) { attachment .waiting(false) .uploading(false) .complete(true) .error(error); - } - else if (attachmentJson) - { + } else if (attachmentJson) { attachment .waiting(false) .uploading(false) @@ -1674,22 +1572,15 @@ class ComposePopupView extends AbstractViewNext attachment.initByUploadJson(attachmentJson); } - if (isUnd(uploadCache[id])) - { - delete (uploadCache[id]); + if (isUnd(uploadCache[id])) { + delete uploadCache[id]; } } }); - this - .addAttachmentEnabled(true) - .dragAndDropEnabled(oJua.isDragAndDropSupported()); - } - else - { - this - .addAttachmentEnabled(false) - .dragAndDropEnabled(false); + this.addAttachmentEnabled(true).dragAndDropEnabled(oJua.isDragAndDropSupported()); + } else { + this.addAttachmentEnabled(false).dragAndDropEnabled(false); } } } @@ -1700,14 +1591,8 @@ class ComposePopupView extends AbstractViewNext prepearAttachmentsForSendOrSave() { const result = {}; _.each(this.attachmentsInReady(), (item) => { - if (item && '' !== item.tempName() && item.enabled()) - { - result[item.tempName()] = [ - item.fileName(), - item.isInline ? '1' : '0', - item.CID, - item.contentLocation - ]; + if (item && '' !== item.tempName() && item.enabled()) { + result[item.tempName()] = [item.fileName(), item.isInline ? '1' : '0', item.CID, item.contentLocation]; } }); @@ -1718,18 +1603,18 @@ class ComposePopupView extends AbstractViewNext * @param {MessageModel} message */ addMessageAsAttachment(message) { - if (message) - { + if (message) { let temp = message.subject(); temp = '.eml' === temp.substr(-4).toLowerCase() ? temp : temp + '.eml'; - const attachment = new ComposeAttachmentModel( - message.requestHash, temp, message.size() - ); + const attachment = new ComposeAttachmentModel(message.requestHash, temp, message.size()); attachment.fromMessage = true; attachment.cancel = this.cancelAttachmentHelper(message.requestHash); - attachment.waiting(false).uploading(true).complete(true); + attachment + .waiting(false) + .uploading(true) + .complete(true); this.attachments.push(attachment); } @@ -1746,7 +1631,10 @@ class ComposePopupView extends AbstractViewNext attachment.fromMessage = false; attachment.cancel = this.cancelAttachmentHelper(url); - attachment.waiting(false).uploading(true).complete(false); + attachment + .waiting(false) + .uploading(true) + .complete(false); this.attachments.push(attachment); @@ -1760,38 +1648,34 @@ class ComposePopupView extends AbstractViewNext * @returns {boolean} */ addDropboxAttachment(dropboxFile) { - const - attachmentSizeLimit = pInt(Settings.settingsGet('AttachmentLimit')), + const attachmentSizeLimit = pInt(Settings.settingsGet('AttachmentLimit')), mSize = dropboxFile.bytes, attachment = this.addAttachmentHelper(dropboxFile.link, dropboxFile.name, mSize); - if (0 < mSize && 0 < attachmentSizeLimit && attachmentSizeLimit < mSize) - { + if (0 < mSize && 0 < attachmentSizeLimit && attachmentSizeLimit < mSize) { attachment.uploading(false).complete(true); attachment.error(i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG')); return false; } - Remote.composeUploadExternals((statusResult, data) => { + Remote.composeUploadExternals( + (statusResult, data) => { + let result = false; + attachment.uploading(false).complete(true); - let result = false; - attachment.uploading(false).complete(true); - - if (StorageResultType.Success === statusResult && data && data.Result) - { - if (data.Result[attachment.id]) - { - result = true; - attachment.tempName(data.Result[attachment.id]); + if (StorageResultType.Success === statusResult && data && data.Result) { + if (data.Result[attachment.id]) { + result = true; + attachment.tempName(data.Result[attachment.id]); + } } - } - if (!result) - { - attachment.error(getUploadErrorDescByCode(UploadErrorCode.FileNoUploaded)); - } - - }, [dropboxFile.link]); + if (!result) { + attachment.error(getUploadErrorDescByCode(UploadErrorCode.FileNoUploaded)); + } + }, + [dropboxFile.link] + ); return true; } @@ -1802,39 +1686,36 @@ class ComposePopupView extends AbstractViewNext * @returns {boolean} */ addDriveAttachment(driveFile, accessToken) { - const - attachmentSizeLimit = pInt(Settings.settingsGet('AttachmentLimit')), + const attachmentSizeLimit = pInt(Settings.settingsGet('AttachmentLimit')), size = driveFile.fileSize ? pInt(driveFile.fileSize) : 0, attachment = this.addAttachmentHelper(driveFile.downloadUrl, driveFile.title, size); - if (0 < size && 0 < attachmentSizeLimit && attachmentSizeLimit < size) - { + if (0 < size && 0 < attachmentSizeLimit && attachmentSizeLimit < size) { attachment.uploading(false).complete(true); attachment.error(i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG')); return false; } - Remote.composeUploadDrive((statusResult, data) => { + Remote.composeUploadDrive( + (statusResult, data) => { + let result = false; + attachment.uploading(false).complete(true); - let result = false; - attachment.uploading(false).complete(true); - - if (StorageResultType.Success === statusResult && data && data.Result) - { - if (data.Result[attachment.id]) - { - result = true; - attachment.tempName(data.Result[attachment.id][0]); - attachment.size(pInt(data.Result[attachment.id][1])); + if (StorageResultType.Success === statusResult && data && data.Result) { + if (data.Result[attachment.id]) { + result = true; + attachment.tempName(data.Result[attachment.id][0]); + attachment.size(pInt(data.Result[attachment.id][1])); + } } - } - if (!result) - { - attachment.error(getUploadErrorDescByCode(UploadErrorCode.FileNoUploaded)); - } - - }, driveFile.downloadUrl, accessToken); + if (!result) { + attachment.error(getUploadErrorDescByCode(UploadErrorCode.FileNoUploaded)); + } + }, + driveFile.downloadUrl, + accessToken + ); return true; } @@ -1844,19 +1725,14 @@ class ComposePopupView extends AbstractViewNext * @param {string} type */ prepearMessageAttachments(message, type) { - if (message) - { - if (ComposeType.ForwardAsAttachment === type) - { + if (message) { + if (ComposeType.ForwardAsAttachment === type) { this.addMessageAsAttachment(message); - } - else - { + } else { const attachments = message.attachments(); _.each(isNonEmptyArray(attachments) ? attachments : [], (item) => { let add = false; - switch (type) - { + switch (type) { case ComposeType.Reply: case ComposeType.ReplyAll: add = item.isLinked; @@ -1870,16 +1746,23 @@ class ComposePopupView extends AbstractViewNext // no default } - if (add) - { + if (add) { const attachment = new ComposeAttachmentModel( - item.download, item.fileName, item.estimatedSize, - item.isInline, item.isLinked, item.cid, item.contentLocation + item.download, + item.fileName, + item.estimatedSize, + item.isInline, + item.isLinked, + item.cid, + item.contentLocation ); attachment.fromMessage = true; attachment.cancel = this.cancelAttachmentHelper(item.download); - attachment.waiting(false).uploading(true).complete(false); + attachment + .waiting(false) + .uploading(true) + .complete(false); this.attachments.push(attachment); } @@ -1890,8 +1773,7 @@ class ComposePopupView extends AbstractViewNext removeLinkedAttachments() { const arrachment = _.find(this.attachments(), (item) => item && item.isLinked); - if (arrachment) - { + if (arrachment) { this.attachments.remove(arrachment); delegateRunOnDestroy(arrachment); } @@ -1899,8 +1781,7 @@ class ComposePopupView extends AbstractViewNext setMessageAttachmentFailedDownloadText() { _.each(this.attachments(), (attachment) => { - if (attachment && attachment.fromMessage) - { + if (attachment && attachment.fromMessage) { attachment .waiting(false) .uploading(false) @@ -1915,17 +1796,19 @@ class ComposePopupView extends AbstractViewNext * @returns {boolean} */ isEmptyForm(includeAttachmentInProgress = true) { + const withoutAttachment = includeAttachmentInProgress + ? 0 === this.attachments().length + : 0 === this.attachmentsInReady().length; - const withoutAttachment = includeAttachmentInProgress ? - 0 === this.attachments().length : 0 === this.attachmentsInReady().length; - - return 0 === this.to().length && + return ( + 0 === this.to().length && 0 === this.cc().length && 0 === this.bcc().length && 0 === this.replyTo().length && 0 === this.subject().length && withoutAttachment && - (!this.oEditor || '' === this.oEditor.getData()); + (!this.oEditor || '' === this.oEditor.getData()) + ); } reset() { @@ -1969,8 +1852,7 @@ class ComposePopupView extends AbstractViewNext this.sending(false); this.saving(false); - if (this.oEditor) - { + if (this.oEditor) { this.oEditor.clear(false); } } @@ -1979,9 +1861,7 @@ class ComposePopupView extends AbstractViewNext * @returns {Array} */ getAttachmentsDownloadsForUpload() { - return _.map(_.filter( - this.attachments(), (item) => item && '' === item.tempName(), - ), (item) => item.id); + return _.map(_.filter(this.attachments(), (item) => item && '' === item.tempName()), (item) => item.id); } resizerTrigger() { @@ -1989,4 +1869,4 @@ class ComposePopupView extends AbstractViewNext } } -export {ComposePopupView, ComposePopupView as default}; +export { ComposePopupView, ComposePopupView as default }; diff --git a/dev/View/Popup/ComposeOpenPgp.js b/dev/View/Popup/ComposeOpenPgp.js index 7c126ab05..85a7d3d9a 100644 --- a/dev/View/Popup/ComposeOpenPgp.js +++ b/dev/View/Popup/ComposeOpenPgp.js @@ -1,23 +1,19 @@ - import _ from '_'; import $ from '$'; import ko from 'ko'; import key from 'key'; -import { - inArray, pString, log, isUnd, trim, - defautOptionsAfterRender -} from 'Common/Utils'; +import { inArray, pString, log, isUnd, trim, defautOptionsAfterRender } from 'Common/Utils'; -import {Magics, KeyState} from 'Common/Enums'; -import {i18n} from 'Common/Translator'; +import { Magics, KeyState } from 'Common/Enums'; +import { i18n } from 'Common/Translator'; import PgpStore from 'Stores/User/Pgp'; -import {EmailModel} from 'Model/Email'; +import { EmailModel } from 'Model/Email'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; const KEY_NAME_SUBSTR = -8; @@ -25,8 +21,7 @@ const KEY_NAME_SUBSTR = -8; name: 'View/Popup/ComposeOpenPgp', templateID: 'PopupsComposeOpenPgp' }) -class ComposeOpenPgpPopupView extends AbstractViewNext -{ +class ComposeOpenPgpPopupView extends AbstractViewNext { constructor() { super(); @@ -49,14 +44,11 @@ class ComposeOpenPgpPopupView extends AbstractViewNext this.signKey = ko.observable(null); this.encryptKeys = ko.observableArray([]); - this.encryptKeysView = ko.computed( - () => _.compact(_.map(this.encryptKeys(), (oKey) => (oKey ? oKey.key : null))) - ); + this.encryptKeysView = ko.computed(() => _.compact(_.map(this.encryptKeys(), (oKey) => (oKey ? oKey.key : null)))); this.privateKeysOptions = ko.computed(() => { const opts = _.map(PgpStore.openpgpkeysPrivate(), (oKey, iIndex) => { - if (this.signKey() && this.signKey().key.id === oKey.id) - { + if (this.signKey() && this.signKey().key.id === oKey.id) { return null; } return _.map(oKey.users, (user) => ({ @@ -72,8 +64,7 @@ class ComposeOpenPgpPopupView extends AbstractViewNext this.publicKeysOptions = ko.computed(() => { const opts = _.map(PgpStore.openpgpkeysPublic(), (oKey, index) => { - if (-1 < inArray(oKey, this.encryptKeysView())) - { + if (-1 < inArray(oKey, this.encryptKeysView())) { return null; } return _.map(oKey.users, (user) => ({ @@ -91,16 +82,14 @@ class ComposeOpenPgpPopupView extends AbstractViewNext this.resultCallback = null; this.selectedPrivateKey.subscribe((value) => { - if (value) - { + if (value) { this.selectCommand(); this.updateCommand(); } }); this.selectedPublicKey.subscribe((value) => { - if (value) - { + if (value) { this.addCommand(); } }); @@ -110,11 +99,9 @@ class ComposeOpenPgpPopupView extends AbstractViewNext this.defautOptionsAfterRender = defautOptionsAfterRender; this.addOptionClass = (domOption, item) => { - this.defautOptionsAfterRender(domOption, item); - if (item && !isUnd(item.class) && domOption) - { + if (item && !isUnd(item.class) && domOption) { $(domOption).addClass(item.class); } }; @@ -124,155 +111,130 @@ class ComposeOpenPgpPopupView extends AbstractViewNext @command((self) => !self.submitRequest() && (self.sign() || self.encrypt())) doCommand() { - - let - result = true, + let result = true, privateKey = null, aPublicKeys = []; this.submitRequest(true); - if (result && this.sign()) - { - if (!this.signKey()) - { + if (result && this.sign()) { + if (!this.signKey()) { this.notification(i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND')); result = false; - } - else if (!this.signKey().key) - { - this.notification(i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR', { - 'EMAIL': this.signKey().email - })); + } else if (!this.signKey().key) { + this.notification( + i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR', { + 'EMAIL': this.signKey().email + }) + ); result = false; } - if (result) - { + if (result) { const privateKeys = this.signKey().key.getNativeKeys(); privateKey = privateKeys[0] || null; - try - { - if (privateKey) - { + try { + if (privateKey) { privateKey.decrypt(pString(this.password())); } - } - catch (e) - { + } catch (e) { privateKey = null; } - if (!privateKey) - { + if (!privateKey) { this.notification(i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND')); result = false; } } } - if (result && this.encrypt()) - { - if (0 === this.encryptKeys().length) - { + if (result && this.encrypt()) { + if (0 === this.encryptKeys().length) { this.notification(i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND')); result = false; - } - else if (this.encryptKeys()) - { + } else if (this.encryptKeys()) { aPublicKeys = []; _.each(this.encryptKeys(), (oKey) => { - if (oKey && oKey.key) - { + if (oKey && oKey.key) { aPublicKeys = aPublicKeys.concat(_.compact(_.flatten(oKey.key.getNativeKeys()))); - } - else if (oKey && oKey.email) - { - this.notification(i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR', { - 'EMAIL': oKey.email - })); + } else if (oKey && oKey.email) { + this.notification( + i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR', { + 'EMAIL': oKey.email + }) + ); result = false; } }); - if (result && (0 === aPublicKeys.length || this.encryptKeys().length !== aPublicKeys.length)) - { + if (result && (0 === aPublicKeys.length || this.encryptKeys().length !== aPublicKeys.length)) { result = false; } } } - if (result && this.resultCallback) - { + if (result && this.resultCallback) { _.delay(() => { - let pgpPromise = null; - try - { - if (privateKey && 0 === aPublicKeys.length) - { + try { + if (privateKey && 0 === aPublicKeys.length) { pgpPromise = PgpStore.openpgp.sign({ data: this.text(), privateKeys: [privateKey] }); - } - else if (privateKey && 0 < aPublicKeys.length) - { + } else if (privateKey && 0 < aPublicKeys.length) { pgpPromise = PgpStore.openpgp.encrypt({ data: this.text(), publicKeys: aPublicKeys, privateKeys: [privateKey] }); - } - else if (!privateKey && 0 < aPublicKeys.length) - { + } else if (!privateKey && 0 < aPublicKeys.length) { pgpPromise = PgpStore.openpgp.encrypt({ data: this.text(), publicKeys: aPublicKeys }); } - } - catch (e) - { + } catch (e) { log(e); - this.notification(i18n('PGP_NOTIFICATIONS/PGP_ERROR', { - 'ERROR': '' + e - })); + this.notification( + i18n('PGP_NOTIFICATIONS/PGP_ERROR', { + 'ERROR': '' + e + }) + ); } - if (pgpPromise) - { - try - { - pgpPromise.then((mData) => { - this.resultCallback(mData.data); - this.cancelCommand(); - }).catch((e) => { - this.notification(i18n('PGP_NOTIFICATIONS/PGP_ERROR', { + if (pgpPromise) { + try { + pgpPromise + .then((mData) => { + this.resultCallback(mData.data); + this.cancelCommand(); + }) + .catch((e) => { + this.notification( + i18n('PGP_NOTIFICATIONS/PGP_ERROR', { + 'ERROR': '' + e + }) + ); + }); + } catch (e) { + this.notification( + i18n('PGP_NOTIFICATIONS/PGP_ERROR', { 'ERROR': '' + e - })); - }); - } - catch (e) - { - this.notification(i18n('PGP_NOTIFICATIONS/PGP_ERROR', { - 'ERROR': '' + e - })); + }) + ); } } this.submitRequest(false); - }, Magics.Time20ms); - } - else - { + } else { this.submitRequest(false); } @@ -281,12 +243,10 @@ class ComposeOpenPgpPopupView extends AbstractViewNext @command() selectCommand() { - const - keyId = this.selectedPrivateKey(), + const keyId = this.selectedPrivateKey(), option = keyId ? _.find(this.privateKeysOptions(), (item) => item && keyId === item.id) : null; - if (option) - { + if (option) { this.signKey({ 'empty': !option.key, 'selected': ko.observable(!!option.key), @@ -299,14 +259,11 @@ class ComposeOpenPgpPopupView extends AbstractViewNext @command() addCommand() { - - const - keyId = this.selectedPublicKey(), + const keyId = this.selectedPublicKey(), keys = this.encryptKeys(), - option = keyId ? _.find(this.publicKeysOptions(), (item) => (item && keyId === item.id)) : null; + option = keyId ? _.find(this.publicKeysOptions(), (item) => item && keyId === item.id) : null; - if (option) - { + if (option) { keys.push({ 'empty': !option.key, 'selected': ko.observable(!!option.key), @@ -350,8 +307,7 @@ class ComposeOpenPgpPopupView extends AbstractViewNext onBuild() { key('tab,shift+tab', KeyState.PopupComposeOpenPGP, () => { - switch (true) - { + switch (true) { case this.password.focus(): this.buttonFocus(true); break; @@ -369,58 +325,50 @@ class ComposeOpenPgpPopupView extends AbstractViewNext } onShowWithDelay() { - if (this.sign()) - { + if (this.sign()) { this.password.focus(true); - } - else - { + } else { this.buttonFocus(true); } } onShow(fCallback, sText, identity, sTo, sCc, sBcc) { - this.clearPopup(); - let - rec = [], + let rec = [], emailLine = ''; const email = new EmailModel(); this.resultCallback = fCallback; - if ('' !== sTo) - { + if ('' !== sTo) { rec.push(sTo); } - if ('' !== sCc) - { + if ('' !== sCc) { rec.push(sCc); } - if ('' !== sBcc) - { + if ('' !== sBcc) { rec.push(sBcc); } rec = rec.join(', ').split(','); - rec = _.compact(_.map(rec, (value) => { - email.clear(); - email.parse(trim(value)); - return '' === email.email ? false : email.email; - })); + rec = _.compact( + _.map(rec, (value) => { + email.clear(); + email.parse(trim(value)); + return '' === email.email ? false : email.email; + }) + ); - if (identity && identity.email()) - { + if (identity && identity.email()) { emailLine = identity.email(); rec.unshift(emailLine); const keys = PgpStore.findAllPrivateKeysByEmailNotNative(emailLine); - if (keys && keys[0]) - { + if (keys && keys[0]) { this.signKey({ 'users': keys[0].users || [emailLine], 'hash': keys[0].id.substr(KEY_NAME_SUBSTR).toUpperCase(), @@ -429,27 +377,38 @@ class ComposeOpenPgpPopupView extends AbstractViewNext } } - if (this.signKey()) - { + if (this.signKey()) { this.sign(true); } - if (rec && 0 < rec.length) - { - this.encryptKeys(_.uniq(_.compact(_.flatten(_.map(rec, (recEmail) => { - const keys = PgpStore.findAllPublicKeysByEmailNotNative(recEmail); - return keys ? _.map(keys, (publicKey) => ({ - 'empty': !publicKey, - 'selected': ko.observable(!!publicKey), - 'removable': ko.observable(!this.sign() || !this.signKey() || this.signKey().key.id !== publicKey.id), - 'users': publicKey ? (publicKey.users || [recEmail]) : [recEmail], - 'hash': publicKey ? publicKey.id.substr(KEY_NAME_SUBSTR).toUpperCase() : '', - 'key': publicKey - })) : []; - }), true)), (encryptKey) => encryptKey.hash)); + if (rec && 0 < rec.length) { + this.encryptKeys( + _.uniq( + _.compact( + _.flatten( + _.map(rec, (recEmail) => { + const keys = PgpStore.findAllPublicKeysByEmailNotNative(recEmail); + return keys + ? _.map(keys, (publicKey) => ({ + 'empty': !publicKey, + 'selected': ko.observable(!!publicKey), + 'removable': ko.observable( + !this.sign() || !this.signKey() || this.signKey().key.id !== publicKey.id + ), + 'users': publicKey ? publicKey.users || [recEmail] : [recEmail], + 'hash': publicKey ? publicKey.id.substr(KEY_NAME_SUBSTR).toUpperCase() : '', + 'key': publicKey + })) + : []; + }), + true + ) + ), + (encryptKey) => encryptKey.hash + ) + ); - if (0 < this.encryptKeys().length) - { + if (0 < this.encryptKeys().length) { this.encrypt(true); } } @@ -458,4 +417,4 @@ class ComposeOpenPgpPopupView extends AbstractViewNext } } -export {ComposeOpenPgpPopupView, ComposeOpenPgpPopupView as default}; +export { ComposeOpenPgpPopupView, ComposeOpenPgpPopupView as default }; diff --git a/dev/View/Popup/Contacts.js b/dev/View/Popup/Contacts.js index 1eb9638f1..6b2832092 100644 --- a/dev/View/Popup/Contacts.js +++ b/dev/View/Popup/Contacts.js @@ -1,4 +1,3 @@ - import window from 'window'; import _ from '_'; import $ from '$'; @@ -7,22 +6,34 @@ import key from 'key'; import Jua from 'Jua'; import { - SaveSettingsStep, ContactPropertyType, ComposeType, - Capa, Magics, StorageResultType, Notification, KeyState + SaveSettingsStep, + ContactPropertyType, + ComposeType, + Capa, + Magics, + StorageResultType, + Notification, + KeyState } from 'Common/Enums'; import { - delegateRunOnDestroy, computedPagenatorHelper, - inArray, trim, windowResizeCallback, - isNonEmptyArray, fakeMd5, pInt, isUnd + delegateRunOnDestroy, + computedPagenatorHelper, + inArray, + trim, + windowResizeCallback, + isNonEmptyArray, + fakeMd5, + pInt, + isUnd } from 'Common/Utils'; -import {CONTACTS_PER_PAGE} from 'Common/Consts'; -import {bMobileDevice} from 'Common/Globals'; +import { CONTACTS_PER_PAGE } from 'Common/Consts'; +import { bMobileDevice } from 'Common/Globals'; -import {Selector} from 'Common/Selector'; -import {exportContactsVcf, exportContactsCsv, uploadContacts} from 'Common/Links'; -import {i18n, getNotification} from 'Common/Translator'; +import { Selector } from 'Common/Selector'; +import { exportContactsVcf, exportContactsCsv, uploadContacts } from 'Common/Links'; +import { i18n, getNotification } from 'Common/Translator'; import SettingsStore from 'Stores/User/Settings'; import ContactStore from 'Stores/User/Contact'; @@ -31,31 +42,29 @@ import Remote from 'Remote/User/Ajax'; import * as Settings from 'Storage/Settings'; -import {EmailModel} from 'Model/Email'; -import {ContactModel} from 'Model/Contact'; -import {ContactPropertyModel} from 'Model/ContactProperty'; +import { EmailModel } from 'Model/Email'; +import { ContactModel } from 'Model/Contact'; +import { ContactPropertyModel } from 'Model/ContactProperty'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command, showScreenPopup, hideScreenPopup, routeOn, routeOff} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command, showScreenPopup, hideScreenPopup, routeOn, routeOff } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Contacts', templateID: 'PopupsContacts' }) -class ContactsPopupView extends AbstractViewNext -{ +class ContactsPopupView extends AbstractViewNext { constructor() { super(); - const - fFastClearEmptyListHelper = (list) => { - if (list && 0 < list.length) { - this.viewProperties.removeAll(list); - delegateRunOnDestroy(list); - } - }; + const fFastClearEmptyListHelper = (list) => { + if (list && 0 < list.length) { + this.viewProperties.removeAll(list); + delegateRunOnDestroy(list); + } + }; this.bBackToCompose = false; this.sLastComposeFocusedField = ''; @@ -98,36 +107,28 @@ class ContactsPopupView extends AbstractViewNext // ); this.viewPropertiesOther = ko.computed(() => { - const list = _.filter(this.viewProperties(), + const list = _.filter( + this.viewProperties(), (property) => -1 < inArray(property.type(), [ContactPropertyType.Nick]) ); return _.sortBy(list, (property) => property.type()); }); - this.viewPropertiesEmails = this.viewProperties.filter( - (property) => ContactPropertyType.Email === property.type() - ); + this.viewPropertiesEmails = this.viewProperties.filter((property) => ContactPropertyType.Email === property.type()); - this.viewPropertiesWeb = this.viewProperties.filter( - (property) => ContactPropertyType.Web === property.type() - ); + this.viewPropertiesWeb = this.viewProperties.filter((property) => ContactPropertyType.Web === property.type()); this.viewHasNonEmptyRequaredProperties = ko.computed(() => { - const - names = this.viewPropertiesNames(), + const names = this.viewPropertiesNames(), emails = this.viewPropertiesEmails(), fFilter = (property) => '' !== trim(property.value()); return !!(_.find(names, fFilter) || _.find(emails, fFilter)); }); - this.viewPropertiesPhones = this.viewProperties.filter( - (property) => ContactPropertyType.Phone === property.type() - ); + this.viewPropertiesPhones = this.viewProperties.filter((property) => ContactPropertyType.Phone === property.type()); - this.viewPropertiesEmailsNonEmpty = this.viewPropertiesNames.filter( - (property) => '' !== trim(property.value()) - ); + this.viewPropertiesEmailsNonEmpty = this.viewPropertiesNames.filter((property) => '' !== trim(property.value())); this.viewPropertiesEmailsEmptyAndOnFocused = this.viewPropertiesEmails.filter((property) => { const foc = property.focused(); @@ -144,8 +145,8 @@ class ContactsPopupView extends AbstractViewNext return '' === trim(property.value()) && !foc; }); - this.viewPropertiesOtherEmptyAndOnFocused = ko.computed( - () => _.filter(this.viewPropertiesOther(), (property) => { + this.viewPropertiesOtherEmptyAndOnFocused = ko.computed(() => + _.filter(this.viewPropertiesOther(), (property) => { const foc = property.focused(); return '' === trim(property.value()) && !foc; }) @@ -178,31 +179,32 @@ class ContactsPopupView extends AbstractViewNext this.contacts.subscribe(windowResizeCallback); this.viewProperties.subscribe(windowResizeCallback); - this.contactsChecked = ko.computed( - () => _.filter(this.contacts(), (item) => item.checked()) - ); + this.contactsChecked = ko.computed(() => _.filter(this.contacts(), (item) => item.checked())); this.contactsCheckedOrSelected = ko.computed(() => { - const - checked = this.contactsChecked(), + const checked = this.contactsChecked(), selected = this.currentContact(); return _.union(checked, selected ? [selected] : []); }); - this.contactsCheckedOrSelectedUids = ko.computed( - () => _.map(this.contactsCheckedOrSelected(), (contact) => contact.idContact) + this.contactsCheckedOrSelectedUids = ko.computed(() => + _.map(this.contactsCheckedOrSelected(), (contact) => contact.idContact) ); this.selector = new Selector( - this.contacts, this.currentContact, null, - '.e-contact-item .actionHandle', '.e-contact-item.selected', - '.e-contact-item .checkboxItem', '.e-contact-item.focused'); + this.contacts, + this.currentContact, + null, + '.e-contact-item .actionHandle', + '.e-contact-item.selected', + '.e-contact-item .checkboxItem', + '.e-contact-item.focused' + ); this.selector.on('onItemSelect', (contact) => { this.populateViewContact(contact ? contact : null); - if (!contact) - { + if (!contact) { this.emptySelection(true); } }); @@ -219,8 +221,7 @@ class ContactsPopupView extends AbstractViewNext // this.saveCommandDebounce = _.debounce(_.bind(this.saveCommand, this), 1000); this.viewHash.subscribe(() => { - if (this.watchHash() && !this.viewReadOnly() && !this.watchDirty()) - { + if (this.watchHash() && !this.viewReadOnly() && !this.watchDirty()) { this.watchDirty(true); } }); @@ -242,30 +243,23 @@ class ContactsPopupView extends AbstractViewNext @command((self) => 0 < self.contactsCheckedOrSelected().length) newMessageCommand() { - - if (!Settings.capa(Capa.Composer)) - { + if (!Settings.capa(Capa.Composer)) { return false; } - let - aE = [], + let aE = [], toEmails = null, ccEmails = null, bccEmails = null; const aC = this.contactsCheckedOrSelected(); - if (isNonEmptyArray(aC)) - { + if (isNonEmptyArray(aC)) { aE = _.map(aC, (oItem) => { - if (oItem) - { - const - data = oItem.getNameAndEmailHelper(), + if (oItem) { + const data = oItem.getNameAndEmailHelper(), email = data ? new EmailModel(data[0], data[1]) : null; - if (email && email.validate()) - { + if (email && email.validate()) { return email; } } @@ -276,14 +270,12 @@ class ContactsPopupView extends AbstractViewNext aE = _.compact(aE); } - if (isNonEmptyArray(aE)) - { + if (isNonEmptyArray(aE)) { this.bBackToCompose = false; hideScreenPopup(ContactsPopupView); - switch (this.sLastComposeFocusedField) - { + switch (this.sLastComposeFocusedField) { case 'cc': ccEmails = aE; break; @@ -312,67 +304,66 @@ class ContactsPopupView extends AbstractViewNext } @command((self) => { - const - bV = self.viewHasNonEmptyRequaredProperties(), + const bV = self.viewHasNonEmptyRequaredProperties(), bReadOnly = self.viewReadOnly(); return !self.viewSaving() && bV && !bReadOnly; }) saveCommand() { - this.viewSaving(true); this.viewSaveTrigger(SaveSettingsStep.Animate); - const - requestUid = fakeMd5(), + const requestUid = fakeMd5(), properties = []; _.each(this.viewProperties(), (oItem) => { - if (oItem.type() && oItem.type() !== ContactPropertyType.FullName && '' !== trim(oItem.value())) - { + if (oItem.type() && oItem.type() !== ContactPropertyType.FullName && '' !== trim(oItem.value())) { properties.push([oItem.type(), oItem.value(), oItem.typeStr()]); } }); - Remote.contactSave((sResult, oData) => { + Remote.contactSave( + (sResult, oData) => { + let res = false; + this.viewSaving(false); - let res = false; - this.viewSaving(false); + if ( + StorageResultType.Success === sResult && + oData && + oData.Result && + oData.Result.RequestUid === requestUid && + 0 < pInt(oData.Result.ResultID) + ) { + if ('' === this.viewID()) { + this.viewID(pInt(oData.Result.ResultID)); + } - if (StorageResultType.Success === sResult && oData && oData.Result && - oData.Result.RequestUid === requestUid && 0 < pInt(oData.Result.ResultID)) - { - if ('' === this.viewID()) - { - this.viewID(pInt(oData.Result.ResultID)); + this.reloadContactList(); + res = true; } - this.reloadContactList(); - res = true; - } - - _.delay(() => { - this.viewSaveTrigger(res ? SaveSettingsStep.TrueResult : SaveSettingsStep.FalseResult); - }, Magics.Time350ms); - - if (res) - { - this.watchDirty(false); - _.delay(() => { - this.viewSaveTrigger(SaveSettingsStep.Idle); - }, Magics.Time1s); - } + this.viewSaveTrigger(res ? SaveSettingsStep.TrueResult : SaveSettingsStep.FalseResult); + }, Magics.Time350ms); - }, requestUid, this.viewID(), properties); + if (res) { + this.watchDirty(false); + + _.delay(() => { + this.viewSaveTrigger(SaveSettingsStep.Idle); + }, Magics.Time1s); + } + }, + requestUid, + this.viewID(), + properties + ); } @command((self) => !self.contacts.syncing() && !self.contacts.importing()) syncCommand() { getApp().contactsSync((result, data) => { - if (StorageResultType.Success !== result || !data || !data.Result) - { - window.alert(getNotification( - data && data.ErrorCode ? data.ErrorCode : Notification.ContactsSyncError)); + if (StorageResultType.Success !== result || !data || !data.Result) { + window.alert(getNotification(data && data.ErrorCode ? data.ErrorCode : Notification.ContactsSyncError)); } this.reloadContactList(true); @@ -381,8 +372,7 @@ class ContactsPopupView extends AbstractViewNext getPropertyPlaceholder(type) { let result = ''; - switch (type) - { + switch (type) { case ContactPropertyType.LastName: result = 'CONTACTS/PLACEHOLDER_ENTER_LAST_NAME'; break; @@ -399,17 +389,16 @@ class ContactsPopupView extends AbstractViewNext } addNewProperty(type, typeStr) { - this.viewProperties.push(new ContactPropertyModel(type, typeStr || '', '', true, this.getPropertyPlaceholder(type))); + this.viewProperties.push( + new ContactPropertyModel(type, typeStr || '', '', true, this.getPropertyPlaceholder(type)) + ); } addNewOrFocusProperty(type, typeStr) { const item = _.find(this.viewProperties(), (prop) => type === prop.type()); - if (item) - { + if (item) { item.focused(true); - } - else - { + } else { this.addNewProperty(type, typeStr); } } @@ -447,53 +436,42 @@ class ContactsPopupView extends AbstractViewNext } initUploader() { - if (this.importUploaderButton()) - { - const - j = new Jua({ - 'action': uploadContacts(), - 'name': 'uploader', - 'queueSize': 1, - 'multipleSizeLimit': 1, - 'disableDragAndDrop': true, - 'disableMultiple': true, - 'disableDocumentDropPrevent': true, - 'clickElement': this.importUploaderButton() - }); + if (this.importUploaderButton()) { + const j = new Jua({ + 'action': uploadContacts(), + 'name': 'uploader', + 'queueSize': 1, + 'multipleSizeLimit': 1, + 'disableDragAndDrop': true, + 'disableMultiple': true, + 'disableDocumentDropPrevent': true, + 'clickElement': this.importUploaderButton() + }); - if (j) - { - j - .on('onStart', () => { - this.contacts.importing(true); - }) - .on('onComplete', (id, result, data) => { - this.contacts.importing(false); - this.reloadContactList(); - if (!id || !result || !data || !data.Result) - { - window.alert(i18n('CONTACTS/ERROR_IMPORT_FILE')); - } - }); + if (j) { + j.on('onStart', () => { + this.contacts.importing(true); + }).on('onComplete', (id, result, data) => { + this.contacts.importing(false); + this.reloadContactList(); + if (!id || !result || !data || !data.Result) { + window.alert(i18n('CONTACTS/ERROR_IMPORT_FILE')); + } + }); } } } removeCheckedOrSelectedContactsFromList() { - const - koContacts = this.contacts, + const koContacts = this.contacts, contacts = this.contactsCheckedOrSelected(); - let - currentContact = this.currentContact(), + let currentContact = this.currentContact(), count = this.contacts().length; - if (0 < contacts.length) - { + if (0 < contacts.length) { _.each(contacts, (contact) => { - - if (currentContact && currentContact.idContact === contact.idContact) - { + if (currentContact && currentContact.idContact === contact.idContact) { currentContact = null; this.currentContact(null); } @@ -502,8 +480,7 @@ class ContactsPopupView extends AbstractViewNext count -= 1; }); - if (0 >= count) - { + if (0 >= count) { this.bDropPageAfterDelete = true; } @@ -517,12 +494,8 @@ class ContactsPopupView extends AbstractViewNext } deleteSelectedContacts() { - if (0 < this.contactsCheckedOrSelected().length) - { - Remote.contactsDelete( - _.bind(this.deleteResponse, this), - this.contactsCheckedOrSelectedUids() - ); + if (0 < this.contactsCheckedOrSelected().length) { + Remote.contactsDelete(_.bind(this.deleteResponse, this), this.contactsCheckedOrSelectedUids()); this.removeCheckedOrSelectedContactsFromList(); } @@ -533,12 +506,9 @@ class ContactsPopupView extends AbstractViewNext * @param {AjaxJsonDefaultResponse} oData */ deleteResponse(sResult, oData) { - if (Magics.Time500ms < (StorageResultType.Success === sResult && oData && oData.Time ? pInt(oData.Time) : 0)) - { + if (Magics.Time500ms < (StorageResultType.Success === sResult && oData && oData.Time ? pInt(oData.Time) : 0)) { this.reloadContactList(this.bDropPageAfterDelete); - } - else - { + } else { _.delay(() => { this.reloadContactList(this.bDropPageAfterDelete); }, Magics.Time500ms); @@ -554,36 +524,26 @@ class ContactsPopupView extends AbstractViewNext * @param {?ContactModel} contact */ populateViewContact(contact) { - let - id = '', + let id = '', lastName = '', firstName = ''; - const - list = []; + const list = []; this.watchHash(false); this.emptySelection(false); this.viewReadOnly(false); - if (contact) - { + if (contact) { id = contact.idContact; - if (isNonEmptyArray(contact.properties)) - { + if (isNonEmptyArray(contact.properties)) { _.each(contact.properties, (property) => { - if (property && property[0]) - { - if (ContactPropertyType.LastName === property[0]) - { + if (property && property[0]) { + if (ContactPropertyType.LastName === property[0]) { lastName = property[1]; - } - else if (ContactPropertyType.FirstName === property[0]) - { + } else if (ContactPropertyType.FirstName === property[0]) { firstName = property[1]; - } - else - { + } else { list.push(new ContactPropertyModel(property[0], property[2] || '', property[1])); } } @@ -593,11 +553,25 @@ class ContactsPopupView extends AbstractViewNext this.viewReadOnly(!!contact.readOnly); } - list.unshift(new ContactPropertyModel(ContactPropertyType.LastName, '', lastName, false, - this.getPropertyPlaceholder(ContactPropertyType.LastName))); + list.unshift( + new ContactPropertyModel( + ContactPropertyType.LastName, + '', + lastName, + false, + this.getPropertyPlaceholder(ContactPropertyType.LastName) + ) + ); - list.unshift(new ContactPropertyModel(ContactPropertyType.FirstName, '', firstName, !contact, - this.getPropertyPlaceholder(ContactPropertyType.FirstName))); + list.unshift( + new ContactPropertyModel( + ContactPropertyType.FirstName, + '', + firstName, + !contact, + this.getPropertyPlaceholder(ContactPropertyType.FirstName) + ) + ); this.viewID(id); @@ -614,49 +588,47 @@ class ContactsPopupView extends AbstractViewNext * @param {boolean=} dropPagePosition = false */ reloadContactList(dropPagePosition = false) { - let offset = (this.contactsPage() - 1) * CONTACTS_PER_PAGE; this.bDropPageAfterDelete = false; - if (dropPagePosition) - { + if (dropPagePosition) { this.contactsPage(1); offset = 0; } this.contacts.loading(true); - Remote.contacts((result, data) => { + Remote.contacts( + (result, data) => { + let count = 0, + list = []; - let - count = 0, - list = []; + if (StorageResultType.Success === result && data && data.Result && data.Result.List) { + if (isNonEmptyArray(data.Result.List)) { + list = _.map(data.Result.List, (item) => { + const contact = new ContactModel(); + return contact.parse(item) ? contact : null; + }); - if (StorageResultType.Success === result && data && data.Result && data.Result.List) - { - if (isNonEmptyArray(data.Result.List)) - { - list = _.map(data.Result.List, (item) => { - const contact = new ContactModel(); - return contact.parse(item) ? contact : null; - }); + list = _.compact(list); - list = _.compact(list); - - count = pInt(data.Result.Count); - count = 0 < count ? count : 0; + count = pInt(data.Result.Count); + count = 0 < count ? count : 0; + } } - } - this.contactsCount(count); + this.contactsCount(count); - delegateRunOnDestroy(this.contacts()); - this.contacts(list); + delegateRunOnDestroy(this.contacts()); + this.contacts(list); - this.contacts.loading(false); - this.viewClearSearch('' !== this.search()); - - }, offset, CONTACTS_PER_PAGE, this.search()); + this.contacts.loading(false); + this.viewClearSearch('' !== this.search()); + }, + offset, + CONTACTS_PER_PAGE, + this.search() + ); } onBuild(dom) { @@ -677,15 +649,14 @@ class ContactsPopupView extends AbstractViewNext const self = this; - dom - .on('click', '.e-pagenator .e-page', function() { // eslint-disable-line prefer-arrow-callback - const page = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (page) - { - self.contactsPage(pInt(page.value)); - self.reloadContactList(); - } - }); + dom.on('click', '.e-pagenator .e-page', function() { + // eslint-disable-line prefer-arrow-callback + const page = ko.dataFor(this); // eslint-disable-line no-invalid-this + if (page) { + self.contactsPage(pInt(page.value)); + self.reloadContactList(); + } + }); this.initUploader(); } @@ -711,16 +682,14 @@ class ContactsPopupView extends AbstractViewNext this.sLastComposeFocusedField = ''; - if (this.bBackToCompose) - { + if (this.bBackToCompose) { this.bBackToCompose = false; - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose')); } } } } -export {ContactsPopupView, ContactsPopupView as default}; +export { ContactsPopupView, ContactsPopupView as default }; diff --git a/dev/View/Popup/Domain.js b/dev/View/Popup/Domain.js index da99ea46d..58018dcb8 100644 --- a/dev/View/Popup/Domain.js +++ b/dev/View/Popup/Domain.js @@ -1,28 +1,26 @@ - import _ from '_'; import ko from 'ko'; -import {StorageResultType, ServerSecure, Ports, Notification} from 'Common/Enums'; -import {IMAP_DEFAULT_PORT, SIEVE_DEFAULT_PORT, SMTP_DEFAULT_PORT} from 'Common/Consts'; -import {bMobileDevice} from 'Common/Globals'; -import {trim, pInt, pString} from 'Common/Utils'; -import {i18n} from 'Common/Translator'; +import { StorageResultType, ServerSecure, Ports, Notification } from 'Common/Enums'; +import { IMAP_DEFAULT_PORT, SIEVE_DEFAULT_PORT, SMTP_DEFAULT_PORT } from 'Common/Consts'; +import { bMobileDevice } from 'Common/Globals'; +import { trim, pInt, pString } from 'Common/Utils'; +import { i18n } from 'Common/Translator'; import CapaAdminStore from 'Stores/Admin/Capa'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Domain', templateID: 'PopupsDomain' }) -class DomainPopupView extends AbstractViewNext -{ +class DomainPopupView extends AbstractViewNext { constructor() { super(); @@ -42,22 +40,19 @@ class DomainPopupView extends AbstractViewNext this.testingSmtpErrorDesc = ko.observable(''); this.testingImapError.subscribe((value) => { - if (!value) - { + if (!value) { this.testingImapErrorDesc(''); } }); this.testingSieveError.subscribe((value) => { - if (!value) - { + if (!value) { this.testingSieveErrorDesc(''); } }); this.testingSmtpError.subscribe((value) => { - if (!value) - { + if (!value) { this.testingSmtpErrorDesc(''); } }); @@ -92,49 +87,43 @@ class DomainPopupView extends AbstractViewNext this.allowSieve = ko.computed(() => CapaAdminStore.filters() && CapaAdminStore.sieve()); this.headerText = ko.computed(() => { - - const - name = this.name(), + const name = this.name(), aliasName = this.aliasName(); let result = ''; - if (this.edit()) - { - result = i18n('POPUPS_DOMAIN/TITLE_EDIT_DOMAIN', {'NAME': name}); - if (aliasName) - { + if (this.edit()) { + result = i18n('POPUPS_DOMAIN/TITLE_EDIT_DOMAIN', { 'NAME': name }); + if (aliasName) { result += ' ← ' + aliasName; } - } - else - { - result = ('' === name ? i18n('POPUPS_DOMAIN/TITLE_ADD_DOMAIN') : - i18n('POPUPS_DOMAIN/TITLE_ADD_DOMAIN_WITH_NAME', {'NAME': name})); + } else { + result = + '' === name + ? i18n('POPUPS_DOMAIN/TITLE_ADD_DOMAIN') + : i18n('POPUPS_DOMAIN/TITLE_ADD_DOMAIN_WITH_NAME', { 'NAME': name }); } return result; - }); this.domainDesc = ko.computed(() => { const name = this.name(); - return !this.edit() && name ? i18n('POPUPS_DOMAIN/NEW_DOMAIN_DESC', {'NAME': '*@' + name}) : ''; + return !this.edit() && name ? i18n('POPUPS_DOMAIN/NEW_DOMAIN_DESC', { 'NAME': '*@' + name }) : ''; }); this.domainIsComputed = ko.computed(() => { - - const - usePhpMail = this.smtpPhpMail(), + const usePhpMail = this.smtpPhpMail(), allowSieve = this.allowSieve(), useSieve = this.useSieve(); - return '' !== this.name() && + return ( + '' !== this.name() && '' !== this.imapServer() && '' !== this.imapPort() && - (allowSieve && useSieve ? ('' !== this.sieveServer() && '' !== this.sievePort()) : true) && - (('' !== this.smtpServer() && '' !== this.smtpPort()) || usePhpMail); - + (allowSieve && useSieve ? '' !== this.sieveServer() && '' !== this.sievePort() : true) && + (('' !== this.smtpServer() && '' !== this.smtpPort()) || usePhpMail) + ); }); this.canBeTested = ko.computed(() => !this.testing() && this.domainIsComputed()); @@ -146,42 +135,35 @@ class DomainPopupView extends AbstractViewNext // smart form improvements this.imapServerFocus.subscribe((value) => { - if (value && '' !== this.name() && '' === this.imapServer()) - { + if (value && '' !== this.name() && '' === this.imapServer()) { this.imapServer(this.name().replace(/[.]?[*][.]?/g, '')); } }); this.sieveServerFocus.subscribe((value) => { - if (value && '' !== this.imapServer() && '' === this.sieveServer()) - { + if (value && '' !== this.imapServer() && '' === this.sieveServer()) { this.sieveServer(this.imapServer()); } }); this.smtpServerFocus.subscribe((value) => { - if (value && '' !== this.imapServer() && '' === this.smtpServer()) - { - this.smtpServer(this.imapServer().replace(/imap/ig, 'smtp')); + if (value && '' !== this.imapServer() && '' === this.smtpServer()) { + this.smtpServer(this.imapServer().replace(/imap/gi, 'smtp')); } }); this.imapSecure.subscribe((value) => { - if (this.enableSmartPorts()) - { + if (this.enableSmartPorts()) { const port = pInt(this.imapPort()); - switch (pString(value)) - { + switch (pString(value)) { case '0': case '2': - if (Ports.ImapSsl === port) - { + if (Ports.ImapSsl === port) { this.imapPort(pString(Ports.Imap)); } break; case '1': - if (Ports.Imap === port) - { + if (Ports.Imap === port) { this.imapPort(pString(Ports.ImapSsl)); } break; @@ -191,26 +173,21 @@ class DomainPopupView extends AbstractViewNext }); this.smtpSecure.subscribe((value) => { - if (this.enableSmartPorts()) - { + if (this.enableSmartPorts()) { const port = pInt(this.smtpPort()); - switch (pString(value)) - { + switch (pString(value)) { case '0': - if (Ports.SmtpSsl === port || Ports.SmtpStartTls === port) - { + if (Ports.SmtpSsl === port || Ports.SmtpStartTls === port) { this.smtpPort(pString(Ports.Smtp)); } break; case '1': - if (Ports.Smtp === port || Ports.SmtpStartTls === port) - { + if (Ports.Smtp === port || Ports.SmtpStartTls === port) { this.smtpPort(pString(Ports.SmtpSsl)); } break; case '2': - if (Ports.Smtp === port || Ports.SmtpSsl === port) - { + if (Ports.Smtp === port || Ports.SmtpSsl === port) { this.smtpPort(pString(Ports.SmtpStartTls)); } break; @@ -252,7 +229,6 @@ class DomainPopupView extends AbstractViewNext @command((self) => self.canBeTested()) testConnectionCommand() { - this.page('main'); this.testingDone(false); @@ -300,10 +276,8 @@ class DomainPopupView extends AbstractViewNext onTestConnectionResponse(sResult, oData) { this.testing(false); - if (StorageResultType.Success === sResult && oData.Result) - { - let - bImap = false, + if (StorageResultType.Success === sResult && oData.Result) { + let bImap = false, bSieve = false; this.testingDone(true); @@ -311,40 +285,31 @@ class DomainPopupView extends AbstractViewNext this.testingSieveError(true !== oData.Result.Sieve); this.testingSmtpError(true !== oData.Result.Smtp); - if (this.testingImapError() && oData.Result.Imap) - { + if (this.testingImapError() && oData.Result.Imap) { bImap = true; this.testingImapErrorDesc(''); this.testingImapErrorDesc(oData.Result.Imap); } - if (this.testingSieveError() && oData.Result.Sieve) - { + if (this.testingSieveError() && oData.Result.Sieve) { bSieve = true; this.testingSieveErrorDesc(''); this.testingSieveErrorDesc(oData.Result.Sieve); } - if (this.testingSmtpError() && oData.Result.Smtp) - { + if (this.testingSmtpError() && oData.Result.Smtp) { this.testingSmtpErrorDesc(''); this.testingSmtpErrorDesc(oData.Result.Smtp); } - if (this.sieveSettings()) - { - if (!bSieve && bImap) - { + if (this.sieveSettings()) { + if (!bSieve && bImap) { this.sieveSettings(false); } - } - else if (bSieve && !bImap) - { + } else if (bSieve && !bImap) { this.sieveSettings(true); } - } - else - { + } else { this.testingImapError(true); this.testingSieveError(true); this.testingSmtpError(true); @@ -354,20 +319,14 @@ class DomainPopupView extends AbstractViewNext onDomainCreateOrSaveResponse(sResult, oData) { this.saving(false); - if (StorageResultType.Success === sResult && oData) - { - if (oData.Result) - { + if (StorageResultType.Success === sResult && oData) { + if (oData.Result) { getApp().reloadDomainList(); this.closeCommand(); - } - else if (Notification.DomainAlreadyExists === oData.ErrorCode) - { + } else if (Notification.DomainAlreadyExists === oData.ErrorCode) { this.savingError(i18n('ERRORS/DOMAIN_ALREADY_EXISTS')); } - } - else - { + } else { this.savingError(i18n('ERRORS/UNKNOWN_ERROR')); } } @@ -394,8 +353,7 @@ class DomainPopupView extends AbstractViewNext this.clearTesting(); this.clearForm(); - if (oDomain) - { + if (oDomain) { this.enableSmartPorts(false); this.edit(true); @@ -424,8 +382,7 @@ class DomainPopupView extends AbstractViewNext } onShowWithDelay() { - if ('' === this.name() && !bMobileDevice) - { + if ('' === this.name() && !bMobileDevice) { this.name.focused(true); } } @@ -467,4 +424,4 @@ class DomainPopupView extends AbstractViewNext } } -export {DomainPopupView, DomainPopupView as default}; +export { DomainPopupView, DomainPopupView as default }; diff --git a/dev/View/Popup/DomainAlias.js b/dev/View/Popup/DomainAlias.js index cc4d17a31..d0f03960d 100644 --- a/dev/View/Popup/DomainAlias.js +++ b/dev/View/Popup/DomainAlias.js @@ -1,26 +1,24 @@ - import _ from '_'; import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {bMobileDevice} from 'Common/Globals'; -import {i18n} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { bMobileDevice } from 'Common/Globals'; +import { i18n } from 'Common/Translator'; import DomainStore from 'Stores/Admin/Domain'; import Remote from 'Remote/Admin/Ajax'; -import {getApp} from 'Helper/Apps/Admin'; +import { getApp } from 'Helper/Apps/Admin'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/DomainAlias', templateID: 'PopupsDomainAlias' }) -class DomainAliasPopupView extends AbstractViewNext -{ +class DomainAliasPopupView extends AbstractViewNext { constructor() { super(); @@ -34,8 +32,8 @@ class DomainAliasPopupView extends AbstractViewNext this.domains = DomainStore.domainsWithoutAliases; - this.domainsOptions = ko.computed( - () => _.map(this.domains(), (item) => ({optValue: item.name, optText: item.name})) + this.domainsOptions = ko.computed(() => + _.map(this.domains(), (item) => ({ optValue: item.name, optText: item.name })) ); this.canBeSaved = ko.computed(() => !this.saving() && '' !== this.name() && '' !== this.alias()); @@ -46,29 +44,19 @@ class DomainAliasPopupView extends AbstractViewNext @command((self) => self.canBeSaved()) createCommand() { this.saving(true); - Remote.createDomainAlias( - this.onDomainAliasCreateOrSaveResponse, - this.name(), - this.alias() - ); + Remote.createDomainAlias(this.onDomainAliasCreateOrSaveResponse, this.name(), this.alias()); } onDomainAliasCreateOrSaveResponse(result, data) { this.saving(false); - if (StorageResultType.Success === result && data) - { - if (data.Result) - { + if (StorageResultType.Success === result && data) { + if (data.Result) { getApp().reloadDomainList(); this.closeCommand(); - } - else if (Notification.DomainAlreadyExists === data.ErrorCode) - { + } else if (Notification.DomainAlreadyExists === data.ErrorCode) { this.savingError(i18n('ERRORS/DOMAIN_ALREADY_EXISTS')); } - } - else - { + } else { this.savingError(i18n('ERRORS/UNKNOWN_ERROR')); } } @@ -78,8 +66,7 @@ class DomainAliasPopupView extends AbstractViewNext } onShowWithDelay() { - if ('' === this.name() && !bMobileDevice) - { + if ('' === this.name() && !bMobileDevice) { this.name.focused(true); } } @@ -95,4 +82,4 @@ class DomainAliasPopupView extends AbstractViewNext } } -export {DomainAliasPopupView, DomainAliasPopupView as default}; +export { DomainAliasPopupView, DomainAliasPopupView as default }; diff --git a/dev/View/Popup/Filter.js b/dev/View/Popup/Filter.js index 737276229..42c1c4d15 100644 --- a/dev/View/Popup/Filter.js +++ b/dev/View/Popup/Filter.js @@ -1,24 +1,22 @@ - import _ from '_'; import ko from 'ko'; -import {FiltersAction, FilterConditionField, FilterConditionType} from 'Common/Enums'; -import {bMobileDevice} from 'Common/Globals'; -import {defautOptionsAfterRender, delegateRun} from 'Common/Utils'; -import {i18n, initOnStartOrLangChange} from 'Common/Translator'; +import { FiltersAction, FilterConditionField, FilterConditionType } from 'Common/Enums'; +import { bMobileDevice } from 'Common/Globals'; +import { defautOptionsAfterRender, delegateRun } from 'Common/Utils'; +import { i18n, initOnStartOrLangChange } from 'Common/Translator'; import FilterStore from 'Stores/User/Filter'; import FolderStore from 'Stores/User/Folder'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Filter', templateID: 'PopupsFilter' }) -class FilterPopupView extends AbstractViewNext -{ +class FilterPopupView extends AbstractViewNext { constructor() { super(); @@ -36,8 +34,7 @@ class FilterPopupView extends AbstractViewNext this.selectedFolderValue = ko.observable(''); this.selectedFolderValue.subscribe(() => { - if (this.filter()) - { + if (this.filter()) { this.filter().actionValue.error(false); } }); @@ -54,26 +51,20 @@ class FilterPopupView extends AbstractViewNext @command() saveFilterCommand() { - - if (this.filter()) - { - if (FiltersAction.MoveTo === this.filter().actionType()) - { + if (this.filter()) { + if (FiltersAction.MoveTo === this.filter().actionType()) { this.filter().actionValue(this.selectedFolderValue()); } - if (!this.filter().verify()) - { + if (!this.filter().verify()) { return false; } - if (this.fTrueCallback) - { + if (this.fTrueCallback) { this.fTrueCallback(this.filter()); } - if (this.modalVisibility()) - { + if (this.modalVisibility()) { delegateRun(this, 'closeCommand'); } } @@ -88,71 +79,66 @@ class FilterPopupView extends AbstractViewNext // 'name': i18n('POPUPS_FILTER/SELECT_ACTION_NONE')}); const modules = this.modules(); - if (modules) - { - if (modules.markasread) - { + if (modules) { + if (modules.markasread) { this.allowMarkAsRead(true); } - if (modules.moveto) - { - this.actionTypeOptions.push({'id': FiltersAction.MoveTo, - 'name': i18n('POPUPS_FILTER/SELECT_ACTION_MOVE_TO')}); + if (modules.moveto) { + this.actionTypeOptions.push({ + 'id': FiltersAction.MoveTo, + 'name': i18n('POPUPS_FILTER/SELECT_ACTION_MOVE_TO') + }); } - if (modules.redirect) - { - this.actionTypeOptions.push({'id': FiltersAction.Forward, - 'name': i18n('POPUPS_FILTER/SELECT_ACTION_FORWARD_TO')}); + if (modules.redirect) { + this.actionTypeOptions.push({ + 'id': FiltersAction.Forward, + 'name': i18n('POPUPS_FILTER/SELECT_ACTION_FORWARD_TO') + }); } - if (modules.reject) - { - this.actionTypeOptions.push({'id': FiltersAction.Reject, - 'name': i18n('POPUPS_FILTER/SELECT_ACTION_REJECT')}); + if (modules.reject) { + this.actionTypeOptions.push({ 'id': FiltersAction.Reject, 'name': i18n('POPUPS_FILTER/SELECT_ACTION_REJECT') }); } - if (modules.vacation) - { - this.actionTypeOptions.push({'id': FiltersAction.Vacation, - 'name': i18n('POPUPS_FILTER/SELECT_ACTION_VACATION_MESSAGE')}); - + if (modules.vacation) { + this.actionTypeOptions.push({ + 'id': FiltersAction.Vacation, + 'name': i18n('POPUPS_FILTER/SELECT_ACTION_VACATION_MESSAGE') + }); } } - this.actionTypeOptions.push({'id': FiltersAction.Discard, - 'name': i18n('POPUPS_FILTER/SELECT_ACTION_DISCARD')}); + this.actionTypeOptions.push({ 'id': FiltersAction.Discard, 'name': i18n('POPUPS_FILTER/SELECT_ACTION_DISCARD') }); this.fieldOptions([ - {'id': FilterConditionField.From, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_FROM')}, - {'id': FilterConditionField.Recipient, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_RECIPIENTS')}, - {'id': FilterConditionField.Subject, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_SUBJECT')}, - {'id': FilterConditionField.Size, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_SIZE')}, - {'id': FilterConditionField.Header, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_HEADER')} + { 'id': FilterConditionField.From, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_FROM') }, + { 'id': FilterConditionField.Recipient, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_RECIPIENTS') }, + { 'id': FilterConditionField.Subject, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_SUBJECT') }, + { 'id': FilterConditionField.Size, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_SIZE') }, + { 'id': FilterConditionField.Header, 'name': i18n('POPUPS_FILTER/SELECT_FIELD_HEADER') } ]); this.typeOptions([ - {'id': FilterConditionType.Contains, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_CONTAINS')}, - {'id': FilterConditionType.NotContains, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_NOT_CONTAINS')}, - {'id': FilterConditionType.EqualTo, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_EQUAL_TO')}, - {'id': FilterConditionType.NotEqualTo, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_NOT_EQUAL_TO')} + { 'id': FilterConditionType.Contains, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_CONTAINS') }, + { 'id': FilterConditionType.NotContains, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_NOT_CONTAINS') }, + { 'id': FilterConditionType.EqualTo, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_EQUAL_TO') }, + { 'id': FilterConditionType.NotEqualTo, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_NOT_EQUAL_TO') } ]); - if (modules && modules.regex) - { - this.typeOptions.push({'id': FilterConditionType.Regex, 'name': 'Regex'}); + if (modules && modules.regex) { + this.typeOptions.push({ 'id': FilterConditionType.Regex, 'name': 'Regex' }); } this.typeOptionsSize([ - {'id': FilterConditionType.Over, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_OVER')}, - {'id': FilterConditionType.Under, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_UNDER')} + { 'id': FilterConditionType.Over, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_OVER') }, + { 'id': FilterConditionType.Under, 'name': i18n('POPUPS_FILTER/SELECT_TYPE_UNDER') } ]); } removeCondition(oConditionToDelete) { - if (this.filter()) - { + if (this.filter()) { this.filter().removeCondition(oConditionToDelete); } } @@ -170,25 +156,22 @@ class FilterPopupView extends AbstractViewNext this.fTrueCallback = fTrueCallback; this.filter(oFilter); - if (oFilter) - { + if (oFilter) { this.selectedFolderValue(oFilter.actionValue()); } this.isNew(!bEdit); - if (!bEdit && oFilter) - { + if (!bEdit && oFilter) { oFilter.name.focused(true); } } onShowWithDelay() { - if (this.isNew() && this.filter() && !bMobileDevice) - { + if (this.isNew() && this.filter() && !bMobileDevice) { this.filter().name.focused(true); } } } -export {FilterPopupView, FilterPopupView as default}; +export { FilterPopupView, FilterPopupView as default }; diff --git a/dev/View/Popup/FolderClear.js b/dev/View/Popup/FolderClear.js index d0948973a..9090ca504 100644 --- a/dev/View/Popup/FolderClear.js +++ b/dev/View/Popup/FolderClear.js @@ -1,25 +1,23 @@ - import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {i18n, getNotification} from 'Common/Translator'; -import {setFolderHash} from 'Common/Cache'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { i18n, getNotification } from 'Common/Translator'; +import { setFolderHash } from 'Common/Cache'; import MessageStore from 'Stores/User/Message'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/FolderClear', templateID: 'PopupsFolderClear' }) -class FolderClearPopupView extends AbstractViewNext -{ +class FolderClearPopupView extends AbstractViewNext { constructor() { super(); @@ -37,23 +35,20 @@ class FolderClearPopupView extends AbstractViewNext return folder ? folder.localName() : ''; }); - this.dangerDescHtml = ko.computed( - () => i18n('POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1', {'FOLDER': this.folderNameForClear()}) + this.dangerDescHtml = ko.computed(() => + i18n('POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1', { 'FOLDER': this.folderNameForClear() }) ); } @command((self) => { - const - folder = self.selectedFolder(), + const folder = self.selectedFolder(), isClearing = self.clearingProcess(); return !isClearing && null !== folder; }) clearCommand() { - const folderToClear = this.selectedFolder(); - if (folderToClear) - { + if (folderToClear) { MessageStore.message(null); MessageStore.messageList([]); @@ -65,21 +60,14 @@ class FolderClearPopupView extends AbstractViewNext setFolderHash(folderToClear.fullNameRaw, ''); Remote.folderClear((result, data) => { - this.clearingProcess(false); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { getApp().reloadMessageList(true); this.cancelCommand(); - } - else - { - if (data && data.ErrorCode) - { + } else { + if (data && data.ErrorCode) { this.clearingError(getNotification(data.ErrorCode)); - } - else - { + } else { this.clearingError(getNotification(Notification.MailServerError)); } } @@ -94,11 +82,10 @@ class FolderClearPopupView extends AbstractViewNext onShow(folder) { this.clearPopup(); - if (folder) - { + if (folder) { this.selectedFolder(folder); } } } -export {FolderClearPopupView, FolderClearPopupView as default}; +export { FolderClearPopupView, FolderClearPopupView as default }; diff --git a/dev/View/Popup/FolderCreate.js b/dev/View/Popup/FolderCreate.js index 8e1526f29..f4187ada7 100644 --- a/dev/View/Popup/FolderCreate.js +++ b/dev/View/Popup/FolderCreate.js @@ -1,26 +1,24 @@ - import ko from 'ko'; -import {Notification} from 'Common/Enums'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {bMobileDevice} from 'Common/Globals'; -import {trim, defautOptionsAfterRender, folderListOptionsBuilder} from 'Common/Utils'; +import { Notification } from 'Common/Enums'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { bMobileDevice } from 'Common/Globals'; +import { trim, defautOptionsAfterRender, folderListOptionsBuilder } from 'Common/Utils'; import FolderStore from 'Stores/User/Folder'; import Promises from 'Promises/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/FolderCreate', templateID: 'PopupsFolderCreate' }) -class FolderCreateView extends AbstractViewNext -{ +class FolderCreateView extends AbstractViewNext { constructor() { super(); @@ -30,22 +28,19 @@ class FolderCreateView extends AbstractViewNext this.selectedParentValue = ko.observable(UNUSED_OPTION_VALUE); this.parentFolderSelectList = ko.computed(() => { - - const - top = [], + const top = [], list = FolderStore.folderList(), - fRenameCallback = (oItem) => (oItem ? (oItem.isSystemFolder() ? oItem.name() + ' ' + oItem.manageFolderSystemName() : oItem.name()) : ''); + fRenameCallback = (oItem) => + oItem ? (oItem.isSystemFolder() ? oItem.name() + ' ' + oItem.manageFolderSystemName() : oItem.name()) : ''; top.push(['', '']); let fDisableCallback = null; - if ('' !== FolderStore.namespace) - { + if ('' !== FolderStore.namespace) { fDisableCallback = (item) => FolderStore.namespace !== item.fullNameRaw.substr(0, FolderStore.namespace.length); } return folderListOptionsBuilder([], list, [], top, null, fDisableCallback, null, fRenameCallback); - }); this.defautOptionsAfterRender = defautOptionsAfterRender; @@ -53,10 +48,8 @@ class FolderCreateView extends AbstractViewNext @command((self) => self.simpleFolderNameValidation(self.folderName())) createFolderCommand() { - let parentFolderName = this.selectedParentValue(); - if ('' === parentFolderName && 1 < FolderStore.namespace.length) - { + if ('' === parentFolderName && 1 < FolderStore.namespace.length) { parentFolderName = FolderStore.namespace.substr(0, FolderStore.namespace.length - 1); } @@ -69,7 +62,7 @@ class FolderCreateView extends AbstractViewNext } simpleFolderNameValidation(sName) { - return (/^[^\\\/]+$/g).test(trim(sName)); + return /^[^\\/]+$/g.test(trim(sName)); } clearPopup() { @@ -83,11 +76,10 @@ class FolderCreateView extends AbstractViewNext } onShowWithDelay() { - if (!bMobileDevice) - { + if (!bMobileDevice) { this.folderName.focused(true); } } } -export {FolderCreateView, FolderCreateView as default}; +export { FolderCreateView, FolderCreateView as default }; diff --git a/dev/View/Popup/FolderSystem.js b/dev/View/Popup/FolderSystem.js index e400ccab9..068a0fcc3 100644 --- a/dev/View/Popup/FolderSystem.js +++ b/dev/View/Popup/FolderSystem.js @@ -1,26 +1,24 @@ - import _ from '_'; import ko from 'ko'; -import {SetSystemFoldersNotification, Magics} from 'Common/Enums'; -import {UNUSED_OPTION_VALUE} from 'Common/Consts'; -import {folderListOptionsBuilder, noop, defautOptionsAfterRender} from 'Common/Utils'; -import {initOnStartOrLangChange, i18n} from 'Common/Translator'; +import { SetSystemFoldersNotification, Magics } from 'Common/Enums'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; +import { folderListOptionsBuilder, noop, defautOptionsAfterRender } from 'Common/Utils'; +import { initOnStartOrLangChange, i18n } from 'Common/Translator'; import FolderStore from 'Stores/User/Folder'; import * as Settings from 'Storage/Settings'; import Remote from 'Remote/User/Ajax'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/FolderSystem', templateID: 'PopupsFolderSystem' }) -class FolderSystemPopupView extends AbstractViewNext -{ +class FolderSystemPopupView extends AbstractViewNext { constructor() { super(); @@ -34,10 +32,19 @@ class FolderSystemPopupView extends AbstractViewNext this.notification = ko.observable(''); - this.folderSelectList = ko.computed( - () => folderListOptionsBuilder([], FolderStore.folderList(), FolderStore.folderListSystemNames(), [ - ['', this.sChooseOnText], [UNUSED_OPTION_VALUE, this.sUnuseText] - ], null, null, null, null, null, true) + this.folderSelectList = ko.computed(() => + folderListOptionsBuilder( + [], + FolderStore.folderList(), + FolderStore.folderListSystemNames(), + [['', this.sChooseOnText], [UNUSED_OPTION_VALUE, this.sUnuseText]], + null, + null, + null, + null, + null, + true + ) ); this.sentFolder = FolderStore.sentFolder; @@ -46,28 +53,24 @@ class FolderSystemPopupView extends AbstractViewNext this.trashFolder = FolderStore.trashFolder; this.archiveFolder = FolderStore.archiveFolder; - const - fSetSystemFolders = () => { + const fSetSystemFolders = () => { Settings.settingsSet('SentFolder', FolderStore.sentFolder()); Settings.settingsSet('DraftFolder', FolderStore.draftFolder()); Settings.settingsSet('SpamFolder', FolderStore.spamFolder()); Settings.settingsSet('TrashFolder', FolderStore.trashFolder()); Settings.settingsSet('ArchiveFolder', FolderStore.archiveFolder()); }, - fSaveSystemFolders = _.debounce( - () => { - fSetSystemFolders(); - Remote.saveSystemFolders(noop, { - SentFolder: FolderStore.sentFolder(), - DraftFolder: FolderStore.draftFolder(), - SpamFolder: FolderStore.spamFolder(), - TrashFolder: FolderStore.trashFolder(), - ArchiveFolder: FolderStore.archiveFolder(), - NullFolder: 'NullFolder' - }); - }, - Magics.Time1s - ), + fSaveSystemFolders = _.debounce(() => { + fSetSystemFolders(); + Remote.saveSystemFolders(noop, { + SentFolder: FolderStore.sentFolder(), + DraftFolder: FolderStore.draftFolder(), + SpamFolder: FolderStore.spamFolder(), + TrashFolder: FolderStore.trashFolder(), + ArchiveFolder: FolderStore.archiveFolder(), + NullFolder: 'NullFolder' + }); + }, Magics.Time1s), fCallback = () => { fSetSystemFolders(); fSaveSystemFolders(); @@ -86,10 +89,8 @@ class FolderSystemPopupView extends AbstractViewNext * @param {number=} notificationType = SetSystemFoldersNotification.None */ onShow(notificationType = SetSystemFoldersNotification.None) { - let notification = ''; - switch (notificationType) - { + switch (notificationType) { case SetSystemFoldersNotification.Sent: notification = i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT'); break; @@ -112,4 +113,4 @@ class FolderSystemPopupView extends AbstractViewNext } } -export {FolderSystemPopupView, FolderSystemPopupView as default}; +export { FolderSystemPopupView, FolderSystemPopupView as default }; diff --git a/dev/View/Popup/Identity.js b/dev/View/Popup/Identity.js index 966e1f029..61748f1d7 100644 --- a/dev/View/Popup/Identity.js +++ b/dev/View/Popup/Identity.js @@ -1,24 +1,22 @@ - import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {bMobileDevice} from 'Common/Globals'; -import {trim, fakeMd5} from 'Common/Utils'; -import {getNotification} from 'Common/Translator'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { bMobileDevice } from 'Common/Globals'; +import { trim, fakeMd5 } from 'Common/Utils'; +import { getNotification } from 'Common/Translator'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Identity', templateID: 'PopupsIdentity' }) -class IdentityPopupView extends AbstractViewNext -{ +class IdentityPopupView extends AbstractViewNext { constructor() { super(); @@ -45,15 +43,13 @@ class IdentityPopupView extends AbstractViewNext this.submitError = ko.observable(''); this.bcc.subscribe((value) => { - if (false === this.showBcc() && 0 < value.length) - { + if (false === this.showBcc() && 0 < value.length) { this.showBcc(true); } }); this.replyTo.subscribe((value) => { - if (false === this.showReplyTo() && 0 < value.length) - { + if (false === this.showReplyTo() && 0 < value.length) { this.showReplyTo(true); } }); @@ -61,62 +57,56 @@ class IdentityPopupView extends AbstractViewNext @command((self) => !self.submitRequest()) addOrEditIdentityCommand() { - - if (this.signature && this.signature.__fetchEditorValue) - { + if (this.signature && this.signature.__fetchEditorValue) { this.signature.__fetchEditorValue(); } - if (!this.email.hasError()) - { + if (!this.email.hasError()) { this.email.hasError('' === trim(this.email())); } - if (this.email.hasError()) - { - if (!this.owner()) - { + if (this.email.hasError()) { + if (!this.owner()) { this.email.focused(true); } return false; } - if (this.replyTo.hasError()) - { + if (this.replyTo.hasError()) { this.replyTo.focused(true); return false; } - if (this.bcc.hasError()) - { + if (this.bcc.hasError()) { this.bcc.focused(true); return false; } this.submitRequest(true); - Remote.identityUpdate((result, data) => { - - this.submitRequest(false); - if (StorageResultType.Success === result && data) - { - if (data.Result) - { - getApp().accountsAndIdentities(); - this.cancelCommand(); + Remote.identityUpdate( + (result, data) => { + this.submitRequest(false); + if (StorageResultType.Success === result && data) { + if (data.Result) { + getApp().accountsAndIdentities(); + this.cancelCommand(); + } else if (data.ErrorCode) { + this.submitError(getNotification(data.ErrorCode)); + } + } else { + this.submitError(getNotification(Notification.UnknownError)); } - else if (data.ErrorCode) - { - this.submitError(getNotification(data.ErrorCode)); - } - } - else - { - this.submitError(getNotification(Notification.UnknownError)); - } - - }, this.id, this.email(), this.name(), this.replyTo(), this.bcc(), this.signature(), this.signatureInsertBefore()); + }, + this.id, + this.email(), + this.name(), + this.replyTo(), + this.bcc(), + this.signature(), + this.signatureInsertBefore() + ); return true; } @@ -148,11 +138,9 @@ class IdentityPopupView extends AbstractViewNext * @param {?IdentityModel} oIdentity */ onShow(identity) { - this.clearPopup(); - if (identity) - { + if (identity) { this.edit(true); this.id = identity.id() || ''; @@ -164,16 +152,13 @@ class IdentityPopupView extends AbstractViewNext this.signatureInsertBefore(identity.signatureInsertBefore()); this.owner('' === this.id); - } - else - { + } else { this.id = fakeMd5(); } } onShowWithDelay() { - if (!this.owner() && !bMobileDevice) - { + if (!this.owner() && !bMobileDevice) { this.email.focused(true); } } @@ -183,4 +168,4 @@ class IdentityPopupView extends AbstractViewNext } } -export {IdentityPopupView, IdentityPopupView as default}; +export { IdentityPopupView, IdentityPopupView as default }; diff --git a/dev/View/Popup/KeyboardShortcutsHelp.js b/dev/View/Popup/KeyboardShortcutsHelp.js index 9a583dffc..55d67204c 100644 --- a/dev/View/Popup/KeyboardShortcutsHelp.js +++ b/dev/View/Popup/KeyboardShortcutsHelp.js @@ -1,54 +1,50 @@ - import _ from '_'; import key from 'key'; -import {KeyState, Magics} from 'Common/Enums'; +import { KeyState, Magics } from 'Common/Enums'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/KeyboardShortcutsHelp', templateID: 'PopupsKeyboardShortcutsHelp' }) -class KeyboardShortcutsHelpPopupView extends AbstractViewNext -{ +class KeyboardShortcutsHelpPopupView extends AbstractViewNext { constructor() { super(); this.sDefaultKeyScope = KeyState.PopupKeyboardShortcutsHelp; } onBuild(dom) { - key('tab, shift+tab, left, right', KeyState.PopupKeyboardShortcutsHelp, _.throttle((event, handler) => { + key( + 'tab, shift+tab, left, right', + KeyState.PopupKeyboardShortcutsHelp, + _.throttle((event, handler) => { + if (event && handler) { + const $tabs = dom.find('.nav.nav-tabs > li'), + isNext = handler && ('tab' === handler.shortcut || 'right' === handler.shortcut); - if (event && handler) - { - const - $tabs = dom.find('.nav.nav-tabs > li'), - isNext = handler && ('tab' === handler.shortcut || 'right' === handler.shortcut); + let index = $tabs.index($tabs.filter('.active')); + if (!isNext && 0 < index) { + index -= 1; + } else if (isNext && index < $tabs.length - 1) { + index += 1; + } else { + index = isNext ? 0 : $tabs.length - 1; + } - let index = $tabs.index($tabs.filter('.active')); - if (!isNext && 0 < index) - { - index -= 1; - } - else if (isNext && index < $tabs.length - 1) - { - index += 1; - } - else - { - index = isNext ? 0 : $tabs.length - 1; + $tabs + .eq(index) + .find('a[data-toggle="tab"]') + .tab('show'); + return false; } - $tabs.eq(index).find('a[data-toggle="tab"]').tab('show'); - return false; - } - - return true; - - }, Magics.Time100ms)); + return true; + }, Magics.Time100ms) + ); } } -export {KeyboardShortcutsHelpPopupView, KeyboardShortcutsHelpPopupView as default}; +export { KeyboardShortcutsHelpPopupView, KeyboardShortcutsHelpPopupView as default }; diff --git a/dev/View/Popup/Languages.js b/dev/View/Popup/Languages.js index 34f9056a5..8a5683355 100644 --- a/dev/View/Popup/Languages.js +++ b/dev/View/Popup/Languages.js @@ -1,19 +1,17 @@ - import _ from '_'; import ko from 'ko'; -import {convertLangName} from 'Common/Utils'; +import { convertLangName } from 'Common/Utils'; // import {view, ViewType} from 'Knoin/Knoin'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Languages', templateID: 'PopupsLanguages' }) -class LanguagesPopupView extends AbstractViewNext -{ +class LanguagesPopupView extends AbstractViewNext { constructor() { super(); @@ -64,8 +62,7 @@ class LanguagesPopupView extends AbstractViewNext } changeLanguage(lang) { - if (this.fLang) - { + if (this.fLang) { this.fLang(lang); } @@ -73,4 +70,4 @@ class LanguagesPopupView extends AbstractViewNext } } -export {LanguagesPopupView, LanguagesPopupView as default}; +export { LanguagesPopupView, LanguagesPopupView as default }; diff --git a/dev/View/Popup/MessageOpenPgp.js b/dev/View/Popup/MessageOpenPgp.js index 3e155fdc1..7362e41e4 100644 --- a/dev/View/Popup/MessageOpenPgp.js +++ b/dev/View/Popup/MessageOpenPgp.js @@ -1,21 +1,19 @@ - import _ from '_'; import ko from 'ko'; import key from 'key'; import $ from '$'; -import {pString, log} from 'Common/Utils'; -import {KeyState, Magics} from 'Common/Enums'; +import { pString, log } from 'Common/Utils'; +import { KeyState, Magics } from 'Common/Enums'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/MessageOpenPgp', templateID: 'PopupsMessageOpenPgp' }) -class MessageOpenPgpPopupView extends AbstractViewNext -{ +class MessageOpenPgpPopupView extends AbstractViewNext { constructor() { super(); @@ -37,44 +35,31 @@ class MessageOpenPgpPopupView extends AbstractViewNext @command((self) => !self.submitRequest()) doCommand() { - this.submitRequest(true); _.delay(() => { - let privateKey = null; - try - { - if (this.resultCallback && this.selectedKey()) - { + try { + if (this.resultCallback && this.selectedKey()) { const privateKeys = this.selectedKey().getNativeKeys(); privateKey = privateKeys && privateKeys[0] ? privateKeys[0] : null; - if (privateKey) - { - try - { - if (!privateKey.decrypt(pString(this.password()))) - { + if (privateKey) { + try { + if (!privateKey.decrypt(pString(this.password()))) { log('Error: Private key cannot be decrypted'); privateKey = null; } - } - catch (e) - { + } catch (e) { log(e); privateKey = null; } - } - else - { + } else { log('Error: Private key cannot be found'); } } - } - catch (e) - { + } catch (e) { log(e); privateKey = null; } @@ -83,7 +68,6 @@ class MessageOpenPgpPopupView extends AbstractViewNext this.cancelCommand(); this.resultCallback(privateKey); - }, Magics.Time100ms); } @@ -103,9 +87,7 @@ class MessageOpenPgpPopupView extends AbstractViewNext onBuild(oDom) { key('tab,shift+tab', KeyState.PopupMessageOpenPGP, () => { - - switch (true) - { + switch (true) { case this.password.focus(): this.buttonFocus(true); break; @@ -116,26 +98,27 @@ class MessageOpenPgpPopupView extends AbstractViewNext } return false; - }); const self = this; - oDom - .on('click', '.key-list__item', function() { // eslint-disable-line prefer-arrow-callback + oDom.on('click', '.key-list__item', function() { + // eslint-disable-line prefer-arrow-callback - oDom.find('.key-list__item .key-list__item__radio') - .addClass('icon-radio-unchecked') - .removeClass('icon-radio-checked'); + oDom + .find('.key-list__item .key-list__item__radio') + .addClass('icon-radio-unchecked') + .removeClass('icon-radio-checked'); - $(this).find('.key-list__item__radio') // eslint-disable-line no-invalid-this - .removeClass('icon-radio-unchecked') - .addClass('icon-radio-checked'); + $(this) + .find('.key-list__item__radio') // eslint-disable-line no-invalid-this + .removeClass('icon-radio-unchecked') + .addClass('icon-radio-checked'); - self.selectedKey(ko.dataFor(this)); // eslint-disable-line no-invalid-this + self.selectedKey(ko.dataFor(this)); // eslint-disable-line no-invalid-this - self.password.focus(true); - }); + self.password.focus(true); + }); } onHideWithDelay() { @@ -144,7 +127,7 @@ class MessageOpenPgpPopupView extends AbstractViewNext onShowWithDelay() { this.password.focus(true); - // this.buttonFocus(true); + // this.buttonFocus(true); } onShow(fCallback, privateKeys) { @@ -153,11 +136,13 @@ class MessageOpenPgpPopupView extends AbstractViewNext this.resultCallback = fCallback; this.privateKeys(privateKeys); - if (this.viewModelDom) - { - this.viewModelDom.find('.key-list__item').first().click(); + if (this.viewModelDom) { + this.viewModelDom + .find('.key-list__item') + .first() + .click(); } } } -export {MessageOpenPgpPopupView, MessageOpenPgpPopupView as default}; +export { MessageOpenPgpPopupView, MessageOpenPgpPopupView as default }; diff --git a/dev/View/Popup/NewOpenPgpKey.js b/dev/View/Popup/NewOpenPgpKey.js index 33db706c3..6bca68626 100644 --- a/dev/View/Popup/NewOpenPgpKey.js +++ b/dev/View/Popup/NewOpenPgpKey.js @@ -1,23 +1,21 @@ - import _ from '_'; import ko from 'ko'; -import {Magics} from 'Common/Enums'; -import {trim, log, delegateRun, pInt} from 'Common/Utils'; +import { Magics } from 'Common/Enums'; +import { trim, log, delegateRun, pInt } from 'Common/Utils'; import PgpStore from 'Stores/User/Pgp'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/NewOpenPgpKey', templateID: 'PopupsNewOpenPgpKey' }) -class NewOpenPgpKeyPopupView extends AbstractViewNext -{ +class NewOpenPgpKeyPopupView extends AbstractViewNext { constructor() { super(); @@ -39,20 +37,16 @@ class NewOpenPgpKeyPopupView extends AbstractViewNext @command() generateOpenPgpKeyCommand() { - - const - userId = {}, + const userId = {}, openpgpKeyring = PgpStore.openpgpKeyring; this.email.error('' === trim(this.email())); - if (!openpgpKeyring || this.email.error()) - { + if (!openpgpKeyring || this.email.error()) { return false; } userId.email = this.email(); - if ('' !== this.name()) - { + if ('' !== this.name()) { userId.name = this.name(); } @@ -60,39 +54,34 @@ class NewOpenPgpKeyPopupView extends AbstractViewNext this.submitError(''); _.delay(() => { - try { + PgpStore.openpgp + .generateKey({ + userIds: [userId], + numBits: pInt(this.keyBitLength()), + passphrase: trim(this.password()) + }) + .then((keyPair) => { + this.submitRequest(false); - PgpStore.openpgp.generateKey({ - userIds: [userId], - numBits: pInt(this.keyBitLength()), - passphrase: trim(this.password()) - }).then((keyPair) => { + if (keyPair && keyPair.privateKeyArmored) { + openpgpKeyring.privateKeys.importKey(keyPair.privateKeyArmored); + openpgpKeyring.publicKeys.importKey(keyPair.publicKeyArmored); - this.submitRequest(false); + openpgpKeyring.store(); - if (keyPair && keyPair.privateKeyArmored) - { - openpgpKeyring.privateKeys.importKey(keyPair.privateKeyArmored); - openpgpKeyring.publicKeys.importKey(keyPair.publicKeyArmored); - - openpgpKeyring.store(); - - getApp().reloadOpenPgpKeys(); - delegateRun(this, 'cancelCommand'); - } - - }).catch((e) => { - this.submitRequest(false); - this.showError(e); - }); - } - catch (e) - { + getApp().reloadOpenPgpKeys(); + delegateRun(this, 'cancelCommand'); + } + }) + .catch((e) => { + this.submitRequest(false); + this.showError(e); + }); + } catch (e) { this.submitRequest(false); this.showError(e); } - }, Magics.Time100ms); return true; @@ -100,8 +89,7 @@ class NewOpenPgpKeyPopupView extends AbstractViewNext showError(e) { log(e); - if (e && e.message) - { + if (e && e.message) { this.submitError(e.message); } } @@ -126,4 +114,4 @@ class NewOpenPgpKeyPopupView extends AbstractViewNext } } -export {NewOpenPgpKeyPopupView, NewOpenPgpKeyPopupView as default}; +export { NewOpenPgpKeyPopupView, NewOpenPgpKeyPopupView as default }; diff --git a/dev/View/Popup/Plugin.js b/dev/View/Popup/Plugin.js index 94530fc9e..c8a47cef1 100644 --- a/dev/View/Popup/Plugin.js +++ b/dev/View/Popup/Plugin.js @@ -1,23 +1,21 @@ - import _ from '_'; import ko from 'ko'; import key from 'key'; -import {KeyState, Magics, StorageResultType, Notification} from 'Common/Enums'; -import {isNonEmptyArray, delegateRun} from 'Common/Utils'; -import {getNotification, i18n} from 'Common/Translator'; +import { KeyState, Magics, StorageResultType, Notification } from 'Common/Enums'; +import { isNonEmptyArray, delegateRun } from 'Common/Utils'; +import { getNotification, i18n } from 'Common/Translator'; import Remote from 'Remote/Admin/Ajax'; -import {popup, command, isPopupVisible, showScreenPopup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command, isPopupVisible, showScreenPopup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Plugin', templateID: 'PopupsPlugin' }) -class PluginPopupView extends AbstractViewNext -{ +class PluginPopupView extends AbstractViewNext { constructor() { super(); @@ -50,14 +48,12 @@ class PluginPopupView extends AbstractViewNext @command((self) => self.hasConfiguration()) saveCommand() { - const list = {}; list.Name = this.name(); _.each(this.configures(), (oItem) => { let value = oItem.value(); - if (false === value || true === value) - { + if (false === value || true === value) { value = value ? '1' : '0'; } list['_' + oItem.Name] = value; @@ -68,19 +64,13 @@ class PluginPopupView extends AbstractViewNext } onPluginSettingsUpdateResponse(result, data) { - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { this.cancelCommand(); - } - else - { + } else { this.saveError(''); - if (data && data.ErrorCode) - { + if (data && data.ErrorCode) { this.saveError(getNotification(data.ErrorCode)); - } - else - { + } else { this.saveError(getNotification(Notification.CantSavePluginSettings)); } } @@ -91,44 +81,44 @@ class PluginPopupView extends AbstractViewNext this.readme(); this.configures([]); - if (oPlugin) - { + if (oPlugin) { this.name(oPlugin.Name); this.readme(oPlugin.Readme); const config = oPlugin.Config; - if (isNonEmptyArray(config)) - { - this.configures(_.map(config, (item) => ({ - 'value': ko.observable(item[0]), - 'placeholder': ko.observable(item[6]), - 'Name': item[1], - 'Type': item[2], - 'Label': item[3], - 'Default': item[4], - 'Desc': item[5] - }))); + if (isNonEmptyArray(config)) { + this.configures( + _.map(config, (item) => ({ + 'value': ko.observable(item[0]), + 'placeholder': ko.observable(item[6]), + 'Name': item[1], + 'Type': item[2], + 'Label': item[3], + 'Default': item[4], + 'Desc': item[5] + })) + ); } } } tryToClosePopup() { const PopupsAskViewModel = require('View/Popup/Ask'); - if (!isPopupVisible(PopupsAskViewModel)) - { - showScreenPopup(PopupsAskViewModel, [i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), () => { - if (this.modalVisibility()) - { - delegateRun(this, 'cancelCommand'); + if (!isPopupVisible(PopupsAskViewModel)) { + showScreenPopup(PopupsAskViewModel, [ + i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), + () => { + if (this.modalVisibility()) { + delegateRun(this, 'cancelCommand'); + } } - }]); + ]); } } onBuild() { key('esc', KeyState.All, () => { - if (this.modalVisibility()) - { + if (this.modalVisibility()) { this.tryToClosePopup(); } @@ -137,4 +127,4 @@ class PluginPopupView extends AbstractViewNext } } -export {PluginPopupView, PluginPopupView as default}; +export { PluginPopupView, PluginPopupView as default }; diff --git a/dev/View/Popup/Template.js b/dev/View/Popup/Template.js index aef5cae89..bfa4fb1fe 100644 --- a/dev/View/Popup/Template.js +++ b/dev/View/Popup/Template.js @@ -1,24 +1,22 @@ - import ko from 'ko'; -import {StorageResultType, Notification} from 'Common/Enums'; -import {trim, isNormal} from 'Common/Utils'; -import {getNotification} from 'Common/Translator'; -import {HtmlEditor} from 'Common/HtmlEditor'; +import { StorageResultType, Notification } from 'Common/Enums'; +import { trim, isNormal } from 'Common/Utils'; +import { getNotification } from 'Common/Translator'; +import { HtmlEditor } from 'Common/HtmlEditor'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/Template', templateID: 'PopupsTemplate' }) -class TemplatePopupView extends AbstractViewNext -{ +class TemplatePopupView extends AbstractViewNext { constructor() { super(); @@ -49,40 +47,35 @@ class TemplatePopupView extends AbstractViewNext @command((self) => !self.submitRequest()) addTemplateCommand() { - this.populateBodyFromEditor(); this.name.error('' === trim(this.name())); this.body.error('' === trim(this.body()) || ':HTML:' === trim(this.body())); - if (this.name.error() || this.body.error()) - { + if (this.name.error() || this.body.error()) { return false; } this.submitRequest(true); - Remote.templateSetup((result, data) => { - - this.submitRequest(false); - if (StorageResultType.Success === result && data) - { - if (data.Result) - { - getApp().templates(); - this.cancelCommand(); + Remote.templateSetup( + (result, data) => { + this.submitRequest(false); + if (StorageResultType.Success === result && data) { + if (data.Result) { + getApp().templates(); + this.cancelCommand(); + } else if (data.ErrorCode) { + this.submitError(getNotification(data.ErrorCode)); + } + } else { + this.submitError(getNotification(Notification.UnknownError)); } - else if (data.ErrorCode) - { - this.submitError(getNotification(data.ErrorCode)); - } - } - else - { - this.submitError(getNotification(Notification.UnknownError)); - } - - }, this.id(), this.name(), this.body()); + }, + this.id(), + this.name(), + this.body() + ); return true; } @@ -100,79 +93,71 @@ class TemplatePopupView extends AbstractViewNext this.submitRequest(false); this.submitError(''); - if (this.editor) - { + if (this.editor) { this.editor.setPlain('', false); } } populateBodyFromEditor() { - if (this.editor) - { + if (this.editor) { this.body(this.editor.getDataWithHtmlMark()); } } editorSetBody(sBody) { - if (!this.editor && this.signatureDom()) - { - this.editor = new HtmlEditor(this.signatureDom(), () => { - this.populateBodyFromEditor(); - }, () => { - this.editor.setHtmlOrPlain(sBody); - }); - } - else - { + if (!this.editor && this.signatureDom()) { + this.editor = new HtmlEditor( + this.signatureDom(), + () => { + this.populateBodyFromEditor(); + }, + () => { + this.editor.setHtmlOrPlain(sBody); + } + ); + } else { this.editor.setHtmlOrPlain(sBody); } } onShow(template) { - this.clearPopup(); - if (template && template.id) - { + if (template && template.id) { this.id(template.id); this.name(template.name); this.body(template.body); - if (template.populated) - { + if (template.populated) { this.editorSetBody(this.body()); - } - else - { + } else { this.body.loading(true); this.body.error(false); Remote.templateGetById((result, data) => { - this.body.loading(false); - if (StorageResultType.Success === result && data && data.Result && - 'Object/Template' === data.Result['@Object'] && isNormal(data.Result.Body)) - { + if ( + StorageResultType.Success === result && + data && + data.Result && + 'Object/Template' === data.Result['@Object'] && + isNormal(data.Result.Body) + ) { template.body = data.Result.Body; template.populated = true; this.body(template.body); this.body.error(false); - } - else - { + } else { this.body(''); this.body.error(true); } this.editorSetBody(this.body()); - }, this.id()); } - } - else - { + } else { this.editorSetBody(''); } } @@ -182,4 +167,4 @@ class TemplatePopupView extends AbstractViewNext } } -export {TemplatePopupView, TemplatePopupView as default}; +export { TemplatePopupView, TemplatePopupView as default }; diff --git a/dev/View/Popup/TwoFactorConfiguration.js b/dev/View/Popup/TwoFactorConfiguration.js index 4fce32efb..283e131be 100644 --- a/dev/View/Popup/TwoFactorConfiguration.js +++ b/dev/View/Popup/TwoFactorConfiguration.js @@ -1,28 +1,26 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; import qr from 'qr'; -import {Capa, StorageResultType} from 'Common/Enums'; -import {pString} from 'Common/Utils'; -import {i18n, trigger as translatorTrigger} from 'Common/Translator'; +import { Capa, StorageResultType } from 'Common/Enums'; +import { pString } from 'Common/Utils'; +import { i18n, trigger as translatorTrigger } from 'Common/Translator'; import * as Settings from 'Storage/Settings'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {popup, showScreenPopup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, showScreenPopup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/TwoFactorConfiguration', templateID: 'PopupsTwoFactorConfiguration' }) -class TwoFactorConfigurationPopupView extends AbstractViewNext -{ +class TwoFactorConfigurationPopupView extends AbstractViewNext { constructor() { super(); @@ -50,26 +48,20 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext read: this.viewEnable_, write: (value) => { value = !!value; - if (value && this.twoFactorTested()) - { + if (value && this.twoFactorTested()) { this.viewEnable_(value); Remote.enableTwoFactor((result, data) => { - if (StorageResultType.Success !== result || !data || !data.Result) - { + if (StorageResultType.Success !== result || !data || !data.Result) { this.viewEnable_(false); } }, true); - } - else - { - if (!value) - { + } else { + if (!value) { this.viewEnable_(value); } Remote.enableTwoFactor((result, data) => { - if (StorageResultType.Success !== result || !data || !data.Result) - { + if (StorageResultType.Success !== result || !data || !data.Result) { this.viewEnable_(false); } }, false); @@ -79,15 +71,17 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext this.viewTwoFactorEnableTooltip = ko.computed(() => { translatorTrigger(); - return this.twoFactorTested() || this.viewEnable_() ? '' : - i18n('POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_TEST_BEFORE_DESC'); + return this.twoFactorTested() || this.viewEnable_() + ? '' + : i18n('POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_TEST_BEFORE_DESC'); }); this.viewTwoFactorStatus = ko.computed(() => { translatorTrigger(); - return i18n(this.twoFactorStatus() ? - 'POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_CONFIGURED_DESC' : - 'POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC' + return i18n( + this.twoFactorStatus() + ? 'POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_CONFIGURED_DESC' + : 'POPUPS_TWO_FACTOR_CFG/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC' ); }); @@ -144,24 +138,27 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext } onHide() { - if (this.lock()) - { + if (this.lock()) { window.location.reload(); } } getQr() { - return 'otpauth://totp/' + window.encodeURIComponent(this.viewUser()) + - '?secret=' + window.encodeURIComponent(this.viewSecret()) + - '&issuer=' + window.encodeURIComponent(''); + return ( + 'otpauth://totp/' + + window.encodeURIComponent(this.viewUser()) + + '?secret=' + + window.encodeURIComponent(this.viewSecret()) + + '&issuer=' + + window.encodeURIComponent('') + ); } onResult(sResult, oData) { this.processing(false); this.clearing(false); - if (StorageResultType.Success === sResult && oData && oData.Result) - { + if (StorageResultType.Success === sResult && oData && oData.Result) { this.viewUser(pString(oData.Result.User)); this.viewEnable_(!!oData.Result.Enable); this.twoFactorStatus(!!oData.Result.IsSet); @@ -171,10 +168,8 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext this.viewBackupCodes(pString(oData.Result.BackupCodes).replace(/[\s]+/g, ' ')); this.viewUrlTitle(pString(oData.Result.UrlTitle)); - this.viewUrl(qr.toDataURL({level: 'M', size: 8, value: this.getQr()})); - } - else - { + this.viewUrl(qr.toDataURL({ level: 'M', size: 8, value: this.getQr() })); + } else { this.viewUser(''); this.viewEnable_(false); this.twoFactorStatus(false); @@ -190,14 +185,11 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext onShowSecretResult(result, data) { this.secreting(false); - if (StorageResultType.Success === result && data && data.Result) - { + if (StorageResultType.Success === result && data && data.Result) { this.viewSecret(pString(data.Result.Secret)); this.viewUrlTitle(pString(data.Result.UrlTitle)); - this.viewUrl(qr.toDataURL({level: 'M', size: 6, value: this.getQr()})); - } - else - { + this.viewUrl(qr.toDataURL({ level: 'M', size: 6, value: this.getQr() })); + } else { this.viewSecret(''); this.viewUrlTitle(''); this.viewUrl(''); @@ -205,12 +197,11 @@ class TwoFactorConfigurationPopupView extends AbstractViewNext } onBuild() { - if (this.capaTwoFactor) - { + if (this.capaTwoFactor) { this.processing(true); Remote.getTwoFactor(this.onResult); } } } -export {TwoFactorConfigurationPopupView, TwoFactorConfigurationPopupView as default}; +export { TwoFactorConfigurationPopupView, TwoFactorConfigurationPopupView as default }; diff --git a/dev/View/Popup/TwoFactorTest.js b/dev/View/Popup/TwoFactorTest.js index 842c31f97..f2e502950 100644 --- a/dev/View/Popup/TwoFactorTest.js +++ b/dev/View/Popup/TwoFactorTest.js @@ -1,20 +1,18 @@ - import ko from 'ko'; -import {StorageResultType} from 'Common/Enums'; -import {bMobileDevice} from 'Common/Globals'; +import { StorageResultType } from 'Common/Enums'; +import { bMobileDevice } from 'Common/Globals'; import Remote from 'Remote/User/Ajax'; -import {popup, command} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup, command } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/TwoFactorTest', templateID: 'PopupsTwoFactorTest' }) -class TwoFactorTestPopupView extends AbstractViewNext -{ +class TwoFactorTestPopupView extends AbstractViewNext { constructor() { super(); @@ -29,18 +27,14 @@ class TwoFactorTestPopupView extends AbstractViewNext @command((self) => '' !== self.code() && !self.testing()) testCodeCommand() { - this.testing(true); Remote.testTwoFactor((result, data) => { - this.testing(false); this.code.status(StorageResultType.Success === result && data && !!data.Result); - if (this.koTestedTrigger && this.code.status()) - { + if (this.koTestedTrigger && this.code.status()) { this.koTestedTrigger(true); } - }, this.code()); } @@ -60,11 +54,10 @@ class TwoFactorTestPopupView extends AbstractViewNext } onShowWithDelay() { - if (!bMobileDevice) - { + if (!bMobileDevice) { this.code.focused(true); } } } -export {TwoFactorTestPopupView, TwoFactorTestPopupView as default}; +export { TwoFactorTestPopupView, TwoFactorTestPopupView as default }; diff --git a/dev/View/Popup/ViewOpenPgpKey.js b/dev/View/Popup/ViewOpenPgpKey.js index 9f2b38d75..fe1346df4 100644 --- a/dev/View/Popup/ViewOpenPgpKey.js +++ b/dev/View/Popup/ViewOpenPgpKey.js @@ -1,19 +1,17 @@ - import ko from 'ko'; import key from 'key'; -import {KeyState} from 'Common/Enums'; -import {selectElement} from 'Common/Utils'; +import { KeyState } from 'Common/Enums'; +import { selectElement } from 'Common/Utils'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/ViewOpenPgpKey', templateID: 'PopupsViewOpenPgpKey' }) -class ViewOpenPgpKeyPopupView extends AbstractViewNext -{ +class ViewOpenPgpKeyPopupView extends AbstractViewNext { constructor() { super(); @@ -29,8 +27,7 @@ class ViewOpenPgpKeyPopupView extends AbstractViewNext selectKey() { const el = this.keyDom(); - if (el) - { + if (el) { selectElement(el); } } @@ -38,8 +35,7 @@ class ViewOpenPgpKeyPopupView extends AbstractViewNext onShow(openPgpKey) { this.clearPopup(); - if (openPgpKey) - { + if (openPgpKey) { this.key(openPgpKey.armor); } } @@ -52,4 +48,4 @@ class ViewOpenPgpKeyPopupView extends AbstractViewNext } } -export {ViewOpenPgpKeyPopupView, ViewOpenPgpKeyPopupView as default}; +export { ViewOpenPgpKeyPopupView, ViewOpenPgpKeyPopupView as default }; diff --git a/dev/View/Popup/WelcomePage.js b/dev/View/Popup/WelcomePage.js index 72abbfeda..77c7a5213 100644 --- a/dev/View/Popup/WelcomePage.js +++ b/dev/View/Popup/WelcomePage.js @@ -1,17 +1,15 @@ - import ko from 'ko'; import Promises from 'Promises/User/Ajax'; -import {popup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { popup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @popup({ name: 'View/Popup/WelcomePage', templateID: 'PopupsWelcomePage' }) -class WelcomePagePopupView extends AbstractViewNext -{ +class WelcomePagePopupView extends AbstractViewNext { constructor() { super(); @@ -44,4 +42,4 @@ class WelcomePagePopupView extends AbstractViewNext } } -export {WelcomePagePopupView, WelcomePagePopupView as default}; +export { WelcomePagePopupView, WelcomePagePopupView as default }; diff --git a/dev/View/User/About.js b/dev/View/User/About.js index 772c3723e..99fca8606 100644 --- a/dev/View/User/About.js +++ b/dev/View/User/About.js @@ -1,22 +1,20 @@ - import ko from 'ko'; import * as Settings from 'Storage/Settings'; -import {view, ViewType} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/User/About', type: ViewType.Center, templateID: 'About' }) -class AboutUserView extends AbstractViewNext -{ +class AboutUserView extends AbstractViewNext { constructor() { super(); this.version = ko.observable(Settings.appSettingsGet('version')); } } -export {AboutUserView, AboutUserView as default}; +export { AboutUserView, AboutUserView as default }; diff --git a/dev/View/User/AbstractSystemDropDown.js b/dev/View/User/AbstractSystemDropDown.js index 32b27040b..59efb68a5 100644 --- a/dev/View/User/AbstractSystemDropDown.js +++ b/dev/View/User/AbstractSystemDropDown.js @@ -1,4 +1,3 @@ - import _ from '_'; import ko from 'ko'; import key from 'key'; @@ -7,20 +6,19 @@ import AppStore from 'Stores/User/App'; import AccountStore from 'Stores/User/Account'; import MessageStore from 'Stores/User/Message'; -import {Capa, Magics, KeyState} from 'Common/Enums'; -import {trim, isUnd} from 'Common/Utils'; -import {settings} from 'Common/Links'; +import { Capa, Magics, KeyState } from 'Common/Enums'; +import { trim, isUnd } from 'Common/Utils'; +import { settings } from 'Common/Links'; import * as Events from 'Common/Events'; import * as Settings from 'Storage/Settings'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {showScreenPopup, setHash} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { showScreenPopup, setHash } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; -class AbstractSystemDropDownUserView extends AbstractViewNext -{ +class AbstractSystemDropDownUserView extends AbstractViewNext { constructor() { super(); @@ -54,8 +52,7 @@ class AbstractSystemDropDownUserView extends AbstractViewNext } accountClick(account, event) { - if (account && event && !isUnd(event.which) && 1 === event.which) - { + if (account && event && !isUnd(event.which) && 1 === event.which) { AccountStore.accounts.loading(true); _.delay(() => AccountStore.accounts.loading(false), Magics.Time1s); } @@ -68,23 +65,19 @@ class AbstractSystemDropDownUserView extends AbstractViewNext } settingsClick() { - if (Settings.capa(Capa.Settings)) - { + if (Settings.capa(Capa.Settings)) { setHash(settings()); } } - settingsHelp() - { - if (Settings.capa(Capa.Help)) - { + settingsHelp() { + if (Settings.capa(Capa.Help)) { showScreenPopup(require('View/Popup/KeyboardShortcutsHelp')); } } addAccountClick() { - if (this.capaAdditionalAccounts()) - { + if (this.capaAdditionalAccounts()) { showScreenPopup(require('View/Popup/Account')); } } @@ -95,8 +88,7 @@ class AbstractSystemDropDownUserView extends AbstractViewNext onBuild() { key('`', [KeyState.MessageList, KeyState.MessageView, KeyState.Settings], () => { - if (this.viewModelVisibility()) - { + if (this.viewModelVisibility()) { MessageStore.messageFullScreenMode(false); this.accountMenuDropdownTrigger(true); } @@ -104,8 +96,7 @@ class AbstractSystemDropDownUserView extends AbstractViewNext // shortcuts help key('shift+/', [KeyState.MessageList, KeyState.MessageView, KeyState.Settings], () => { - if (this.viewModelVisibility()) - { + if (this.viewModelVisibility()) { showScreenPopup(require('View/Popup/KeyboardShortcutsHelp')); return false; } @@ -114,4 +105,4 @@ class AbstractSystemDropDownUserView extends AbstractViewNext } } -export {AbstractSystemDropDownUserView, AbstractSystemDropDownUserView as default}; +export { AbstractSystemDropDownUserView, AbstractSystemDropDownUserView as default }; diff --git a/dev/View/User/Login.js b/dev/View/User/Login.js index 45a4e0a0e..855ae2cc1 100644 --- a/dev/View/User/Login.js +++ b/dev/View/User/Login.js @@ -1,4 +1,3 @@ - import window from 'window'; import _ from '_'; import ko from 'ko'; @@ -12,14 +11,11 @@ import { Notification } from 'Common/Enums'; -import { - trim, inArray, pInt, - convertLangName, triggerAutocompleteInputChange -} from 'Common/Utils'; +import { trim, inArray, pInt, convertLangName, triggerAutocompleteInputChange } from 'Common/Utils'; -import {$win} from 'Common/Globals'; -import {socialFacebook, socialGoogle, socialTwitter} from 'Common/Links'; -import {getNotification, getNotificationFromResponse, reload as translatorReload} from 'Common/Translator'; +import { $win } from 'Common/Globals'; +import { socialFacebook, socialGoogle, socialTwitter } from 'Common/Links'; +import { getNotification, getNotificationFromResponse, reload as translatorReload } from 'Common/Translator'; import * as Plugins from 'Common/Plugins'; @@ -31,18 +27,17 @@ import * as Local from 'Storage/Client'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {view, command, ViewType, routeOff, showScreenPopup} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, command, ViewType, routeOff, showScreenPopup } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: ['View/App/Login', 'View/User/Login'], type: ViewType.Center, templateID: 'Login' }) -class LoginUserView extends AbstractViewNext -{ +class LoginUserView extends AbstractViewNext { constructor() { super(); @@ -56,7 +51,7 @@ class LoginUserView extends AbstractViewNext this.additionalCode = ko.observable(''); this.additionalCode.error = ko.observable(false); - this.additionalCode.errorAnimation = ko.observable(false).extend({falseTimeout: 500}); + this.additionalCode.errorAnimation = ko.observable(false).extend({ falseTimeout: 500 }); this.additionalCode.focused = ko.observable(false); this.additionalCode.visibility = ko.observable(false); this.additionalCodeSignMe = ko.observable(false); @@ -74,13 +69,15 @@ class LoginUserView extends AbstractViewNext this.emailError = ko.observable(false); this.passwordError = ko.observable(false); - this.emailErrorAnimation = ko.observable(false).extend({falseTimeout: 500}); - this.passwordErrorAnimation = ko.observable(false).extend({falseTimeout: 500}); + this.emailErrorAnimation = ko.observable(false).extend({ falseTimeout: 500 }); + this.passwordErrorAnimation = ko.observable(false).extend({ falseTimeout: 500 }); this.formHidden = ko.observable(false); this.formError = ko.computed( - () => this.emailErrorAnimation() || this.passwordErrorAnimation() || + () => + this.emailErrorAnimation() || + this.passwordErrorAnimation() || (this.additionalCode.visibility() && this.additionalCode.errorAnimation()) ); @@ -122,8 +119,7 @@ class LoginUserView extends AbstractViewNext this.submitErrorAddidional = ko.observable(''); this.submitError.subscribe((value) => { - if ('' === value) - { + if ('' === value) { this.submitErrorAddidional(''); } }); @@ -136,9 +132,7 @@ class LoginUserView extends AbstractViewNext this.bSendLanguage = false; - this.languageFullName = ko.computed( - () => convertLangName(this.language()) - ); + this.languageFullName = ko.computed(() => convertLangName(this.language())); this.signMeType = ko.observable(LoginSignMeType.Unused); @@ -146,9 +140,7 @@ class LoginUserView extends AbstractViewNext this.signMe(LoginSignMeType.DefaultOn === iValue); }); - this.signMeVisibility = ko.computed( - () => LoginSignMeType.Unused !== this.signMeType() - ); + this.signMeVisibility = ko.computed(() => LoginSignMeType.Unused !== this.signMeType()); this.facebookLoginEnabled = ko.observable(false); this.googleLoginEnabled = ko.observable(false); @@ -156,16 +148,14 @@ class LoginUserView extends AbstractViewNext this.twitterLoginEnabled = ko.observable(false); this.socialLoginEnabled = ko.computed(() => { - const - bF = this.facebookLoginEnabled(), + const bF = this.facebookLoginEnabled(), bG = this.googleLoginEnabled(), bT = this.twitterLoginEnabled(); return bF || bG || bT; }); - if (Settings.settingsGet('AdditionalLoginError') && !this.submitError()) - { + if (Settings.settingsGet('AdditionalLoginError') && !this.submitError()) { this.submitError(Settings.settingsGet('AdditionalLoginError')); } } @@ -200,7 +190,6 @@ class LoginUserView extends AbstractViewNext @command((self) => !self.submitRequest()) submitCommand() { - triggerAutocompleteInputChange(); this.emailError(false); @@ -209,17 +198,17 @@ class LoginUserView extends AbstractViewNext this.emailError('' === trim(this.email())); this.passwordError('' === trim(this.password())); - if (this.additionalCode.visibility()) - { + if (this.additionalCode.visibility()) { this.additionalCode.error(false); this.additionalCode.error('' === trim(this.additionalCode())); } - if (this.emailError() || this.passwordError() || - (this.additionalCode.visibility() && this.additionalCode.error())) - { - switch (true) - { + if ( + this.emailError() || + this.passwordError() || + (this.additionalCode.visibility() && this.additionalCode.error()) + ) { + switch (true) { case this.emailError(): this.emailFocus(true); break; @@ -235,24 +224,19 @@ class LoginUserView extends AbstractViewNext return false; } - let - pluginResultCode = 0, + let pluginResultCode = 0, pluginResultMessage = ''; - const - fSubmitResult = (iResultCode, sResultMessage) => { - pluginResultCode = iResultCode || 0; - pluginResultMessage = sResultMessage || ''; - }; + const fSubmitResult = (iResultCode, sResultMessage) => { + pluginResultCode = iResultCode || 0; + pluginResultMessage = sResultMessage || ''; + }; Plugins.runHook('user-login-submit', [fSubmitResult]); - if (0 < pluginResultCode) - { + if (0 < pluginResultCode) { this.submitError(getNotification(pluginResultCode)); return false; - } - else if ('' !== pluginResultMessage) - { + } else if ('' !== pluginResultMessage) { this.submitError(pluginResultMessage); return false; } @@ -260,79 +244,57 @@ class LoginUserView extends AbstractViewNext this.submitRequest(true); $win.trigger('rl.tooltips.diactivate'); - const - fLoginRequest = (sLoginPassword) => { + const fLoginRequest = (sLoginPassword) => { + Remote.login( + (sResult, oData) => { + $win.trigger('rl.tooltips.diactivate'); + $win.trigger('rl.tooltips.activate'); - Remote.login( - (sResult, oData) => { - - $win.trigger('rl.tooltips.diactivate'); - $win.trigger('rl.tooltips.activate'); - - if (StorageResultType.Success === sResult && oData && 'Login' === oData.Action) - { - if (oData.Result) - { - if (oData.TwoFactorAuth) - { - this.additionalCode(''); - this.additionalCode.visibility(true); - this.submitRequest(false); - - _.delay(() => this.additionalCode.focused(true), Magics.Time100ms); - } - else if (oData.Admin) - { - getApp().redirectToAdminPanel(); - } - else - { - getApp().loginAndLogoutReload(false); - } - } - else if (oData.ErrorCode) - { + if (StorageResultType.Success === sResult && oData && 'Login' === oData.Action) { + if (oData.Result) { + if (oData.TwoFactorAuth) { + this.additionalCode(''); + this.additionalCode.visibility(true); this.submitRequest(false); - if (-1 < inArray(oData.ErrorCode, [Notification.InvalidInputArgument])) - { - oData.ErrorCode = Notification.AuthError; - } - this.submitError(getNotificationFromResponse(oData)); - - if ('' === this.submitError()) - { - this.submitError(getNotification(Notification.UnknownError)); - } - else if (oData.ErrorMessageAdditional) - { - this.submitErrorAddidional(oData.ErrorMessageAdditional); - } + _.delay(() => this.additionalCode.focused(true), Magics.Time100ms); + } else if (oData.Admin) { + getApp().redirectToAdminPanel(); + } else { + getApp().loginAndLogoutReload(false); } - else - { - this.submitRequest(false); - } - } - else - { + } else if (oData.ErrorCode) { + this.submitRequest(false); + if (-1 < inArray(oData.ErrorCode, [Notification.InvalidInputArgument])) { + oData.ErrorCode = Notification.AuthError; + } + + this.submitError(getNotificationFromResponse(oData)); + + if ('' === this.submitError()) { + this.submitError(getNotification(Notification.UnknownError)); + } else if (oData.ErrorMessageAdditional) { + this.submitErrorAddidional(oData.ErrorMessageAdditional); + } + } else { this.submitRequest(false); - this.submitError(getNotification(Notification.UnknownError)); } + } else { + this.submitRequest(false); + this.submitError(getNotification(Notification.UnknownError)); + } + }, + this.email(), + '', + sLoginPassword, + !!this.signMe(), + this.bSendLanguage ? this.language() : '', + this.additionalCode.visibility() ? this.additionalCode() : '', + this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false + ); - }, - this.email(), - '', - sLoginPassword, - !!this.signMe(), - this.bSendLanguage ? this.language() : '', - this.additionalCode.visibility() ? this.additionalCode() : '', - this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false - ); - - Local.set(ClientSideKeyName.LastSignMe, this.signMe() ? '-1-' : '-0-'); - - }; + Local.set(ClientSideKeyName.LastSignMe, this.signMe() ? '-1-' : '-0-'); + }; fLoginRequest(this.password()); @@ -348,20 +310,13 @@ class LoginUserView extends AbstractViewNext } onShowWithDelay() { - if ('' !== this.email() && '' !== this.password()) - { + if ('' !== this.email() && '' !== this.password()) { this.passwordFocus(true); - } - else if ('' === this.email()) - { + } else if ('' === this.email()) { this.emailFocus(true); - } - else if ('' === this.password()) - { + } else if ('' === this.password()) { this.passwordFocus(true); - } - else - { + } else { this.emailFocus(true); } } @@ -372,38 +327,36 @@ class LoginUserView extends AbstractViewNext } onBuild() { - const - signMeLocal = Local.get(ClientSideKeyName.LastSignMe), + const signMeLocal = Local.get(ClientSideKeyName.LastSignMe), signMe = (Settings.settingsGet('SignMe') || 'unused').toLowerCase(), jsHash = Settings.appSettingsGet('jsHash'), fSocial = (iErrorCode) => { iErrorCode = pInt(iErrorCode); - if (0 === iErrorCode) - { + if (0 === iErrorCode) { this.submitRequest(true); getApp().loginAndLogoutReload(false); - } - else - { + } else { this.submitError(getNotification(iErrorCode)); } }; this.facebookLoginEnabled(!!Settings.settingsGet('AllowFacebookSocial')); this.twitterLoginEnabled(!!Settings.settingsGet('AllowTwitterSocial')); - this.googleLoginEnabled(!!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialAuth')); - this.googleFastLoginEnabled(!!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialAuthFast')); + this.googleLoginEnabled( + !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialAuth') + ); + this.googleFastLoginEnabled( + !!Settings.settingsGet('AllowGoogleSocial') && !!Settings.settingsGet('AllowGoogleSocialAuthFast') + ); - switch (signMe) - { + switch (signMe) { case LoginSignMeTypeAsString.DefaultOff: case LoginSignMeTypeAsString.DefaultOn: + this.signMeType( + LoginSignMeTypeAsString.DefaultOn === signMe ? LoginSignMeType.DefaultOn : LoginSignMeType.DefaultOff + ); - this.signMeType(LoginSignMeTypeAsString.DefaultOn === signMe ? - LoginSignMeType.DefaultOn : LoginSignMeType.DefaultOff); - - switch (signMeLocal) - { + switch (signMeLocal) { case '-1-': this.signMeType(LoginSignMeType.DefaultOn); break; @@ -423,36 +376,32 @@ class LoginUserView extends AbstractViewNext this.email(AppStore.devEmail); this.password(AppStore.devPassword); - if (this.googleLoginEnabled() || this.googleFastLoginEnabled()) - { + if (this.googleLoginEnabled() || this.googleFastLoginEnabled()) { window['rl_' + jsHash + '_google_login_service'] = fSocial; } - if (this.facebookLoginEnabled()) - { + if (this.facebookLoginEnabled()) { window['rl_' + jsHash + '_facebook_login_service'] = fSocial; } - if (this.twitterLoginEnabled()) - { + if (this.twitterLoginEnabled()) { window['rl_' + jsHash + '_twitter_login_service'] = fSocial; } _.delay(() => { - LanguageStore.language.subscribe((value) => { - this.langRequest(true); - translatorReload(false, value).then(() => { - this.langRequest(false); - this.bSendLanguage = true; - }, () => { - this.langRequest(false); - }); - + translatorReload(false, value).then( + () => { + this.langRequest(false); + this.bSendLanguage = true; + }, + () => { + this.langRequest(false); + } + ); }); - }, Magics.Time50ms); triggerAutocompleteInputChange(true); @@ -463,14 +412,11 @@ class LoginUserView extends AbstractViewNext } selectLanguage() { - showScreenPopup(require('View/Popup/Languages'), [ - this.language, this.languages(), LanguageStore.userLanguage() - ]); + showScreenPopup(require('View/Popup/Languages'), [this.language, this.languages(), LanguageStore.userLanguage()]); } selectLanguageOnTab(bShift) { - if (!bShift) - { + if (!bShift) { _.delay(() => { this.emailFocus(true); }, Magics.Time50ms); @@ -482,4 +428,4 @@ class LoginUserView extends AbstractViewNext } } -export {LoginUserView, LoginUserView as default}; +export { LoginUserView, LoginUserView as default }; diff --git a/dev/View/User/MailBox/FolderList.js b/dev/View/User/MailBox/FolderList.js index c482f0aa4..57e1ac4a1 100644 --- a/dev/View/User/MailBox/FolderList.js +++ b/dev/View/User/MailBox/FolderList.js @@ -1,14 +1,13 @@ - import window from 'window'; import $ from '$'; import ko from 'ko'; import key from 'key'; -import {trim, isNormal, isArray, windowResize} from 'Common/Utils'; -import {Capa, Focused, Layout, KeyState, EventKeyCode, Magics} from 'Common/Enums'; -import {$html, leftPanelDisabled, moveAction} from 'Common/Globals'; -import {mailBox, settings} from 'Common/Links'; -import {setFolderHash} from 'Common/Cache'; +import { trim, isNormal, isArray, windowResize } from 'Common/Utils'; +import { Capa, Focused, Layout, KeyState, EventKeyCode, Magics } from 'Common/Enums'; +import { $html, leftPanelDisabled, moveAction } from 'Common/Globals'; +import { mailBox, settings } from 'Common/Links'; +import { setFolderHash } from 'Common/Cache'; import AppStore from 'Stores/User/App'; import SettingsStore from 'Stores/User/Settings'; @@ -17,18 +16,17 @@ import MessageStore from 'Stores/User/Message'; import * as Settings from 'Storage/Settings'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {view, ViewType, showScreenPopup, setHash} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType, showScreenPopup, setHash } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/User/MailBox/FolderList', type: ViewType.Left, templateID: 'MailFolderList' }) -class FolderListMailBoxUserView extends AbstractViewNext -{ +class FolderListMailBoxUserView extends AbstractViewNext { constructor() { super(); @@ -57,40 +55,34 @@ class FolderListMailBoxUserView extends AbstractViewNext this.folderListFocused = ko.computed(() => Focused.FolderList === AppStore.focusedState()); this.isInboxStarred = ko.computed( - () => FolderStore.currentFolder() && + () => + FolderStore.currentFolder() && FolderStore.currentFolder().isInbox() && -1 < trim(MessageStore.messageListSearch()).indexOf('is:flagged') ); } onBuild(dom) { - this.oContentVisible = $('.b-content', dom); this.oContentScrollable = $('.content', this.oContentVisible); - const - self = this, + const self = this, isMobile = Settings.appSettingsGet('mobile'), fSelectFolder = (el, event, starred) => { - const isMove = moveAction(); - if (isMobile) - { + if (isMobile) { leftPanelDisabled(true); } event.preventDefault(); - if (starred) - { + if (starred) { event.stopPropagation(); } const folder = ko.dataFor(el); - if (folder) - { - if (isMove) - { + if (folder) { + if (isMove) { moveAction(false); getApp().moveMessagesToFolder( FolderStore.currentFolderFullNameRaw(), @@ -98,25 +90,18 @@ class FolderListMailBoxUserView extends AbstractViewNext folder.fullNameRaw, false ); - } - else - { - if (Layout.NoPreview === SettingsStore.layout()) - { + } else { + if (Layout.NoPreview === SettingsStore.layout()) { MessageStore.message(null); } - if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) - { + if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { setFolderHash(folder.fullNameRaw, ''); } - if (starred) - { + if (starred) { setHash(mailBox(folder.fullNameHash, 1, 'is:flagged')); - } - else - { + } else { setHash(mailBox(folder.fullNameHash)); } } @@ -126,10 +111,10 @@ class FolderListMailBoxUserView extends AbstractViewNext }; dom - .on('click', '.b-folders .e-item .e-link .e-collapsed-sign', function(event) { // eslint-disable-line prefer-arrow-callback + .on('click', '.b-folders .e-item .e-link .e-collapsed-sign', function(event) { + // eslint-disable-line prefer-arrow-callback const folder = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (folder && event) - { + if (folder && event) { const collapsed = folder.collapsed(); getApp().setExpandedFolder(folder.fullNameHash, collapsed); @@ -138,33 +123,28 @@ class FolderListMailBoxUserView extends AbstractViewNext event.stopPropagation(); } }) - .on('click', '.b-folders .e-item .e-link.selectable .inbox-star-icon', function(event) { // eslint-disable-line prefer-arrow-callback + .on('click', '.b-folders .e-item .e-link.selectable .inbox-star-icon', function(event) { + // eslint-disable-line prefer-arrow-callback fSelectFolder(this, event, !self.isInboxStarred()); // eslint-disable-line no-invalid-this }) - .on('click', '.b-folders .e-item .e-link.selectable', function(event) { // eslint-disable-line prefer-arrow-callback + .on('click', '.b-folders .e-item .e-link.selectable', function(event) { + // eslint-disable-line prefer-arrow-callback fSelectFolder(this, event, false); // eslint-disable-line no-invalid-this }); key('up, down', KeyState.FolderList, (event, handler) => { - - const - keyCode = handler && 'up' === handler.shortcut ? EventKeyCode.Up : EventKeyCode.Down, + const keyCode = handler && 'up' === handler.shortcut ? EventKeyCode.Up : EventKeyCode.Down, $items = $('.b-folders .e-item .e-link:not(.hidden):visible', dom); - if (event && $items.length) - { + if (event && $items.length) { let index = $items.index($items.filter('.focused')); - if (-1 < index) - { + if (-1 < index) { $items.eq(index).removeClass('focused'); } - if (EventKeyCode.Up === keyCode && 0 < index) - { + if (EventKeyCode.Up === keyCode && 0 < index) { index -= 1; - } - else if (EventKeyCode.Down === keyCode && index < $items.length - 1) - { + } else if (EventKeyCode.Down === keyCode && index < $items.length - 1) { index += 1; } @@ -177,8 +157,7 @@ class FolderListMailBoxUserView extends AbstractViewNext key('enter', KeyState.FolderList, () => { const $items = $('.b-folders .e-item .e-link:not(.hidden).focused', dom); - if ($items.length && $items[0]) - { + if ($items.length && $items[0]) { AppStore.focusedState(Focused.MessageList); $items.click(); } @@ -188,11 +167,9 @@ class FolderListMailBoxUserView extends AbstractViewNext key('space', KeyState.FolderList, () => { const $items = $('.b-folders .e-item .e-link:not(.hidden).focused', dom); - if ($items.length && $items[0]) - { + if ($items.length && $items[0]) { const folder = ko.dataFor($items[0]); - if (folder) - { + if (folder) { const collapsed = folder.collapsed(); getApp().setExpandedFolder(folder.fullNameHash, collapsed); folder.collapsed(!collapsed); @@ -210,8 +187,7 @@ class FolderListMailBoxUserView extends AbstractViewNext AppStore.focusedState.subscribe((value) => { $('.b-folders .e-item .e-link.focused', dom).removeClass('focused'); - if (Focused.FolderList === value) - { + if (Focused.FolderList === value) { $('.b-folders .e-item .e-link.selected', dom).addClass('focused'); } }); @@ -219,8 +195,7 @@ class FolderListMailBoxUserView extends AbstractViewNext messagesDropOver(folder) { window.clearTimeout(this.iDropOverTimer); - if (folder && folder.collapsed()) - { + if (folder && folder.collapsed()) { this.iDropOverTimer = window.setTimeout(() => { folder.collapsed(false); getApp().setExpandedFolder(folder.fullNameHash, true); @@ -234,27 +209,23 @@ class FolderListMailBoxUserView extends AbstractViewNext } scrollToFocused() { - if (!this.oContentVisible || !this.oContentScrollable) - { + if (!this.oContentVisible || !this.oContentScrollable) { return false; } - const - offset = 20, + const offset = 20, focused = $('.e-item .e-link.focused', this.oContentScrollable), pos = focused.position(), visibleHeight = this.oContentVisible.height(), focusedHeight = focused.outerHeight(); - if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight)) - { - if (0 > pos.top) - { + if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight)) { + if (0 > pos.top) { this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + pos.top - offset); - } - else - { - this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset); + } else { + this.oContentScrollable.scrollTop( + this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset + ); } return true; @@ -269,23 +240,19 @@ class FolderListMailBoxUserView extends AbstractViewNext * @returns {void} */ messagesDrop(toFolder, ui) { - if (toFolder && ui && ui.helper) - { - const - fromFolderFullNameRaw = ui.helper.data('rl-folder'), + if (toFolder && ui && ui.helper) { + const fromFolderFullNameRaw = ui.helper.data('rl-folder'), copy = $html.hasClass('rl-ctrl-key-pressed'), uids = ui.helper.data('rl-uids'); - if (isNormal(fromFolderFullNameRaw) && '' !== fromFolderFullNameRaw && isArray(uids)) - { + if (isNormal(fromFolderFullNameRaw) && '' !== fromFolderFullNameRaw && isArray(uids)) { getApp().moveMessagesToFolder(fromFolderFullNameRaw, uids, toFolder.fullNameRaw, copy); } } } composeClick() { - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose')); } } @@ -299,11 +266,10 @@ class FolderListMailBoxUserView extends AbstractViewNext } contactsClick() { - if (this.allowContacts) - { + if (this.allowContacts) { showScreenPopup(require('View/Popup/Contacts')); } } } -export {FolderListMailBoxUserView, FolderListMailBoxUserView as default}; +export { FolderListMailBoxUserView, FolderListMailBoxUserView as default }; diff --git a/dev/View/User/MailBox/MessageList.js b/dev/View/User/MailBox/MessageList.js index c82c6a630..221924f25 100644 --- a/dev/View/User/MailBox/MessageList.js +++ b/dev/View/User/MailBox/MessageList.js @@ -1,4 +1,3 @@ - import window from 'window'; import _ from '_'; import $ from '$'; @@ -8,40 +7,34 @@ import Jua from 'Jua'; import ifvisible from 'ifvisible'; import { - Capa, Layout, Focused, ComposeType, - FolderType, Magics, MessageSetAction, KeyState, + Capa, + Layout, + Focused, + ComposeType, + FolderType, + Magics, + MessageSetAction, + KeyState, StorageResultType } from 'Common/Enums'; -import { - UNUSED_OPTION_VALUE -} from 'Common/Consts'; +import { UNUSED_OPTION_VALUE } from 'Common/Consts'; -import { - bMobileDevice, - popupVisibility, - leftPanelDisabled, - moveAction -} from 'Common/Globals'; +import { bMobileDevice, popupVisibility, leftPanelDisabled, moveAction } from 'Common/Globals'; -import { - noop, - noopFalse, - computedPagenatorHelper, - draggablePlace, - friendlySize, - inArray, isUnd -} from 'Common/Utils'; +import { noop, noopFalse, computedPagenatorHelper, draggablePlace, friendlySize, inArray, isUnd } from 'Common/Utils'; -import {mailBox, append} from 'Common/Links'; -import {Selector} from 'Common/Selector'; +import { mailBox, append } from 'Common/Links'; +import { Selector } from 'Common/Selector'; import * as Events from 'Common/Events'; -import {i18n, initOnStartOrLangChange} from 'Common/Translator'; +import { i18n, initOnStartOrLangChange } from 'Common/Translator'; import { - getFolderFromCacheList, clearMessageFlagsFromCacheByFolder, - hasRequestedMessage, addRequestedMessage + getFolderFromCacheList, + clearMessageFlagsFromCacheByFolder, + hasRequestedMessage, + addRequestedMessage } from 'Common/Cache'; import AppStore from 'Stores/User/App'; @@ -53,10 +46,10 @@ import MessageStore from 'Stores/User/Message'; import * as Settings from 'Storage/Settings'; import Remote from 'Remote/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {view, command, ViewType, showScreenPopup, setHash} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, command, ViewType, showScreenPopup, setHash } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; const canBeMovedHelper = (self) => self.canBeMoved(); @@ -65,8 +58,7 @@ const canBeMovedHelper = (self) => self.canBeMoved(); type: ViewType.Right, templateID: 'MailMessageList' }) -class MessageListMailBoxUserView extends AbstractViewNext -{ +class MessageListMailBoxUserView extends AbstractViewNext { constructor() { super(); @@ -130,23 +122,25 @@ class MessageListMailBoxUserView extends AbstractViewNext this.moreDropdownTrigger = ko.observable(false); // append drag and drop - this.dragOver = ko.observable(false).extend({'throttle': 1}); - this.dragOverEnter = ko.observable(false).extend({'throttle': 1}); + this.dragOver = ko.observable(false).extend({ 'throttle': 1 }); + this.dragOverEnter = ko.observable(false).extend({ 'throttle': 1 }); this.dragOverArea = ko.observable(null); this.dragOverBodyArea = ko.observable(null); - this.messageListItemTemplate = ko.computed( - () => (this.mobile || Layout.SidePreview === SettingsStore.layout() ? - 'MailMessageListItem' : 'MailMessageListItemNoPreviewPane') + this.messageListItemTemplate = ko.computed(() => + this.mobile || Layout.SidePreview === SettingsStore.layout() + ? 'MailMessageListItem' + : 'MailMessageListItemNoPreviewPane' ); this.messageListSearchDesc = ko.computed(() => { const value = MessageStore.messageListEndSearch(); - return '' === value ? '' : i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', {'SEARCH': value}); + return '' === value ? '' : i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', { 'SEARCH': value }); }); this.messageListPagenator = ko.computed( - computedPagenatorHelper(MessageStore.messageListPage, MessageStore.messageListPageCount)); + computedPagenatorHelper(MessageStore.messageListPage, MessageStore.messageListPageCount) + ); this.checkAll = ko.computed({ read: () => 0 < MessageStore.messageListChecked().length, @@ -169,8 +163,7 @@ class MessageListMailBoxUserView extends AbstractViewNext }); this.isIncompleteChecked = ko.computed(() => { - const - m = MessageStore.messageList().length, + const m = MessageStore.messageList().length, c = MessageStore.messageListChecked().length; return 0 < m && 0 < c && m > c; }); @@ -232,9 +225,14 @@ class MessageListMailBoxUserView extends AbstractViewNext this.quotaTooltip = _.bind(this.quotaTooltip, this); this.selector = new Selector( - this.messageList, this.selectorMessageSelected, this.selectorMessageFocused, - '.messageListItem .actionHandle', '.messageListItem.selected', - '.messageListItem .checkboxMessage', '.messageListItem.focused'); + this.messageList, + this.selectorMessageSelected, + this.selectorMessageFocused, + '.messageListItem .actionHandle', + '.messageListItem.selected', + '.messageListItem .checkboxMessage', + '.messageListItem.focused' + ); this.selector.on('onItemSelect', (message) => { MessageStore.selectMessage(message); @@ -257,28 +255,24 @@ class MessageListMailBoxUserView extends AbstractViewNext }); Events.sub('mailbox.message.show', (sFolder, sUid) => { + const message = _.find( + this.messageList(), + (item) => item && sFolder === item.folderFullNameRaw && sUid === item.uid + ); - const message = _.find(this.messageList(), (item) => item && sFolder === item.folderFullNameRaw && sUid === item.uid); - - if ('INBOX' === sFolder) - { + if ('INBOX' === sFolder) { setHash(mailBox(sFolder, 1)); } - if (message) - { + if (message) { this.selector.selectMessageItem(message); - } - else - { - if ('INBOX' !== sFolder) - { + } else { + if ('INBOX' !== sFolder) { setHash(mailBox(sFolder, 1)); } MessageStore.selectMessageByFolderAndUid(sFolder, sUid); } - }); MessageStore.messageListEndHash.subscribe(() => { @@ -288,65 +282,78 @@ class MessageListMailBoxUserView extends AbstractViewNext @command() clearCommand() { - if (Settings.capa(Capa.DangerousActions)) - { + if (Settings.capa(Capa.DangerousActions)) { showScreenPopup(require('View/Popup/FolderClear'), [FolderStore.currentFolder()]); } } @command() reloadCommand() { - if (!MessageStore.messageListCompleteLoadingThrottleForAnimation() && this.allowReload) - { + if (!MessageStore.messageListCompleteLoadingThrottleForAnimation() && this.allowReload) { getApp().reloadMessageList(false, true); } } @command(canBeMovedHelper) multyForwardCommand() { - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose'), [ - ComposeType.ForwardAsAttachment, MessageStore.messageListCheckedOrSelected()]); + ComposeType.ForwardAsAttachment, + MessageStore.messageListCheckedOrSelected() + ]); } } @command(canBeMovedHelper) deleteWithoutMoveCommand() { - if (Settings.capa(Capa.DangerousActions)) - { - getApp().deleteMessagesFromFolder(FolderType.Trash, + if (Settings.capa(Capa.DangerousActions)) { + getApp().deleteMessagesFromFolder( + FolderType.Trash, FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), false); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + false + ); } } @command(canBeMovedHelper) deleteCommand() { - getApp().deleteMessagesFromFolder(FolderType.Trash, + getApp().deleteMessagesFromFolder( + FolderType.Trash, FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + true + ); } @command(canBeMovedHelper) archiveCommand() { - getApp().deleteMessagesFromFolder(FolderType.Archive, + getApp().deleteMessagesFromFolder( + FolderType.Archive, FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + true + ); } @command(canBeMovedHelper) spamCommand() { - getApp().deleteMessagesFromFolder(FolderType.Spam, + getApp().deleteMessagesFromFolder( + FolderType.Spam, FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + true + ); } @command(canBeMovedHelper) notSpamCommand() { - getApp().deleteMessagesFromFolder(FolderType.NotSpam, + getApp().deleteMessagesFromFolder( + FolderType.NotSpam, FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), true); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + true + ); } @command(canBeMovedHelper) @@ -354,8 +361,7 @@ class MessageListMailBoxUserView extends AbstractViewNext @command(canBeMovedHelper) moveNewCommand(vm, event) { - if (this.newMoveToFolder() && this.mobileCheckedStateShow()) - { + if (this.newMoveToFolder() && this.mobileCheckedStateShow()) { if (vm && event && event.preventDefault) { event.preventDefault(); if (event.stopPropagation) { @@ -363,13 +369,10 @@ class MessageListMailBoxUserView extends AbstractViewNext } } - if (moveAction()) - { + if (moveAction()) { AppStore.focusedState(Focused.MessageList); moveAction(false); - } - else - { + } else { AppStore.focusedState(Focused.FolderList); moveAction(true); } @@ -391,45 +394,35 @@ class MessageListMailBoxUserView extends AbstractViewNext } composeClick() { - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose')); } } goToUpUpOrDownDown(up) { - - if (0 < this.messageListChecked().length) - { + if (0 < this.messageListChecked().length) { return false; } window.clearTimeout(this.iGoToUpUpOrDownDownTimeout); this.iGoToUpUpOrDownDownTimeout = window.setTimeout(() => { - - let - prev = null, + let prev = null, next = null, temp = null, current = null; _.find(this.messageListPagenator(), (item) => { - - if (item) - { - if (current) - { + if (item) { + if (current) { next = item; } - if (item.current) - { + if (item.current) { current = item; prev = temp; } - if (next) - { + if (next) { return true; } @@ -439,34 +432,27 @@ class MessageListMailBoxUserView extends AbstractViewNext return false; }); - if (Layout.NoPreview === SettingsStore.layout() && !this.message()) - { + if (Layout.NoPreview === SettingsStore.layout() && !this.message()) { this.selector.iFocusedNextHelper = up ? -1 : 1; - } - else - { + } else { this.selector.iSelectNextHelper = up ? -1 : 1; } - if (up ? prev : next) - { + if (up ? prev : next) { this.selector.unselect(); this.gotoPage(up ? prev : next); } - }, Magics.Time350ms); return true; } useAutoSelect() { - if (this.messageListDisableAutoSelect()) - { + if (this.messageListDisableAutoSelect()) { return false; } - if ((/is:unseen/).test(this.mainMessageListSearch())) - { + if (/is:unseen/.test(this.mainMessageListSearch())) { return false; } @@ -492,11 +478,13 @@ class MessageListMailBoxUserView extends AbstractViewNext } cancelThreadUid() { - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - MessageStore.messageListPageBeforeThread(), - MessageStore.messageListSearch() - )); + setHash( + mailBox( + FolderStore.currentFolderFullNameHash(), + MessageStore.messageListPageBeforeThread(), + MessageStore.messageListSearch() + ) + ); } /** @@ -505,24 +493,24 @@ class MessageListMailBoxUserView extends AbstractViewNext * @returns {boolean} */ moveSelectedMessagesToFolder(sToFolderFullNameRaw, bCopy) { - if (this.canBeMoved()) - { + if (this.canBeMoved()) { getApp().moveMessagesToFolder( FolderStore.currentFolderFullNameRaw(), - MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy); + MessageStore.messageListCheckedOrSelectedUidsWithSubMails(), + sToFolderFullNameRaw, + bCopy + ); } return false; } dragAndDronHelper(oMessageListItem) { - if (oMessageListItem) - { + if (oMessageListItem) { oMessageListItem.checked(true); } - const - el = draggablePlace(), + const el = draggablePlace(), updateUidsInfo = () => { const uids = MessageStore.messageListCheckedOrSelectedUidsWithSubMails(); el.data('rl-uids', uids); @@ -554,23 +542,18 @@ class MessageListMailBoxUserView extends AbstractViewNext * @returns {void} */ setActionForAll(sFolderFullNameRaw, iSetAction, sThreadUid = '') { - if ('' !== sFolderFullNameRaw) - { + if ('' !== sFolderFullNameRaw) { let cnt = 0; const uids = []; let folder = getFolderFromCacheList(sFolderFullNameRaw); - if (folder) - { - switch (iSetAction) - { + if (folder) { + switch (iSetAction) { case MessageSetAction.SetSeen: folder = getFolderFromCacheList(sFolderFullNameRaw); - if (folder) - { + if (folder) { _.each(MessageStore.messageList(), (message) => { - if (message.unseen()) - { + if (message.unseen()) { cnt += 1; } @@ -578,16 +561,12 @@ class MessageListMailBoxUserView extends AbstractViewNext uids.push(message.uid); }); - if (sThreadUid) - { + if (sThreadUid) { folder.messageCountUnread(folder.messageCountUnread() - cnt); - if (0 > folder.messageCountUnread()) - { + if (0 > folder.messageCountUnread()) { folder.messageCountUnread(0); } - } - else - { + } else { folder.messageCountUnread(0); } @@ -598,11 +577,9 @@ class MessageListMailBoxUserView extends AbstractViewNext break; case MessageSetAction.UnsetSeen: folder = getFolderFromCacheList(sFolderFullNameRaw); - if (folder) - { + if (folder) { _.each(MessageStore.messageList(), (message) => { - if (!message.unseen()) - { + if (!message.unseen()) { cnt += 1; } @@ -610,16 +587,12 @@ class MessageListMailBoxUserView extends AbstractViewNext uids.push(message.uid); }); - if (sThreadUid) - { + if (sThreadUid) { folder.messageCountUnread(folder.messageCountUnread() + cnt); - if (folder.messageCountAll() < folder.messageCountUnread()) - { + if (folder.messageCountAll() < folder.messageCountUnread()) { folder.messageCountUnread(folder.messageCountAll()); } - } - else - { + } else { folder.messageCountUnread(folder.messageCountAll()); } @@ -637,117 +610,137 @@ class MessageListMailBoxUserView extends AbstractViewNext } listSetSeen() { - this.setAction(FolderStore.currentFolderFullNameRaw(), - MessageSetAction.SetSeen, MessageStore.messageListCheckedOrSelected()); + this.setAction( + FolderStore.currentFolderFullNameRaw(), + MessageSetAction.SetSeen, + MessageStore.messageListCheckedOrSelected() + ); } listSetAllSeen() { - this.setActionForAll(FolderStore.currentFolderFullNameRaw(), MessageSetAction.SetSeen, this.messageListEndThreadUid()); + this.setActionForAll( + FolderStore.currentFolderFullNameRaw(), + MessageSetAction.SetSeen, + this.messageListEndThreadUid() + ); } listUnsetSeen() { - this.setAction(FolderStore.currentFolderFullNameRaw(), - MessageSetAction.UnsetSeen, MessageStore.messageListCheckedOrSelected()); + this.setAction( + FolderStore.currentFolderFullNameRaw(), + MessageSetAction.UnsetSeen, + MessageStore.messageListCheckedOrSelected() + ); } listSetFlags() { - this.setAction(FolderStore.currentFolderFullNameRaw(), - MessageSetAction.SetFlag, MessageStore.messageListCheckedOrSelected()); + this.setAction( + FolderStore.currentFolderFullNameRaw(), + MessageSetAction.SetFlag, + MessageStore.messageListCheckedOrSelected() + ); } listUnsetFlags() { - this.setAction(FolderStore.currentFolderFullNameRaw(), - MessageSetAction.UnsetFlag, MessageStore.messageListCheckedOrSelected()); + this.setAction( + FolderStore.currentFolderFullNameRaw(), + MessageSetAction.UnsetFlag, + MessageStore.messageListCheckedOrSelected() + ); } flagMessages(currentMessage) { const checked = this.messageListCheckedOrSelected(); - if (currentMessage) - { + if (currentMessage) { const checkedUids = _.map(checked, (message) => message.uid); - if (0 < checkedUids.length && -1 < inArray(currentMessage.uid, checkedUids)) - { - this.setAction(currentMessage.folderFullNameRaw, currentMessage.flagged() ? - MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, checked); - } - else - { - this.setAction(currentMessage.folderFullNameRaw, currentMessage.flagged() ? - MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, [currentMessage]); + if (0 < checkedUids.length && -1 < inArray(currentMessage.uid, checkedUids)) { + this.setAction( + currentMessage.folderFullNameRaw, + currentMessage.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + checked + ); + } else { + this.setAction( + currentMessage.folderFullNameRaw, + currentMessage.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + [currentMessage] + ); } } } flagMessagesFast(bFlag) { const checked = this.messageListCheckedOrSelected(); - if (0 < checked.length) - { - if (isUnd(bFlag)) - { + if (0 < checked.length) { + if (isUnd(bFlag)) { const flagged = _.filter(checked, (message) => message.flagged()); - this.setAction(checked[0].folderFullNameRaw, - checked.length === flagged.length ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, checked); - } - else - { - this.setAction(checked[0].folderFullNameRaw, - !bFlag ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, checked); + this.setAction( + checked[0].folderFullNameRaw, + checked.length === flagged.length ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + checked + ); + } else { + this.setAction( + checked[0].folderFullNameRaw, + !bFlag ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + checked + ); } } } seenMessagesFast(seen) { const checked = this.messageListCheckedOrSelected(); - if (0 < checked.length) - { - if (isUnd(seen)) - { + if (0 < checked.length) { + if (isUnd(seen)) { const unseen = _.filter(checked, (message) => message.unseen()); - this.setAction(checked[0].folderFullNameRaw, - 0 < unseen.length ? MessageSetAction.SetSeen : MessageSetAction.UnsetSeen, checked); - } - else - { - this.setAction(checked[0].folderFullNameRaw, - seen ? MessageSetAction.SetSeen : MessageSetAction.UnsetSeen, checked); + this.setAction( + checked[0].folderFullNameRaw, + 0 < unseen.length ? MessageSetAction.SetSeen : MessageSetAction.UnsetSeen, + checked + ); + } else { + this.setAction( + checked[0].folderFullNameRaw, + seen ? MessageSetAction.SetSeen : MessageSetAction.UnsetSeen, + checked + ); } } } gotoPage(page) { - if (page) - { - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - page.value, - MessageStore.messageListSearch(), - MessageStore.messageListThreadUid() - )); + if (page) { + setHash( + mailBox( + FolderStore.currentFolderFullNameHash(), + page.value, + MessageStore.messageListSearch(), + MessageStore.messageListThreadUid() + ) + ); } } gotoThread(message) { - if (message && 0 < message.threadsLen()) - { + if (message && 0 < message.threadsLen()) { MessageStore.messageListPageBeforeThread(MessageStore.messageListPage()); - setHash(mailBox( - FolderStore.currentFolderFullNameHash(), - 1, - MessageStore.messageListSearch(), - message.uid - )); + setHash(mailBox(FolderStore.currentFolderFullNameHash(), 1, MessageStore.messageListSearch(), message.uid)); } } clearListIsVisible() { - return '' === this.messageListSearchDesc() && '' === this.messageListError() && + return ( + '' === this.messageListSearchDesc() && + '' === this.messageListError() && '' === this.messageListEndThreadUid() && - 0 < this.messageList().length && (this.isSpamFolder() || this.isTrashFolder()); + 0 < this.messageList().length && + (this.isSpamFolder() || this.isTrashFolder()) + ); } onBuild(dom) { - const self = this; this.oContentVisible = $('.b-content', dom); @@ -755,42 +748,42 @@ class MessageListMailBoxUserView extends AbstractViewNext this.selector.init(this.oContentVisible, this.oContentScrollable, KeyState.MessageList); - if (this.mobile) - { - dom - .on('click', () => { - leftPanelDisabled(true); - }); + if (this.mobile) { + dom.on('click', () => { + leftPanelDisabled(true); + }); } dom .on('click', '.messageList .b-message-list-wrapper', () => { - if (Focused.MessageView === AppStore.focusedState()) - { + if (Focused.MessageView === AppStore.focusedState()) { AppStore.focusedState(Focused.MessageList); } }) - .on('click', '.e-pagenator .e-page', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.e-pagenator .e-page', function() { + // eslint-disable-line prefer-arrow-callback self.gotoPage(ko.dataFor(this)); // eslint-disable-line no-invalid-this }) .on('click', '.messageList .checkboxCkeckAll', () => { this.checkAll(!this.checkAll()); }) - .on('click', '.messageList .messageListItem .flagParent', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.messageList .messageListItem .flagParent', function() { + // eslint-disable-line prefer-arrow-callback self.flagMessages(ko.dataFor(this)); // eslint-disable-line no-invalid-this }) - .on('click', '.messageList .messageListItem .threads-len', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.messageList .messageListItem .threads-len', function() { + // eslint-disable-line prefer-arrow-callback self.gotoThread(ko.dataFor(this)); // eslint-disable-line no-invalid-this }) - .on('dblclick', '.messageList .messageListItem .actionHandle', function() { // eslint-disable-line prefer-arrow-callback + .on('dblclick', '.messageList .messageListItem .actionHandle', function() { + // eslint-disable-line prefer-arrow-callback self.gotoThread(ko.dataFor(this)); // eslint-disable-line no-invalid-this }); this.initUploaderForAppend(); this.initShortcuts(); - if (!bMobileDevice && ifvisible && Settings.capa(Capa.Prefetch)) - { + if (!bMobileDevice && ifvisible && Settings.capa(Capa.Prefetch)) { ifvisible.setIdleDuration(Magics.ifvisibleIdle10s); ifvisible.idle(() => { @@ -800,10 +793,8 @@ class MessageListMailBoxUserView extends AbstractViewNext } initShortcuts() { - key('enter', KeyState.MessageList, () => { - if (this.message() && this.useAutoSelect()) - { + if (this.message() && this.useAutoSelect()) { Events.pub('mailbox.message-view.toggle-full-screen'); return false; } @@ -811,8 +802,7 @@ class MessageListMailBoxUserView extends AbstractViewNext return true; }); - if (Settings.capa(Capa.MessageListActions)) - { + if (Settings.capa(Capa.MessageListActions)) { // archive (zip) key('z', [KeyState.MessageList, KeyState.MessageView], () => { this.archiveCommand(); @@ -821,16 +811,11 @@ class MessageListMailBoxUserView extends AbstractViewNext // delete key('delete, shift+delete, shift+3', KeyState.MessageList, (event, handler) => { - if (event) - { - if (0 < MessageStore.messageListCheckedOrSelected().length) - { - if (handler && 'shift+delete' === handler.shortcut) - { + if (event) { + if (0 < MessageStore.messageListCheckedOrSelected().length) { + if (handler && 'shift+delete' === handler.shortcut) { this.deleteWithoutMoveCommand(); - } - else - { + } else { this.deleteCommand(); } } @@ -842,8 +827,7 @@ class MessageListMailBoxUserView extends AbstractViewNext }); } - if (Settings.capa(Capa.Reload)) - { + if (Settings.capa(Capa.Reload)) { // check mail key('ctrl+r, command+r', [KeyState.FolderList, KeyState.MessageList, KeyState.MessageView], () => { this.reloadCommand(); @@ -857,8 +841,7 @@ class MessageListMailBoxUserView extends AbstractViewNext return false; }); - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { // write/compose (open compose popup) key('w,c', [KeyState.MessageList, KeyState.MessageView], () => { showScreenPopup(require('View/Popup/Compose')); @@ -866,8 +849,7 @@ class MessageListMailBoxUserView extends AbstractViewNext }); } - if (Settings.capa(Capa.MessageListActions)) - { + if (Settings.capa(Capa.MessageListActions)) { // important - star/flag messages key('i', [KeyState.MessageList, KeyState.MessageView], () => { this.flagMessagesFast(); @@ -876,32 +858,24 @@ class MessageListMailBoxUserView extends AbstractViewNext } key('t', [KeyState.MessageList], () => { - let message = this.selectorMessageSelected(); - if (!message) - { + if (!message) { message = this.selectorMessageFocused(); } - if (message && 0 < message.threadsLen()) - { + if (message && 0 < message.threadsLen()) { this.gotoThread(message); } return false; }); - if (Settings.capa(Capa.MessageListActions)) - { + if (Settings.capa(Capa.MessageListActions)) { // move key('m', KeyState.MessageList, () => { - - if (this.newMoveToFolder()) - { + if (this.newMoveToFolder()) { this.moveNewCommand(); - } - else - { + } else { this.moveDropdownTrigger(true); } @@ -909,8 +883,7 @@ class MessageListMailBoxUserView extends AbstractViewNext }); } - if (Settings.capa(Capa.MessageListActions)) - { + if (Settings.capa(Capa.MessageListActions)) { // read key('q', [KeyState.MessageList, KeyState.MessageView], () => { this.seenMessagesFast(true); @@ -924,16 +897,14 @@ class MessageListMailBoxUserView extends AbstractViewNext }); } - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { key('shift+f', [KeyState.MessageList, KeyState.MessageView], () => { this.multyForwardCommand(); return false; }); } - if (Settings.capa(Capa.Search)) - { + if (Settings.capa(Capa.Search)) { // search input focus key('/', [KeyState.MessageList, KeyState.MessageView], () => { this.inputMessageListSearchFocus(true); @@ -943,13 +914,10 @@ class MessageListMailBoxUserView extends AbstractViewNext // cancel search key('esc', KeyState.MessageList, () => { - if ('' !== this.messageListSearchDesc()) - { + if ('' !== this.messageListSearchDesc()) { this.cancelSearch(); return false; - } - else if ('' !== this.messageListEndThreadUid()) - { + } else if ('' !== this.messageListEndThreadUid()) { this.cancelThreadUid(); return false; } @@ -959,12 +927,9 @@ class MessageListMailBoxUserView extends AbstractViewNext // change focused state key('tab, shift+tab, left, right', KeyState.MessageList, (event, handler) => { - if (event && handler && ('shift+tab' === handler.shortcut || 'left' === handler.shortcut)) - { + if (event && handler && ('shift+tab' === handler.shortcut || 'left' === handler.shortcut)) { AppStore.focusedState(Focused.FolderList); - } - else if (this.message()) - { + } else if (this.message()) { AppStore.focusedState(Focused.MessageView); } @@ -976,33 +941,35 @@ class MessageListMailBoxUserView extends AbstractViewNext } prefetchNextTick() { - if (ifvisible && !this.bPrefetch && !ifvisible.now() && this.viewModelVisibility()) - { - const message = _.find(this.messageList(), (item) => item && !hasRequestedMessage(item.folderFullNameRaw, item.uid)); - if (message) - { + if (ifvisible && !this.bPrefetch && !ifvisible.now() && this.viewModelVisibility()) { + const message = _.find( + this.messageList(), + (item) => item && !hasRequestedMessage(item.folderFullNameRaw, item.uid) + ); + if (message) { this.bPrefetch = true; addRequestedMessage(message.folderFullNameRaw, message.uid); - Remote.message((result, data) => { - const next = !!(StorageResultType.Success === result && data && data.Result); - _.delay(() => { - this.bPrefetch = false; - if (next) - { - this.prefetchNextTick(); - } - }, Magics.Time1s); - - }, message.folderFullNameRaw, message.uid); + Remote.message( + (result, data) => { + const next = !!(StorageResultType.Success === result && data && data.Result); + _.delay(() => { + this.bPrefetch = false; + if (next) { + this.prefetchNextTick(); + } + }, Magics.Time1s); + }, + message.folderFullNameRaw, + message.uid + ); } } } advancedSearchClick() { - if (Settings.capa(Capa.SearchAdv)) - { + if (Settings.capa(Capa.SearchAdv)) { showScreenPopup(require('View/Popup/AdvancedSearch'), [this.mainMessageListSearch()]); } } @@ -1016,27 +983,24 @@ class MessageListMailBoxUserView extends AbstractViewNext } initUploaderForAppend() { - if (!Settings.appSettingsGet('allowAppendMessage') || !this.dragOverArea()) - { + if (!Settings.appSettingsGet('allowAppendMessage') || !this.dragOverArea()) { return false; } - const - oJua = new Jua({ - action: append(), - name: 'AppendFile', - queueSize: 1, - multipleSizeLimit: 1, - hidden: { - Folder: () => FolderStore.currentFolderFullNameRaw() - }, - dragAndDropElement: this.dragOverArea(), - dragAndDropBodyElement: this.dragOverBodyArea() - }); + const oJua = new Jua({ + action: append(), + name: 'AppendFile', + queueSize: 1, + multipleSizeLimit: 1, + hidden: { + Folder: () => FolderStore.currentFolderFullNameRaw() + }, + dragAndDropElement: this.dragOverArea(), + dragAndDropBodyElement: this.dragOverBodyArea() + }); this.dragOver.subscribe((value) => { - if (value) - { + if (value) { this.selector.scrollToTop(); } }); @@ -1055,15 +1019,12 @@ class MessageListMailBoxUserView extends AbstractViewNext this.dragOver(false); }) .on('onSelect', (sUid, oData) => { - - if (sUid && oData && 'message/rfc822' === oData.Type) - { + if (sUid && oData && 'message/rfc822' === oData.Type) { MessageStore.messageListLoading(true); return true; } return false; - }) .on('onComplete', () => { getApp().reloadMessageList(true, true); @@ -1073,4 +1034,4 @@ class MessageListMailBoxUserView extends AbstractViewNext } } -export {MessageListMailBoxUserView, MessageListMailBoxUserView as default}; +export { MessageListMailBoxUserView, MessageListMailBoxUserView as default }; diff --git a/dev/View/User/MailBox/MessageView.js b/dev/View/User/MailBox/MessageView.js index 0a894fce3..6179e9bc9 100644 --- a/dev/View/User/MailBox/MessageView.js +++ b/dev/View/User/MailBox/MessageView.js @@ -1,41 +1,47 @@ - import window from 'window'; import _ from '_'; import $ from '$'; import ko from 'ko'; import key from 'key'; -import {DATA_IMAGE_USER_DOT_PIC, UNUSED_OPTION_VALUE} from 'Common/Consts'; +import { DATA_IMAGE_USER_DOT_PIC, UNUSED_OPTION_VALUE } from 'Common/Consts'; import { - Capa, ComposeType, ClientSideKeyName, KeyState, - FolderType, Focused, Layout, Magics, MessageSetAction + Capa, + ComposeType, + ClientSideKeyName, + KeyState, + FolderType, + Focused, + Layout, + Magics, + MessageSetAction } from 'Common/Enums'; -import { - $html, - leftPanelDisabled, - keyScopeReal, - useKeyboardShortcuts, - moveAction -} from 'Common/Globals'; +import { $html, leftPanelDisabled, keyScopeReal, useKeyboardShortcuts, moveAction } from 'Common/Globals'; import { - inArray, isArray, isNonEmptyArray, trim, noop, - windowResize, windowResizeCallback, inFocus, - removeSelection, removeInFocus, mailToHelper, isTransparent + inArray, + isArray, + isNonEmptyArray, + trim, + noop, + windowResize, + windowResizeCallback, + inFocus, + removeSelection, + removeInFocus, + mailToHelper, + isTransparent } from 'Common/Utils'; import Audio from 'Common/Audio'; import * as Events from 'Common/Events'; -import {i18n} from 'Common/Translator'; -import {attachmentDownload} from 'Common/Links'; +import { i18n } from 'Common/Translator'; +import { attachmentDownload } from 'Common/Links'; -import { - getUserPic, - storeMessageFlagsToCache -} from 'Common/Cache'; +import { getUserPic, storeMessageFlagsToCache } from 'Common/Cache'; import SocialStore from 'Stores/Social'; import AppStore from 'Stores/User/App'; @@ -50,45 +56,36 @@ import * as Settings from 'Storage/Settings'; import Remote from 'Remote/User/Ajax'; import Promises from 'Promises/User/Ajax'; -import {getApp} from 'Helper/Apps/User'; +import { getApp } from 'Helper/Apps/User'; -import {view, command, ViewType, showScreenPopup, createCommand} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, command, ViewType, showScreenPopup, createCommand } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/User/MailBox/MessageView', type: ViewType.Right, templateID: 'MailMessageView' }) -class MessageViewMailBoxUserView extends AbstractViewNext -{ +class MessageViewMailBoxUserView extends AbstractViewNext { constructor() { super(); let lastEmail = ''; - const - createCommandReplyHelper = (type) => createCommand( - () => { - this.lastReplyAction(type); - this.replyOrforward(type); - }, - this.canBeRepliedOrForwarded - ); + const createCommandReplyHelper = (type) => + createCommand(() => { + this.lastReplyAction(type); + this.replyOrforward(type); + }, this.canBeRepliedOrForwarded); - const - createCommandActionHelper = (folderType, useFolder) => createCommand( - () => { - const message = this.message(); - if (message && this.allowMessageListActions) - { - this.message(null); - getApp().deleteMessagesFromFolder( - folderType, message.folderFullNameRaw, [message.uid], useFolder); - } - }, - this.messageVisibility - ); + const createCommandActionHelper = (folderType, useFolder) => + createCommand(() => { + const message = this.message(); + if (message && this.allowMessageListActions) { + this.message(null); + getApp().deleteMessagesFromFolder(folderType, message.folderFullNameRaw, [message.uid], useFolder); + } + }, this.messageVisibility); this.oDom = null; this.oHeaderDom = null; @@ -127,8 +124,8 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.fullScreenMode = MessageStore.messageFullScreenMode; - this.messageListOfThreadsLoading = ko.observable(false).extend({rateLimit: 1}); - this.highlightUnselectedAttachments = ko.observable(false).extend({falseTimeout: 2000}); + this.messageListOfThreadsLoading = ko.observable(false).extend({ rateLimit: 1 }); + this.highlightUnselectedAttachments = ko.observable(false).extend({ falseTimeout: 2000 }); this.showAttachmnetControls = ko.observable(false); @@ -145,26 +142,24 @@ class MessageViewMailBoxUserView extends AbstractViewNext ); this.downloadAsZipLoading = ko.observable(false); - this.downloadAsZipError = ko.observable(false).extend({falseTimeout: 7000}); + this.downloadAsZipError = ko.observable(false).extend({ falseTimeout: 7000 }); this.saveToOwnCloudAllowed = ko.computed( () => -1 < inArray('owncloud', this.attachmentsActions()) && this.allowAttachmnetControls() ); this.saveToOwnCloudLoading = ko.observable(false); - this.saveToOwnCloudSuccess = ko.observable(false).extend({falseTimeout: 2000}); - this.saveToOwnCloudError = ko.observable(false).extend({falseTimeout: 7000}); + this.saveToOwnCloudSuccess = ko.observable(false).extend({ falseTimeout: 2000 }); + this.saveToOwnCloudError = ko.observable(false).extend({ falseTimeout: 7000 }); this.saveToOwnCloudSuccess.subscribe((v) => { - if (v) - { + if (v) { this.saveToOwnCloudError(false); } }); this.saveToOwnCloudError.subscribe((v) => { - if (v) - { + if (v) { this.saveToOwnCloudSuccess(false); } }); @@ -174,29 +169,25 @@ class MessageViewMailBoxUserView extends AbstractViewNext ); this.saveToDropboxLoading = ko.observable(false); - this.saveToDropboxSuccess = ko.observable(false).extend({falseTimeout: 2000}); - this.saveToDropboxError = ko.observable(false).extend({falseTimeout: 7000}); + this.saveToDropboxSuccess = ko.observable(false).extend({ falseTimeout: 2000 }); + this.saveToDropboxError = ko.observable(false).extend({ falseTimeout: 7000 }); this.saveToDropboxSuccess.subscribe((v) => { - if (v) - { + if (v) { this.saveToDropboxError(false); } }); this.saveToDropboxError.subscribe((v) => { - if (v) - { + if (v) { this.saveToDropboxSuccess(false); } }); this.showAttachmnetControls.subscribe((v) => { - if (this.message()) - { + if (this.message()) { _.each(this.message().attachments(), (item) => { - if (item) - { + if (item) { item.checked(!!v); } }); @@ -207,9 +198,11 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.lastReplyAction = ko.computed({ read: this.lastReplyAction_, write: (value) => { - this.lastReplyAction_(-1 === inArray(value, [ - ComposeType.Reply, ComposeType.ReplyAll, ComposeType.Forward - ]) ? ComposeType.Reply : value); + this.lastReplyAction_( + -1 === inArray(value, [ComposeType.Reply, ComposeType.ReplyAll, ComposeType.Forward]) + ? ComposeType.Reply + : value + ); } }); @@ -222,13 +215,12 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.showFullInfo = ko.observable('1' === Local.get(ClientSideKeyName.MessageHeaderFullInfo)); this.moreDropdownTrigger = ko.observable(false); - this.messageDomFocused = ko.observable(false).extend({rateLimit: 0}); + this.messageDomFocused = ko.observable(false).extend({ rateLimit: 0 }); this.messageVisibility = ko.computed(() => !this.messageLoadingThrottle() && !!this.message()); this.message.subscribe((message) => { - if (!message) - { + if (!message) { MessageStore.selectorMessageSelected(null); } }); @@ -284,8 +276,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.viewFromDkimVisibility = ko.computed(() => 'none' !== this.viewFromDkimData()[0]); this.viewFromDkimStatusIconClass = ko.computed(() => { - switch (this.viewFromDkimData()[0]) - { + switch (this.viewFromDkimData()[0]) { case 'none': return 'icon-none iconcolor-display-none'; case 'pass': @@ -296,16 +287,11 @@ class MessageViewMailBoxUserView extends AbstractViewNext }); this.viewFromDkimStatusTitle = ko.computed(() => { - const status = this.viewFromDkimData(); - if (isNonEmptyArray(status)) - { - if (status[0] && status[1]) - { + if (isNonEmptyArray(status)) { + if (status[0] && status[1]) { return status[1]; - } - else if (status[0]) - { + } else if (status[0]) { return 'DKIM: ' + status[0]; } } @@ -318,21 +304,17 @@ class MessageViewMailBoxUserView extends AbstractViewNext }, this); this.message.subscribe((message) => { - this.messageActiveDom(null); - if (message) - { + if (message) { this.showAttachmnetControls(false); - if (Local.get(ClientSideKeyName.MessageAttachmnetControls)) - { + if (Local.get(ClientSideKeyName.MessageAttachmnetControls)) { _.delay(() => { this.showAttachmnetControls(true); }, Magics.Time50ms); } - if (this.viewHash !== message.hash) - { + if (this.viewHash !== message.hash) { this.scrollMessageToTop(); } @@ -359,37 +341,29 @@ class MessageViewMailBoxUserView extends AbstractViewNext lastEmail = message.fromAsSingleEmail(); getUserPic(lastEmail, (pic, email) => { - if (pic !== this.viewUserPic() && lastEmail === email) - { + if (pic !== this.viewUserPic() && lastEmail === email) { this.viewUserPicVisible(false); this.viewUserPic(DATA_IMAGE_USER_DOT_PIC); - if ('' !== pic) - { + if ('' !== pic) { this.viewUserPicVisible(true); this.viewUserPic(pic); } } }); - } - else - { + } else { this.viewFolder = ''; this.viewUid = ''; this.viewHash = ''; this.scrollMessageToTop(); } - }); this.message.viewTrigger.subscribe(() => { const message = this.message(); - if (message) - { + if (message) { this.viewIsFlagged(message.flagged()); - } - else - { + } else { this.viewIsFlagged(false); } }); @@ -429,35 +403,27 @@ class MessageViewMailBoxUserView extends AbstractViewNext @command((self) => !self.messageListAndMessageViewLoading()) goUpCommand() { - Events.pub('mailbox.message-list.selector.go-up', [ - Layout.NoPreview === this.layout() ? !!this.message() : true - ]); + Events.pub('mailbox.message-list.selector.go-up', [Layout.NoPreview === this.layout() ? !!this.message() : true]); } @command((self) => !self.messageListAndMessageViewLoading()) goDownCommand() { - Events.pub('mailbox.message-list.selector.go-down', [ - Layout.NoPreview === this.layout() ? !!this.message() : true - ]); + Events.pub('mailbox.message-list.selector.go-down', [Layout.NoPreview === this.layout() ? !!this.message() : true]); } detectDomBackgroundColor(dom) { - let - limit = 5, + let limit = 5, result = ''; - const - fFindDom = function(inputDom) { + const fFindDom = function(inputDom) { const children = inputDom ? inputDom.children() : null; - return (children && 1 === children.length && children.is('table,div,center')) ? children : null; + return children && 1 === children.length && children.is('table,div,center') ? children : null; }, fFindColor = function(inputDom) { let color = ''; - if (inputDom) - { + if (inputDom) { color = inputDom.css('background-color') || ''; - if (!inputDom.is('table')) - { + if (!inputDom.is('table')) { color = isTransparent(color) ? '' : color; } } @@ -465,24 +431,18 @@ class MessageViewMailBoxUserView extends AbstractViewNext return color; }; - if (dom && 1 === dom.length) - { + if (dom && 1 === dom.length) { let aC = dom; - while ('' === result) - { + while ('' === result) { limit -= 1; - if (0 >= limit) - { + if (0 >= limit) { break; } aC = fFindDom(aC); - if (aC) - { + if (aC) { result = fFindColor(aC); - } - else - { + } else { break; } } @@ -515,17 +475,20 @@ class MessageViewMailBoxUserView extends AbstractViewNext * @returns {void} */ replyOrforward(sType) { - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose'), [sType, MessageStore.message()]); } } checkHeaderHeight() { - if (this.oHeaderDom) - { - this.viewBodyTopValue(this.message() ? this.oHeaderDom.height() + - Magics.Size20px /* padding-(top/bottom): 20px */ + Magics.Size1px /* borded-bottom: 1px */ : 0); + if (this.oHeaderDom) { + this.viewBodyTopValue( + this.message() + ? this.oHeaderDom.height() + + Magics.Size20px /* padding-(top/bottom): 20px */ + + Magics.Size1px /* borded-bottom: 1px */ + : 0 + ); } } @@ -556,37 +519,33 @@ class MessageViewMailBoxUserView extends AbstractViewNext * @returns {boolean} */ attachmentPreview(attachment) { - if (attachment && attachment.isImage() && !attachment.isLinked && this.message() && this.message().attachments()) - { - let - index = 0, + if (attachment && attachment.isImage() && !attachment.isLinked && this.message() && this.message().attachments()) { + let index = 0, listIndex = 0; - const - div = $(''), - dynamicEls = _.compact(_.map(this.message().attachments(), (item) => { - if (item && !item.isLinked && item.isImage()) - { - if (item === attachment) - { - index = listIndex; + const div = $(''), + dynamicEls = _.compact( + _.map(this.message().attachments(), (item) => { + if (item && !item.isLinked && item.isImage()) { + if (item === attachment) { + index = listIndex; + } + + listIndex += 1; + + return { + src: item.linkPreview(), + thumb: item.linkThumbnail(), + subHtml: item.fileName, + downloadUrl: item.linkPreview() + }; } - listIndex += 1; + return null; + }) + ); - return { - src: item.linkPreview(), - thumb: item.linkThumbnail(), - subHtml: item.fileName, - downloadUrl: item.linkPreview() - }; - } - - return null; - })); - - if (0 < dynamicEls.length) - { + if (0 < dynamicEls.length) { div.on('onBeforeOpen.lg', () => { useKeyboardShortcuts(false); removeInFocus(true); @@ -616,16 +575,13 @@ class MessageViewMailBoxUserView extends AbstractViewNext } onBuild(dom) { - - const - self = this, + const self = this, fCheckHeaderHeight = _.bind(this.checkHeaderHeight, this); this.oDom = dom; this.fullScreenMode.subscribe((value) => { - if (value && this.message()) - { + if (value && this.message()) { AppStore.focusedState(Focused.MessageView); } }); @@ -635,11 +591,14 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.showFullInfo.subscribe(fCheckHeaderHeight); this.message.subscribe(fCheckHeaderHeight); - Events.sub('window.resize', _.throttle(() => { - _.delay(fCheckHeaderHeight, 1); - _.delay(fCheckHeaderHeight, Magics.Time200ms); - _.delay(fCheckHeaderHeight, Magics.Time500ms); - }, Magics.Time50ms)); + Events.sub( + 'window.resize', + _.throttle(() => { + _.delay(fCheckHeaderHeight, 1); + _.delay(fCheckHeaderHeight, Magics.Time200ms); + _.delay(fCheckHeaderHeight, Magics.Time500ms); + }, Magics.Time50ms) + ); this.showFullInfo.subscribe((value) => { windowResize(); @@ -652,37 +611,39 @@ class MessageViewMailBoxUserView extends AbstractViewNext this.oHeaderDom = $('.messageItemHeader', dom); this.oHeaderDom = this.oHeaderDom[0] ? this.oHeaderDom : null; - if (this.mobile) - { + if (this.mobile) { dom.on('click', () => { leftPanelDisabled(true); }); } dom - .on('click', 'a', function(event) { // eslint-disable-line prefer-arrow-callback + .on('click', 'a', function(event) { + // eslint-disable-line prefer-arrow-callback // setup maito protocol - return !(!!event && Magics.EventWhichMouseMiddle !== event.which && mailToHelper( - $(this).attr('href'), Settings.capa(Capa.Composer) ? require('View/Popup/Compose') : null // eslint-disable-line no-invalid-this - )); + return !( + !!event && + Magics.EventWhichMouseMiddle !== event.which && + mailToHelper( + $(this).attr('href'), + Settings.capa(Capa.Composer) ? require('View/Popup/Compose') : null // eslint-disable-line no-invalid-this + ) + ); }) .on('click', '.attachmentsPlace .attachmentIconParent', (event) => { - if (event && event.stopPropagation) - { + if (event && event.stopPropagation) { event.stopPropagation(); } }) - .on('click', '.attachmentsPlace .showPreplay', function(event) { // eslint-disable-line prefer-arrow-callback - if (event && event.stopPropagation) - { + .on('click', '.attachmentsPlace .showPreplay', function(event) { + // eslint-disable-line prefer-arrow-callback + if (event && event.stopPropagation) { event.stopPropagation(); } const attachment = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (attachment && Audio.supported) - { - switch (true) - { + if (attachment && Audio.supported) { + switch (true) { case Audio.supportedMp3 && attachment.isMp3(): Audio.playMp3(attachment.linkDownload(), attachment.fileName); break; @@ -696,27 +657,33 @@ class MessageViewMailBoxUserView extends AbstractViewNext } } }) - .on('click', '.attachmentsPlace .attachmentItem .attachmentNameParent', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.attachmentsPlace .attachmentItem .attachmentNameParent', function() { + // eslint-disable-line prefer-arrow-callback const attachment = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (attachment && attachment.download) - { + if (attachment && attachment.download) { getApp().download(attachment.linkDownload()); } }) - .on('click', '.messageItemHeader .subjectParent .flagParent', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.messageItemHeader .subjectParent .flagParent', function() { + // eslint-disable-line prefer-arrow-callback const message = self.message(); - if (message) - { - getApp().messageListAction(message.folderFullNameRaw, - message.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, [message]); + if (message) { + getApp().messageListAction( + message.folderFullNameRaw, + message.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + [message] + ); } }) - .on('click', '.thread-list .flagParent', function() { // eslint-disable-line prefer-arrow-callback + .on('click', '.thread-list .flagParent', function() { + // eslint-disable-line prefer-arrow-callback const message = ko.dataFor(this); // eslint-disable-line no-invalid-this - if (message && message.folder && message.uid) - { - getApp().messageListAction(message.folder, - message.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, [message]); + if (message && message.folder && message.uid) { + getApp().messageListAction( + message.folder, + message.flagged() ? MessageSetAction.UnsetFlag : MessageSetAction.SetFlag, + [message] + ); } self.threadsDropdownTrigger(true); @@ -725,8 +692,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext }); AppStore.focusedState.subscribe((value) => { - if (Focused.MessageView !== value) - { + if (Focused.MessageView !== value) { this.scrollMessageToTop(); this.scrollMessageToLeft(); } @@ -737,7 +703,8 @@ class MessageViewMailBoxUserView extends AbstractViewNext }); this.oMessageScrollerDom = dom.find('.messageItem .content'); - this.oMessageScrollerDom = this.oMessageScrollerDom && this.oMessageScrollerDom[0] ? this.oMessageScrollerDom : null; + this.oMessageScrollerDom = + this.oMessageScrollerDom && this.oMessageScrollerDom[0] ? this.oMessageScrollerDom : null; this.initShortcuts(); } @@ -746,23 +713,16 @@ class MessageViewMailBoxUserView extends AbstractViewNext * @returns {boolean} */ escShortcuts() { - if (this.viewModelVisibility() && this.message()) - { - if (this.fullScreenMode()) - { + if (this.viewModelVisibility() && this.message()) { + if (this.fullScreenMode()) { this.fullScreenMode(false); - if (Layout.NoPreview !== this.layout()) - { + if (Layout.NoPreview !== this.layout()) { AppStore.focusedState(Focused.MessageList); } - } - else if (Layout.NoPreview === this.layout()) - { + } else if (Layout.NoPreview === this.layout()) { this.message(null); - } - else - { + } else { AppStore.focusedState(Focused.MessageList); } @@ -773,7 +733,6 @@ class MessageViewMailBoxUserView extends AbstractViewNext } initShortcuts() { - // exit fullscreen, back key('esc, backspace', KeyState.MessageView, _.bind(this.escShortcuts, this)); @@ -785,8 +744,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext // reply key('r', [KeyState.MessageList, KeyState.MessageView], () => { - if (MessageStore.message()) - { + if (MessageStore.message()) { this.replyCommand(); return false; } @@ -796,8 +754,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext // replaAll key('a', [KeyState.MessageList, KeyState.MessageView], () => { - if (MessageStore.message()) - { + if (MessageStore.message()) { this.replyAllCommand(); return false; } @@ -807,8 +764,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext // forward key('f', [KeyState.MessageList, KeyState.MessageView], () => { - if (MessageStore.message()) - { + if (MessageStore.message()) { this.forwardCommand(); return false; } @@ -818,8 +774,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext // message information key('ctrl+i, command+i', [KeyState.MessageList, KeyState.MessageView], () => { - if (MessageStore.message()) - { + if (MessageStore.message()) { this.showFullInfo(!this.showFullInfo()); } return false; @@ -827,9 +782,10 @@ class MessageViewMailBoxUserView extends AbstractViewNext // toggle message blockquotes key('b', [KeyState.MessageList, KeyState.MessageView], () => { - if (MessageStore.message() && MessageStore.message().body) - { - MessageStore.message().body.find('.rlBlockquoteSwitcher').click(); + if (MessageStore.message() && MessageStore.message().body) { + MessageStore.message() + .body.find('.rlBlockquoteSwitcher') + .click(); return false; } @@ -848,8 +804,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext // print key('ctrl+p, command+p', [KeyState.MessageView, KeyState.MessageList], () => { - if (this.message()) - { + if (this.message()) { this.message().printMessage(); } @@ -858,14 +813,10 @@ class MessageViewMailBoxUserView extends AbstractViewNext // delete key('delete, shift+delete', KeyState.MessageView, (event, handler) => { - if (event) - { - if (handler && 'shift+delete' === handler.shortcut) - { + if (event) { + if (handler && 'shift+delete' === handler.shortcut) { this.deleteWithoutMoveCommand(); - } - else - { + } else { this.deleteCommand(); } @@ -877,24 +828,23 @@ class MessageViewMailBoxUserView extends AbstractViewNext // change focused state key('tab, shift+tab, left', KeyState.MessageView, (event, handler) => { - if (!this.fullScreenMode() && this.message() && Layout.NoPreview !== this.layout()) - { - if (event && handler && 'left' === handler.shortcut) - { - if (this.oMessageScrollerDom && 0 < this.oMessageScrollerDom.scrollLeft()) - { + if (!this.fullScreenMode() && this.message() && Layout.NoPreview !== this.layout()) { + if (event && handler && 'left' === handler.shortcut) { + if (this.oMessageScrollerDom && 0 < this.oMessageScrollerDom.scrollLeft()) { return true; } AppStore.focusedState(Focused.MessageList); - } - else - { + } else { AppStore.focusedState(Focused.MessageList); } - } - else if (this.message() && Layout.NoPreview === this.layout() && event && handler && 'left' === handler.shortcut) - { + } else if ( + this.message() && + Layout.NoPreview === this.layout() && + event && + handler && + 'left' === handler.shortcut + ) { return true; } @@ -952,30 +902,22 @@ class MessageViewMailBoxUserView extends AbstractViewNext } composeClick() { - if (Settings.capa(Capa.Composer)) - { + if (Settings.capa(Capa.Composer)) { showScreenPopup(require('View/Popup/Compose')); } } editMessage() { - if (Settings.capa(Capa.Composer) && MessageStore.message()) - { + if (Settings.capa(Capa.Composer) && MessageStore.message()) { showScreenPopup(require('View/Popup/Compose'), [ComposeType.Draft, MessageStore.message()]); } } scrollMessageToTop() { - if (this.oMessageScrollerDom) - { - if (Magics.Size50px < this.oMessageScrollerDom.scrollTop()) - { - this.oMessageScrollerDom - .scrollTop(Magics.Size50px) - .animate({'scrollTop': 0}, Magics.Time200ms); - } - else - { + if (this.oMessageScrollerDom) { + if (Magics.Size50px < this.oMessageScrollerDom.scrollTop()) { + this.oMessageScrollerDom.scrollTop(Magics.Size50px).animate({ 'scrollTop': 0 }, Magics.Time200ms); + } else { this.oMessageScrollerDom.scrollTop(0); } @@ -984,8 +926,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext } scrollMessageToLeft() { - if (this.oMessageScrollerDom) - { + if (this.oMessageScrollerDom) { this.oMessageScrollerDom.scrollLeft(0); windowResize(); } @@ -998,108 +939,90 @@ class MessageViewMailBoxUserView extends AbstractViewNext downloadAsZip() { const hashes = this.getAttachmentsHashes(); - if (0 < hashes.length) - { - Promises.attachmentsActions('Zip', hashes, this.downloadAsZipLoading).then((result) => { - if (result && result.Result && result.Result.Files && - result.Result.Files[0] && result.Result.Files[0].Hash) - { - getApp().download(attachmentDownload(result.Result.Files[0].Hash)); - } - else - { + if (0 < hashes.length) { + Promises.attachmentsActions('Zip', hashes, this.downloadAsZipLoading) + .then((result) => { + if (result && result.Result && result.Result.Files && result.Result.Files[0] && result.Result.Files[0].Hash) { + getApp().download(attachmentDownload(result.Result.Files[0].Hash)); + } else { + this.downloadAsZipError(true); + } + }) + .catch(() => { this.downloadAsZipError(true); - } - }).catch(() => { - this.downloadAsZipError(true); - }); - } - else - { + }); + } else { this.highlightUnselectedAttachments(true); } } saveToOwnCloud() { - const hashes = this.getAttachmentsHashes(); - if (0 < hashes.length) - { - Promises.attachmentsActions('OwnCloud', hashes, this.saveToOwnCloudLoading).then((result) => { - if (result && result.Result) - { - this.saveToOwnCloudSuccess(true); - } - else - { + if (0 < hashes.length) { + Promises.attachmentsActions('OwnCloud', hashes, this.saveToOwnCloudLoading) + .then((result) => { + if (result && result.Result) { + this.saveToOwnCloudSuccess(true); + } else { + this.saveToOwnCloudError(true); + } + }) + .catch(() => { this.saveToOwnCloudError(true); - } - }).catch(() => { - this.saveToOwnCloudError(true); - }); - } - else - { + }); + } else { this.highlightUnselectedAttachments(true); } } saveToDropbox() { - - const - files = [], + const files = [], hashes = this.getAttachmentsHashes(); - if (0 < hashes.length) - { - if (window.Dropbox) - { - Promises.attachmentsActions('Dropbox', hashes, this.saveToDropboxLoading).then((result) => { - if (result && result.Result && result.Result.Url && result.Result.ShortLife && result.Result.Files) - { - if (window.Dropbox && isArray(result.Result.Files)) - { - _.each(result.Result.Files, (item) => { - files.push({ - url: result.Result.Url + attachmentDownload(item.Hash, result.Result.ShortLife), - filename: item.FileName + if (0 < hashes.length) { + if (window.Dropbox) { + Promises.attachmentsActions('Dropbox', hashes, this.saveToDropboxLoading) + .then((result) => { + if (result && result.Result && result.Result.Url && result.Result.ShortLife && result.Result.Files) { + if (window.Dropbox && isArray(result.Result.Files)) { + _.each(result.Result.Files, (item) => { + files.push({ + url: result.Result.Url + attachmentDownload(item.Hash, result.Result.ShortLife), + filename: item.FileName + }); }); - }); - window.Dropbox.save({ - files: files, - progress: () => { - this.saveToDropboxLoading(true); - this.saveToDropboxError(false); - this.saveToDropboxSuccess(false); - }, - cancel: () => { - this.saveToDropboxSuccess(false); - this.saveToDropboxError(false); - this.saveToDropboxLoading(false); - }, - success: () => { - this.saveToDropboxSuccess(true); - this.saveToDropboxLoading(false); - }, - error: () => { - this.saveToDropboxError(true); - this.saveToDropboxLoading(false); - } - }); + window.Dropbox.save({ + files: files, + progress: () => { + this.saveToDropboxLoading(true); + this.saveToDropboxError(false); + this.saveToDropboxSuccess(false); + }, + cancel: () => { + this.saveToDropboxSuccess(false); + this.saveToDropboxError(false); + this.saveToDropboxLoading(false); + }, + success: () => { + this.saveToDropboxSuccess(true); + this.saveToDropboxLoading(false); + }, + error: () => { + this.saveToDropboxError(true); + this.saveToDropboxLoading(false); + } + }); + } else { + this.saveToDropboxError(true); + } } - else - { - this.saveToDropboxError(true); - } - } - }).catch(() => { - this.saveToDropboxError(true); - }); + }) + .catch(() => { + this.saveToDropboxError(true); + }); } - } - else - { + } else { this.highlightUnselectedAttachments(true); } } @@ -1109,8 +1032,7 @@ class MessageViewMailBoxUserView extends AbstractViewNext * @returns {void} */ showImages(message) { - if (message && message.showExternalImages) - { + if (message && message.showExternalImages) { message.showExternalImages(true); } @@ -1130,12 +1052,15 @@ class MessageViewMailBoxUserView extends AbstractViewNext * @returns {void} */ readReceipt(oMessage) { - if (oMessage && '' !== oMessage.readReceipt()) - { - Remote.sendReadReceiptMessage(noop, oMessage.folderFullNameRaw, oMessage.uid, + if (oMessage && '' !== oMessage.readReceipt()) { + Remote.sendReadReceiptMessage( + noop, + oMessage.folderFullNameRaw, + oMessage.uid, oMessage.readReceipt(), - i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}), - i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': AccountStore.email()})); + i18n('READ_RECEIPT/SUBJECT', { 'SUBJECT': oMessage.subject() }), + i18n('READ_RECEIPT/BODY', { 'READ-RECEIPT': AccountStore.email() }) + ); oMessage.isReadReceipt(true); @@ -1148,4 +1073,4 @@ class MessageViewMailBoxUserView extends AbstractViewNext } } -export {MessageViewMailBoxUserView, MessageViewMailBoxUserView as default}; +export { MessageViewMailBoxUserView, MessageViewMailBoxUserView as default }; diff --git a/dev/View/User/MailBox/SystemDropDown.js b/dev/View/User/MailBox/SystemDropDown.js index cc74708b6..809f135cf 100644 --- a/dev/View/User/MailBox/SystemDropDown.js +++ b/dev/View/User/MailBox/SystemDropDown.js @@ -1,6 +1,5 @@ - -import {view, ViewType} from 'Knoin/Knoin'; -import {AbstractSystemDropDownUserView} from 'View/User/AbstractSystemDropDown'; +import { view, ViewType } from 'Knoin/Knoin'; +import { AbstractSystemDropDownUserView } from 'View/User/AbstractSystemDropDown'; @view({ name: 'View/User/MailBox/SystemDropDown', @@ -9,4 +8,4 @@ import {AbstractSystemDropDownUserView} from 'View/User/AbstractSystemDropDown'; }) class SystemDropDownMailBoxUserView extends AbstractSystemDropDownUserView {} -export {SystemDropDownMailBoxUserView, SystemDropDownMailBoxUserView as default}; +export { SystemDropDownMailBoxUserView, SystemDropDownMailBoxUserView as default }; diff --git a/dev/View/User/Settings/Menu.js b/dev/View/User/Settings/Menu.js index 6ee483732..2eae807c9 100644 --- a/dev/View/User/Settings/Menu.js +++ b/dev/View/User/Settings/Menu.js @@ -1,24 +1,22 @@ - import $ from '$'; import key from 'key'; -import {KeyState} from 'Common/Enums'; -import {leftPanelDisabled} from 'Common/Globals'; -import {settings, inbox} from 'Common/Links'; -import {getFolderInboxName} from 'Common/Cache'; +import { KeyState } from 'Common/Enums'; +import { leftPanelDisabled } from 'Common/Globals'; +import { settings, inbox } from 'Common/Links'; +import { getFolderInboxName } from 'Common/Cache'; import * as Settings from 'Storage/Settings'; -import {view, ViewType, setHash, settingsMenuKeysHandler} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType, setHash, settingsMenuKeysHandler } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/User/Settings/Menu', type: ViewType.Left, templateID: 'SettingsMenu' }) -class MenuSettingsUserView extends AbstractViewNext -{ +class MenuSettingsUserView extends AbstractViewNext { /** * @param {Object} screen */ @@ -33,8 +31,7 @@ class MenuSettingsUserView extends AbstractViewNext } onBuild(dom) { - if (this.mobile) - { + if (this.mobile) { dom.on('click', '.b-settings-menu .e-item.selectable', () => { leftPanelDisabled(true); }); @@ -52,4 +49,4 @@ class MenuSettingsUserView extends AbstractViewNext } } -export {MenuSettingsUserView, MenuSettingsUserView as default}; +export { MenuSettingsUserView, MenuSettingsUserView as default }; diff --git a/dev/View/User/Settings/Pane.js b/dev/View/User/Settings/Pane.js index ebaf49ca0..307c4000f 100644 --- a/dev/View/User/Settings/Pane.js +++ b/dev/View/User/Settings/Pane.js @@ -1,22 +1,20 @@ - -import {inbox} from 'Common/Links'; -import {getFolderInboxName} from 'Common/Cache'; -import {leftPanelDisabled} from 'Common/Globals'; +import { inbox } from 'Common/Links'; +import { getFolderInboxName } from 'Common/Cache'; +import { leftPanelDisabled } from 'Common/Globals'; import * as Settings from 'Storage/Settings'; import MessageStore from 'Stores/User/Message'; -import {view, ViewType, setHash} from 'Knoin/Knoin'; -import {AbstractViewNext} from 'Knoin/AbstractViewNext'; +import { view, ViewType, setHash } from 'Knoin/Knoin'; +import { AbstractViewNext } from 'Knoin/AbstractViewNext'; @view({ name: 'View/User/Settings/Pane', type: ViewType.Right, templateID: 'SettingsPane' }) -class PaneSettingsUserView extends AbstractViewNext -{ +class PaneSettingsUserView extends AbstractViewNext { constructor() { super(); @@ -44,8 +42,7 @@ class PaneSettingsUserView extends AbstractViewNext } onBuild(dom) { - if (this.mobile) - { + if (this.mobile) { dom.on('click', () => { leftPanelDisabled(true); }); @@ -57,4 +54,4 @@ class PaneSettingsUserView extends AbstractViewNext } } -export {PaneSettingsUserView, PaneSettingsUserView as default}; +export { PaneSettingsUserView, PaneSettingsUserView as default }; diff --git a/dev/View/User/Settings/SystemDropDown.js b/dev/View/User/Settings/SystemDropDown.js index 926b31375..3fdedcfd9 100644 --- a/dev/View/User/Settings/SystemDropDown.js +++ b/dev/View/User/Settings/SystemDropDown.js @@ -1,6 +1,5 @@ - -import {view, ViewType} from 'Knoin/Knoin'; -import {AbstractSystemDropDownUserView} from 'View/User/AbstractSystemDropDown'; +import { view, ViewType } from 'Knoin/Knoin'; +import { AbstractSystemDropDownUserView } from 'View/User/AbstractSystemDropDown'; @view({ name: 'View/User/Settings/SystemDropDown', @@ -9,4 +8,4 @@ import {AbstractSystemDropDownUserView} from 'View/User/AbstractSystemDropDown'; }) class SystemDropDownSettingsUserView extends AbstractSystemDropDownUserView {} -export {SystemDropDownSettingsUserView, SystemDropDownSettingsUserView as default}; +export { SystemDropDownSettingsUserView, SystemDropDownSettingsUserView as default }; diff --git a/dev/admin.js b/dev/admin.js index 75b836765..88fd6c8c8 100644 --- a/dev/admin.js +++ b/dev/admin.js @@ -1,4 +1,3 @@ - import bootstrap from 'bootstrap'; import App from 'App/Admin'; diff --git a/dev/app.js b/dev/app.js index 08aa049d5..7f4dcd596 100644 --- a/dev/app.js +++ b/dev/app.js @@ -1,4 +1,3 @@ - import bootstrap from 'bootstrap'; import App from 'App/User'; diff --git a/dev/boot.js b/dev/boot.js index 9e911d967..40fef1062 100644 --- a/dev/boot.js +++ b/dev/boot.js @@ -5,28 +5,25 @@ require('json3'); require('intersection-observer'); import window from 'window'; -import {progressJs} from '../vendors/Progress.js/src/progress.js'; +import { progressJs } from '../vendors/Progress.js/src/progress.js'; window.progressJs = window.progressJs || progressJs(); window.progressJs.onbeforeend(() => { const _$ = window.$; - if (_$) - { + if (_$) { try { _$('.progressjs-container').hide(); window.setTimeout(() => { _$('.progressjs-container').remove(); }, 200); // eslint-disable-line no-magic-numbers - } - catch (e) {} // eslint-disable-line no-empty + } catch (e) {} // eslint-disable-line no-empty } }); require('../vendors/modernizr/modernizr-custom.js'); require('Common/Booter'); -if (window.__runBoot) -{ +if (window.__runBoot) { window.__runBoot(); } diff --git a/dev/bootstrap.js b/dev/bootstrap.js index 1a7b99f79..5106eeb5d 100644 --- a/dev/bootstrap.js +++ b/dev/bootstrap.js @@ -1,25 +1,19 @@ - import window from 'window'; -import {killCtrlACtrlS, detectDropdownVisibility, createCommandLegacy, domReady} from 'Common/Utils'; -import {$win, $html, data as GlobalsData, bMobileDevice} from 'Common/Globals'; +import { killCtrlACtrlS, detectDropdownVisibility, createCommandLegacy, domReady } from 'Common/Utils'; +import { $win, $html, data as GlobalsData, bMobileDevice } from 'Common/Globals'; import * as Enums from 'Common/Enums'; import * as Plugins from 'Common/Plugins'; -import {i18n} from 'Common/Translator'; -import {EmailModel} from 'Model/Email'; +import { i18n } from 'Common/Translator'; +import { EmailModel } from 'Model/Email'; export default (App) => { - GlobalsData.__APP__ = App; - $win - .on('keydown', killCtrlACtrlS) - .on('unload', () => { - GlobalsData.bUnload = true; - }); + $win.on('keydown', killCtrlACtrlS).on('unload', () => { + GlobalsData.bUnload = true; + }); - $html - .addClass(bMobileDevice ? 'mobile' : 'no-mobile') - .on('click.dropdown.data-api', detectDropdownVisibility); + $html.addClass(bMobileDevice ? 'mobile' : 'no-mobile').on('click.dropdown.data-api', detectDropdownVisibility); const rl = window.rl || {}; @@ -40,34 +34,22 @@ export default (App) => { window.rl = rl; window.__APP_BOOT = (fErrorCallback) => { - domReady(() => { - window.setTimeout(() => { - - if (window.rainloopTEMPLATES && window.rainloopTEMPLATES[0]) - { + if (window.rainloopTEMPLATES && window.rainloopTEMPLATES[0]) { window.document.getElementById('rl-templates').innerHTML = window.rainloopTEMPLATES[0]; window.setTimeout(() => { - - $html - .removeClass('no-js rl-booted-trigger') - .addClass('rl-booted'); + $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted'); App.bootstart(); - }, Enums.Magics.Time10ms); - } - else - { + } else { fErrorCallback(); } window.__APP_BOOT = null; - }, Enums.Magics.Time10ms); - }); }; }; diff --git a/tasks/js.js b/tasks/js.js index 374c1ca88..0258ad2fc 100644 --- a/tasks/js.js +++ b/tasks/js.js @@ -82,8 +82,7 @@ const jsMin = () => .pipe(gulp.dest(config.paths.staticMinJS)) .on('error', gutil.log); -const jsLint = (cb) => cb(); -const jsLint1 = () => +const jsLint = () => gulp .src(config.paths.globjs) .pipe(cache('eslint'))