diff --git a/dev/App/Abstract.jsx b/dev/App/Abstract.jsx index de52c9667..6f26f78d5 100644 --- a/dev/App/Abstract.jsx +++ b/dev/App/Abstract.jsx @@ -1,8 +1,14 @@ import {window, _, $, key} from 'common'; -import Globals from 'Common/Globals'; -import * as Enums from 'Common/Enums'; -import Utils from 'Common/Utils'; + +import { + $win, $html, $doc, + startMicrotime, leftPanelDisabled, leftPanelType, + sUserAgent, bMobileDevice, bAnimationSupported +} from 'Common/Globals'; + +import {KeyState} from 'Common/Enums'; +import {noop, isNormal, pString, inArray, microtime, timestamp, detectDropdownVisibility, windowResizeCallback} from 'Common/Utils'; import Links from 'Common/Links'; import Events from 'Common/Events'; import Translator from 'Common/Translator'; @@ -15,6 +21,7 @@ class AbstractApp extends AbstractBoot googlePreviewSupportedCache = null; isLocalAutocomplete = true; iframe = null; + lastErrorTime = 0; /** * @param {RemoteStorage|AdminRemoteStorage} Remote @@ -25,39 +32,47 @@ class AbstractApp extends AbstractBoot this.iframe = $('').appendTo('body'); - Globals.$win.on('error', function (oEvent) { - if (oEvent && oEvent.originalEvent && oEvent.originalEvent.message && - -1 === Utils.inArray(oEvent.originalEvent.message, [ + $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.' ])) { + const time = timestamp(); + if (this.lastErrorTime >= time) + { + return; + } + + this.lastErrorTime = time; + Remote.jsError( - Utils.emptyFunction, - oEvent.originalEvent.message, - oEvent.originalEvent.filename, - oEvent.originalEvent.lineno, + noop, + event.originalEvent.message, + event.originalEvent.filename, + event.originalEvent.lineno, window.location && window.location.toString ? window.location.toString() : '', - Globals.$html.attr('class'), - Utils.microtime() - Globals.startMicrotime + $html.attr('class'), + microtime() - startMicrotime ); } }); - Globals.$win.on('resize', function () { + $win.on('resize', function () { Events.pub('window.resize'); }); Events.sub('window.resize', _.throttle(function () { var - iH = Globals.$win.height(), - iW = Globals.$win.height() + iH = $win.height(), + iW = $win.height() ; - if (Globals.$win.__sizes[0] !== iH || Globals.$win.__sizes[1] !== iW) + if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) { - Globals.$win.__sizes[0] = iH; - Globals.$win.__sizes[1] = iW; + $win.__sizes[0] = iH; + $win.__sizes[1] = iW; Events.pub('window.resize.real'); } @@ -74,24 +89,24 @@ class AbstractApp extends AbstractBoot // } // }); - Globals.$doc.on('keydown', function (oEvent) { + $doc.on('keydown', function (oEvent) { if (oEvent && oEvent.ctrlKey) { - Globals.$html.addClass('rl-ctrl-key-pressed'); + $html.addClass('rl-ctrl-key-pressed'); } }).on('keyup', function (oEvent) { if (oEvent && !oEvent.ctrlKey) { - Globals.$html.removeClass('rl-ctrl-key-pressed'); + $html.removeClass('rl-ctrl-key-pressed'); } }); - Globals.$doc.on('mousemove keypress click', _.debounce(function () { + $doc.on('mousemove keypress click', _.debounce(function () { Events.pub('rl.auto-logout-refresh'); }, 5000)); - key('esc, enter', Enums.KeyState.All, _.bind(function () { - Utils.detectDropdownVisibility(); + key('esc, enter', KeyState.All, _.bind(function () { + detectDropdownVisibility(); }, this)); } @@ -113,7 +128,7 @@ class AbstractApp extends AbstractBoot */ download(link) { - if (Globals.sUserAgent && (Globals.sUserAgent.indexOf('chrome') > -1 || Globals.sUserAgent.indexOf('chrome') > -1)) + if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1)) { const oLink = window.document.createElement('a'); oLink.href = link; @@ -130,7 +145,7 @@ class AbstractApp extends AbstractBoot } } - if (Globals.bMobileDevice) + if (bMobileDevice) { window.open(link, '_self'); window.focus(); @@ -161,7 +176,7 @@ class AbstractApp extends AbstractBoot * @param {string} title */ setWindowTitle(title) { - title = ((Utils.isNormal(title) && 0 < title.length) ? '' + title : ''); + title = ((isNormal(title) && 0 < title.length) ? '' + title : ''); if (Settings.settingsGet('Title')) { title += (title ? ' - ' : '') + Settings.settingsGet('Title'); @@ -208,7 +223,7 @@ class AbstractApp extends AbstractBoot inIframe = !!Settings.appSettingsGet('inIframe') ; - let customLogoutLink = Utils.pString(Settings.appSettingsGet('customLogoutLink')); + let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink')); if (logout) { @@ -260,7 +275,7 @@ class AbstractApp extends AbstractBoot bootstart() { - // Utils.log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); + // log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); Events.pub('rl.bootstart'); @@ -279,7 +294,7 @@ class AbstractApp extends AbstractBoot ko.components.register('x-script', require('Component/Script')); // ko.components.register('svg-icon', require('Component/SvgIcon')); - if (Settings.appSettingsGet('materialDesign') && Globals.bAnimationSupported) + if (Settings.appSettingsGet('materialDesign') && bAnimationSupported) { ko.components.register('Checkbox', require('Component/MaterialDesign/Checkbox')); ko.components.register('CheckboxSimple', require('Component/Checkbox')); @@ -294,14 +309,14 @@ class AbstractApp extends AbstractBoot Translator.initOnStartOrLangChange(Translator.initNotificationLanguage, Translator); - _.delay(Utils.windowResizeCallback, 1000); + _.delay(windowResizeCallback, 1000); Events.sub('ssm.mobile-enter', () => { - Globals.leftPanelDisabled(true); + leftPanelDisabled(true); }); Events.sub('ssm.mobile-leave', () => { - Globals.leftPanelDisabled(false); + leftPanelDisabled(false); }); if (!mobile) @@ -310,11 +325,11 @@ class AbstractApp extends AbstractBoot id: 'mobile', maxWidth: 767, onEnter: () => { - Globals.$html.addClass('ssm-state-mobile'); + $html.addClass('ssm-state-mobile'); Events.pub('ssm.mobile-enter'); }, onLeave: () => { - Globals.$html.removeClass('ssm-state-mobile'); + $html.removeClass('ssm-state-mobile'); Events.pub('ssm.mobile-leave'); } }); @@ -324,10 +339,10 @@ class AbstractApp extends AbstractBoot minWidth: 768, maxWidth: 999, onEnter: function() { - Globals.$html.addClass('ssm-state-tablet'); + $html.addClass('ssm-state-tablet'); }, onLeave: function() { - Globals.$html.removeClass('ssm-state-tablet'); + $html.removeClass('ssm-state-tablet'); } }); @@ -336,10 +351,10 @@ class AbstractApp extends AbstractBoot minWidth: 1000, maxWidth: 1400, onEnter: () => { - Globals.$html.addClass('ssm-state-desktop'); + $html.addClass('ssm-state-desktop'); }, onLeave: () => { - Globals.$html.removeClass('ssm-state-desktop'); + $html.removeClass('ssm-state-desktop'); } }); @@ -347,30 +362,30 @@ class AbstractApp extends AbstractBoot id: 'desktop-large', minWidth: 1400, onEnter: () => { - Globals.$html.addClass('ssm-state-desktop-large'); + $html.addClass('ssm-state-desktop-large'); }, onLeave: () => { - Globals.$html.removeClass('ssm-state-desktop-large'); + $html.removeClass('ssm-state-desktop-large'); } }); } else { - Globals.$html.addClass('ssm-state-mobile').addClass('rl-mobile'); + $html.addClass('ssm-state-mobile').addClass('rl-mobile'); Events.pub('ssm.mobile-enter'); } - Globals.leftPanelDisabled.subscribe((bValue) => { - Globals.$html.toggleClass('rl-left-panel-disabled', bValue); - Globals.$html.toggleClass('rl-left-panel-enabled', !bValue); + leftPanelDisabled.subscribe((bValue) => { + $html.toggleClass('rl-left-panel-disabled', bValue); + $html.toggleClass('rl-left-panel-enabled', !bValue); }); - Globals.leftPanelType.subscribe((sValue) => { - Globals.$html.toggleClass('rl-left-panel-none', 'none' === sValue); - Globals.$html.toggleClass('rl-left-panel-short', 'short' === sValue); + leftPanelType.subscribe((sValue) => { + $html.toggleClass('rl-left-panel-none', 'none' === sValue); + $html.toggleClass('rl-left-panel-short', 'short' === sValue); }); - Globals.leftPanelDisabled.valueHasMutated(); + leftPanelDisabled.valueHasMutated(); ssm.ready(); diff --git a/dev/App/Admin.jsx b/dev/App/Admin.jsx index 4be270f11..283d99dbf 100644 --- a/dev/App/Admin.jsx +++ b/dev/App/Admin.jsx @@ -3,10 +3,10 @@ import {window, _} from 'common'; import ko from 'ko'; import progressJs from 'progressJs'; -import * as Enums from 'Common/Enums'; -import Utils from 'Common/Utils'; import Links from 'Common/Links'; import Translator from 'Common/Translator'; +import {StorageResultType, Notification} from 'Common/Enums'; +import {pInt, isNormal, isArray, inArray, isUnd} from 'Common/Utils'; import Settings from 'Storage/Settings'; @@ -37,7 +37,7 @@ class AdminApp extends AbstractApp DomainStore.domains.loading(true); Remote.domainList((result, data) => { DomainStore.domains.loading(false); - if (Enums.StorageResultType.Success === result && data && data.Result) + if (StorageResultType.Success === result && data && data.Result) { DomainStore.domains(_.map(data.Result, (enabled, name) => { return { @@ -54,7 +54,7 @@ class AdminApp extends AbstractApp PluginStore.plugins.loading(true); Remote.pluginList((result, data) => { PluginStore.plugins.loading(false); - if (Enums.StorageResultType.Success === result && data && data.Result) + if (StorageResultType.Success === result && data && data.Result) { PluginStore.plugins(_.map(data.Result, (item) => { return { @@ -72,7 +72,7 @@ class AdminApp extends AbstractApp PackageStore.packagesReal(true); Remote.packagesList((result, data) => { PackageStore.packages.loading(false); - if (Enums.StorageResultType.Success === result && data && data.Result) + if (StorageResultType.Success === result && data && data.Result) { PackageStore.packagesReal(!!data.Result.Real); PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable); @@ -89,12 +89,12 @@ class AdminApp extends AbstractApp } }); - if (Utils.isArray(data.Result.List)) + if (isArray(data.Result.List)) { list = _.compact(_.map(data.Result.List, (item) => { if (item) { - item.loading = ko.observable(!Utils.isUnd(loading[item.file])); + item.loading = ko.observable(!isUnd(loading[item.file])); return 'core' === item.type && !item.canBeInstalled ? null : item; } return null; @@ -118,7 +118,7 @@ class AdminApp extends AbstractApp CoreStore.coreRemoteVersion(''); CoreStore.coreRemoteRelease(''); CoreStore.coreVersionCompare(-2); - if (Enums.StorageResultType.Success === result && data && data.Result) + if (StorageResultType.Success === result && data && data.Result) { CoreStore.coreReal(true); window.location.reload(); @@ -135,7 +135,7 @@ class AdminApp extends AbstractApp CoreStore.coreReal(true); Remote.coreData((result, data) => { CoreStore.coreChecking(false); - if (Enums.StorageResultType.Success === result && data && data.Result) + if (StorageResultType.Success === result && data && data.Result) { CoreStore.coreReal(!!data.Result.Real); CoreStore.coreChannel(data.Result.Channel || 'stable'); @@ -146,7 +146,7 @@ class AdminApp extends AbstractApp CoreStore.coreVersion(data.Result.Version || ''); CoreStore.coreRemoteVersion(data.Result.RemoteVersion || ''); CoreStore.coreRemoteRelease(data.Result.RemoteRelease || ''); - CoreStore.coreVersionCompare(Utils.pInt(data.Result.VersionCompare)); + CoreStore.coreVersionCompare(pInt(data.Result.VersionCompare)); } else { @@ -170,29 +170,29 @@ class AdminApp extends AbstractApp LicenseStore.licenseError(''); Remote.licensing((result, data) => { LicenseStore.licensingProcess(false); - if (Enums.StorageResultType.Success === result && data && data.Result && Utils.isNormal(data.Result.Expired)) + if (StorageResultType.Success === result && data && data.Result && isNormal(data.Result.Expired)) { LicenseStore.licenseValid(true); - LicenseStore.licenseExpired(Utils.pInt(data.Result.Expired)); + LicenseStore.licenseExpired(pInt(data.Result.Expired)); LicenseStore.licenseError(''); LicenseStore.licensing(true); AppStore.prem(true); } else { - if (data && data.ErrorCode && -1 < Utils.inArray(Utils.pInt(data.ErrorCode), [ - Enums.Notification.LicensingServerIsUnavailable, - Enums.Notification.LicensingExpired + if (data && data.ErrorCode && -1 < inArray(pInt(data.ErrorCode), [ + Notification.LicensingServerIsUnavailable, + Notification.LicensingExpired ])) { - LicenseStore.licenseError(Translator.getNotification(Utils.pInt(data.ErrorCode))); + LicenseStore.licenseError(Translator.getNotification(pInt(data.ErrorCode))); LicenseStore.licensing(true); } else { - if (Enums.StorageResultType.Abort === result) + if (StorageResultType.Abort === result) { - LicenseStore.licenseError(Translator.getNotification(Enums.Notification.LicensingServerIsUnavailable)); + LicenseStore.licenseError(Translator.getNotification(Notification.LicensingServerIsUnavailable)); LicenseStore.licensing(true); } else diff --git a/dev/App/User.jsx b/dev/App/User.jsx index 6d466f514..4813943f0 100644 --- a/dev/App/User.jsx +++ b/dev/App/User.jsx @@ -3,11 +3,24 @@ import {window, _, $} from 'common'; import progressJs from 'progressJs'; import Tinycon from 'Tinycon'; -import * as Enums from 'Common/Enums'; -import * as Consts from 'Common/Consts'; -import Globals from 'Common/Globals'; +import { + noop, trim, log, isArray, inArray, isUnd, isNormal, isPosNumeric, isNonEmptyArray, + pInt, pString, delegateRunOnDestroy, mailToHelper, windowResize +} from 'Common/Utils'; + +import { + Layout, Capa, StorageResultType, Notification, FolderType, + SetSystemFoldersNotification, MessageSetAction, ClientSideKeyName +} from 'Common/Enums'; + +import { + $html, + leftPanelWidth, leftPanelDisabled, + bAnimationSupported, bMobileDevice +} from 'Common/Globals'; + +import {UNUSED_OPTION_VALUE} from 'Common/Consts'; import Plugins from 'Common/Plugins'; -import Utils from 'Common/Utils'; import Links from 'Common/Links'; import Events from 'Common/Events'; import Translator from 'Common/Translator'; @@ -74,7 +87,7 @@ class AppUser extends AbstractApp } Remote.jsVersion((sResult, oData) => { - if (Enums.StorageResultType.Success === sResult && oData && !oData.Result) + if (StorageResultType.Success === sResult && oData && !oData.Result) { this.reload(); } @@ -93,7 +106,7 @@ class AppUser extends AbstractApp $('#rl-bg') .attr('style', 'background-image: none !important;') .backstretch(Links.userBackground(Settings.settingsGet('UserBackgroundHash')), { - fade: Globals.bAnimationSupported ? 1000 : 0, + fade: bAnimationSupported ? 1000 : 0, centeredX: true, centeredY: true }) @@ -159,19 +172,19 @@ class AppUser extends AbstractApp MessageStore.messageListLoading(true); Remote.messageList((sResult, oData, bCached) => { - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) + if (StorageResultType.Success === sResult && oData && oData.Result) { MessageStore.messageListError(''); MessageStore.messageListLoading(false); MessageStore.setMessageList(oData, bCached); } - else if (Enums.StorageResultType.Unload === sResult) + else if (StorageResultType.Unload === sResult) { MessageStore.messageListError(''); MessageStore.messageListLoading(false); } - else if (Enums.StorageResultType.Abort !== sResult) + else if (StorageResultType.Abort !== sResult) { MessageStore.messageList([]); MessageStore.messageListLoading(false); @@ -185,7 +198,7 @@ class AppUser extends AbstractApp } recacheInboxMessageList() { - Remote.messageList(Utils.emptyFunction, Cache.getFolderInboxName(), 0, SettingsStore.messagesPerPage(), '', '', true); + Remote.messageList(noop, Cache.getFolderInboxName(), 0, SettingsStore.messagesPerPage(), '', '', true); } /** @@ -272,9 +285,9 @@ class AppUser extends AbstractApp moveOrDeleteResponseHelper(sResult, oData) { - if (Enums.StorageResultType.Success === sResult && FolderStore.currentFolder()) + if (StorageResultType.Success === sResult && FolderStore.currentFolder()) { - if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length) + if (oData && isArray(oData.Result) && 2 === oData.Result.length) { Cache.setFolderHash(oData.Result[0], oData.Result[1]); } @@ -282,8 +295,8 @@ class AppUser extends AbstractApp { Cache.setFolderHash(FolderStore.currentFolderFullNameRaw(), ''); - if (oData && -1 < Utils.inArray(oData.ErrorCode, - [Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage])) + if (oData && -1 < inArray(oData.ErrorCode, + [Notification.CantMoveMessage, Notification.CantCopyMessage])) { window.alert(Translator.getNotification(oData.ErrorCode)); } @@ -318,29 +331,29 @@ class AppUser extends AbstractApp switch (iDeleteType) { - case Enums.FolderType.Spam: + case FolderType.Spam: oMoveFolder = Cache.getFolderFromCacheList(FolderStore.spamFolder()); - nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam; + nSetSystemFoldersNotification = SetSystemFoldersNotification.Spam; break; - case Enums.FolderType.NotSpam: + case FolderType.NotSpam: oMoveFolder = Cache.getFolderFromCacheList(Cache.getFolderInboxName()); break; - case Enums.FolderType.Trash: + case FolderType.Trash: oMoveFolder = Cache.getFolderFromCacheList(FolderStore.trashFolder()); - nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash; + nSetSystemFoldersNotification = SetSystemFoldersNotification.Trash; break; - case Enums.FolderType.Archive: + case FolderType.Archive: oMoveFolder = Cache.getFolderFromCacheList(FolderStore.archiveFolder()); - nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive; + nSetSystemFoldersNotification = SetSystemFoldersNotification.Archive; break; } - bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder; + bUseFolder = isUnd(bUseFolder) ? true : !!bUseFolder; if (bUseFolder) { - if ((Enums.FolderType.Spam === iDeleteType && Consts.UNUSED_OPTION_VALUE === FolderStore.spamFolder()) || - (Enums.FolderType.Trash === iDeleteType && Consts.UNUSED_OPTION_VALUE === FolderStore.trashFolder()) || - (Enums.FolderType.Archive === iDeleteType && Consts.UNUSED_OPTION_VALUE === FolderStore.archiveFolder())) + 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())) { bUseFolder = false; } @@ -350,7 +363,7 @@ class AppUser extends AbstractApp { kn.showScreenPopup(require('View/Popup/FolderSystem'), [nSetSystemFoldersNotification]); } - else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType && + else if (!bUseFolder || (FolderType.Trash === iDeleteType && (sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder()))) { kn.showScreenPopup(require('View/Popup/Ask'), [Translator.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => { @@ -373,7 +386,7 @@ class AppUser extends AbstractApp */ moveMessagesToFolder(sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy) { - if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length) + if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && isArray(aUidForMove) && 0 < aUidForMove.length) { const oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw), @@ -382,7 +395,7 @@ class AppUser extends AbstractApp if (oFromFolder && oToFolder) { - if (Utils.isUnd(bCopy) ? false : !!bCopy) + if (isUnd(bCopy) ? false : !!bCopy) { this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove); } @@ -486,7 +499,7 @@ class AppUser extends AbstractApp } }); - Utils.delegateRunOnDestroy(PgpStore.openpgpkeys()); + delegateRunOnDestroy(PgpStore.openpgpkeys()); PgpStore.openpgpkeys(aKeys); } } @@ -499,7 +512,7 @@ class AppUser extends AbstractApp // // AccountStore.accounts.loading(false); // -// if (Enums.StorageResultType.Success === sResult && oData.Result && oData.Result['Counts']) +// if (StorageResultType.Success === sResult && oData.Result && oData.Result['Counts']) // { // var // sEmail = AccountStore.email(), @@ -514,7 +527,7 @@ class AppUser extends AbstractApp // // if (oAccount) // { -// oAccount.count(Utils.pInt(oItem[1])); +// oAccount.count(pInt(oItem[1])); // } // }); // } @@ -531,7 +544,7 @@ class AppUser extends AbstractApp AccountStore.accounts.loading(false); IdentityStore.identities.loading(false); - if (Enums.StorageResultType.Success === sResult && oData.Result) + if (StorageResultType.Success === sResult && oData.Result) { var aCounts = {}, @@ -541,40 +554,40 @@ class AppUser extends AbstractApp sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail; - if (Utils.isArray(oData.Result.Accounts)) + if (isArray(oData.Result.Accounts)) { _.each(AccountStore.accounts(), (oAccount) => { aCounts[oAccount.email] = oAccount.count(); }); - Utils.delegateRunOnDestroy(AccountStore.accounts()); + delegateRunOnDestroy(AccountStore.accounts()); AccountStore.accounts(_.map(oData.Result.Accounts, (sValue) => new AccountModel(sValue, sValue !== sParentEmail, aCounts[sValue] || 0))); } - if (Utils.isUnd(bBoot) ? false : !!bBoot) + if (isUnd(bBoot) ? false : !!bBoot) { _.delay(() => this.accountsCounts(), 1000 * 5); Events.sub('interval.10m-after5m', () => this.accountsCounts()); } - if (Utils.isArray(oData.Result.Identities)) + if (isArray(oData.Result.Identities)) { - Utils.delegateRunOnDestroy(IdentityStore.identities()); + delegateRunOnDestroy(IdentityStore.identities()); IdentityStore.identities(_.map(oData.Result.Identities, (oIdentityData) => { const - sId = Utils.pString(oIdentityData.Id), - sEmail = Utils.pString(oIdentityData.Email), + sId = pString(oIdentityData.Id), + sEmail = pString(oIdentityData.Email), oIdentity = new IdentityModel(sId, sEmail) ; - oIdentity.name(Utils.pString(oIdentityData.Name)); - oIdentity.replyTo(Utils.pString(oIdentityData.ReplyTo)); - oIdentity.bcc(Utils.pString(oIdentityData.Bcc)); - oIdentity.signature(Utils.pString(oIdentityData.Signature)); + oIdentity.name(pString(oIdentityData.Name)); + oIdentity.replyTo(pString(oIdentityData.ReplyTo)); + oIdentity.bcc(pString(oIdentityData.Bcc)); + oIdentity.signature(pString(oIdentityData.Signature)); oIdentity.signatureInsertBefore(!!oIdentityData.SignatureInsertBefore); return oIdentity; @@ -592,10 +605,10 @@ class AppUser extends AbstractApp TemplateStore.templates.loading(false); - if (Enums.StorageResultType.Success === result && data.Result && - Utils.isArray(data.Result.Templates)) + if (StorageResultType.Success === result && data.Result && + isArray(data.Result.Templates)) { - Utils.delegateRunOnDestroy(TemplateStore.templates()); + delegateRunOnDestroy(TemplateStore.templates()); TemplateStore.templates(_.compact(_.map(data.Result.Templates, (templateData) => { const template = new TemplateModel(); @@ -607,12 +620,12 @@ class AppUser extends AbstractApp quota() { Remote.quota((result, data) => { - if (Enums.StorageResultType.Success === result && data && data.Result && - Utils.isArray(data.Result) && 1 < data.Result.length && - Utils.isPosNumeric(data.Result[0], true) && Utils.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)) { require('Stores/User/Quota').populateData( - Utils.pInt(data.Result[1]), Utils.pInt(data.Result[0])); + pInt(data.Result[1]), pInt(data.Result[0])); } }); } @@ -622,10 +635,10 @@ class AppUser extends AbstractApp * @param {Array=} list = [] */ folderInformation(folder, list) { - if ('' !== Utils.trim(folder)) + if ('' !== trim(folder)) { Remote.folderInformation((result, data) => { - if (Enums.StorageResultType.Success === result) + if (StorageResultType.Success === result) { if (data && data.Result && data.Result.Hash && data.Result.Folder) { @@ -645,14 +658,14 @@ class AppUser extends AbstractApp Cache.setFolderHash(data.Result.Folder, data.Result.Hash); } - if (Utils.isNormal(data.Result.MessageCount)) + if (isNormal(data.Result.MessageCount)) { folderFromCache.messageCountAll(data.Result.MessageCount); } - if (Utils.isNormal(data.Result.MessageUnseenCount)) + if (isNormal(data.Result.MessageUnseenCount)) { - if (Utils.pInt(folderFromCache.messageCountUnread()) !== Utils.pInt(data.Result.MessageUnseenCount)) + if (pInt(folderFromCache.messageCountUnread()) !== pInt(data.Result.MessageUnseenCount)) { unreadCountChange = true; } @@ -712,12 +725,12 @@ class AppUser extends AbstractApp folderInformationMultiply(boot = false) { const folders = FolderStore.getNextFolderNames(); - if (Utils.isNonEmptyArray(folders)) + if (isNonEmptyArray(folders)) { Remote.folderInformationMultiply((sResult, oData) => { - if (Enums.StorageResultType.Success === sResult) + if (StorageResultType.Success === sResult) { - if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List)) + if (oData && oData.Result && oData.Result.List && isNonEmptyArray(oData.Result.List)) { const utc = Momentor.momentNowUnix(); _.each(oData.Result.List, (oItem) => { @@ -737,14 +750,14 @@ class AppUser extends AbstractApp Cache.setFolderHash(oItem.Folder, oItem.Hash); } - if (Utils.isNormal(oItem.MessageCount)) + if (isNormal(oItem.MessageCount)) { oFolder.messageCountAll(oItem.MessageCount); } - if (Utils.isNormal(oItem.MessageUnseenCount)) + if (isNormal(oItem.MessageUnseenCount)) { - if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount)) + if (pInt(oFolder.messageCountUnread()) !== pInt(oItem.MessageUnseenCount)) { bUnreadCountChange = true; } @@ -769,7 +782,7 @@ class AppUser extends AbstractApp if (oFolder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { const aList = MessageStore.messageList(); - if (Utils.isNonEmptyArray(aList)) + if (isNonEmptyArray(aList)) { this.folderInformation(oFolder.fullNameRaw, aList); } @@ -802,7 +815,7 @@ class AppUser extends AbstractApp iAlreadyUnread = 0 ; - if (Utils.isUnd(aMessages)) + if (isUnd(aMessages)) { aMessages = MessageStore.messageListChecked(); } @@ -812,7 +825,7 @@ class AppUser extends AbstractApp if ('' !== sFolderFullNameRaw && 0 < aRootUids.length) { switch (iSetAction) { - case Enums.MessageSetAction.SetSeen: + case MessageSetAction.SetSeen: _.each(aRootUids, (sSubUid) => { iAlreadyUnread += Cache.storeMessageFlagsToCacheBySetAction( @@ -825,10 +838,10 @@ class AppUser extends AbstractApp oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread); } - Remote.messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aRootUids, true); + Remote.messageSetSeen(noop, sFolderFullNameRaw, aRootUids, true); break; - case Enums.MessageSetAction.UnsetSeen: + case MessageSetAction.UnsetSeen: _.each(aRootUids, (sSubUid) => { iAlreadyUnread += Cache.storeMessageFlagsToCacheBySetAction( @@ -841,27 +854,27 @@ class AppUser extends AbstractApp oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread + aRootUids.length); } - Remote.messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aRootUids, false); + Remote.messageSetSeen(noop, sFolderFullNameRaw, aRootUids, false); break; - case Enums.MessageSetAction.SetFlag: + case MessageSetAction.SetFlag: _.each(aRootUids, (sSubUid) => { Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); - Remote.messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aRootUids, true); + Remote.messageSetFlagged(noop, sFolderFullNameRaw, aRootUids, true); break; - case Enums.MessageSetAction.UnsetFlag: + case MessageSetAction.UnsetFlag: _.each(aRootUids, (sSubUid) => { Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); - Remote.messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aRootUids, false); + Remote.messageSetFlagged(noop, sFolderFullNameRaw, aRootUids, false); break; } @@ -895,7 +908,7 @@ class AppUser extends AbstractApp Remote.socialUsers((result, data) => { - if (Enums.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 || ''); @@ -935,12 +948,12 @@ class AppUser extends AbstractApp */ getAutocomplete(query, callback) { Remote.suggestions((result, data) => { - if (Enums.StorageResultType.Success === result && data && Utils.isArray(data.Result)) + if (StorageResultType.Success === result && data && isArray(data.Result)) { callback(_.compact(_.map(data.Result, (item) => item && item[0] ? new EmailModel(item[0], item[1]) : null))); } - else if (Enums.StorageResultType.Abort !== result) + else if (StorageResultType.Abort !== result) { callback([]); } @@ -952,8 +965,8 @@ class AppUser extends AbstractApp * @param {boolean} bExpanded */ setExpandedFolder(sFullNameHash, bExpanded) { - let aExpandedList = Local.get(Enums.ClientSideKeyName.ExpandedFolders); - if (!Utils.isArray(aExpandedList)) + let aExpandedList = Local.get(ClientSideKeyName.ExpandedFolders); + if (!isArray(aExpandedList)) { aExpandedList = []; } @@ -968,7 +981,7 @@ class AppUser extends AbstractApp aExpandedList = _.without(aExpandedList, sFullNameHash); } - Local.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList); + Local.set(ClientSideKeyName.ExpandedFolders, aExpandedList); } initHorizontalLayoutResizer(sClientSideKeyName) { @@ -1001,32 +1014,32 @@ class AppUser extends AbstractApp oResizableHandle .on('mousedown', () => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }) .on('mouseup', () => { - Globals.$html.removeClass('rl-resizer'); + $html.removeClass('rl-resizer'); }) ; } }, fResizeStartFunction = () => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }, fResizeResizeFunction = _.debounce(() => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }, 500, true), fResizeStopFunction = (oEvent, oObject) => { - Globals.$html.removeClass('rl-resizer'); + $html.removeClass('rl-resizer'); if (oObject && oObject.size && oObject.size.height) { Local.set(sClientSideKeyName, oObject.size.height); fSetHeight(oObject.size.height); - Utils.windowResize(); + windowResize(); } }, @@ -1057,7 +1070,7 @@ class AppUser extends AbstractApp oBottom.removeAttr('style'); } } - else if (Globals.$html.hasClass('rl-bottom-preview-pane')) + else if ($html.hasClass('rl-bottom-preview-pane')) { oTop = $('.b-message-list-wrapper'); oBottom = $('.b-message-view-wrapper'); @@ -1067,7 +1080,7 @@ class AppUser extends AbstractApp oTop.resizable(oOptions); } - const iHeight = Utils.pInt(Local.get(sClientSideKeyName)) || 300; + const iHeight = pInt(Local.get(sClientSideKeyName)) || 300; fSetHeight(iHeight > iMinHeight ? iHeight : iMinHeight); } } @@ -1076,7 +1089,7 @@ class AppUser extends AbstractApp fDisable(false); Events.sub('layout', (layout) => { - fDisable(Enums.Layout.BottomPreview !== layout); + fDisable(Layout.BottomPreview !== layout); }); } @@ -1093,9 +1106,9 @@ class AppUser extends AbstractApp fSetWidth = (iWidth) => { if (iWidth) { - Globals.leftPanelWidth(iWidth); + leftPanelWidth(iWidth); - Globals.$html.removeClass('rl-resizer'); + $html.removeClass('rl-resizer'); oLeft.css({ width: '' + iWidth + 'px' @@ -1116,7 +1129,7 @@ class AppUser extends AbstractApp else { oLeft.resizable('enable'); - var iWidth = Utils.pInt(Local.get(sClientSideKeyName)) || iMinWidth; + var iWidth = pInt(Local.get(sClientSideKeyName)) || iMinWidth; fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth); } }, @@ -1126,27 +1139,27 @@ class AppUser extends AbstractApp { $(oEvent.target).find('.ui-resizable-handle') .on('mousedown', () => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }) .on('mouseup', () => { - Globals.$html.removeClass('rl-resizer'); + $html.removeClass('rl-resizer'); }) ; } }, fResizeResizeFunction = _.debounce(() => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }, 500, true), fResizeStartFunction = () => { - Globals.$html.addClass('rl-resizer'); + $html.addClass('rl-resizer'); }, fResizeStopFunction = (oEvent, oObject) => { - Globals.$html.removeClass('rl-resizer'); + $html.removeClass('rl-resizer'); if (oObject && oObject.size && oObject.size.width) { Local.set(sClientSideKeyName, oObject.size.width); - Globals.leftPanelWidth(oObject.size.width); + leftPanelWidth(oObject.size.width); oRight.css({ left: '' + oObject.size.width + 'px' @@ -1204,9 +1217,9 @@ class AppUser extends AbstractApp bootstartLoginScreen() { - Globals.$html.removeClass('rl-user-auth').addClass('rl-user-no-auth'); + $html.removeClass('rl-user-auth').addClass('rl-user-no-auth'); - const customLoginLink = Utils.pString(Settings.appSettingsGet('customLoginLink')); + const customLoginLink = pString(Settings.appSettingsGet('customLoginLink')); if (!customLoginLink) { kn.startScreens([ @@ -1253,8 +1266,8 @@ class AppUser extends AbstractApp var sJsHash = Settings.appSettingsGet('jsHash'), - sStartupUrl = Utils.pString(Settings.settingsGet('StartupUrl')), - iContactsSyncInterval = Utils.pInt(Settings.settingsGet('ContactsSyncInterval')), + sStartupUrl = pString(Settings.settingsGet('StartupUrl')), + iContactsSyncInterval = pInt(Settings.settingsGet('ContactsSyncInterval')), bGoogle = Settings.settingsGet('AllowGoogleSocial'), bFacebook = Settings.settingsGet('AllowFacebookSocial'), bTwitter = Settings.settingsGet('AllowTwitterSocial') @@ -1265,17 +1278,17 @@ class AppUser extends AbstractApp progressJs.set(90); } - Globals.leftPanelDisabled.subscribe((value) => { + leftPanelDisabled.subscribe((value) => { Events.pub('left-panel.' + (value ? 'off' : 'on')); }); this.setWindowTitle(''); if (Settings.settingsGet('Auth')) { - Globals.$html.addClass('rl-user-auth'); + $html.addClass('rl-user-auth'); - if (Settings.capa(Enums.Capa.TwoFactor) && - Settings.capa(Enums.Capa.TwoFactorForce) && + if (Settings.capa(Capa.TwoFactor) && + Settings.capa(Capa.TwoFactorForce) && Settings.settingsGet('RequireTwoFactor')) { this.bootend(); @@ -1300,7 +1313,7 @@ class AppUser extends AbstractApp kn.routeOn(); } - if (window.jassl && window.crypto && window.crypto.getRandomValues && Settings.capa(Enums.Capa.OpenPGP)) + if (window.jassl && window.crypto && window.crypto.getRandomValues && Settings.capa(Capa.OpenPGP)) { const openpgpCallback = (openpgp) => { @@ -1314,7 +1327,7 @@ class AppUser extends AbstractApp } catch (e) { - Utils.log(e); + log(e); } } @@ -1347,7 +1360,7 @@ class AppUser extends AbstractApp kn.startScreens([ require('Screen/User/MailBox'), - Settings.capa(Enums.Capa.Settings) ? require('Screen/User/Settings') : null + Settings.capa(Capa.Settings) ? require('Screen/User/Settings') : null // false ? require('Screen/User/About') : null ]); @@ -1388,7 +1401,7 @@ class AppUser extends AbstractApp }, 1000); _.delay(() => this.quota(), 5000); - _.delay(() => Remote.appDelayStart(Utils.emptyFunction), 35000); + _.delay(() => Remote.appDelayStart(noop), 35000); Events.sub('rl.auto-logout', () => this.logout()); @@ -1402,7 +1415,7 @@ class AppUser extends AbstractApp if (!!Settings.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler && - Settings.capa(Enums.Capa.Composer)) + Settings.capa(Capa.Composer)) { _.delay(() => { try { @@ -1413,14 +1426,14 @@ class AppUser extends AbstractApp if (Settings.settingsGet('MailToEmail')) { - Utils.mailToHelper(Settings.settingsGet('MailToEmail'), require('View/Popup/Compose')); + mailToHelper(Settings.settingsGet('MailToEmail'), require('View/Popup/Compose')); } }, 500); } - if (!Globals.bMobileDevice) + if (!bMobileDevice) { - _.defer(() => this.initVerticalLayoutResizer(Enums.ClientSideKeyName.FolderListSize)); + _.defer(() => this.initVerticalLayoutResizer(ClientSideKeyName.FolderListSize)); if (Tinycon && Settings.appSettingsGet('faviconStatus') && !Settings.appSettingsGet('listPermanentFiltered')) { diff --git a/dev/Common/Audio.jsx b/dev/Common/Audio.jsx index 7a0ae10d1..bcf8d82c3 100644 --- a/dev/Common/Audio.jsx +++ b/dev/Common/Audio.jsx @@ -1,9 +1,9 @@ import {window, $} from 'common'; -import Globals from 'Common/Globals'; -import Utils from 'Common/Utils'; +import {bMobileDevice, bSafari} from 'Common/Globals'; import Links from 'Common/Links'; import Events from 'Common/Events'; +import {trim} from 'Common/Utils'; class Audio { @@ -20,7 +20,7 @@ class Audio { this.player = this.createNewObject(); - this.supported = !Globals.bMobileDevice && !Globals.bSafari && !!this.player && !!this.player.play; + this.supported = !bMobileDevice && !bSafari && !!this.player && !!this.player.play; if (this.supported && this.player.canPlayType) { this.supportedMp3 = '' !== this.player.canPlayType('audio/mpeg;').replace(/no/, ''); @@ -78,10 +78,10 @@ class Audio clearName(name = '', ext = '') { - name = Utils.trim(name); + name = trim(name); if (ext && '.' + ext === name.toLowerCase().substr((ext.length + 1) * -1)) { - name = Utils.trim(name.substr(0, name.length - 4)); + name = trim(name.substr(0, name.length - 4)); } return '' === name ? 'audio' : name; diff --git a/dev/Common/Booter.jsx b/dev/Common/Booter.jsx index d07ddf7d2..ab72aa09a 100644 --- a/dev/Common/Booter.jsx +++ b/dev/Common/Booter.jsx @@ -146,11 +146,8 @@ function runMainBoot(withError, additionalError) { if (window.__APP_BOOT && !withError) { - window.__APP_BOOT(function (bV) { - if (!bV) - { - showError(additionalError); - } + window.__APP_BOOT(() => { + showError(additionalError); }); } else diff --git a/dev/Common/Cache.jsx b/dev/Common/Cache.jsx index 77ed2e054..870eee9ab 100644 --- a/dev/Common/Cache.jsx +++ b/dev/Common/Cache.jsx @@ -1,7 +1,7 @@ import {_} from 'common'; import {Capa, MessageSetAction} from 'Common/Enums'; -import Utils from 'Common/Utils'; +import {trim, pInt, isArray} from 'Common/Utils'; import Links from 'Common/Links'; import Settings from 'Storage/Settings'; @@ -38,7 +38,7 @@ class CacheUserStorage * @return {string} */ getUserPic(email, callback) { - email = Utils.trim(email); + email = trim(email); callback(this.bCapaGravatar && '' !== email ? Links.avatarLink(email) : '', email); } @@ -253,8 +253,8 @@ class CacheUserStorage return false; }); - message.hasUnseenSubMessage(unseenSubUid && 0 < Utils.pInt(unseenSubUid)); - message.hasFlaggedSubMessage(flaggedSubUid && 0 < Utils.pInt(flaggedSubUid)); + message.hasUnseenSubMessage(unseenSubUid && 0 < pInt(unseenSubUid)); + message.hasFlaggedSubMessage(flaggedSubUid && 0 < pInt(flaggedSubUid)); } } } @@ -279,7 +279,7 @@ class CacheUserStorage * @param {Array} flags */ storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) { - if (Utils.isArray(flags) && 0 < flags.length) + if (isArray(flags) && 0 < flags.length) { this.setMessageFlagsToCache(folder, uid, flags); } @@ -295,7 +295,7 @@ class CacheUserStorage let unread = 0; const flags = this.getMessageFlagsFromCache(folder, uid); - if (Utils.isArray(flags) && 0 < flags.length) + if (isArray(flags) && 0 < flags.length) { if (flags[0]) { diff --git a/dev/Common/ClientStorageDriver/Cookie.jsx b/dev/Common/ClientStorageDriver/Cookie.jsx index d7c493ede..d69cbb380 100644 --- a/dev/Common/ClientStorageDriver/Cookie.jsx +++ b/dev/Common/ClientStorageDriver/Cookie.jsx @@ -1,6 +1,6 @@ import {window, JSON, $} from 'common'; -import Utils from 'Common/Utils'; +import {isUnd} from 'Common/Utils'; import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; class CookieDriver @@ -60,7 +60,7 @@ class CookieDriver storageResult = null === storageValue ? null : JSON.parse(storageValue) ; - result = (storageResult && !Utils.isUnd(storageResult[key])) ? storageResult[key] : null; + result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; } catch (e) { diff --git a/dev/Common/ClientStorageDriver/LocalStorage.jsx b/dev/Common/ClientStorageDriver/LocalStorage.jsx index b71799644..8ba2f2519 100644 --- a/dev/Common/ClientStorageDriver/LocalStorage.jsx +++ b/dev/Common/ClientStorageDriver/LocalStorage.jsx @@ -1,6 +1,6 @@ import {window, JSON} from 'common'; -import Utils from 'Common/Utils'; +import {isUnd} from 'Common/Utils'; import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts'; class LocalStorageDriver @@ -57,7 +57,7 @@ class LocalStorageDriver storageResult = null === storageValue ? null : JSON.parse(storageValue) ; - result = (storageResult && !Utils.isUnd(storageResult[key])) ? storageResult[key] : null; + result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; } catch (e) { diff --git a/dev/Common/Events.jsx b/dev/Common/Events.jsx index 08997fbdc..2d03f1deb 100644 --- a/dev/Common/Events.jsx +++ b/dev/Common/Events.jsx @@ -1,6 +1,6 @@ import {_} from 'common'; -import Utils from 'Common/Utils'; +import {isObject, isUnd} from 'Common/Utils'; import Plugins from 'Common/Plugins'; class Events @@ -17,7 +17,7 @@ class Events */ sub(name, func, context) { - if (Utils.isObject(name)) + if (isObject(name)) { context = func || null; func = null; @@ -28,7 +28,7 @@ class Events } else { - if (Utils.isUnd(this.subs[name])) + if (isUnd(this.subs[name])) { this.subs[name] = []; } @@ -48,7 +48,7 @@ class Events Plugins.runHook('rl-pub', [name, args]); - if (!Utils.isUnd(this.subs[name])) + if (!isUnd(this.subs[name])) { _.each(this.subs[name], (items) => { if (items[0]) diff --git a/dev/Common/Globals.js b/dev/Common/Globals.js deleted file mode 100644 index 4f4be8add..000000000 --- a/dev/Common/Globals.js +++ /dev/null @@ -1,303 +0,0 @@ - -/* global RL_COMMUNITY */ - -(function () { - - 'use strict'; - - var - Globals = {}, - - window = require('window'), - _ = require('_'), - $ = require('$'), - ko = require('ko'), - key = require('key'), - - Enums = require('Common/Enums') - ; - - Globals.$win = $(window); - Globals.$doc = $(window.document); - Globals.$html = $('html'); - Globals.$body = $('body'); - Globals.$div = $('
'); - - Globals.$win.__sizes = [0, 0]; - - /** - * @type {?} - */ - Globals.startMicrotime = (new window.Date()).getTime(); - - /** - * @type {boolean} - */ - Globals.community = RL_COMMUNITY; - - /** - * @type {?} - */ - Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0}); - - /** - * @type {boolean} - */ - Globals.useKeyboardShortcuts = ko.observable(true); - - /** - * @type {number} - */ - Globals.iAjaxErrorCount = 0; - - /** - * @type {number} - */ - Globals.iTokenErrorCount = 0; - - /** - * @type {number} - */ - Globals.iMessageBodyCacheCount = 0; - - /** - * @type {boolean} - */ - Globals.bUnload = false; - - /** - * @type {string} - */ - Globals.sUserAgent = 'navigator' in window && 'userAgent' in window.navigator && - window.navigator.userAgent.toLowerCase() || ''; - - /** - * @type {boolean} - */ - Globals.bIE = Globals.sUserAgent.indexOf('msie') > -1; - - /** - * @type {boolean} - */ - Globals.bChrome = Globals.sUserAgent.indexOf('chrome') > -1; - - /** - * @type {boolean} - */ - Globals.bSafari = !Globals.bChrome && Globals.sUserAgent.indexOf('safari') > -1; - - /** - * @type {boolean} - */ - Globals.bMobileDevice = - /android/i.test(Globals.sUserAgent) || - /iphone/i.test(Globals.sUserAgent) || - /ipod/i.test(Globals.sUserAgent) || - /ipad/i.test(Globals.sUserAgent) || - /blackberry/i.test(Globals.sUserAgent) - ; - - /** - * @type {boolean} - */ - Globals.bDisableNanoScroll = Globals.bMobileDevice; - - /** - * @type {boolean} - */ - Globals.bAllowPdfPreview = !Globals.bMobileDevice; - - /** - * @type {boolean} - */ - Globals.bAnimationSupported = !Globals.bMobileDevice && - Globals.$html.hasClass('csstransitions') && - Globals.$html.hasClass('cssanimations'); - - /** - * @type {boolean} - */ - Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest; - - /** - * @type {*} - */ - Globals.__APP__ = null; - - /** - * @type {Object} - */ - Globals.oHtmlEditorDefaultConfig = { - 'title': false, - 'stylesSet': false, - 'customConfig': '', - 'contentsCss': '', - 'toolbarGroups': [ - {name: 'spec'}, - {name: 'styles'}, - {name: 'basicstyles', groups: ['basicstyles', 'cleanup', 'bidi']}, - {name: 'colors'}, - Globals.bMobileDevice ? {} : {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']}, - {name: 'links'}, - {name: 'insert'}, - {name: 'document', groups: ['mode', 'document', 'doctools']}, - {name: 'others'} - ], - - 'removePlugins': 'liststyle', - 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll,Source', - 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced', - - 'extraPlugins': 'plain,signature', - - 'allowedContent': true, - 'extraAllowedContent': true, - - 'fillEmptyBlocks': false, - 'ignoreEmptyParagraph': true, - 'disableNativeSpellChecker': false, - - 'font_defaultLabel': 'Arial', - 'fontSize_defaultLabel': '13', - 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px' - }; - - /** - * @type {Object} - */ - Globals.oHtmlEditorLangsMap = { - 'bg_bg': 'bg', - 'de_de': 'de', - 'el_gr': 'el', - 'es_es': 'es', - 'fr_fr': 'fr', - 'hu_hu': 'hu', - 'is_is': 'is', - 'it_it': 'it', - 'ja_jp': 'ja', - 'ko_kr': 'ko', - 'lt_lt': 'lt', - 'lv_lv': 'lv', - 'nl_nl': 'nl', - 'bg_no': 'no', - 'pl_pl': 'pl', - 'pt_pt': 'pt', - 'pt_br': 'pt-br', - 'ro_ro': 'ro', - 'ru_ru': 'ru', - 'sk_sk': 'sk', - 'sl_si': 'sl', - 'sv_se': 'sv', - 'tr_tr': 'tr', - 'uk_ua': 'ru', - 'zh_tw': 'zh', - 'zh_cn': 'zh-cn' - }; - - if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) - { - Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) { - return oType && 'application/pdf' === oType.type; - }); - - if (!Globals.bAllowPdfPreview) - { - Globals.bAllowPdfPreview = (typeof window.navigator.mimeTypes['application/pdf'] !== 'undefined'); - } - } - - Globals.aBootstrapDropdowns = []; - - Globals.aViewModels = { - 'settings': [], - 'settings-removed': [], - 'settings-disabled': [] - }; - - Globals.leftPanelDisabled = ko.observable(false); - Globals.leftPanelType = ko.observable(''); - Globals.leftPanelWidth = ko.observable(0); - - // popups - Globals.popupVisibilityNames = ko.observableArray([]); - - Globals.popupVisibility = ko.computed(function () { - return 0 < Globals.popupVisibilityNames().length; - }, this); - - Globals.popupVisibility.subscribe(function (bValue) { - Globals.$html.toggleClass('rl-modal', bValue); - }); - - // keys - Globals.keyScopeReal = ko.observable(Enums.KeyState.All); - Globals.keyScopeFake = ko.observable(Enums.KeyState.All); - - Globals.keyScope = ko.computed({ - 'owner': this, - 'read': function () { - return Globals.keyScopeFake(); - }, - 'write': function (sValue) { - - if (Enums.KeyState.Menu !== sValue) - { - if (Enums.KeyState.Compose === sValue) - { - // disableKeyFilter - key.filter = function () { - return Globals.useKeyboardShortcuts(); - }; - } - else - { - // restoreKeyFilter - key.filter = function (event) { - - if (Globals.useKeyboardShortcuts()) - { - var - oElement = event.target || event.srcElement, - sTagName = oElement ? oElement.tagName : '' - ; - - sTagName = sTagName.toUpperCase(); - return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' || - (oElement && sTagName === 'DIV' && ('editorHtmlArea' === oElement.className || 'true' === '' + oElement.contentEditable)) - ); - } - - return false; - }; - } - - Globals.keyScopeFake(sValue); - if (Globals.dropdownVisibility()) - { - sValue = Enums.KeyState.Menu; - } - } - - Globals.keyScopeReal(sValue); - } - }); - - Globals.keyScopeReal.subscribe(function (sValue) { -// window.console.log('keyScope=' + sValue); // DEBUG - key.setScope(sValue); - }); - - Globals.dropdownVisibility.subscribe(function (bValue) { - if (bValue) - { - Globals.keyScope(Enums.KeyState.Menu); - } - else if (Enums.KeyState.Menu === key.getScope()) - { - Globals.keyScope(Globals.keyScopeFake()); - } - }); - - module.exports = Globals; - -}()); \ No newline at end of file diff --git a/dev/Common/Globals.jsx b/dev/Common/Globals.jsx new file mode 100644 index 000000000..26ea5e45f --- /dev/null +++ b/dev/Common/Globals.jsx @@ -0,0 +1,276 @@ + +/* global RL_COMMUNITY */ +import {window, _, $, key} from 'common'; +import ko from 'ko'; +import {KeyState} from 'Common/Enums'; + +const $win = $(window); +$win.__sizes = [0, 0]; + +export {$win}; + +export const $doc = $(window.document); + +export const $html = $('html'); + +export const $body = $('body'); + +export const $div = $(''); + +export const startMicrotime = (new window.Date()).getTime(); + +/** + * @type {boolean} + */ +export const community = RL_COMMUNITY; + +/** + * @type {?} + */ +export const dropdownVisibility = ko.observable(false).extend({rateLimit: 0}); + +/** + * @type {boolean} + */ +export const useKeyboardShortcuts = ko.observable(true); + +/** + * @type {string} + */ +export const sUserAgent = 'navigator' in window && 'userAgent' in window.navigator && + window.navigator.userAgent.toLowerCase() || ''; + +/** + * @type {boolean} + */ +export const bIE = sUserAgent.indexOf('msie') > -1; + +/** + * @type {boolean} + */ +export const bChrome = sUserAgent.indexOf('chrome') > -1; + +/** + * @type {boolean} + */ +export const bSafari = !bChrome && sUserAgent.indexOf('safari') > -1; + +/** + * @type {boolean} + */ +export const bMobileDevice = + /android/i.test(sUserAgent) || + /iphone/i.test(sUserAgent) || + /ipod/i.test(sUserAgent) || + /ipad/i.test(sUserAgent) || + /blackberry/i.test(sUserAgent) +; + +/** + * @type {boolean} + */ +export let bDisableNanoScroll = bMobileDevice; + +/** + * @type {boolean} + */ +export let bAnimationSupported = !bMobileDevice && + $html.hasClass('csstransitions') && + $html.hasClass('cssanimations') +; + +/** + * @type {boolean} + */ +export const bXMLHttpRequestSupported = !!window.XMLHttpRequest; + +/** + * @type {Object} + */ +export const oHtmlEditorDefaultConfig = { + title: false, + stylesSet: false, + 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'} + ], + + removePlugins: 'liststyle', + removeButtons: 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll,Source', + removeDialogTabs: 'link:advanced;link:target;image:advanced;images:advanced', + + extraPlugins: 'plain,signature', + + allowedContent: true, + extraAllowedContent: true, + + fillEmptyBlocks: false, + ignoreEmptyParagraph: true, + disableNativeSpellChecker: false, + + font_defaultLabel: 'Arial', + fontSize_defaultLabel: '13', + fontSize_sizes: '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px' +}; + +/** + * @type {Object} + */ +export const oHtmlEditorLangsMap = { + bg_bg: 'bg', + de_de: 'de', + el_gr: 'el', + es_es: 'es', + fr_fr: 'fr', + hu_hu: 'hu', + is_is: 'is', + it_it: 'it', + ja_jp: 'ja', + ko_kr: 'ko', + lt_lt: 'lt', + lv_lv: 'lv', + nl_nl: 'nl', + bg_no: 'no', + pl_pl: 'pl', + pt_pt: 'pt', + pt_br: 'pt-br', + ro_ro: 'ro', + ru_ru: 'ru', + sk_sk: 'sk', + sl_si: 'sl', + sv_se: 'sv', + tr_tr: 'tr', + uk_ua: 'ru', + zh_tw: 'zh', + zh_cn: 'zh-cn' +}; + +/** + * @type {boolean} + */ +let bAllowPdfPreview = !bMobileDevice; + +if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) +{ + bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) { + return oType && 'application/pdf' === oType.type; + }); + + if (!bAllowPdfPreview) + { + bAllowPdfPreview = (typeof window.navigator.mimeTypes['application/pdf'] !== 'undefined'); + } +} + +export {bAllowPdfPreview}; + +export const aViewModels = { + settings: [], + 'settings-removed': [], + 'settings-disabled': [] +}; + +export const leftPanelDisabled = ko.observable(false); +export const leftPanelType = ko.observable(''); +export const leftPanelWidth = ko.observable(0); + +// popups +export const popupVisibilityNames = ko.observableArray([]); + +export const popupVisibility = ko.computed(() => { + return 0 < popupVisibilityNames().length; +}); + +popupVisibility.subscribe((bValue) => { + $html.toggleClass('rl-modal', bValue); +}); + +// keys +export const keyScopeReal = ko.observable(KeyState.All); +export const keyScopeFake = ko.observable(KeyState.All); + +export const keyScope = ko.computed({ + owner: this, + read: () => { + return keyScopeFake(); + }, + write: function (sValue) { + + if (KeyState.Menu !== sValue) + { + if (KeyState.Compose === sValue) + { + // disableKeyFilter + key.filter = function () { + return useKeyboardShortcuts(); + }; + } + else + { + // restoreKeyFilter + key.filter = function (event) { + + if (useKeyboardShortcuts()) + { + var + oElement = event.target || event.srcElement, + sTagName = oElement ? oElement.tagName : '' + ; + + sTagName = sTagName.toUpperCase(); + return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' || + (oElement && sTagName === 'DIV' && ('editorHtmlArea' === oElement.className || 'true' === '' + oElement.contentEditable)) + ); + } + + return false; + }; + } + + keyScopeFake(sValue); + if (dropdownVisibility()) + { + sValue = KeyState.Menu; + } + } + + keyScopeReal(sValue); + } +}); + +keyScopeReal.subscribe(function (sValue) { +// window.console.log('keyScope=' + sValue); // DEBUG + key.setScope(sValue); +}); + +dropdownVisibility.subscribe(function (bValue) { + if (bValue) + { + keyScope(KeyState.Menu); + } + else if (KeyState.Menu === key.getScope()) + { + keyScope(keyScopeFake()); + } +}); + +/** + * @type {*} + */ +export const data = { + __APP__: null, + iAjaxErrorCount: 0, + iTokenErrorCount: 0, + aBootstrapDropdowns: [], + iMessageBodyCacheCount: 0, + bUnload: false +}; diff --git a/dev/Common/HtmlEditor.jsx b/dev/Common/HtmlEditor.jsx index e98dd506e..e79f3d5b8 100644 --- a/dev/Common/HtmlEditor.jsx +++ b/dev/Common/HtmlEditor.jsx @@ -1,6 +1,6 @@ import {window, _, $} from 'common'; -import Globals from 'Common/Globals'; +import {oHtmlEditorDefaultConfig, oHtmlEditorLangsMap} from 'Common/Globals'; import Settings from 'Storage/Settings'; class HtmlEditor @@ -236,7 +236,7 @@ class HtmlEditor initFunc = () => { const - config = Globals.oHtmlEditorDefaultConfig, + config = oHtmlEditorDefaultConfig, language = Settings.settingsGet('Language'), allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'), biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons') @@ -260,7 +260,7 @@ class HtmlEditor config.enterMode = window.CKEDITOR.ENTER_BR; config.shiftEnterMode = window.CKEDITOR.ENTER_P; - config.language = Globals.oHtmlEditorLangsMap[language] || 'en'; + config.language = oHtmlEditorLangsMap[language] || 'en'; if (window.CKEDITOR.env) { window.CKEDITOR.env.isCompatible = true; diff --git a/dev/Common/Links.jsx b/dev/Common/Links.jsx index 3bb2ada7d..2c6f5bb89 100644 --- a/dev/Common/Links.jsx +++ b/dev/Common/Links.jsx @@ -1,18 +1,19 @@ import {window} from 'common'; -import Utils from 'Common/Utils'; +import {pString, pInt, isUnd, isNormal, trim, encodeURIComponent} from 'Common/Utils'; import Settings from 'Storage/Settings'; class Links { constructor() { - this.sBase = '#/'; - this.sServer = './?'; + this.sHashPrefix = '#/'; + this.sServerPrefix = './?'; this.sVersion = Settings.appSettingsGet('version'); this.sWebPrefix = Settings.appSettingsGet('webPath') || ''; this.sVersionPrefix = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + this.sVersion + '/'; + this.bAminHostUse = !!Settings.appSettingsGet('adminHostUse'); this.sAdminPath = Settings.appSettingsGet('adminPath') || 'admin'; this.sAuthSuffix = Settings.settingsGet('AuthAccountHash') || '0'; @@ -36,14 +37,14 @@ class Links * @return {string} */ root(startupUrl = '') { - return this.sBase + Utils.pString(startupUrl); + return this.sHashPrefix + pString(startupUrl); } /** * @return {string} */ rootAdmin() { - return this.sServer + this.sAdminPath; + return this.bAminHostUse ? './' : this.sServerPrefix + this.sAdminPath; } /** @@ -60,8 +61,8 @@ class Links * @return {string} */ attachmentRaw(type, download, customSpecSuffix) { - customSpecSuffix = Utils.isUnd(customSpecSuffix) ? this.sAuthSuffix : customSpecSuffix; - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + customSpecSuffix + '/' + type + '/' + + customSpecSuffix = isUnd(customSpecSuffix) ? this.sAuthSuffix : customSpecSuffix; + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + customSpecSuffix + '/' + type + '/' + this.subQueryPrefix() + '/' + download; } @@ -114,28 +115,28 @@ class Links * @return {string} */ upload() { - return this.sServer + '/Upload/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; + return this.sServerPrefix + '/Upload/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; } /** * @return {string} */ uploadContacts() { - return this.sServer + '/UploadContacts/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; + return this.sServerPrefix + '/UploadContacts/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; } /** * @return {string} */ uploadBackground() { - return this.sServer + '/UploadBackground/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; + return this.sServerPrefix + '/UploadBackground/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; } /** * @return {string} */ append() { - return this.sServer + '/Append/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; + return this.sServerPrefix + '/Append/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/'; } /** @@ -143,7 +144,7 @@ class Links * @return {string} */ change(email) { - return this.sServer + '/Change/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' + Utils.encodeURIComponent(email) + '/'; + return this.sServerPrefix + '/Change/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' + encodeURIComponent(email) + '/'; } /** @@ -151,7 +152,7 @@ class Links * @return {string} */ ajax(add) { - return this.sServer + '/Ajax/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' + add; + return this.sServerPrefix + '/Ajax/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' + add; } /** @@ -159,7 +160,7 @@ class Links * @return {string} */ messageViewLink(requestHash) { - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ViewAsPlain/' + this.subQueryPrefix() + '/' + requestHash; + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ViewAsPlain/' + this.subQueryPrefix() + '/' + requestHash; } /** @@ -167,7 +168,7 @@ class Links * @return {string} */ messageDownloadLink(requestHash) { - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/Download/' + this.subQueryPrefix() + '/' + requestHash; + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/Download/' + this.subQueryPrefix() + '/' + requestHash; } /** @@ -175,7 +176,7 @@ class Links * @return {string} */ avatarLink(email) { - return this.sServer + '/Raw/0/Avatar/' + Utils.encodeURIComponent(email) + '/'; + return this.sServerPrefix + '/Raw/0/Avatar/' + encodeURIComponent(email) + '/'; } /** @@ -183,7 +184,7 @@ class Links * @return {string} */ publicLink(hash) { - return this.sServer + '/Raw/0/Public/' + hash + '/'; + return this.sServerPrefix + '/Raw/0/Public/' + hash + '/'; } /** @@ -191,7 +192,7 @@ class Links * @return {string} */ userBackground(hash) { - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/UserBackground/' + this.subQueryPrefix() + '/' + hash; } @@ -200,7 +201,7 @@ class Links * @return {string} */ inbox(inboxFolderName = 'INBOX') { - return this.sBase + 'mailbox/' + inboxFolderName; + return this.sHashPrefix + 'mailbox/' + inboxFolderName; } /** @@ -208,14 +209,14 @@ class Links * @return {string} */ settings(screenName = '') { - return this.sBase + 'settings' + (screenName ? '/' + screenName : ''); + return this.sHashPrefix + 'settings' + (screenName ? '/' + screenName : ''); } /** * @return {string} */ about() { - return this.sBase + 'about'; + return this.sHashPrefix + 'about'; } /** @@ -223,7 +224,7 @@ class Links * @return {string} */ admin (screenName) { - let result = this.sBase; + let result = this.sHashPrefix; switch (screenName) { case 'AdminDomains': result += 'domains'; @@ -248,14 +249,14 @@ class Links */ mailBox(folder, page = 1, search = '', threadUid = '') { - page = Utils.isNormal(page) ? Utils.pInt(page) : 1; - search = Utils.pString(search); + page = isNormal(page) ? pInt(page) : 1; + search = pString(search); - let result = this.sBase + 'mailbox/'; + let result = this.sHashPrefix + 'mailbox/'; if ('' !== folder) { - const resultThreadUid = Utils.pInt(threadUid); + const resultThreadUid = pInt(threadUid); result += window.encodeURI(folder) + (0 < resultThreadUid ? '~' + resultThreadUid : ''); } @@ -278,7 +279,7 @@ class Links * @return {string} */ phpInfo() { - return this.sServer + 'Info'; + return this.sServerPrefix + 'Info'; } /** @@ -287,21 +288,21 @@ class Links * @return {string} */ langLink(lang, admin) { - return this.sServer + '/Lang/0/' + (admin ? 'Admin' : 'App') + '/' + window.encodeURI(lang) + '/' + this.sVersion + '/'; + return this.sServerPrefix + '/Lang/0/' + (admin ? 'Admin' : 'App') + '/' + window.encodeURI(lang) + '/' + this.sVersion + '/'; } /** * @return {string} */ exportContactsVcf() { - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ContactsVcf/'; + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ContactsVcf/'; } /** * @return {string} */ exportContactsCsv() { - return this.sServer + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ContactsCsv/'; + return this.sServerPrefix + '/Raw/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/ContactsCsv/'; } /** @@ -327,7 +328,7 @@ class Links let prefix = this.sVersionPrefix; if ('@custom' === theme.substr(-7)) { - theme = Utils.trim(theme.substring(0, theme.length - 7)); + theme = trim(theme.substring(0, theme.length - 7)); prefix = this.sWebPrefix; } @@ -367,7 +368,7 @@ class Links * @return {string} */ socialGoogle(xauth = false) { - return this.sServer + 'SocialGoogle' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : '') + + return this.sServerPrefix + 'SocialGoogle' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : '') + (xauth ? '&xauth=1' : ''); } @@ -375,14 +376,14 @@ class Links * @return {string} */ socialTwitter() { - return this.sServer + 'SocialTwitter' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : ''); + return this.sServerPrefix + 'SocialTwitter' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : ''); } /** * @return {string} */ socialFacebook() { - return this.sServer + 'SocialFacebook' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : ''); + return this.sServerPrefix + 'SocialFacebook' + ('' !== this.sAuthSuffix ? '/' + this.subQueryPrefix() + '/' + this.sAuthSuffix + '/' : ''); } } diff --git a/dev/Common/Plugins.jsx b/dev/Common/Plugins.jsx index 89f891656..ee0719025 100644 --- a/dev/Common/Plugins.jsx +++ b/dev/Common/Plugins.jsx @@ -1,7 +1,7 @@ import {_} from 'common'; -import Utils from 'Common/Utils'; -import Globals from 'Common/Globals'; +import {isFunc, isArray, isUnd} from 'Common/Utils'; +import {data as GlobalsData} from 'Common/Globals'; import Settings from 'Storage/Settings'; class Plugins @@ -17,9 +17,9 @@ class Plugins * @param {Function} callback */ addHook(name, callback) { - if (Utils.isFunc(callback)) + if (isFunc(callback)) { - if (!Utils.isArray(this.oSimpleHooks[name])) + if (!isArray(this.oSimpleHooks[name])) { this.oSimpleHooks[name] = []; } @@ -33,7 +33,7 @@ class Plugins * @param {Array=} args */ runHook(name, args = []) { - if (Utils.isArray(this.oSimpleHooks[name])) + if (isArray(this.oSimpleHooks[name])) { _.each(this.oSimpleHooks[name], (callback) => { callback.apply(null, args); @@ -56,9 +56,9 @@ class Plugins * @param {?number=} timeout */ remoteRequest(callback, action, parameters, timeout) { - if (Globals.__APP__) + if (GlobalsData.__APP__) { - Globals.__APP__.remote().defaultRequest(callback, 'Plugin' + action, parameters, timeout); + GlobalsData.__APP__.remote().defaultRequest(callback, 'Plugin' + action, parameters, timeout); } } @@ -99,8 +99,8 @@ class Plugins */ settingsGet(pluginSection, name) { let plugins = Settings.settingsGet('Plugins'); - plugins = plugins && !Utils.isUnd(plugins[pluginSection]) ? plugins[pluginSection] : null; - return plugins ? (Utils.isUnd(plugins[name]) ? null : plugins[name]) : null; + plugins = plugins && !isUnd(plugins[pluginSection]) ? plugins[pluginSection] : null; + return plugins ? (isUnd(plugins[name]) ? null : plugins[name]) : null; } } diff --git a/dev/Common/Selector.jsx b/dev/Common/Selector.jsx index d23caead1..23c7766c1 100644 --- a/dev/Common/Selector.jsx +++ b/dev/Common/Selector.jsx @@ -2,7 +2,7 @@ import {$, _, key} from 'common'; import ko from 'ko'; import {EventKeyCode} from 'Common/Enums'; -import Utils from 'Common/Utils'; +import {isArray, inArray} from 'Common/Utils'; class Selector { @@ -137,7 +137,7 @@ class Selector this.list.subscribe((items) => { - if (Utils.isArray(items)) + if (isArray(items)) { _.each(items, (item) => { if (item) @@ -179,7 +179,7 @@ class Selector this.focusedItem(null); this.selectedItem(null); - if (Utils.isArray(aItems)) + if (isArray(aItems)) { iLen = aCheckedCache.length; @@ -194,7 +194,7 @@ class Selector mFocused = null; } - if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache)) + if (0 < iLen && -1 < inArray(sUid, aCheckedCache)) { bChecked = true; oItem.checked(true); @@ -223,7 +223,7 @@ class Selector { bGetNext = false; mNextFocused = _.find(aCache, (sUid) => { - if (bGetNext && -1 < Utils.inArray(sUid, aUids)) + if (bGetNext && -1 < inArray(sUid, aUids)) { return sUid; } diff --git a/dev/Common/Translator.jsx b/dev/Common/Translator.jsx index 4efa11c26..1da021564 100644 --- a/dev/Common/Translator.jsx +++ b/dev/Common/Translator.jsx @@ -2,8 +2,8 @@ import {window, $, _} from 'common'; import ko from 'ko'; import {Notification, UploadErrorCode} from 'Common/Enums'; -import Utils from 'Common/Utils'; -import Globals from 'Common/Globals'; +import {pInt, microtime, noop, inArray} from 'Common/Utils'; +import {$html, bAnimationSupported} from 'Common/Globals'; class Translator { @@ -94,7 +94,7 @@ class Translator this.i18nToNode(item); }); - if (animate && Globals.bAnimationSupported) + if (animate && bAnimationSupported) { $('.i18n-animation[data-i18n]', elements).letterfx({ fx: 'fall fade', @@ -256,7 +256,7 @@ class Translator */ getNotificationFromResponse(response, defCode = Notification.UnknownNotification) { return response && response.ErrorCode ? - this.getNotification(Utils.pInt(response.ErrorCode), response.ErrorMessage || '') : + this.getNotification(pInt(response.ErrorCode), response.ErrorMessage || '') : this.getNotification(defCode); } @@ -303,40 +303,40 @@ class Translator const self = this, - start = Utils.microtime() + start = microtime() ; - Globals.$html.addClass('rl-changing-language'); + $html.addClass('rl-changing-language'); $.ajax({ url: require('Common/Links').langLink(language, admin), dataType: 'script', cache: true }) - .fail(fail || Utils.emptyFunction) + .fail(fail || noop) .done(function () { _.delay(function () { self.reloadData(); - (done || Utils.emptyFunction)(); + (done || noop)(); - const isRtl = -1 < Utils.inArray(language, ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']); + const isRtl = -1 < inArray(language, ['ar', 'ar_sa', 'he', 'he_he', 'ur', 'ur_ir']); - Globals.$html + $html .removeClass('rl-changing-language') .removeClass('rl-rtl rl-ltr') .addClass(isRtl ? 'rl-rtl' : 'rl-ltr') // .attr('dir', isRtl ? 'rtl' : 'ltr') ; - }, 500 < Utils.microtime() - start ? 1 : 500); + }, 500 < microtime() - start ? 1 : 500); }) ; } init() { - Globals.$html.addClass('rl-' + (Globals.$html.attr('dir') || 'ltr')); + $html.addClass('rl-' + ($html.attr('dir') || 'ltr')); } } diff --git a/dev/Common/Utils.js b/dev/Common/Utils.js deleted file mode 100644 index be006dba6..000000000 --- a/dev/Common/Utils.js +++ /dev/null @@ -1,1641 +0,0 @@ - -(function () { - - 'use strict'; - - var - oEncryptObject = null, - - Utils = {}, - - window = require('window'), - _ = require('_'), - $ = require('$'), - ko = require('ko'), - Autolinker = require('Autolinker'), - JSON = require('JSON'), - JSEncrypt = require('JSEncrypt'), - - Mime = require('Common/Mime'), - - Enums = require('Common/Enums'), - Globals = require('Common/Globals') - ; - - Utils.trim = $.trim; - Utils.inArray = $.inArray; - Utils.isArray = _.isArray; - Utils.isObject = _.isObject; - Utils.isFunc = _.isFunction; - Utils.isUnd = _.isUndefined; - Utils.isNull = _.isNull; - Utils.emptyFunction = Utils.noop = function () {}; - - /** - * @param {Function} callback - */ - Utils.silentTryCatch = function (callback) - { - try - { - callback(); - } - catch (e) - { - // eslint-disable-line no-empty - } - }; - - /** - * @param {*} oValue - * @return {boolean} - */ - Utils.isNormal = function (oValue) - { - return !Utils.isUnd(oValue) && !Utils.isNull(oValue); - }; - - Utils.windowResize = _.debounce(function (iTimeout) { - if (Utils.isUnd(iTimeout)) - { - Globals.$win.resize(); - } - else - { - window.setTimeout(function () { - Globals.$win.resize(); - }, iTimeout); - } - }, 50); - - Utils.windowResizeCallback = function () { - Utils.windowResize(); - }; - - /** - * @param {(string|number)} mValue - * @param {boolean=} bIncludeZero - * @return {boolean} - */ - Utils.isPosNumeric = function (mValue, bIncludeZero) - { - return Utils.isNormal(mValue) ? - ((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ? - (/^[0-9]*$/).test(mValue.toString()) : - (/^[1-9]+[0-9]*$/).test(mValue.toString())) : - false; - }; - - /** - * @param {*} iValue - * @param {number=} iDefault = 0 - * @return {number} - */ - Utils.pInt = function (iValue, iDefault) - { - var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0); - return window.isNaN(iResult) ? (iDefault || 0) : iResult; - }; - - /** - * @param {*} mValue - * @return {string} - */ - Utils.pString = function (mValue) - { - return Utils.isNormal(mValue) ? '' + mValue : ''; - }; - - /** - * @param {*} mValue - * @return {boolean} - */ - Utils.pBool = function (mValue) - { - return !!mValue; - }; - - /** - * @param {string} sComponent - * @return {string} - */ - Utils.encodeURIComponent = function (sComponent) - { - return window.encodeURIComponent(sComponent); - }; - - /** - * @param {*} aValue - * @return {boolean} - */ - Utils.isNonEmptyArray = function (aValue) - { - return Utils.isArray(aValue) && 0 < aValue.length; - }; - - /** - * @param {string} sQueryString - * @return {Object} - */ - Utils.simpleQueryParser = function (sQueryString) - { - var - oParams = {}, - aQueries = [], - aTemp = [], - iIndex = 0, - iLen = 0 - ; - - aQueries = sQueryString.split('&'); - for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++) - { - aTemp = aQueries[iIndex].split('='); - oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]); - } - - return oParams; - }; - - /** - * @param {string} sMailToUrl - * @param {Function} PopupComposeVoreModel - * @return {boolean} - */ - Utils.mailToHelper = function (sMailToUrl, PopupComposeVoreModel) - { - if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase()) - { - if (!PopupComposeVoreModel) - { - return true; - } - - sMailToUrl = sMailToUrl.toString().substr(7); - - var - aTo = [], - aCc = null, - aBcc = null, - oParams = {}, - EmailModel = require('Model/Email'), - sEmail = sMailToUrl.replace(/\?.+$/, ''), - sQueryString = sMailToUrl.replace(/^[^\?]*\?/, ''), - fParseEmailLine = function (sLine) { - return sLine ? _.compact(_.map(window.decodeURIComponent(sLine).split(/[,]/), function (sItem) { - var oEmailModel = new EmailModel(); - oEmailModel.mailsoParse(sItem); - return '' !== oEmailModel.email ? oEmailModel : null; - })) : null; - } - ; - - aTo = fParseEmailLine(sEmail); - - oParams = Utils.simpleQueryParser(sQueryString); - - if (!Utils.isUnd(oParams.cc)) - { - aCc = fParseEmailLine(window.decodeURIComponent(oParams.cc)); - } - - if (!Utils.isUnd(oParams.bcc)) - { - aBcc = fParseEmailLine(window.decodeURIComponent(oParams.bcc)); - } - - require('Knoin/Knoin').showScreenPopup(PopupComposeVoreModel, [Enums.ComposeType.Empty, null, - aTo, aCc, aBcc, - Utils.isUnd(oParams.subject) ? null : - Utils.pString(window.decodeURIComponent(oParams.subject)), - Utils.isUnd(oParams.body) ? null : - Utils.plainToHtml(Utils.pString(window.decodeURIComponent(oParams.body))) - ]); - - return true; - } - - return false; - }; - - /** - * @param {string} sPublicKey - * @return {JSEncrypt} - */ - Utils.rsaObject = function (sPublicKey) - { - if (JSEncrypt && sPublicKey && (null === oEncryptObject || (oEncryptObject && oEncryptObject.__sPublicKey !== sPublicKey)) && - window.crypto && window.crypto.getRandomValues) - { - oEncryptObject = new JSEncrypt(); - oEncryptObject.setPublicKey(sPublicKey); - oEncryptObject.__sPublicKey = sPublicKey; - } - else - { - oEncryptObject = false; - } - - return oEncryptObject; - }; - - /** - * @param {string} sValue - * @param {string} sPublicKey - * @return {string} - */ - Utils.rsaEncode = function (sValue, sPublicKey) - { - if (window.crypto && window.crypto.getRandomValues && sPublicKey) - { - var - sResultValue = false, - oEncrypt = Utils.rsaObject(sPublicKey) - ; - - if (oEncrypt) - { - sResultValue = oEncrypt.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5()); - if (false !== sResultValue && Utils.isNormal(sResultValue)) - { - return 'rsa:xxx:' + sResultValue; - } - } - } - - return sValue; - }; - - Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && false && JSEncrypt); - - /** - * @param {string} sText - * @return {string} - */ - Utils.encodeHtml = function (sText) - { - return Utils.isNormal(sText) ? _.escape(sText.toString()) : ''; - }; - - /** - * @param {string} sText - * @param {number=} iLen - * @return {string} - */ - Utils.splitPlainText = function (sText, iLen) - { - var - sPrefix = '', - sSubText = '', - sResult = sText, - iSpacePos = 0, - iNewLinePos = 0 - ; - - iLen = Utils.isUnd(iLen) ? 100 : iLen; - - while (sResult.length > iLen) - { - sSubText = sResult.substring(0, iLen); - iSpacePos = sSubText.lastIndexOf(' '); - iNewLinePos = sSubText.lastIndexOf('\n'); - - if (-1 !== iNewLinePos) - { - iSpacePos = iNewLinePos; - } - - if (-1 === iSpacePos) - { - iSpacePos = iLen; - } - - sPrefix += sSubText.substring(0, iSpacePos) + '\n'; - sResult = sResult.substring(iSpacePos + 1); - } - - return sPrefix + sResult; - }; - - Utils.timeOutAction = (function () { - - var - oTimeOuts = {} - ; - - return function (sAction, fFunction, iTimeOut) - { - if (Utils.isUnd(oTimeOuts[sAction])) - { - oTimeOuts[sAction] = 0; - } - - window.clearTimeout(oTimeOuts[sAction]); - oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut); - }; - }()); - - Utils.timeOutActionSecond = (function () { - - var - oTimeOuts = {} - ; - - return function (sAction, fFunction, iTimeOut) - { - if (!oTimeOuts[sAction]) - { - oTimeOuts[sAction] = window.setTimeout(function () { - fFunction(); - oTimeOuts[sAction] = 0; - }, iTimeOut); - } - }; - }()); - - /** - * @param {(Object|null|undefined)} oObject - * @param {string} sProp - * @return {boolean} - */ - Utils.hos = function (oObject, sProp) - { - return oObject && window.Object && window.Object.hasOwnProperty ? window.Object.hasOwnProperty.call(oObject, sProp) : false; - }; - - /** - * @return {boolean} - */ - Utils.inFocus = function () - { - if (window.document.activeElement) - { - if (Utils.isUnd(window.document.activeElement.__inFocusCache)) - { - window.document.activeElement.__inFocusCache = $(window.document.activeElement).is('input,textarea,iframe,.cke_editable'); - } - - return !!window.document.activeElement.__inFocusCache; - } - - return false; - }; - - Utils.removeInFocus = function (force) - { - if (window.document && window.document.activeElement && window.document.activeElement.blur) - { - var oA = $(window.document.activeElement); - if (oA.is('input,textarea')) - { - window.document.activeElement.blur(); - } - else if (force) - { - try { - window.document.activeElement.blur(); - } catch (e) {} - } - } - }; - - Utils.removeSelection = function () - { - if (window && window.getSelection) - { - var oSel = window.getSelection(); - if (oSel && oSel.removeAllRanges) - { - oSel.removeAllRanges(); - } - } - else if (window.document && window.document.selection && window.document.selection.empty) - { - window.document.selection.empty(); - } - }; - - /** - * @param {string} sPrefix - * @param {string} sSubject - * @return {string} - */ - Utils.replySubjectAdd = function (sPrefix, sSubject) - { - sPrefix = Utils.trim(sPrefix.toUpperCase()); - sSubject = Utils.trim(sSubject.replace(/[\s]+/g, ' ')); - - var - bDrop = false, - aSubject = [], - bRe = 'RE' === sPrefix, - bFwd = 'FWD' === sPrefix, - bPrefixIsRe = !bFwd - ; - - if ('' !== sSubject) - { - _.each(sSubject.split(':'), function (sPart) { - var sTrimmedPart = Utils.trim(sPart); - if (!bDrop && (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))) - { - if (!bRe) - { - bRe = !!(/^RE/i.test(sTrimmedPart)); - } - - if (!bFwd) - { - bFwd = !!(/^FWD/i.test(sTrimmedPart)); - } - } - else - { - aSubject.push(sPart); - bDrop = true; - } - }); - } - - if (bPrefixIsRe) - { - bRe = false; - } - else - { - bFwd = false; - } - - return Utils.trim( - (bPrefixIsRe ? 'Re: ' : 'Fwd: ') + - (bRe ? 'Re: ' : '') + - (bFwd ? 'Fwd: ' : '') + - Utils.trim(aSubject.join(':')) - ); - }; - - /** - * @param {number} iNum - * @param {number} iDec - * @return {number} - */ - Utils.roundNumber = function (iNum, iDec) - { - return window.Math.round(iNum * window.Math.pow(10, iDec)) / window.Math.pow(10, iDec); - }; - - /** - * @param {(number|string)} iSizeInBytes - * @return {string} - */ - Utils.friendlySize = function (iSizeInBytes) - { - iSizeInBytes = Utils.pInt(iSizeInBytes); - - if (iSizeInBytes >= 1073741824) - { - return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB'; - } - else if (iSizeInBytes >= 1048576) - { - return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB'; - } - else if (iSizeInBytes >= 1024) - { - return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB'; - } - - return iSizeInBytes + 'B'; - }; - - /** - * @param {string} sDesc - */ - Utils.log = function (sDesc) - { - if (window.console && window.console.log) - { - window.console.log(sDesc); - } - }; - - /** - * @param {?} oObject - * @param {string} sMethodName - * @param {Array=} aParameters - * @param {number=} nDelay - */ - Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay) - { - if (oObject && oObject[sMethodName]) - { - nDelay = Utils.pInt(nDelay); - if (0 >= nDelay) - { - oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []); - } - else - { - _.delay(function () { - oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []); - }, nDelay); - } - } - }; - - /** - * @param {?} oEvent - */ - Utils.kill_CtrlA_CtrlS = function (oEvent) - { - oEvent = oEvent || window.event; - if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey) - { - var - oSender = oEvent.target || oEvent.srcElement, - iKey = oEvent.keyCode || oEvent.which - ; - - if (iKey === Enums.EventKeyCode.S) - { - oEvent.preventDefault(); - return; - } - else if (iKey === Enums.EventKeyCode.A) - { - if (oSender && ('true' === '' + oSender.contentEditable || - (oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i)))) - { - return; - } - - if (window.getSelection) - { - window.getSelection().removeAllRanges(); - } - else if (window.document.selection && window.document.selection.clear) - { - window.document.selection.clear(); - } - - oEvent.preventDefault(); - } - } - }; - - /** - * @param {(Object|null|undefined)} oContext - * @param {Function} fExecute - * @param {(Function|boolean|null)=} fCanExecute - * @return {Function} - */ - Utils.createCommand = function (oContext, fExecute, fCanExecute) - { - var - fResult = Utils.emptyFunction, - fNonEmpty = function () { - if (fResult && fResult.canExecute && fResult.canExecute()) - { - fExecute.apply(oContext, Array.prototype.slice.call(arguments)); - } - return false; - } - ; - - fResult = fExecute ? fNonEmpty : Utils.emptyFunction; - fResult.enabled = ko.observable(true); - - fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute; - if (Utils.isFunc(fCanExecute)) - { - fResult.canExecute = ko.computed(function () { - return fResult.enabled() && fCanExecute.call(oContext); - }); - } - else - { - fResult.canExecute = ko.computed(function () { - return fResult.enabled() && !!fCanExecute; - }); - } - - return fResult; - }; - - /** - * @param {string} sTheme - * @return {string} - */ - Utils.convertThemeName = _.memoize(function (sTheme) - { - if ('@custom' === sTheme.substr(-7)) - { - sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7)); - } - - return Utils.trim(sTheme.replace(/[^a-zA-Z0-9]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' ')); - }); - - /** - * @param {string} sName - * @return {string} - */ - Utils.quoteName = function (sName) - { - return sName.replace(/["]/g, '\\"'); - }; - - /** - * @return {number} - */ - Utils.microtime = function () - { - return (new window.Date()).getTime(); - }; - - /** - * @return {number} - */ - Utils.timestamp = function () - { - return window.Math.round(Utils.microtime() / 1000); - }; - - /** - * - * @param {string} sLanguage - * @param {boolean=} bEng = false - * @return {string} - */ - Utils.convertLangName = function (sLanguage, bEng) - { - return require('Common/Translator').i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' + - sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'), null, sLanguage); - }; - - /** - * @param {number=} iLen - * @return {string} - */ - Utils.fakeMd5 = function(iLen) - { - var - sResult = '', - sLine = '0123456789abcdefghijklmnopqrstuvwxyz' - ; - - iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen); - - while (sResult.length < iLen) - { - sResult += sLine.substr(window.Math.round(window.Math.random() * sLine.length), 1); - } - - return sResult; - }; - - Utils.draggablePlace = function () - { - return $(']*><\/p>/gi, '') - .replace(/
]*>([\s\S\r\n\t]*)<\/pre>/gmi, convertPre)
- .replace(/[\s]+/gm, ' ')
- .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
- .replace(/
]*>/gmi, '\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(/<\/div>/gi, '\n') - .replace(/ /gi, ' ') - .replace(/"/gi, '"') - .replace(/<[^>]*>/gm, '') - ; - - sText = Globals.$div.html(sText).text(); - - sText = sText - .replace(/\n[ \t]+/gm, '\n') - .replace(/[\n]{3,}/gm, '\n\n') - .replace(/>/gi, '>') - .replace(/</gi, '<') - .replace(/&/gi, '&') - ; - - sText = Utils.splitPlainText(Utils.trim(sText)); - - iPos = 0; - iLimit = 800; - - while (0 < iLimit) - { - iLimit--; - iP1 = sText.indexOf('__bq__start__', iPos); - if (-1 < iP1) - { - iP2 = sText.indexOf('__bq__start__', iP1 + 5); - iP3 = sText.indexOf('__bq__end__', iP1 + 5); - - if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3) - { - sText = sText.substring(0, iP1) + - convertBlockquote(sText.substring(iP1 + 13, iP3)) + - sText.substring(iP3 + 11); - - iPos = 0; - } - else if (-1 < iP2 && iP2 < iP3) - { - iPos = iP2 - 1; - } - else - { - iPos = 0; - } - } - else - { - break; - } - } - - sText = sText - .replace(/__bq__start__/gm, '') - .replace(/__bq__end__/gm, '') - ; - - return sText; - }; - - /** - * @param {string} sPlain - * @param {boolean} bFindEmailAndLinks = false - * @return {string} - */ - Utils.plainToHtml = function (sPlain, bFindEmailAndLinks) - { - sPlain = sPlain.toString().replace(/\r/g, ''); - - bFindEmailAndLinks = Utils.isUnd(bFindEmailAndLinks) ? false : !!bFindEmailAndLinks; - - var - bIn = false, - bDo = true, - bStart = true, - aNextText = [], - sLine = '', - iIndex = 0, - aText = sPlain.split("\n") - ; - - do - { - bDo = false; - aNextText = []; - for (iIndex = 0; iIndex < aText.length; iIndex++) - { - sLine = aText[iIndex]; - bStart = '>' === sLine.substr(0, 1); - if (bStart && !bIn) - { - bDo = true; - bIn = true; - aNextText.push('~~~blockquote~~~'); - aNextText.push(sLine.substr(1)); - } - else if (!bStart && bIn) - { - if ('' !== sLine) - { - bIn = false; - aNextText.push('~~~/blockquote~~~'); - aNextText.push(sLine); - } - else - { - aNextText.push(sLine); - } - } - else if (bStart && bIn) - { - aNextText.push(sLine.substr(1)); - } - else - { - aNextText.push(sLine); - } - } - - if (bIn) - { - bIn = false; - aNextText.push('~~~/blockquote~~~'); - } - - aText = aNextText; - } - while (bDo); - - sPlain = aText.join("\n"); - - sPlain = sPlain -// .replace(/~~~\/blockquote~~~\n~~~blockquote~~~/g, '\n') - .replace(/&/g, '&') - .replace(/>/g, '>').replace(/') - .replace(/[\s]*~~~\/blockquote~~~/g, '') - .replace(/\u200C([\s\S]*)\u200C/g, '\u0002$1\u0002') - .replace(/\n/g, '
]*><\/p>/gi, '') + .replace(/
]*>([\s\S\r\n\t]*)<\/pre>/gmi, convertPre)
+ .replace(/[\s]+/gm, ' ')
+ .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
+ .replace(/
]*>/gmi, '\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(/<\/div>/gi, '\n') + .replace(/ /gi, ' ') + .replace(/"/gi, '"') + .replace(/<[^>]*>/gm, '') + ; + + text = $div.html(text).text(); + + text = text + .replace(/\n[ \t]+/gm, '\n') + .replace(/[\n]{3,}/gm, '\n\n') + .replace(/>/gi, '>') + .replace(/</gi, '<') + .replace(/&/gi, '&') + ; + + text = splitPlainText(trim(text)); + + iPos = 0; + iLimit = 800; + + while (0 < iLimit) + { + iLimit--; + iP1 = text.indexOf('__bq__start__', iPos); + 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); + + iPos = 0; + } + else if (-1 < iP2 && iP2 < iP3) + { + iPos = iP2 - 1; + } + else + { + iPos = 0; + } + } + else + { + break; + } + } + + text = text + .replace(/__bq__start__/gm, '') + .replace(/__bq__end__/gm, '') + ; + + return text; +} + +/** + * @param {string} plain + * @param {boolean} findEmailAndLinksInText = false + * @return {string} + */ +export function plainToHtml(plain, findEmailAndLinksInText = false) +{ + plain = plain.toString().replace(/\r/g, ''); + + let + bIn = false, + bDo = true, + bStart = true, + aNextText = [], + sLine = '', + iIndex = 0, + aText = plain.split('\n') + ; + + do + { + bDo = false; + aNextText = []; + for (iIndex = 0; iIndex < aText.length; iIndex++) + { + sLine = aText[iIndex]; + bStart = '>' === sLine.substr(0, 1); + if (bStart && !bIn) + { + bDo = true; + bIn = true; + aNextText.push('~~~blockquote~~~'); + aNextText.push(sLine.substr(1)); + } + else if (!bStart && bIn) + { + if ('' !== sLine) + { + bIn = false; + aNextText.push('~~~/blockquote~~~'); + aNextText.push(sLine); + } + else + { + aNextText.push(sLine); + } + } + else if (bStart && bIn) + { + aNextText.push(sLine.substr(1)); + } + else + { + aNextText.push(sLine); + } + } + + if (bIn) + { + bIn = false; + aNextText.push('~~~/blockquote~~~'); + } + + aText = aNextText; + } + while (bDo); + + plain = aText.join('\n'); + + plain = plain +// .replace(/~~~\/blockquote~~~\n~~~blockquote~~~/g, '\n') + .replace(/&/g, '&') + .replace(/>/g, '>').replace(/') + .replace(/[\s]*~~~\/blockquote~~~/g, '') + .replace(/\u200C([\s\S]*)\u200C/g, '\u0002$1\u0002') + .replace(/\n/g, '