diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 86541a0ec..000000000 --- a/.babelrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - plugins: [] -} \ No newline at end of file diff --git a/dev/App/Abstract.js b/dev/App/Abstract.jsx similarity index 63% rename from dev/App/Abstract.js rename to dev/App/Abstract.jsx index 94b715986..69edd66b3 100644 --- a/dev/App/Abstract.js +++ b/dev/App/Abstract.jsx @@ -1,36 +1,27 @@ -(function () { +import {window, _, $, key} from 'common'; +import Globals from 'Common/Globals'; +import * as Enums from 'Common/Enums'; +import Utils from 'Common/Utils'; +import Links from 'Common/Links'; +import Events from 'Common/Events'; +import Translator from 'Common/Translator'; +import Settings from 'Storage/Settings'; - 'use strict'; +import {AbstractBoot} from 'Knoin/AbstractBoot'; - var - window = require('window'), - _ = require('_'), - $ = require('$'), - key = require('key'), - - Globals = require('Common/Globals'), - Enums = require('Common/Enums'), - Utils = require('Common/Utils'), - Links = require('Common/Links'), - Events = require('Common/Events'), - Translator = require('Common/Translator'), - - Settings = require('Storage/Settings'), - - AbstractBoot = require('Knoin/AbstractBoot') - ; +class AbstractApp extends AbstractBoot +{ + googlePreviewSupportedCache = null; + isLocalAutocomplete = true; + iframe = null; /** - * @constructor * @param {RemoteStorage|AdminRemoteStorage} Remote - * @extends AbstractBoot */ - function AbstractApp(Remote) + constructor(Remote) { - AbstractBoot.call(this); - - this.isLocalAutocomplete = true; + super(); this.iframe = $('').appendTo('body'); @@ -104,37 +95,28 @@ }, this)); } - _.extend(AbstractApp.prototype, AbstractBoot.prototype); - - AbstractApp.prototype.remote = function () - { + remote() { return null; - }; + } - AbstractApp.prototype.data = function () - { + data() { return null; - }; + } /** - * @param {string} sLink + * @param {string} link * @return {boolean} */ - AbstractApp.prototype.download = function (sLink) - { - var - oE = null, - oLink = null - ; + download(link) { if (Globals.sUserAgent && (Globals.sUserAgent.indexOf('chrome') > -1 || Globals.sUserAgent.indexOf('chrome') > -1)) { - oLink = window.document.createElement('a'); - oLink['href'] = sLink; + const oLink = window.document.createElement('a'); + oLink['href'] = link; if (window.document['createEvent']) { - oE = window.document['createEvent']('MouseEvents'); + const oE = window.document['createEvent']('MouseEvents'); if (oE && oE['initEvent'] && oLink['dispatchEvent']) { oE['initEvent']('click', true, true); @@ -146,25 +128,22 @@ if (Globals.bMobileDevice) { - window.open(sLink, '_self'); + window.open(link, '_self'); window.focus(); } else { - this.iframe.attr('src', sLink); - // window.document.location.href = sLink; + this.iframe.attr('src', link); + // window.document.location.href = link; } return true; - }; - - AbstractApp.prototype.googlePreviewSupportedCache = null; + } /** * @return {boolean} */ - AbstractApp.prototype.googlePreviewSupported = function () - { + googlePreviewSupported() { if (null === this.googlePreviewSupportedCache) { this.googlePreviewSupportedCache = !!Settings.settingsGet('AllowGoogleSocial') && @@ -172,90 +151,82 @@ } return this.googlePreviewSupportedCache; - }; + } /** - * @param {string} sTitle + * @param {string} title */ - AbstractApp.prototype.setWindowTitle = function (sTitle) - { - sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? '' + sTitle : ''); + setWindowTitle(title) { + title = ((Utils.isNormal(title) && 0 < title.length) ? '' + title : ''); if (Settings.settingsGet('Title')) { - sTitle += (sTitle ? ' - ' : '') + Settings.settingsGet('Title'); + title += (title ? ' - ' : '') + Settings.settingsGet('Title'); } - window.document.title = sTitle + ' ...'; - window.document.title = sTitle; - }; + window.document.title = title + ' ...'; + window.document.title = title; + } - AbstractApp.prototype.redirectToAdminPanel = function () - { - _.delay(function () { - window.location.href = Links.rootAdmin(); - }, 100); - }; + redirectToAdminPanel() { + _.delay(() => window.location.href = Links.rootAdmin(), 100); + } - AbstractApp.prototype.clearClientSideToken = function () - { + clearClientSideToken() { if (window.__rlah_clear) { window.__rlah_clear(); } - }; + } /** - * @param {string} sKey + * @param {string} key */ - AbstractApp.prototype.setClientSideToken = function (sKey) - { + setClientSideToken(key) { if (window.__rlah_set) { - window.__rlah_set(sKey); + window.__rlah_set(key); - require('Storage/Settings').settingsSet('AuthAccountHash', sKey); + require('Storage/Settings').settingsSet('AuthAccountHash', key); require('Common/Links').populateAuthSuffix(); } - }; + } /** - * @param {boolean=} bAdmin = false - * @param {boolean=} bLogout = false - * @param {boolean=} bClose = false + * @param {boolean=} admin = false + * @param {boolean=} logout = false + * @param {boolean=} close = false */ - AbstractApp.prototype.loginAndLogoutReload = function (bAdmin, bLogout, bClose) - { - var + loginAndLogoutReload(admin = false, logout = false, close = false) { + + const kn = require('Knoin/Knoin'), - sCustomLogoutLink = Utils.pString(Settings.settingsGet('CustomLogoutLink')), - bInIframe = !!Settings.settingsGet('InIframe') + inIframe = !!Settings.settingsGet('InIframe') ; - bLogout = Utils.isUnd(bLogout) ? false : !!bLogout; - bClose = Utils.isUnd(bClose) ? false : !!bClose; + let customLogoutLink = Utils.pString(Settings.settingsGet('CustomLogoutLink')) - if (bLogout) + if (logout) { this.clearClientSideToken(); } - if (bLogout && bClose && window.close) + if (logout && close && window.close) { window.close(); } - sCustomLogoutLink = sCustomLogoutLink || (bAdmin ? Links.rootAdmin() : Links.rootUser()); + customLogoutLink = customLogoutLink || (admin ? Links.rootAdmin() : Links.rootUser()); - if (bLogout && window.location.href !== sCustomLogoutLink) + if (logout && window.location.href !== customLogoutLink) { - _.delay(function () { - if (bInIframe && window.parent) + _.delay(() => { + if (inIframe && window.parent) { - window.parent.location.href = sCustomLogoutLink; + window.parent.location.href = customLogoutLink; } else { - window.location.href = sCustomLogoutLink; + window.location.href = customLogoutLink; } }, 100); } @@ -265,8 +236,8 @@ kn.setHash(Links.root(), true); kn.routeOff(); - _.delay(function () { - if (bInIframe && window.parent) + _.delay(() => { + if (inIframe && window.parent) { window.parent.location.reload(); } @@ -276,20 +247,19 @@ } }, 100); } - }; + } - AbstractApp.prototype.historyBack = function () - { + historyBack() { window.history.back(); - }; + } - AbstractApp.prototype.bootstart = function () - { - Utils.log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); + bootstart() { + + // Utils.log('Ps' + 'ss, hac' + 'kers! The' + 're\'s not' + 'hing inte' + 'resting :' + ')'); Events.pub('rl.bootstart'); - var + const ssm = require('ssm'), ko = require('ko') ; @@ -323,11 +293,11 @@ ssm.addState({ 'id': 'mobile', 'maxWidth': 767, - 'onEnter': function() { + 'onEnter': () => { Globals.$html.addClass('ssm-state-mobile'); Events.pub('ssm.mobile-enter'); }, - 'onLeave': function() { + 'onLeave': () => { Globals.$html.removeClass('ssm-state-mobile'); Events.pub('ssm.mobile-leave'); } @@ -349,10 +319,10 @@ 'id': 'desktop', 'minWidth': 1000, 'maxWidth': 1400, - 'onEnter': function() { + 'onEnter': () => { Globals.$html.addClass('ssm-state-desktop'); }, - 'onLeave': function() { + 'onLeave': () => { Globals.$html.removeClass('ssm-state-desktop'); } }); @@ -360,27 +330,27 @@ ssm.addState({ 'id': 'desktop-large', 'minWidth': 1400, - 'onEnter': function() { + 'onEnter': () => { Globals.$html.addClass('ssm-state-desktop-large'); }, - 'onLeave': function() { + 'onLeave': () => { Globals.$html.removeClass('ssm-state-desktop-large'); } }); - Events.sub('ssm.mobile-enter', function () { + Events.sub('ssm.mobile-enter', () => { Globals.leftPanelDisabled(true); }); - Events.sub('ssm.mobile-leave', function () { + Events.sub('ssm.mobile-leave', () => { Globals.leftPanelDisabled(false); }); - Globals.leftPanelDisabled.subscribe(function (bValue) { + Globals.leftPanelDisabled.subscribe((bValue) => { Globals.$html.toggleClass('rl-left-panel-disabled', bValue); }); - Globals.leftPanelType.subscribe(function (sValue) { + Globals.leftPanelType.subscribe((sValue) => { Globals.$html.toggleClass('rl-left-panel-none', 'none' === sValue); Globals.$html.toggleClass('rl-left-panel-short', 'short' === sValue); }); @@ -391,7 +361,6 @@ require('Stores/Theme').populate(); require('Stores/Social').populate(); }; +} - module.exports = AbstractApp; - -}()); \ No newline at end of file +export {AbstractApp, AbstractApp as default}; \ No newline at end of file diff --git a/dev/App/Admin.js b/dev/App/Admin.js deleted file mode 100644 index dfc4790d7..000000000 --- a/dev/App/Admin.js +++ /dev/null @@ -1,301 +0,0 @@ - -(function () { - - 'use strict'; - - var - window = require('window'), - _ = require('_'), - ko = require('ko'), - progressJs = require('progressJs'), - - Enums = require('Common/Enums'), - Utils = require('Common/Utils'), - Links = require('Common/Links'), - Translator = require('Common/Translator'), - - Settings = require('Storage/Settings'), - AppStore = require('Stores/Admin/App'), - DomainStore = require('Stores/Admin/Domain'), - PluginStore = require('Stores/Admin/Plugin'), - LicenseStore = require('Stores/Admin/License'), - PackageStore = require('Stores/Admin/Package'), - CoreStore = require('Stores/Admin/Core'), - Remote = require('Remote/Admin/Ajax'), - - kn = require('Knoin/Knoin'), - AbstractApp = require('App/Abstract') - ; - - /** - * @constructor - * @extends AbstractApp - */ - function AdminApp() - { - AbstractApp.call(this, Remote); - } - - _.extend(AdminApp.prototype, AbstractApp.prototype); - - AdminApp.prototype.remote = function () - { - return Remote; - }; - - AdminApp.prototype.reloadDomainList = function () - { - DomainStore.domains.loading(true); - - Remote.domainList(function (sResult, oData) { - DomainStore.domains.loading(false); - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) - { - var aList = _.map(oData.Result, function (bEnabled, sName) { - return { - 'name': sName, - 'disabled': ko.observable(!bEnabled), - 'deleteAccess': ko.observable(false) - }; - }, this); - - DomainStore.domains(aList); - } - }); - }; - - AdminApp.prototype.reloadPluginList = function () - { - PluginStore.plugins.loading(true); - - Remote.pluginList(function (sResult, oData) { - - PluginStore.plugins.loading(false); - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) - { - var aList = _.map(oData.Result, function (oItem) { - return { - 'name': oItem['Name'], - 'disabled': ko.observable(!oItem['Enabled']), - 'configured': ko.observable(!!oItem['Configured']) - }; - }, this); - - PluginStore.plugins(aList); - } - }); - }; - - AdminApp.prototype.reloadPackagesList = function () - { - PackageStore.packages.loading(true); - PackageStore.packagesReal(true); - - Remote.packagesList(function (sResult, oData) { - - PackageStore.packages.loading(false); - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) - { - PackageStore.packagesReal(!!oData.Result.Real); - PackageStore.packagesMainUpdatable(!!oData.Result.MainUpdatable); - - var - aList = [], - aLoading = {} - ; - - _.each(PackageStore.packages(), function (oItem) { - if (oItem && oItem['loading']()) - { - aLoading[oItem['file']] = oItem; - } - }); - - if (Utils.isArray(oData.Result.List)) - { - aList = _.compact(_.map(oData.Result.List, function (oItem) { - if (oItem) - { - oItem['loading'] = ko.observable(!Utils.isUnd(aLoading[oItem['file']])); - return 'core' === oItem['type'] && !oItem['canBeInstalled'] ? null : oItem; - } - return null; - })); - } - - PackageStore.packages(aList); - } - else - { - PackageStore.packagesReal(false); - } - }); - }; - - AdminApp.prototype.updateCoreData = function () - { - CoreStore.coreUpdating(true); - Remote.updateCoreData(function (sResult, oData) { - - CoreStore.coreUpdating(false); - CoreStore.coreVersion(''); - CoreStore.coreRemoteVersion(''); - CoreStore.coreRemoteRelease(''); - CoreStore.coreVersionCompare(-2); - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) - { - CoreStore.coreReal(true); - window.location.reload(); - } - else - { - CoreStore.coreReal(false); - } - }); - - }; - - AdminApp.prototype.reloadCoreData = function () - { - CoreStore.coreChecking(true); - CoreStore.coreReal(true); - - Remote.coreData(function (sResult, oData) { - - CoreStore.coreChecking(false); - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) - { - CoreStore.coreReal(!!oData.Result.Real); - CoreStore.coreChannel(oData.Result.Channel || 'stable'); - CoreStore.coreType(oData.Result.Type || 'stable'); - CoreStore.coreUpdatable(!!oData.Result.Updatable); - CoreStore.coreAccess(!!oData.Result.Access); - CoreStore.coreWarning(!!oData.Result.Warning); - CoreStore.coreVersion(oData.Result.Version || ''); - CoreStore.coreRemoteVersion(oData.Result.RemoteVersion || ''); - CoreStore.coreRemoteRelease(oData.Result.RemoteRelease || ''); - CoreStore.coreVersionCompare(Utils.pInt(oData.Result.VersionCompare)); - } - else - { - CoreStore.coreReal(false); - CoreStore.coreChannel('stable'); - CoreStore.coreType('stable'); - CoreStore.coreWarning(false); - CoreStore.coreVersion(''); - CoreStore.coreRemoteVersion(''); - CoreStore.coreRemoteRelease(''); - CoreStore.coreVersionCompare(-2); - } - }); - }; - - /** - * - * @param {boolean=} bForce = false - */ - AdminApp.prototype.reloadLicensing = function (bForce) - { - bForce = Utils.isUnd(bForce) ? false : !!bForce; - - LicenseStore.licensingProcess(true); - LicenseStore.licenseError(''); - - Remote.licensing(function (sResult, oData) { - - LicenseStore.licensingProcess(false); - - if (Enums.StorageResultType.Success === sResult && oData && oData.Result && Utils.isNormal(oData.Result['Expired'])) - { - LicenseStore.licenseValid(true); - LicenseStore.licenseExpired(Utils.pInt(oData.Result['Expired'])); - LicenseStore.licenseError(''); - - LicenseStore.licensing(true); - - AppStore.prem(true); - } - else - { - if (oData && oData.ErrorCode && -1 < Utils.inArray(Utils.pInt(oData.ErrorCode), [ - Enums.Notification.LicensingServerIsUnavailable, - Enums.Notification.LicensingExpired - ])) - { - LicenseStore.licenseError(Translator.getNotification(Utils.pInt(oData.ErrorCode))); - LicenseStore.licensing(true); - } - else - { - if (Enums.StorageResultType.Abort === sResult) - { - LicenseStore.licenseError(Translator.getNotification(Enums.Notification.LicensingServerIsUnavailable)); - LicenseStore.licensing(true); - } - else - { - LicenseStore.licensing(false); - } - } - } - }, bForce); - }; - - AdminApp.prototype.bootend = function (callback) - { - if (progressJs) - { - progressJs.end(); - } - - if (callback) - { - callback(); - } - }; - - AdminApp.prototype.bootstart = function () - { - AbstractApp.prototype.bootstart.call(this); - - require('Stores/Admin/App').populate(); - require('Stores/Admin/Capa').populate(); - - kn.hideLoading(); - - if (!Settings.settingsGet('AllowAdminPanel')) - { - kn.routeOff(); - kn.setHash(Links.root(), true); - kn.routeOff(); - - _.defer(function () { - window.location.href = '/'; - }); - } - else - { - if (!!Settings.settingsGet('Auth')) - { - kn.startScreens([ - require('Screen/Admin/Settings') - ]); - } - else - { - kn.startScreens([ - require('Screen/Admin/Login') - ]); - } - } - - this.bootend(); - }; - - module.exports = new AdminApp(); - -}()); \ No newline at end of file diff --git a/dev/App/Admin.jsx b/dev/App/Admin.jsx new file mode 100644 index 000000000..47ab2e34c --- /dev/null +++ b/dev/App/Admin.jsx @@ -0,0 +1,259 @@ + +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 Settings from 'Storage/Settings'; + +import AppStore from 'Stores/Admin/App'; +import DomainStore from 'Stores/Admin/Domain'; +import PluginStore from 'Stores/Admin/Plugin'; +import LicenseStore from 'Stores/Admin/License'; +import PackageStore from 'Stores/Admin/Package'; +import CoreStore from 'Stores/Admin/Core'; +import Remote from 'Remote/Admin/Ajax'; + +import kn from 'Knoin/Knoin'; + +import {AbstractApp} from 'App/Abstract'; + +class AdminApp extends AbstractApp +{ + constructor() + { + super(Remote); + } + + remote() { + return Remote; + } + + reloadDomainList() { + DomainStore.domains.loading(true); + Remote.domainList((result, data) => { + DomainStore.domains.loading(false); + if (Enums.StorageResultType.Success === result && data && data.Result) + { + DomainStore.domains(_.map(data.Result, (enabled, name) => { + return { + 'name': name, + 'disabled': ko.observable(!enabled), + 'deleteAccess': ko.observable(false) + }; + })); + } + }); + } + + reloadPluginList() { + PluginStore.plugins.loading(true); + Remote.pluginList((result, data) => { + PluginStore.plugins.loading(false); + if (Enums.StorageResultType.Success === result && data && data.Result) + { + PluginStore.plugins(_.map(data.Result, (item) => { + return { + 'name': item['Name'], + 'disabled': ko.observable(!item['Enabled']), + 'configured': ko.observable(!!item['Configured']) + }; + })); + } + }); + } + + reloadPackagesList() { + PackageStore.packages.loading(true); + PackageStore.packagesReal(true); + Remote.packagesList((result, data) => { + PackageStore.packages.loading(false); + if (Enums.StorageResultType.Success === result && data && data.Result) + { + PackageStore.packagesReal(!!data.Result.Real); + PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable); + + let + list = [], + loading = {} + ; + + _.each(PackageStore.packages(), (item) => { + if (item && item['loading']()) + { + loading[item['file']] = item; + } + }); + + if (Utils.isArray(data.Result.List)) + { + list = _.compact(_.map(data.Result.List, (item) => { + if (item) + { + item['loading'] = ko.observable(!Utils.isUnd(loading[item['file']])); + return 'core' === item['type'] && !item['canBeInstalled'] ? null : item; + } + return null; + })); + } + + PackageStore.packages(list); + } + else + { + PackageStore.packagesReal(false); + } + }); + } + + updateCoreData() { + CoreStore.coreUpdating(true); + Remote.updateCoreData((result, data) => { + CoreStore.coreUpdating(false); + CoreStore.coreVersion(''); + CoreStore.coreRemoteVersion(''); + CoreStore.coreRemoteRelease(''); + CoreStore.coreVersionCompare(-2); + if (Enums.StorageResultType.Success === result && data && data.Result) + { + CoreStore.coreReal(true); + window.location.reload(); + } + else + { + CoreStore.coreReal(false); + } + }); + } + + reloadCoreData() { + CoreStore.coreChecking(true); + CoreStore.coreReal(true); + Remote.coreData((result, data) => { + CoreStore.coreChecking(false); + if (Enums.StorageResultType.Success === result && data && data.Result) + { + CoreStore.coreReal(!!data.Result.Real); + CoreStore.coreChannel(data.Result.Channel || 'stable'); + CoreStore.coreType(data.Result.Type || 'stable'); + CoreStore.coreUpdatable(!!data.Result.Updatable); + CoreStore.coreAccess(!!data.Result.Access); + CoreStore.coreWarning(!!data.Result.Warning); + CoreStore.coreVersion(data.Result.Version || ''); + CoreStore.coreRemoteVersion(data.Result.RemoteVersion || ''); + CoreStore.coreRemoteRelease(data.Result.RemoteRelease || ''); + CoreStore.coreVersionCompare(Utils.pInt(data.Result.VersionCompare)); + } + else + { + CoreStore.coreReal(false); + CoreStore.coreChannel('stable'); + CoreStore.coreType('stable'); + CoreStore.coreWarning(false); + CoreStore.coreVersion(''); + CoreStore.coreRemoteVersion(''); + CoreStore.coreRemoteRelease(''); + CoreStore.coreVersionCompare(-2); + } + }); + } + + /** + * @param {boolean=} force = false + */ + reloadLicensing(force = false) { + LicenseStore.licensingProcess(true); + LicenseStore.licenseError(''); + Remote.licensing((result, data) => { + LicenseStore.licensingProcess(false); + if (Enums.StorageResultType.Success === result && data && data.Result && Utils.isNormal(data.Result['Expired'])) + { + LicenseStore.licenseValid(true); + LicenseStore.licenseExpired(Utils.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 + ])) + { + LicenseStore.licenseError(Translator.getNotification(Utils.pInt(data.ErrorCode))); + LicenseStore.licensing(true); + } + else + { + if (Enums.StorageResultType.Abort === result) + { + LicenseStore.licenseError(Translator.getNotification(Enums.Notification.LicensingServerIsUnavailable)); + LicenseStore.licensing(true); + } + else + { + LicenseStore.licensing(false); + } + } + } + }, force); + } + + bootend(callback = null) { + if (progressJs) + { + progressJs.end(); + } + + if (callback) + { + callback(); + } + } + + bootstart() { + + super.bootstart(); + + require('Stores/Admin/App').populate(); + require('Stores/Admin/Capa').populate(); + + kn.hideLoading(); + + if (!Settings.settingsGet('AllowAdminPanel')) + { + kn.routeOff(); + kn.setHash(Links.root(), true); + kn.routeOff(); + + _.defer(() => { + window.location.href = '/'; + }); + } + else + { + if (!!Settings.settingsGet('Auth')) + { + kn.startScreens([ + require('Screen/Admin/Settings') + ]); + } + else + { + kn.startScreens([ + require('Screen/Admin/Login') + ]); + } + } + + this.bootend(); + } +} + +const App = new AdminApp(); +export default App; diff --git a/dev/App/User.js b/dev/App/User.jsx similarity index 59% rename from dev/App/User.js rename to dev/App/User.jsx index 9fce378b7..20e453a58 100644 --- a/dev/App/User.js +++ b/dev/App/User.jsx @@ -1,123 +1,75 @@ -(function () { +import {window, _, $} from 'common'; +import ko from 'ko'; +import progressJs from 'progressJs'; +import Tinycon from 'Tinycon'; - 'use strict'; +import * as Enums from 'Common/Enums'; +import * as Consts from 'Common/Consts'; +import Globals from 'Common/Globals'; +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'; +import Momentor from 'Common/Momentor'; +import Cache from 'Common/Cache'; - var - window = require('window'), - _ = require('_'), - $ = require('$'), - progressJs = require('progressJs'), - Tinycon = require('Tinycon'), - Enums = require('Common/Enums'), - Globals = require('Common/Globals'), - Consts = require('Common/Consts'), - Plugins = require('Common/Plugins'), - Utils = require('Common/Utils'), - Links = require('Common/Links'), - Events = require('Common/Events'), +import SocialStore from 'Stores/Social'; +import SettingsStore from 'Stores/User/Settings'; +import AccountStore from 'Stores/User/Account'; +import IdentityStore from 'Stores/User/Identity'; +import TemplateStore from 'Stores/User/Template'; +import FolderStore from 'Stores/User/Folder'; +import PgpStore from 'Stores/User/Pgp'; +import MessageStore from 'Stores/User/Message'; +import ContactStore from 'Stores/User/Contact'; - Translator = require('Common/Translator'), - Momentor = require('Common/Momentor'), +import Local from 'Storage/Client.jsx'; +import Settings from 'Storage/Settings'; - kn = require('Knoin/Knoin'), +import Remote from 'Remote/User/Ajax'; +import Promises from 'Promises/User/Ajax'; - Cache = require('Common/Cache'), +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'; - SocialStore = require('Stores/Social'), - SettingsStore = require('Stores/User/Settings'), - AccountStore = require('Stores/User/Account'), - IdentityStore = require('Stores/User/Identity'), - TemplateStore = require('Stores/User/Template'), - FolderStore = require('Stores/User/Folder'), - PgpStore = require('Stores/User/Pgp'), - MessageStore = require('Stores/User/Message'), - ContactStore = require('Stores/User/Contact'), +import kn from 'Knoin/Knoin'; - Local = require('Storage/Client.jsx'), - Settings = require('Storage/Settings'), +import {AbstractApp} from 'App/Abstract'; - Remote = require('Remote/User/Ajax'), - Promises = require('Promises/User/Ajax'), +class AppUser extends AbstractApp +{ + oMoveCache = {}; - EmailModel = require('Model/Email'), - AccountModel = require('Model/Account'), - IdentityModel = require('Model/Identity'), - TemplateModel = require('Model/Template'), - OpenPgpKeyModel = require('Model/OpenPgpKey'), - - AbstractApp = require('App/Abstract') - ; - - /** - * @constructor - * @extends AbstractApp - */ - function AppUser() + constructor() { - AbstractApp.call(this, Remote); - - this.oMoveCache = {}; + super(Remote); this.quotaDebounce = _.debounce(this.quota, 1000 * 30); this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this); this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500); - window.setInterval(function () { - Events.pub('interval.30s'); - }, 30000); + window.setInterval(() => Events.pub('interval.30s'), 30000); + window.setInterval(() => Events.pub('interval.1m'), 60000); + window.setInterval(() => Events.pub('interval.2m'), 60000 * 2); + window.setInterval(() => Events.pub('interval.3m'), 60000 * 3); + window.setInterval(() => Events.pub('interval.5m'), 60000 * 5); + window.setInterval(() => Events.pub('interval.10m'), 60000 * 10); + window.setInterval(() => Events.pub('interval.15m'), 60000 * 15); + window.setInterval(() => Events.pub('interval.20m'), 60000 * 15); - window.setInterval(function () { - Events.pub('interval.1m'); - }, 60000); + window.setTimeout(() => window.setInterval(() => Events.pub('interval.2m-after5m'), 60000 * 2), 60000 * 5); + window.setTimeout(() => window.setInterval(() => Events.pub('interval.5m-after5m'), 60000 * 5), 60000 * 5); + window.setTimeout(() => window.setInterval(() => Events.pub('interval.10m-after5m'), 60000 * 10), 60000 * 5); - window.setInterval(function () { - Events.pub('interval.2m'); - }, 60000 * 2); - - window.setInterval(function () { - Events.pub('interval.3m'); - }, 60000 * 3); - - window.setInterval(function () { - Events.pub('interval.5m'); - }, 60000 * 5); - - window.setInterval(function () { - Events.pub('interval.10m'); - }, 60000 * 10); - - window.setInterval(function () { - Events.pub('interval.15m'); - }, 60000 * 15); - - window.setInterval(function () { - Events.pub('interval.20m'); - }, 60000 * 15); - - window.setTimeout(function () { - window.setInterval(function () { - Events.pub('interval.2m-after5m'); - }, 60000 * 2); - }, 60000 * 5); - - window.setTimeout(function () { - window.setInterval(function () { - Events.pub('interval.5m-after5m'); - }, 60000 * 5); - }, 60000 * 5); - - window.setTimeout(function () { - window.setInterval(function () { - Events.pub('interval.10m-after5m'); - }, 60000 * 10); - }, 60000 * 5); - - $.wakeUp(function () { - - Remote.jsVersion(function (sResult, oData) { + $.wakeUp(() => { + Remote.jsVersion((sResult, oData) => { if (Enums.StorageResultType.Success === sResult && oData && !oData.Result) { if (window.parent && !!Settings.settingsGet('InIframe')) @@ -130,12 +82,11 @@ } } }, Settings.settingsGet('Version')); - }, {}, 60 * 60 * 1000); if (Settings.settingsGet('UserBackgroundHash')) { - _.delay(function () { + _.delay(() => { $('#rl-bg').attr('style', 'background-image: none !important;') .backstretch(Links.userBackground(Settings.settingsGet('UserBackgroundHash')), { 'fade': Globals.bAnimationSupported ? 1000 : 0, 'centeredX': true, 'centeredY': true @@ -146,38 +97,33 @@ this.socialUsers = _.bind(this.socialUsers, this); } - _.extend(AppUser.prototype, AbstractApp.prototype); - - AppUser.prototype.remote = function () - { + remote() { return Remote; - }; + } - AppUser.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function () - { - _.each(MessageStore.messageList(), function (oMessage) { - Cache.initMessageFlagsFromCache(oMessage); + reloadFlagsCurrentMessageListAndMessageFromCache() { + _.each(MessageStore.messageList(), (message) => { + Cache.initMessageFlagsFromCache(message); }); - Cache.initMessageFlagsFromCache(MessageStore.message()); - }; + } /** * @param {boolean=} bDropPagePosition = false * @param {boolean=} bDropCurrenFolderCache = false */ - AppUser.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache) - { - var + reloadMessageList(bDropPagePosition = false, bDropCurrenFolderCache = false) { + + let iOffset = (MessageStore.messageListPage() - 1) * SettingsStore.messagesPerPage() ; - if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache) + if (bDropCurrenFolderCache) { Cache.setFolderHash(FolderStore.currentFolderFullNameRaw(), ''); } - if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition) + if (bDropPagePosition) { MessageStore.messageListPage(1); MessageStore.messageListPageBeforeThread(1); @@ -192,7 +138,7 @@ } MessageStore.messageListLoading(true); - Remote.messageList(function (sResult, oData, bCached) { + Remote.messageList((sResult, oData, bCached) => { if (Enums.StorageResultType.Success === sResult && oData && oData.Result) { @@ -217,20 +163,19 @@ }, FolderStore.currentFolderFullNameRaw(), iOffset, SettingsStore.messagesPerPage(), MessageStore.messageListSearch(), MessageStore.messageListThreadUid()); - }; + } - AppUser.prototype.recacheInboxMessageList = function () - { + recacheInboxMessageList() { Remote.messageList(Utils.emptyFunction, Cache.getFolderInboxName(), 0, SettingsStore.messagesPerPage(), '', '', true); - }; + } /** * @param {Function} fResultFunc * @return {boolean} */ - AppUser.prototype.contactsSync = function (fResultFunc) - { - var oContacts = ContactStore.contacts; + contactsSync(fResultFunc) { + + const oContacts = ContactStore.contacts; if (oContacts.importing() || oContacts.syncing() || !ContactStore.enableContactsSync() || !ContactStore.allowContactsSync()) { return false; @@ -238,7 +183,7 @@ oContacts.syncing(true); - Remote.contactsSync(function (sResult, oData) { + Remote.contactsSync((sResult, oData) => { oContacts.syncing(false); @@ -249,17 +194,16 @@ }); return true; - }; + } - AppUser.prototype.messagesMoveTrigger = function () - { - var - self = this, + messagesMoveTrigger() { + + const sTrashFolder = FolderStore.trashFolder(), sSpamFolder = FolderStore.spamFolder() ; - _.each(this.oMoveCache, function (oItem) { + _.each(this.oMoveCache, (oItem) => { var bSpam = sSpamFolder === oItem['To'], @@ -267,15 +211,15 @@ bHam = !bSpam && sSpamFolder === oItem['From'] && Cache.getFolderInboxName() === oItem['To'] ; - Remote.messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'], + Remote.messagesMove(this.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'], bSpam ? 'SPAM' : (bHam ? 'HAM' : ''), bSpam || bTrash); }); this.oMoveCache = {}; - }; + } + + messagesMoveHelper(sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove) { - AppUser.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove) - { var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$'; if (!this.oMoveCache[sH]) { @@ -288,29 +232,27 @@ this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove); this.messagesMoveTrigger(); - }; + } - AppUser.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy) - { + messagesCopyHelper(sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy) { Remote.messagesCopy( this.moveOrDeleteResponseHelper, sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy ); - }; + } - AppUser.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove) - { + messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove) { Remote.messagesDelete( this.moveOrDeleteResponseHelper, sFromFolderFullNameRaw, aUidForRemove ); - }; + } + + moveOrDeleteResponseHelper(sResult, oData) { - AppUser.prototype.moveOrDeleteResponseHelper = function (sResult, oData) - { if (Enums.StorageResultType.Success === sResult && FolderStore.currentFolder()) { if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length) @@ -331,17 +273,16 @@ this.reloadMessageList(0 === MessageStore.messageList().length); this.quotaDebounce(); } - }; + } /** * @param {string} sFromFolderFullNameRaw * @param {Array} aUidForRemove */ - AppUser.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove) - { + deleteMessagesFromFolderWithoutCheck(sFromFolderFullNameRaw, aUidForRemove) { this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove); - }; + } /** * @param {number} iDeleteType @@ -349,10 +290,9 @@ * @param {Array} aUidForRemove * @param {boolean=} bUseFolder = true */ - AppUser.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder) - { - var - self = this, + deleteMessagesFromFolder(iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder) { + + let oMoveFolder = null, nSetSystemFoldersNotification = null ; @@ -394,11 +334,9 @@ else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType && (sFromFolderFullNameRaw === FolderStore.spamFolder() || sFromFolderFullNameRaw === FolderStore.trashFolder()))) { - kn.showScreenPopup(require('View/Popup/Ask'), [Translator.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () { - - self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); + kn.showScreenPopup(require('View/Popup/Ask'), [Translator.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), () => { + this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove); MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove); - }]); } else if (oMoveFolder) @@ -406,7 +344,7 @@ this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove); MessageStore.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw); } - }; + } /** * @param {string} sFromFolderFullNameRaw @@ -414,11 +352,11 @@ * @param {string} sToFolderFullNameRaw * @param {boolean=} bCopy = false */ - AppUser.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy) - { + moveMessagesToFolder(sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy) { + if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length) { - var + const oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw), oToFolder = Cache.getFolderFromCacheList(sToFolderFullNameRaw) ; @@ -440,44 +378,42 @@ } return false; - }; + } /** - * @param {Function=} fCallback + * @param {Function=} callback = null */ - AppUser.prototype.foldersReload = function (fCallback) - { - Promises.foldersReload(FolderStore.foldersLoading).then(function (bValue) { - if (fCallback) + foldersReload(callback = null) { + + Promises.foldersReload(FolderStore.foldersLoading).then((value) => { + if (callback) { - fCallback(!!bValue); + callback(!!value); } - }).fail(function () { - if (fCallback) + }).fail(() => { + if (callback) { - fCallback(false); + callback(false); } }); - }; + } + + foldersPromisesActionHelper(promise, errorDefCode) { - AppUser.prototype.foldersPromisesActionHelper = function (oPromise, iErrorDefCode) - { Promises .abort('Folders') .fastResolve(true) - .then(function () { - return oPromise; - }) - .fail(function (iErrorCode) { - FolderStore.folderList.error(Translator.getNotification(iErrorCode, '', iErrorDefCode)); - }).fin(function () { + .then(() => promise) + .fail((errorCode) => { + FolderStore.folderList.error(Translator.getNotification(errorCode, '', errorDefCode)); + }).fin(() => { Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); }).done() ; - }; + } + + reloadOpenPgpKeys() { - AppUser.prototype.reloadOpenPgpKeys = function () - { if (PgpStore.capaOpenPGP()) { var @@ -487,7 +423,7 @@ oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : [] ; - _.each(oOpenpgpKeys, function (oItem, iIndex) { + _.each(oOpenpgpKeys, (oItem, iIndex) => { if (oItem && oItem.primaryKey) { var @@ -518,14 +454,13 @@ Utils.delegateRunOnDestroy(PgpStore.openpgpkeys()); PgpStore.openpgpkeys(aKeys); } - }; + } - AppUser.prototype.accountsCounts = function () - { + accountsCounts() { return false; // AccountStore.accounts.loading(true); // -// Remote.accountsCounts(function (sResult, oData) { +// Remote.accountsCounts((sResult, oData) => { // // AccountStore.accounts.loading(false); // @@ -536,9 +471,9 @@ // aAcounts = AccountStore.accounts() // ; // -// _.each(oData.Result['Counts'], function (oItem) { +// _.each(oData.Result['Counts'], (oItem) => { // -// var oAccount = _.find(aAcounts, function (oAccount) { +// var oAccount = _.find(aAcounts, (oAccount) => { // return oAccount && oItem[0] === oAccount.email && sEmail !== oAccount.email; // }); // @@ -551,14 +486,12 @@ // }); }; - AppUser.prototype.accountsAndIdentities = function (bBoot) - { - var self = this; + accountsAndIdentities(bBoot) { AccountStore.accounts.loading(true); IdentityStore.identities.loading(true); - Remote.accountsAndIdentities(function (sResult, oData) { + Remote.accountsAndIdentities((sResult, oData) => { AccountStore.accounts.loading(false); IdentityStore.identities.loading(false); @@ -575,35 +508,29 @@ if (Utils.isArray(oData.Result['Accounts'])) { - _.each(AccountStore.accounts(), function (oAccount) { + _.each(AccountStore.accounts(), (oAccount) => { aCounts[oAccount.email] = oAccount.count(); }); Utils.delegateRunOnDestroy(AccountStore.accounts()); - AccountStore.accounts(_.map(oData.Result['Accounts'], function (sValue) { - return new AccountModel(sValue, sValue !== sParentEmail, aCounts[sValue] || 0); - })); + AccountStore.accounts(_.map(oData.Result['Accounts'], + (sValue) => new AccountModel(sValue, sValue !== sParentEmail, aCounts[sValue] || 0))); } if (Utils.isUnd(bBoot) ? false : !!bBoot) { - _.delay(function () { - self.accountsCounts(); - }, 1000 * 5); - - Events.sub('interval.10m-after5m', function () { - self.accountsCounts(); - }); + _.delay(() => this.accountsCounts(), 1000 * 5); + Events.sub('interval.10m-after5m', () => this.accountsCounts()); } if (Utils.isArray(oData.Result['Identities'])) { Utils.delegateRunOnDestroy(IdentityStore.identities()); - IdentityStore.identities(_.map(oData.Result['Identities'], function (oIdentityData) { + IdentityStore.identities(_.map(oData.Result['Identities'], (oIdentityData) => { - var + const sId = Utils.pString(oIdentityData['Id']), sEmail = Utils.pString(oIdentityData['Email']), oIdentity = new IdentityModel(sId, sEmail) @@ -620,171 +547,159 @@ } } }); - }; + } + + templates() { - AppUser.prototype.templates = function () - { TemplateStore.templates.loading(true); - Remote.templates(function (sResult, oData) { + Remote.templates((result, data) => { TemplateStore.templates.loading(false); - if (Enums.StorageResultType.Success === sResult && oData.Result && - Utils.isArray(oData.Result['Templates'])) + if (Enums.StorageResultType.Success === result && data.Result && + Utils.isArray(data.Result['Templates'])) { Utils.delegateRunOnDestroy(TemplateStore.templates()); - TemplateStore.templates(_.compact(_.map(oData.Result['Templates'], function (oTemplateData) { - var oTemplate = new TemplateModel(); - return oTemplate.parse(oTemplateData) ? oTemplate : null; + TemplateStore.templates(_.compact(_.map(data.Result['Templates'], (templateData) => { + const template = new TemplateModel(); + return template.parse(templateData) ? template : null; }))); } }); - }; + } - AppUser.prototype.quota = function () - { - Remote.quota(function (sResult, oData) { - if (Enums.StorageResultType.Success === sResult && oData && oData.Result && - Utils.isArray(oData.Result) && 1 < oData.Result.length && - Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true)) + 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)) { require('Stores/User/Quota').populateData( - Utils.pInt(oData.Result[1]), Utils.pInt(oData.Result[0])); + Utils.pInt(data.Result[1]), Utils.pInt(data.Result[0])); } }); - }; + } /** - * @param {string} sFolder - * @param {Array=} aList = [] + * @param {string} folder + * @param {Array=} list = [] */ - AppUser.prototype.folderInformation = function (sFolder, aList) - { - if ('' !== Utils.trim(sFolder)) + folderInformation(folder, list) { + if ('' !== Utils.trim(folder)) { - var self = this; - Remote.folderInformation(function (sResult, oData) { - if (Enums.StorageResultType.Success === sResult) + Remote.folderInformation((result, data) => { + if (Enums.StorageResultType.Success === result) { - if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder) + if (data && data.Result && data.Result.Hash && data.Result.Folder) { - var - iUtc = Momentor.momentNowUnix(), - sHash = Cache.getFolderHash(oData.Result.Folder), - oFolder = Cache.getFolderFromCacheList(oData.Result.Folder), - bCheck = false, - sUid = '', - aList = [], - oFlags = null, - bUnreadCountChange = false + let + uid = '', + list = [], + check = false, + unreadCountChange = false ; - if (oFolder) + const folder = Cache.getFolderFromCacheList(data.Result.Folder); + if (folder) { - oFolder.interval = iUtc; + folder.interval = Momentor.momentNowUnix(); - if (oData.Result.Hash) + if (data.Result.Hash) { - Cache.setFolderHash(oData.Result.Folder, oData.Result.Hash); + Cache.setFolderHash(data.Result.Folder, data.Result.Hash); } - if (Utils.isNormal(oData.Result.MessageCount)) + if (Utils.isNormal(data.Result.MessageCount)) { - oFolder.messageCountAll(oData.Result.MessageCount); + folder.messageCountAll(data.Result.MessageCount); } - if (Utils.isNormal(oData.Result.MessageUnseenCount)) + if (Utils.isNormal(data.Result.MessageUnseenCount)) { - if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount)) + if (Utils.pInt(folder.messageCountUnread()) !== Utils.pInt(data.Result.MessageUnseenCount)) { - bUnreadCountChange = true; + unreadCountChange = true; } - oFolder.messageCountUnread(oData.Result.MessageUnseenCount); + folder.messageCountUnread(data.Result.MessageUnseenCount); } - if (bUnreadCountChange) + if (unreadCountChange) { - Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw); + Cache.clearMessageFlagsFromCacheByFolder(folder.fullNameRaw); } - if (oData.Result.Flags) + if (data.Result.Flags) { - for (sUid in oData.Result.Flags) + for (uid in data.Result.Flags) { - if (oData.Result.Flags.hasOwnProperty(sUid)) + if (data.Result.Flags.hasOwnProperty(uid)) { - bCheck = true; - oFlags = oData.Result.Flags[sUid]; - Cache.storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [ - !oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt'] + check = true; + const flags = data.Result.Flags[uid]; + Cache.storeMessageFlagsToCacheByFolderAndUid(folder.fullNameRaw, uid.toString(), [ + !flags['IsSeen'], !!flags['IsFlagged'], !!flags['IsAnswered'], !!flags['IsForwarded'], !!flags['IsReadReceipt'] ]); } } - if (bCheck) + if (check) { - self.reloadFlagsCurrentMessageListAndMessageFromCache(); + this.reloadFlagsCurrentMessageListAndMessageFromCache(); } } - MessageStore.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages); + MessageStore.initUidNextAndNewMessages(folder.fullNameRaw, data.Result.UidNext, data.Result.NewMessages); - if (oData.Result.Hash !== sHash || '' === sHash) + const hash = Cache.getFolderHash(data.Result.Folder); + if (data.Result.Hash !== hash || '' === hash) { - if (oFolder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) + if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { - self.reloadMessageList(); + this.reloadMessageList(); } - else if (Cache.getFolderInboxName() === oFolder.fullNameRaw) + else if (Cache.getFolderInboxName() === folder.fullNameRaw) { - self.recacheInboxMessageList(); + this.recacheInboxMessageList(); } } - else if (bUnreadCountChange) + else if (unreadCountChange) { - if (oFolder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) + if (folder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { - aList = MessageStore.messageList(); - if (Utils.isNonEmptyArray(aList)) + list = MessageStore.messageList(); + if (Utils.isNonEmptyArray(list)) { - self.folderInformation(oFolder.fullNameRaw, aList); + this.folderInformation(folder.fullNameRaw, list); } } } } } } - }, sFolder, aList); + }, folder, list); } }; /** - * @param {boolean=} bBoot = false + * @param {boolean=} boot = false */ - AppUser.prototype.folderInformationMultiply = function (bBoot) - { - bBoot = Utils.isUnd(bBoot) ? false : !!bBoot; + folderInformationMultiply(boot = false) { - var - self = this, - iUtc = Momentor.momentNowUnix(), - aFolders = FolderStore.getNextFolderNames() - ; - - if (Utils.isNonEmptyArray(aFolders)) + const folders = FolderStore.getNextFolderNames(); + if (Utils.isNonEmptyArray(folders)) { - Remote.folderInformationMultiply(function (sResult, oData) { + Remote.folderInformationMultiply((sResult, oData) => { if (Enums.StorageResultType.Success === sResult) { if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List)) { - _.each(oData.Result.List, function (oItem) { + const utc = Momentor.momentNowUnix(); + _.each(oData.Result.List, (oItem) => { var - aList = [], sHash = Cache.getFolderHash(oItem.Folder), oFolder = Cache.getFolderFromCacheList(oItem.Folder), bUnreadCountChange = false @@ -792,7 +707,7 @@ if (oFolder) { - oFolder.interval = iUtc; + oFolder.interval = utc; if (oItem.Hash) { @@ -823,32 +738,30 @@ { if (oFolder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { - self.reloadMessageList(); + this.reloadMessageList(); } } else if (bUnreadCountChange) { if (oFolder.fullNameRaw === FolderStore.currentFolderFullNameRaw()) { - aList = MessageStore.messageList(); + const aList = MessageStore.messageList(); if (Utils.isNonEmptyArray(aList)) { - self.folderInformation(oFolder.fullNameRaw, aList); + this.folderInformation(oFolder.fullNameRaw, aList); } } } } }); - if (bBoot) + if (boot) { - _.delay(function () { - self.folderInformationMultiply(true); - }, 2000); + _.delay(() => this.folderInformationMultiply(true), 2000); } } } - }, aFolders); + }, folders); } }; @@ -858,8 +771,8 @@ * @param {number} iSetAction * @param {Array=} aMessages = null */ - AppUser.prototype.messageListAction = function (sFolderFullNameRaw, mUid, iSetAction, aMessages) - { + messageListAction(sFolderFullNameRaw, mUid, iSetAction, aMessages) { + var oFolder = null, aRootUids = [], @@ -871,16 +784,14 @@ aMessages = MessageStore.messageListChecked(); } - aRootUids = _.uniq(_.compact(_.map(aMessages, function (oMessage) { - return (oMessage && oMessage.uid) ? oMessage.uid : null; - }))); + aRootUids = _.uniq(_.compact(_.map(aMessages, (oMessage) => (oMessage && oMessage.uid) ? oMessage.uid : null))); if ('' !== sFolderFullNameRaw && 0 < aRootUids.length) { switch (iSetAction) { case Enums.MessageSetAction.SetSeen: - _.each(aRootUids, function (sSubUid) { + _.each(aRootUids, (sSubUid) => { iAlreadyUnread += Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -896,7 +807,7 @@ case Enums.MessageSetAction.UnsetSeen: - _.each(aRootUids, function (sSubUid) { + _.each(aRootUids, (sSubUid) => { iAlreadyUnread += Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -912,7 +823,7 @@ case Enums.MessageSetAction.SetFlag: - _.each(aRootUids, function (sSubUid) { + _.each(aRootUids, (sSubUid) => { Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -922,7 +833,7 @@ case Enums.MessageSetAction.UnsetFlag: - _.each(aRootUids, function (sSubUid) { + _.each(aRootUids, (sSubUid) => { Cache.storeMessageFlagsToCacheBySetAction( sFolderFullNameRaw, sSubUid, iSetAction); }); @@ -934,42 +845,38 @@ this.reloadFlagsCurrentMessageListAndMessageFromCache(); MessageStore.message.viewTrigger(!MessageStore.message.viewTrigger()); } - }; + } - AppUser.prototype.googleConnect = function () - { + googleConnect() { window.open(Links.socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes'); - }; + } - AppUser.prototype.twitterConnect = function () - { + twitterConnect() { window.open(Links.socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes'); - }; + } - AppUser.prototype.facebookConnect = function () - { + facebookConnect() { window.open(Links.socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); - }; + } /** - * @param {boolean=} bFireAllActions + * @param {boolean=} fireAllActions = false */ - AppUser.prototype.socialUsers = function (bFireAllActions) - { - if (true === bFireAllActions) + socialUsers(fireAllActions = false) { + if (true === fireAllActions) { SocialStore.google.loading(true); SocialStore.facebook.loading(true); SocialStore.twitter.loading(true); } - Remote.socialUsers(function (sResult, oData) { + Remote.socialUsers((result, data) => { - if (Enums.StorageResultType.Success === sResult && oData && oData.Result) + if (Enums.StorageResultType.Success === result && data && data.Result) { - SocialStore.google.userName(oData.Result['Google'] || ''); - SocialStore.facebook.userName(oData.Result['Facebook'] || ''); - SocialStore.twitter.userName(oData.Result['Twitter'] || ''); + SocialStore.google.userName(data.Result['Google'] || ''); + SocialStore.facebook.userName(data.Result['Facebook'] || ''); + SocialStore.twitter.userName(data.Result['Twitter'] || ''); } else { @@ -982,60 +889,47 @@ SocialStore.facebook.loading(false); SocialStore.twitter.loading(false); }); - }; + } - AppUser.prototype.googleDisconnect = function () - { + googleDisconnect() { SocialStore.google.loading(true); Remote.googleDisconnect(this.socialUsers); - }; + } - AppUser.prototype.facebookDisconnect = function () - { + facebookDisconnect() { SocialStore.facebook.loading(true); Remote.facebookDisconnect(this.socialUsers); - }; + } - AppUser.prototype.twitterDisconnect = function () - { + twitterDisconnect() { SocialStore.twitter.loading(true); Remote.twitterDisconnect(this.socialUsers); - }; + } /** - * @param {string} sQuery - * @param {Function} fCallback + * @param {string} query + * @param {Function} callback */ - AppUser.prototype.getAutocomplete = function (sQuery, fCallback) - { - var - aData = [] - ; - - Remote.suggestions(function (sResult, oData) { - if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result)) + getAutocomplete(query, callback) { + Remote.suggestions((result, data) => { + if (Enums.StorageResultType.Success === result && data && Utils.isArray(data.Result)) { - aData = _.map(oData.Result, function (aItem) { - return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null; - }); - - fCallback(_.compact(aData)); + callback(_.compact(_.map(data.Result, + (item) => item && item[0] ? new EmailModel(item[0], item[1]) : null))); } - else if (Enums.StorageResultType.Abort !== sResult) + else if (Enums.StorageResultType.Abort !== result) { - fCallback([]); + callback([]); } - - }, sQuery); - }; + }, query); + } /** * @param {string} sFullNameHash * @param {boolean} bExpanded */ - AppUser.prototype.setExpandedFolder = function (sFullNameHash, bExpanded) - { - var aExpandedList = Local.get(Enums.ClientSideKeyName.ExpandedFolders); + setExpandedFolder(sFullNameHash, bExpanded) { + let aExpandedList = Local.get(Enums.ClientSideKeyName.ExpandedFolders); if (!Utils.isArray(aExpandedList)) { aExpandedList = []; @@ -1052,41 +946,41 @@ } Local.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList); - }; + } + + initHorizontalLayoutResizer(sClientSideKeyName) { - AppUser.prototype.initHorizontalLayoutResizer = function (sClientSideKeyName) - { var iMinHeight = 200, iMaxHeight = 500, oTop = null, oBottom = null, - fResizeCreateFunction = function (oEvent) { - if (oEvent && oEvent.target) + fResizeCreateFunction = (event) => { + if (event && event.target) { - var oResizableHandle = $(oEvent.target).find('.ui-resizable-handle'); + var oResizableHandle = $(event.target).find('.ui-resizable-handle'); oResizableHandle - .on('mousedown', function () { + .on('mousedown', () => { Globals.$html.addClass('rl-resizer'); }) - .on('mouseup', function () { + .on('mouseup', () => { Globals.$html.removeClass('rl-resizer'); }) ; } }, - fResizeStartFunction = function () { + fResizeStartFunction = () => { Globals.$html.addClass('rl-resizer'); }, - fResizeResizeFunction = _.debounce(function () { + fResizeResizeFunction = _.debounce(() => { Globals.$html.addClass('rl-resizer'); }, 500, true), - fResizeStopFunction = function (oEvent, oObject) { + fResizeStopFunction = (oEvent, oObject) => { Globals.$html.removeClass('rl-resizer'); if (oObject && oObject.size && oObject.size.height) { @@ -1109,22 +1003,22 @@ 'stop': fResizeStopFunction }, - fSetHeight = function (iHeight) { - if (iHeight) + fSetHeight = (height) => { + if (height) { if (oTop) { - oTop.attr('style', 'height:' + iHeight + 'px'); + oTop.attr('style', 'height:' + height + 'px'); } if (oBottom) { - oBottom.attr('style', 'top:' + (55 /* top toolbar */ + iHeight) + 'px'); + oBottom.attr('style', 'top:' + (55 /* top toolbar */ + height) + 'px'); } } }, - fDisable = function (bDisable) { + fDisable = (bDisable) => { if (bDisable) { if (oTop && oTop.hasClass('ui-resizable')) @@ -1150,7 +1044,7 @@ oTop.resizable(oOptions); } - var iHeight = Utils.pInt(Local.get(sClientSideKeyName)) || 300; + const iHeight = Utils.pInt(Local.get(sClientSideKeyName)) || 300; fSetHeight(iHeight > iMinHeight ? iHeight : iMinHeight); } } @@ -1158,13 +1052,13 @@ fDisable(false); - Events.sub('layout', function (sLayout) { - fDisable(Enums.Layout.BottomPreview !== sLayout); + Events.sub('layout', (layout) => { + fDisable(Enums.Layout.BottomPreview !== layout); }); }; - AppUser.prototype.initVerticalLayoutResizer = function (sClientSideKeyName) - { + initVerticalLayoutResizer(sClientSideKeyName) { + var iDisabledWidth = 60, iMinWidth = 155, @@ -1173,7 +1067,7 @@ mLeftWidth = Local.get(sClientSideKeyName) || null, - fSetWidth = function (iWidth) { + fSetWidth = (iWidth) => { if (iWidth) { oLeft.css({ @@ -1186,7 +1080,7 @@ } }, - fDisable = function (bDisable) { + fDisable = (bDisable) => { if (bDisable) { oLeft.resizable('disable'); @@ -1199,28 +1093,26 @@ fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth); } }, - fResizeCreateFunction = function (oEvent) { + fResizeCreateFunction = (oEvent) => { if (oEvent && oEvent.target) { - var oResizableHandle = $(oEvent.target).find('.ui-resizable-handle'); - - oResizableHandle - .on('mousedown', function () { + $(oEvent.target).find('.ui-resizable-handle') + .on('mousedown', () => { Globals.$html.addClass('rl-resizer'); }) - .on('mouseup', function () { + .on('mouseup', () => { Globals.$html.removeClass('rl-resizer'); }) ; } }, - fResizeResizeFunction = _.debounce(function () { + fResizeResizeFunction = _.debounce(() => { Globals.$html.addClass('rl-resizer'); }, 500, true), - fResizeStartFunction = function () { + fResizeStartFunction = () => { Globals.$html.addClass('rl-resizer'); }, - fResizeStopFunction = function (oEvent, oObject) { + fResizeStopFunction = (oEvent, oObject) => { Globals.$html.removeClass('rl-resizer'); if (oObject && oObject.size && oObject.size.width) { @@ -1249,40 +1141,36 @@ 'stop': fResizeStopFunction }); - Events.sub('left-panel.off', function () { + Events.sub('left-panel.off', () => { fDisable(true); }); - Events.sub('left-panel.on', function () { + Events.sub('left-panel.on', () => { fDisable(false); }); - }; + } - AppUser.prototype.logout = function () - { - var self = this; - Remote.logout(function () { - self.loginAndLogoutReload(false, true, + logout() { + Remote.logout(() => { + this.loginAndLogoutReload(false, true, Settings.settingsGet('ParentEmail') && 0 < Settings.settingsGet('ParentEmail').length); }); }; - AppUser.prototype.bootstartTwoFactorScreen = function () - { + bootstartTwoFactorScreen() { kn.showScreenPopup(require('View/Popup/TwoFactorConfiguration'), [true]); - }; + } - AppUser.prototype.bootstartWelcomePopup = function (sUrl) - { - kn.showScreenPopup(require('View/Popup/WelcomePage'), [sUrl]); - }; + bootstartWelcomePopup(url) { + kn.showScreenPopup(require('View/Popup/WelcomePage'), [url]); + } + + bootstartLoginScreen() { - AppUser.prototype.bootstartLoginScreen = function () - { Globals.$html.removeClass('rl-user-auth').addClass('rl-user-no-auth'); - var sCustomLoginLink = Utils.pString(Settings.settingsGet('CustomLoginLink')); - if (!sCustomLoginLink) + const customLoginLink = Utils.pString(Settings.settingsGet('CustomLoginLink')); + if (!customLoginLink) { kn.startScreens([ require('Screen/User/Login') @@ -1298,19 +1186,21 @@ kn.routeOff(); _.defer(function () { - window.location.href = sCustomLoginLink; + window.location.href = customLoginLink; }); } - }; + } - AppUser.prototype.bootend = function () - { + bootend() { if (progressJs) { kn.hideLoading(); - progressJs.onbeforeend(function () { - $('.progressjs-container').hide().remove(); + progressJs.onbeforeend(() => { + $('.progressjs-container').hide(); + _.delay(() => { + $('.progressjs-container').remove(); + }, 100); }); progressJs.set(100).end(); @@ -1321,9 +1211,9 @@ } }; - AppUser.prototype.bootstart = function () - { - AbstractApp.prototype.bootstart.call(this); + bootstart() { + + super.bootstart(); require('Stores/User/App').populate(); require('Stores/User/Settings').populate(); @@ -1332,7 +1222,6 @@ require('Stores/User/Contact').populate(); var - self = this, $LAB = require('$LAB'), sJsHash = Settings.settingsGet('JsHash'), sStartupUrl = Utils.pString(Settings.settingsGet('StartupUrl')), @@ -1347,8 +1236,8 @@ progressJs.set(90); } - Globals.leftPanelDisabled.subscribe(function (bValue) { - Events.pub('left-panel.' + (bValue ? 'off' : 'on')); + Globals.leftPanelDisabled.subscribe((value) => { + Events.pub('left-panel.' + (value ? 'off' : 'on')); }); this.setWindowTitle(''); @@ -1369,11 +1258,11 @@ //require.ensure([], function() { // require code splitting - self.foldersReload(_.bind(function (bValue) { + this.foldersReload((value) => { this.bootend(); - if (bValue) + if (value) { if ('' !== sStartupUrl) { @@ -1384,7 +1273,7 @@ if ($LAB && window.crypto && window.crypto.getRandomValues && Settings.capa(Enums.Capa.OpenPGP)) { - var fOpenpgpCallback = function (openpgp) { + const openpgpCallback = (openpgp) => { PgpStore.openpgp = openpgp; @@ -1407,19 +1296,19 @@ Events.pub('openpgp.init'); - self.reloadOpenPgpKeys(); + this.reloadOpenPgpKeys(); }; if (window.openpgp) { - fOpenpgpCallback(window.openpgp); + openpgpCallback(window.openpgp); } else { - $LAB.script(Links.openPgpJs()).wait(function () { + $LAB.script(Links.openPgpJs()).wait(() => { if (window.openpgp) { - fOpenpgpCallback(window.openpgp); + openpgpCallback(window.openpgp); } }); } @@ -1437,85 +1326,58 @@ if (bGoogle || bFacebook || bTwitter) { - self.socialUsers(true); + this.socialUsers(true); } - Events.sub('interval.2m', function () { - self.folderInformation(Cache.getFolderInboxName()); - }); - - Events.sub('interval.3m', function () { - var sF = FolderStore.currentFolderFullNameRaw(); + Events.sub('interval.2m', () => this.folderInformation(Cache.getFolderInboxName())); + Events.sub('interval.3m', () => { + const sF = FolderStore.currentFolderFullNameRaw(); if (Cache.getFolderInboxName() !== sF) { - self.folderInformation(sF); + this.folderInformation(sF); } }); - Events.sub('interval.2m-after5m', function () { - self.folderInformationMultiply(); - }); - - Events.sub('interval.15m', function () { - self.quota(); - }); - - Events.sub('interval.20m', function () { - self.foldersReload(); - }); + Events.sub('interval.2m-after5m', () => this.folderInformationMultiply()); + Events.sub('interval.15m', () => this.quota()); + Events.sub('interval.20m', () => this.foldersReload()); iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20; iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320; - _.delay(function () { - self.contactsSync(); - }, 10000); + _.delay(() => this.contactsSync(), 10000); + _.delay(() => this.folderInformationMultiply(true), 2000); - _.delay(function () { - self.folderInformationMultiply(true); - }, 2000); + window.setInterval(() => this.contactsSync(), iContactsSyncInterval * 60000 + 5000); - window.setInterval(function () { - self.contactsSync(); - }, iContactsSyncInterval * 60000 + 5000); + this.accountsAndIdentities(true); - self.accountsAndIdentities(true); - - _.delay(function () { - var sF = FolderStore.currentFolderFullNameRaw(); + _.delay(() => { + const sF = FolderStore.currentFolderFullNameRaw(); if (Cache.getFolderInboxName() !== sF) { - self.folderInformation(sF); + this.folderInformation(sF); } }, 1000); - _.delay(function () { - self.quota(); - }, 5000); + _.delay(() => this.quota(), 5000); + _.delay(() => Remote.appDelayStart(Utils.emptyFunction), 35000); - _.delay(function () { - Remote.appDelayStart(Utils.emptyFunction); - }, 35000); - - Events.sub('rl.auto-logout', function () { - self.logout(); - }); + Events.sub('rl.auto-logout', () => this.logout()); Plugins.runHook('rl-start-user-screens'); Events.pub('rl.bootstart-user-screens'); if (Settings.settingsGet('WelcomePageUrl')) { - _.delay(function () { - self.bootstartWelcomePopup(Settings.settingsGet('WelcomePageUrl')); - }, 1000); + _.delay(() => this.bootstartWelcomePopup(Settings.settingsGet('WelcomePageUrl')), 1000); } if (!!Settings.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler && Settings.capa(Enums.Capa.Composer)) { - _.delay(function () { + _.delay(() => { try { window.navigator.registerProtocolHandler('mailto', window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s', @@ -1531,9 +1393,7 @@ if (!Globals.bMobileDevice) { - _.defer(function () { - self.initVerticalLayoutResizer(Enums.ClientSideKeyName.FolderListSize); - }); + _.defer(() => this.initVerticalLayoutResizer(Enums.ClientSideKeyName.FolderListSize)); if (Tinycon && Settings.settingsGet('FaviconStatus') && !Settings.settingsGet('Filtered') ) { @@ -1541,9 +1401,8 @@ fallback: false }); - Events.sub('mailbox.inbox-unread-count', function (iCount) { - Tinycon.setBubble(0 < iCount ? (99 < iCount ? 99 : iCount) : 0); - }); + Events.sub('mailbox.inbox-unread-count', + (iCount) => Tinycon.setBubble(0 < iCount ? (99 < iCount ? 99 : iCount) : 0)); } } } @@ -1552,7 +1411,7 @@ this.logout(); } - }, self)); + }); //}); // require code splitting @@ -1566,36 +1425,33 @@ if (bGoogle) { - window['rl_' + sJsHash + '_google_service'] = function () { + window['rl_' + sJsHash + '_google_service'] = () => { SocialStore.google.loading(true); - self.socialUsers(); + this.socialUsers(); }; } if (bFacebook) { - window['rl_' + sJsHash + '_facebook_service'] = function () { + window['rl_' + sJsHash + '_facebook_service'] = () => { SocialStore.facebook.loading(true); - self.socialUsers(); + this.socialUsers(); }; } if (bTwitter) { - window['rl_' + sJsHash + '_twitter_service'] = function () { + window['rl_' + sJsHash + '_twitter_service'] = () => { SocialStore.twitter.loading(true); - self.socialUsers(); + this.socialUsers(); }; } - Events.sub('interval.1m', function () { - Momentor.reload(); - }); + Events.sub('interval.1m', () => Momentor.reload()); Plugins.runHook('rl-start-screens'); Events.pub('rl.bootstart-end'); - }; + } +} - module.exports = new AppUser(); - -}()); \ No newline at end of file +export default new AppUser(); diff --git a/dev/Common/Audio.jsx b/dev/Common/Audio.jsx index f14971ba9..a3aa20571 100644 --- a/dev/Common/Audio.jsx +++ b/dev/Common/Audio.jsx @@ -7,15 +7,17 @@ import Events from 'Common/Events'; class Audio { + player = null; + notificator = null; + + supported = false; + supportedMp3 = false; + supportedOgg = false; + supportedWav = false; + supportedNotification = false; + constructor() { - this.notificator = null; - - this.supportedMp3 = false; - this.supportedOgg = false; - this.supportedWav = false; - this.supportedNotification = false; - this.player = this.createNewObject(); this.supported = !Globals.bMobileDevice && !Globals.bSafari && !!this.player && !!this.player.play; @@ -38,13 +40,9 @@ class Audio if (this.supported) { - $(this.player).on('ended error', () => { - this.stop(); - }); + $(this.player).on('ended error', () => this.stop()); - Events.sub('audio.api.stop', () => { - this.stop(); - }); + Events.sub('audio.api.stop', () => this.stop()); } } diff --git a/dev/Common/Base64.jsx b/dev/Common/Base64.jsx index 37c15178a..eeba0c976 100644 --- a/dev/Common/Base64.jsx +++ b/dev/Common/Base64.jsx @@ -8,9 +8,8 @@ const BASE_64_CHR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456 const Base64 = { // public method for urlsafe encoding - urlsafe_encode: (input) => { - return 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) => { diff --git a/dev/Common/Cache.js b/dev/Common/Cache.js deleted file mode 100644 index 86dc950e9..000000000 --- a/dev/Common/Cache.js +++ /dev/null @@ -1,412 +0,0 @@ - -(function () { - - 'use strict'; - - var - _ = require('_'), - - Enums = require('Common/Enums'), - Utils = require('Common/Utils'), - Links = require('Common/Links'), - - Settings = require('Storage/Settings') - ; - - /** - * @constructor - */ - function CacheUserStorage() - { - this.oFoldersCache = {}; - this.oFoldersNamesCache = {}; - this.oFolderHashCache = {}; - this.oFolderUidNextCache = {}; - this.oMessageListHashCache = {}; - this.oMessageFlagsCache = {}; - this.oNewMessage = {}; - this.oRequestedMessage = {}; - - this.bCapaGravatar = Settings.capa(Enums.Capa.Gravatar); - } - - /** - * @type {boolean} - */ - CacheUserStorage.prototype.bCapaGravatar = false; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oFoldersCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oFoldersNamesCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oFolderHashCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oFolderUidNextCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oMessageListHashCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oMessageFlagsCache = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oNewMessage = {}; - - /** - * @type {Object} - */ - CacheUserStorage.prototype.oRequestedMessage = {}; - - CacheUserStorage.prototype.clear = function () - { - this.oFoldersCache = {}; - this.oFoldersNamesCache = {}; - this.oFolderHashCache = {}; - this.oFolderUidNextCache = {}; - this.oMessageListHashCache = {}; - this.oMessageFlagsCache = {}; - }; - - /** - * @param {string} sEmail - * @param {Function} fCallback - * @return {string} - */ - CacheUserStorage.prototype.getUserPic = function (sEmail, fCallback) - { - sEmail = Utils.trim(sEmail); - fCallback(this.bCapaGravatar && '' !== sEmail ? Links.avatarLink(sEmail) : '', sEmail); - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {string} sUid - * @return {string} - */ - CacheUserStorage.prototype.getMessageKey = function (sFolderFullNameRaw, sUid) - { - return sFolderFullNameRaw + '#' + sUid; - }; - - /** - * @param {string} sFolder - * @param {string} sUid - */ - CacheUserStorage.prototype.addRequestedMessage = function (sFolder, sUid) - { - this.oRequestedMessage[this.getMessageKey(sFolder, sUid)] = true; - }; - - /** - * @param {string} sFolder - * @param {string} sUid - * @return {boolean} - */ - CacheUserStorage.prototype.hasRequestedMessage = function (sFolder, sUid) - { - return true === this.oRequestedMessage[this.getMessageKey(sFolder, sUid)]; - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {string} sUid - */ - CacheUserStorage.prototype.addNewMessageCache = function (sFolderFullNameRaw, sUid) - { - this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = true; - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {string} sUid - */ - CacheUserStorage.prototype.hasNewMessageAndRemoveFromCache = function (sFolderFullNameRaw, sUid) - { - if (this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)]) - { - this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = null; - return true; - } - - return false; - }; - - CacheUserStorage.prototype.clearNewMessageCache = function () - { - this.oNewMessage = {}; - }; - - /** - * @type {string} - */ - CacheUserStorage.prototype.sInboxFolderName = ''; - - /** - * @return {string} - */ - CacheUserStorage.prototype.getFolderInboxName = function () - { - return '' === this.sInboxFolderName ? 'INBOX' : this.sInboxFolderName; - }; - - /** - * @param {string} sFolderHash - * @return {string} - */ - CacheUserStorage.prototype.getFolderFullNameRaw = function (sFolderHash) - { - return '' !== sFolderHash && this.oFoldersNamesCache[sFolderHash] ? this.oFoldersNamesCache[sFolderHash] : ''; - }; - - /** - * @param {string} sFolderHash - * @param {string} sFolderFullNameRaw - */ - CacheUserStorage.prototype.setFolderFullNameRaw = function (sFolderHash, sFolderFullNameRaw) - { - this.oFoldersNamesCache[sFolderHash] = sFolderFullNameRaw; - if ('INBOX' === sFolderFullNameRaw || '' === this.sInboxFolderName) - { - this.sInboxFolderName = sFolderFullNameRaw; - } - }; - - /** - * @param {string} sFolderFullNameRaw - * @return {string} - */ - CacheUserStorage.prototype.getFolderHash = function (sFolderFullNameRaw) - { - return '' !== sFolderFullNameRaw && this.oFolderHashCache[sFolderFullNameRaw] ? this.oFolderHashCache[sFolderFullNameRaw] : ''; - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {string} sFolderHash - */ - CacheUserStorage.prototype.setFolderHash = function (sFolderFullNameRaw, sFolderHash) - { - if ('' !== sFolderFullNameRaw) - { - this.oFolderHashCache[sFolderFullNameRaw] = sFolderHash; - } - }; - - /** - * @param {string} sFolderFullNameRaw - * @return {string} - */ - CacheUserStorage.prototype.getFolderUidNext = function (sFolderFullNameRaw) - { - return '' !== sFolderFullNameRaw && this.oFolderUidNextCache[sFolderFullNameRaw] ? this.oFolderUidNextCache[sFolderFullNameRaw] : ''; - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {string} sUidNext - */ - CacheUserStorage.prototype.setFolderUidNext = function (sFolderFullNameRaw, sUidNext) - { - this.oFolderUidNextCache[sFolderFullNameRaw] = sUidNext; - }; - - /** - * @param {string} sFolderFullNameRaw - * @return {?FolderModel} - */ - CacheUserStorage.prototype.getFolderFromCacheList = function (sFolderFullNameRaw) - { - return '' !== sFolderFullNameRaw && this.oFoldersCache[sFolderFullNameRaw] ? this.oFoldersCache[sFolderFullNameRaw] : null; - }; - - /** - * @param {string} sFolderFullNameRaw - * @param {?FolderModel} oFolder - */ - CacheUserStorage.prototype.setFolderToCacheList = function (sFolderFullNameRaw, oFolder) - { - this.oFoldersCache[sFolderFullNameRaw] = oFolder; - }; - - /** - * @param {string} sFolderFullNameRaw - */ - CacheUserStorage.prototype.removeFolderFromCacheList = function (sFolderFullNameRaw) - { - this.setFolderToCacheList(sFolderFullNameRaw, null); - }; - - /** - * @param {string} sFolderFullName - * @param {string} sUid - * @return {?Array} - */ - CacheUserStorage.prototype.getMessageFlagsFromCache = function (sFolderFullName, sUid) - { - return this.oMessageFlagsCache[sFolderFullName] && this.oMessageFlagsCache[sFolderFullName][sUid] ? - this.oMessageFlagsCache[sFolderFullName][sUid] : null; - }; - - /** - * @param {string} sFolderFullName - * @param {string} sUid - * @param {Array} aFlagsCache - */ - CacheUserStorage.prototype.setMessageFlagsToCache = function (sFolderFullName, sUid, aFlagsCache) - { - if (!this.oMessageFlagsCache[sFolderFullName]) - { - this.oMessageFlagsCache[sFolderFullName] = {}; - } - - this.oMessageFlagsCache[sFolderFullName][sUid] = aFlagsCache; - }; - - /** - * @param {string} sFolderFullName - */ - CacheUserStorage.prototype.clearMessageFlagsFromCacheByFolder = function (sFolderFullName) - { - this.oMessageFlagsCache[sFolderFullName] = {}; - }; - - /** - * @param {(MessageModel|null)} oMessage - */ - CacheUserStorage.prototype.initMessageFlagsFromCache = function (oMessage) - { - if (oMessage) - { - var - self = this, - sUid = oMessage.uid, - aFlags = this.getMessageFlagsFromCache(oMessage.folderFullNameRaw, sUid), - mUnseenSubUid = null, - mFlaggedSubUid = null - ; - - if (aFlags && 0 < aFlags.length) - { - oMessage.flagged(!!aFlags[1]); - - if (!oMessage.__simple_message__) - { - oMessage.unseen(!!aFlags[0]); - oMessage.answered(!!aFlags[2]); - oMessage.forwarded(!!aFlags[3]); - oMessage.isReadReceipt(!!aFlags[4]); - oMessage.deletedMark(!!aFlags[5]); - } - } - - if (0 < oMessage.threads().length) - { - mUnseenSubUid = _.find(oMessage.threads(), function (sSubUid) { - if (sUid === sSubUid){ - return false; - } - var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, sSubUid); - return aFlags && 0 < aFlags.length && !!aFlags[0]; - }); - - mFlaggedSubUid = _.find(oMessage.threads(), function (sSubUid) { - if (sUid === sSubUid){ - return false; - } - var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, sSubUid); - return aFlags && 0 < aFlags.length && !!aFlags[1]; - }); - - oMessage.hasUnseenSubMessage(mUnseenSubUid && 0 < Utils.pInt(mUnseenSubUid)); - oMessage.hasFlaggedSubMessage(mFlaggedSubUid && 0 < Utils.pInt(mFlaggedSubUid)); - } - } - }; - - /** - * @param {(MessageModel|null)} oMessage - */ - CacheUserStorage.prototype.storeMessageFlagsToCache = function (oMessage) - { - if (oMessage) - { - this.setMessageFlagsToCache( - oMessage.folderFullNameRaw, - oMessage.uid, - [oMessage.unseen(), oMessage.flagged(), oMessage.answered(), oMessage.forwarded(), - oMessage.isReadReceipt(), oMessage.deletedMark()] - ); - } - }; - - /** - * @param {string} sFolder - * @param {string} sUid - * @param {Array} aFlags - */ - CacheUserStorage.prototype.storeMessageFlagsToCacheByFolderAndUid = function (sFolder, sUid, aFlags) - { - if (Utils.isArray(aFlags) && 0 < aFlags.length) - { - this.setMessageFlagsToCache(sFolder, sUid, aFlags); - } - }; - - /** - * @param {string} sFolder - * @param {string} sUid - * @param {number} iSetAction - */ - CacheUserStorage.prototype.storeMessageFlagsToCacheBySetAction = function (sFolder, sUid, iSetAction) - { - var iUnread = 0, aFlags = this.getMessageFlagsFromCache(sFolder, sUid); - if (Utils.isArray(aFlags) && 0 < aFlags.length) - { - if (aFlags[0]) - { - iUnread = 1; - } - - switch (iSetAction) - { - case Enums.MessageSetAction.SetSeen: - aFlags[0] = false; - break; - case Enums.MessageSetAction.UnsetSeen: - aFlags[0] = true; - break; - case Enums.MessageSetAction.SetFlag: - aFlags[1] = true; - break; - case Enums.MessageSetAction.UnsetFlag: - aFlags[1] = false; - break; - } - - this.setMessageFlagsToCache(sFolder, sUid, aFlags); - } - - return iUnread; - }; - - module.exports = new CacheUserStorage(); - -}()); \ No newline at end of file diff --git a/dev/Common/Cache.jsx b/dev/Common/Cache.jsx new file mode 100644 index 000000000..369c7677f --- /dev/null +++ b/dev/Common/Cache.jsx @@ -0,0 +1,329 @@ + + +import {_} from 'common'; +import {Capa, MessageSetAction} from 'Common/Enums'; +import Utils from 'Common/Utils'; +import Links from 'Common/Links'; +import Settings from 'Storage/Settings'; + +class CacheUserStorage +{ + oFoldersCache = {}; + oFoldersNamesCache = {}; + oFolderHashCache = {}; + oFolderUidNextCache = {}; + oMessageListHashCache = {}; + oMessageFlagsCache = {}; + oNewMessage = {}; + oRequestedMessage = {}; + bCapaGravatar = false; + inboxFolderName = ''; + + constructor() + { + this.bCapaGravatar = Settings.capa(Capa.Gravatar); + } + + clear() { + this.oFoldersCache = {}; + this.oFoldersNamesCache = {}; + this.oFolderHashCache = {}; + this.oFolderUidNextCache = {}; + this.oMessageListHashCache = {}; + this.oMessageFlagsCache = {}; + } + + /** + * @param {string} email + * @param {Function} callback + * @return {string} + */ + getUserPic(email, callback) { + email = Utils.trim(email); + callback(this.bCapaGravatar && '' !== email ? Links.avatarLink(email) : '', email); + } + + /** + * @param {string} folderFullNameRaw + * @param {string} uid + * @return {string} + */ + getMessageKey(folderFullNameRaw, uid) { + return `${folderFullNameRaw}#${uid}`; + } + + /** + * @param {string} folder + * @param {string} uid + */ + addRequestedMessage(folder, uid) { + this.oRequestedMessage[this.getMessageKey(folder, uid)] = true; + } + + /** + * @param {string} folder + * @param {string} uid + * @return {boolean} + */ + hasRequestedMessage(folder, uid) { + return true === this.oRequestedMessage[this.getMessageKey(folder, uid)]; + } + + /** + * @param {string} folderFullNameRaw + * @param {string} uid + */ + addNewMessageCache(folderFullNameRaw, uid) { + this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)] = true; + } + + /** + * @param {string} folderFullNameRaw + * @param {string} uid + */ + hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid) { + if (this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)]) + { + this.oNewMessage[this.getMessageKey(folderFullNameRaw, uid)] = null; + return true; + } + return false; + } + + clearNewMessageCache() { + this.oNewMessage = {}; + } + + /** + * @return {string} + */ + getFolderInboxName() { + return '' === this.inboxFolderName ? 'INBOX' : this.inboxFolderName; + } + + /** + * @param {string} folderHash + * @return {string} + */ + getFolderFullNameRaw(folderHash) { + return '' !== folderHash && this.oFoldersNamesCache[folderHash] ? this.oFoldersNamesCache[folderHash] : ''; + } + + /** + * @param {string} folderHash + * @param {string} folderFullNameRaw + */ + setFolderFullNameRaw(folderHash, folderFullNameRaw) { + this.oFoldersNamesCache[folderHash] = folderFullNameRaw; + if ('INBOX' === folderFullNameRaw || '' === this.inboxFolderName) + { + this.inboxFolderName = folderFullNameRaw; + } + } + + /** + * @param {string} folderFullNameRaw + * @return {string} + */ + getFolderHash(folderFullNameRaw) { + return '' !== folderFullNameRaw && this.oFolderHashCache[folderFullNameRaw] ? this.oFolderHashCache[folderFullNameRaw] : ''; + } + + /** + * @param {string} folderFullNameRaw + * @param {string} folderHash + */ + setFolderHash(folderFullNameRaw, folderHash) { + if ('' !== folderFullNameRaw) + { + this.oFolderHashCache[folderFullNameRaw] = folderHash; + } + } + + /** + * @param {string} folderFullNameRaw + * @return {string} + */ + getFolderUidNext(folderFullNameRaw) { + return '' !== folderFullNameRaw && this.oFolderUidNextCache[folderFullNameRaw] ? this.oFolderUidNextCache[folderFullNameRaw] : ''; + } + + /** + * @param {string} folderFullNameRaw + * @param {string} uidNext + */ + setFolderUidNext(folderFullNameRaw, uidNext) { + this.oFolderUidNextCache[folderFullNameRaw] = uidNext; + } + + /** + * @param {string} folderFullNameRaw + * @return {?FolderModel} + */ + getFolderFromCacheList(folderFullNameRaw) { + return '' !== folderFullNameRaw && this.oFoldersCache[folderFullNameRaw] ? this.oFoldersCache[folderFullNameRaw] : null; + } + + /** + * @param {string} folderFullNameRaw + * @param {?FolderModel} folder + */ + setFolderToCacheList(folderFullNameRaw, folder) { + this.oFoldersCache[folderFullNameRaw] = folder; + } + + /** + * @param {string} folderFullNameRaw + */ + removeFolderFromCacheList(folderFullNameRaw) { + this.setFolderToCacheList(folderFullNameRaw, null); + } + + /** + * @param {string} folderFullName + * @param {string} uid + * @return {?Array} + */ + getMessageFlagsFromCache(folderFullName, uid) { + return this.oMessageFlagsCache[folderFullName] && this.oMessageFlagsCache[folderFullName][uid] ? + this.oMessageFlagsCache[folderFullName][uid] : null; + } + + /** + * @param {string} folderFullName + * @param {string} uid + * @param {Array} flagsCache + */ + setMessageFlagsToCache(folderFullName, uid, flagsCache) { + if (!this.oMessageFlagsCache[folderFullName]) + { + this.oMessageFlagsCache[folderFullName] = {}; + } + + this.oMessageFlagsCache[folderFullName][uid] = flagsCache; + } + + /** + * @param {string} folderFullName + */ + clearMessageFlagsFromCacheByFolder(folderFullName) { + this.oMessageFlagsCache[folderFullName] = {}; + } + + /** + * @param {(MessageModel|null)} message + */ + initMessageFlagsFromCache(message) { + + if (message) + { + const + uid = message.uid, + flags = this.getMessageFlagsFromCache(message.folderFullNameRaw, uid) + ; + + if (flags && 0 < flags.length) + { + message.flagged(!!flags[1]); + + if (!message.__simple_message__) + { + message.unseen(!!flags[0]); + message.answered(!!flags[2]); + message.forwarded(!!flags[3]); + message.isReadReceipt(!!flags[4]); + message.deletedMark(!!flags[5]); + } + } + + if (0 < message.threads().length) + { + const unseenSubUid = _.find(message.threads(), (sSubUid) => { + if (uid !== sSubUid){ + const flags = this.getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); + return flags && 0 < flags.length && !!flags[0]; + } + return false; + }); + + const flaggedSubUid = _.find(message.threads(), (sSubUid) => { + if (uid !== sSubUid) { + const flags = this.getMessageFlagsFromCache(message.folderFullNameRaw, sSubUid); + return flags && 0 < flags.length && !!flags[1]; + } + return false; + }); + + message.hasUnseenSubMessage(unseenSubUid && 0 < Utils.pInt(unseenSubUid)); + message.hasFlaggedSubMessage(flaggedSubUid && 0 < Utils.pInt(flaggedSubUid)); + } + } + } + + /** + * @param {(MessageModel|null)} message + */ + storeMessageFlagsToCache(message) { + if (message) + { + this.setMessageFlagsToCache( + message.folderFullNameRaw, message.uid, + [message.unseen(), message.flagged(), message.answered(), message.forwarded(), + message.isReadReceipt(), message.deletedMark()] + ); + } + } + + /** + * @param {string} folder + * @param {string} uid + * @param {Array} flags + */ + storeMessageFlagsToCacheByFolderAndUid(folder, uid, flags) { + if (Utils.isArray(flags) && 0 < flags.length) + { + this.setMessageFlagsToCache(folder, uid, flags); + } + } + + /** + * @param {string} folder + * @param {string} uid + * @param {number} setAction + */ + storeMessageFlagsToCacheBySetAction(folder, uid, setAction) { + + let unread = 0; + const flags = this.getMessageFlagsFromCache(folder, uid); + + if (Utils.isArray(flags) && 0 < flags.length) + { + if (flags[0]) + { + unread = 1; + } + + switch (setAction) + { + case MessageSetAction.SetSeen: + flags[0] = false; + break; + case MessageSetAction.UnsetSeen: + flags[0] = true; + break; + case MessageSetAction.SetFlag: + flags[1] = true; + break; + case MessageSetAction.UnsetFlag: + flags[1] = false; + break; + } + + this.setMessageFlagsToCache(folder, uid, flags); + } + + return unread; + } +} + +module.exports = new CacheUserStorage(); diff --git a/dev/Common/Events.jsx b/dev/Common/Events.jsx index 736266a5d..08997fbdc 100644 --- a/dev/Common/Events.jsx +++ b/dev/Common/Events.jsx @@ -5,9 +5,9 @@ import Plugins from 'Common/Plugins'; class Events { - constructor() { - this.subs = {}; - } + subs = {}; + + constructor() {} /** * @param {string|Object} name diff --git a/dev/Common/HtmlEditor.js b/dev/Common/HtmlEditor.js deleted file mode 100644 index 16b5ef9d9..000000000 --- a/dev/Common/HtmlEditor.js +++ /dev/null @@ -1,435 +0,0 @@ - -(function () { - - 'use strict'; - - var - window = require('window'), - _ = require('_'), - - Globals = require('Common/Globals'), - - Settings = require('Storage/Settings') - ; - - /** - * @constructor - * @param {Object} oElement - * @param {Function=} fOnBlur - * @param {Function=} fOnReady - * @param {Function=} fOnModeChange - */ - function HtmlEditor(oElement, fOnBlur, fOnReady, fOnModeChange) - { - this.editor = null; - this.iBlurTimer = 0; - this.fOnBlur = fOnBlur || null; - this.fOnReady = fOnReady || null; - this.fOnModeChange = fOnModeChange || null; - - this.$element = $(oElement); - - this.resize = _.throttle(_.bind(this.resize, this), 100); - - this.__inited = false; - - this.init(); - } - - HtmlEditor.prototype.blurTrigger = function () - { - if (this.fOnBlur) - { - var self = this; - window.clearTimeout(this.iBlurTimer); - this.iBlurTimer = window.setTimeout(function () { - self.fOnBlur(); - }, 200); - } - }; - - HtmlEditor.prototype.focusTrigger = function () - { - if (this.fOnBlur) - { - window.clearTimeout(this.iBlurTimer); - } - }; - - /** - * @return {boolean} - */ - HtmlEditor.prototype.isHtml = function () - { - return this.editor ? 'wysiwyg' === this.editor.mode : false; - }; - - /** - * @param {string} sSignature - * @param {bool} bHtml - * @param {bool} bInsertBefore - */ - HtmlEditor.prototype.setSignature = function (sSignature, bHtml, bInsertBefore) - { - if (this.editor) - { - this.editor.execCommand('insertSignature', { - 'isHtml': bHtml, - 'insertBefore': bInsertBefore, - 'signature': sSignature - }); - } - }; - - /** - * @return {boolean} - */ - HtmlEditor.prototype.checkDirty = function () - { - return this.editor ? this.editor.checkDirty() : false; - }; - - HtmlEditor.prototype.resetDirty = function () - { - if (this.editor) - { - this.editor.resetDirty(); - } - }; - - /** - * @param {string} sText - * @return {string} - */ - HtmlEditor.prototype.clearSignatureSigns = function (sText) - { - return sText.replace(/(\u200C|\u0002)/g, ''); - }; - - /** - * @param {boolean=} bWrapIsHtml = false - * @param {boolean=} bClearSignatureSigns = false - * @return {string} - */ - HtmlEditor.prototype.getData = function (bWrapIsHtml, bClearSignatureSigns) - { - var sResult = ''; - if (this.editor) - { - try - { - if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain) - { - sResult = this.editor.__plain.getRawData(); - } - else - { - sResult = bWrapIsHtml ? - '
]*><\/p>/ig, '');
-
- try {
- this.editor.setData(sHtml);
- } catch (e) {}
-
- if (bFocus)
- {
- this.focus();
- }
- }
- };
-
- HtmlEditor.prototype.replaceHtml = function (mFind, sReplaceHtml)
- {
- if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode)
- {
- try {
- this.editor.setData(
- this.editor.getData().replace(mFind, sReplaceHtml));
- } catch (e) {}
- }
- };
-
- HtmlEditor.prototype.setPlain = function (sPlain, bFocus)
- {
- if (this.editor && this.__inited)
- {
- this.modeToggle(false);
- if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
- {
- return this.editor.__plain.setRawData(sPlain);
- }
- else
- {
- try {
- this.editor.setData(sPlain);
- } catch (e) {}
- }
-
- if (bFocus)
- {
- this.focus();
- }
- }
- };
-
- HtmlEditor.prototype.init = function ()
- {
- if (this.$element && this.$element[0] && !this.editor)
- {
- var
- self = this,
- fInit = function () {
-
- var
- oConfig = Globals.oHtmlEditorDefaultConfig,
- sLanguage = Settings.settingsGet('Language'),
- bSource = !!Settings.settingsGet('AllowHtmlEditorSourceButton'),
- bBiti = !!Settings.settingsGet('AllowHtmlEditorBitiButtons')
- ;
-
- if ((bSource || !bBiti) && !oConfig.toolbarGroups.__cfgInited)
- {
- oConfig.toolbarGroups.__cfgInited = true;
-
- if (bSource)
- {
- oConfig.removeButtons = oConfig.removeButtons.replace(',Source', '');
- }
-
- if (!bBiti)
- {
- oConfig.removePlugins += (oConfig.removePlugins ? ',' : '') + 'bidi';
- }
- }
-
- oConfig.enterMode = window.CKEDITOR.ENTER_BR;
- oConfig.shiftEnterMode = window.CKEDITOR.ENTER_P;
-
- oConfig.language = Globals.oHtmlEditorLangsMap[sLanguage] || 'en';
- if (window.CKEDITOR.env)
- {
- window.CKEDITOR.env.isCompatible = true;
- }
-
- self.editor = window.CKEDITOR.appendTo(self.$element[0], oConfig);
-
- self.editor.on('key', function(oEvent) {
- if (oEvent && oEvent.data && 9 /* Tab */ === oEvent.data.keyCode)
- {
- return false;
- }
- });
-
- self.editor.on('blur', function() {
- self.blurTrigger();
- });
-
- self.editor.on('mode', function() {
-
- self.blurTrigger();
-
- if (self.fOnModeChange)
- {
- self.fOnModeChange('plain' !== self.editor.mode);
- }
- });
-
- self.editor.on('focus', function() {
- self.focusTrigger();
- });
-
- if (window.FileReader)
- {
- self.editor.on('drop', function(evt) {
- if (0 < evt.data.dataTransfer.getFilesCount())
- {
- var file = evt.data.dataTransfer.getFile(0);
- if (file && window.FileReader && evt.data.dataTransfer.id &&
- file.type && file.type.match(/^image/i))
- {
- var
- id = evt.data.dataTransfer.id,
- imageId = '[img=' + id +']',
- reader = new window.FileReader()
- ;
-
- reader.onloadend = function () {
- if (reader.result)
- {
- self.replaceHtml(imageId, '');
- }
- };
-
- reader.readAsDataURL(file);
-
- evt.data.dataTransfer.setData('text/html', imageId);
- }
- }
- });
- }
-
- self.editor.on('instanceReady', function () {
-
- if (self.editor.removeMenuItem)
- {
- self.editor.removeMenuItem('cut');
- self.editor.removeMenuItem('copy');
- self.editor.removeMenuItem('paste');
- }
-
- self.__resizable = true;
- self.__inited = true;
-
- self.resize();
-
- if (self.fOnReady)
- {
- self.fOnReady();
- }
-
- });
- }
- ;
-
- if (window.CKEDITOR)
- {
- fInit();
- }
- else
- {
- window.__initEditor = fInit;
- }
- }
- };
-
- HtmlEditor.prototype.focus = function ()
- {
- if (this.editor)
- {
- try {
- this.editor.focus();
- } catch (e) {}
- }
- };
-
- HtmlEditor.prototype.hasFocus = function ()
- {
- if (this.editor)
- {
- try {
- return !!this.editor.focusManager.hasFocus;
- } catch (e) {}
- }
-
- return false;
- };
-
- HtmlEditor.prototype.blur = function ()
- {
- if (this.editor)
- {
- try {
- this.editor.focusManager.blur(true);
- } catch (e) {}
- }
- };
-
- HtmlEditor.prototype.resize = function ()
- {
- if (this.editor && this.__resizable)
- {
- try {
- this.editor.resize(this.$element.width(), this.$element.innerHeight());
- } catch (e) {}
- }
- };
-
- HtmlEditor.prototype.setReadOnly = function (bValue)
- {
- if (this.editor)
- {
- try {
- this.editor.setReadOnly(!!bValue);
- } catch (e) {}
- }
- };
-
- HtmlEditor.prototype.clear = function (bFocus)
- {
- this.setHtml('', bFocus);
- };
-
- module.exports = HtmlEditor;
-
-}());
\ No newline at end of file
diff --git a/dev/Common/HtmlEditor.jsx b/dev/Common/HtmlEditor.jsx
new file mode 100644
index 000000000..d323a0a8b
--- /dev/null
+++ b/dev/Common/HtmlEditor.jsx
@@ -0,0 +1,412 @@
+
+import {window, _} from 'common';
+import Globals from 'Common/Globals';
+import Settings from 'Storage/Settings';
+
+class HtmlEditor
+{
+ editor = null;
+ $element = null;
+
+ blurTimer = 0;
+
+ onBlur = null;
+ onReady = null;
+ onModeChange = null;
+
+ __inited = null;
+
+ /**
+ * @param {Object} element
+ * @param {Function=} onBlur
+ * @param {Function=} onReady
+ * @param {Function=} onModeChange
+ */
+ constructor(element, onBlur = null, onReady = null, onModeChange = null)
+ {
+ this.onBlur = onBlur;
+ this.onReady = onReady;
+ this.onModeChange = onModeChange;
+
+ this.$element = $(element);
+
+ this.resize = _.throttle(_.bind(this.resize, this), 100);
+
+ this.__inited = false;
+
+ this.init();
+ }
+
+ blurTrigger() {
+ if (this.onBlur)
+ {
+ window.clearTimeout(this.blurTimer);
+ this.blurTimer = window.setTimeout(() => {
+ this.onBlur();
+ }, 200);
+ }
+ }
+
+ focusTrigger() {
+ if (this.onBlur)
+ {
+ window.clearTimeout(this.blurTimer);
+ }
+ }
+
+ /**
+ * @return {boolean}
+ */
+ isHtml() {
+ return this.editor ? 'wysiwyg' === this.editor.mode : false;
+ }
+
+ /**
+ * @param {string} signature
+ * @param {bool} html
+ * @param {bool} insertBefore
+ */
+ setSignature(signature, html, insertBefore) {
+ if (this.editor)
+ {
+ this.editor.execCommand('insertSignature', {
+ 'isHtml': html,
+ 'insertBefore': insertBefore,
+ 'signature': signature
+ });
+ }
+ }
+
+ /**
+ * @return {boolean}
+ */
+ checkDirty() {
+ return this.editor ? this.editor.checkDirty() : false;
+ }
+
+ resetDirty() {
+ if (this.editor)
+ {
+ this.editor.resetDirty();
+ }
+ }
+
+ /**
+ * @param {string} text
+ * @return {string}
+ */
+ clearSignatureSigns(text) {
+ return text.replace(/(\u200C|\u0002)/g, '');
+ }
+
+ /**
+ * @param {boolean=} wrapIsHtml = false
+ * @param {boolean=} clearSignatureSigns = false
+ * @return {string}
+ */
+ getData(wrapIsHtml = false, clearSignatureSigns = false) {
+
+ let result = '';
+ 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, '');
+
+ try {
+ this.editor.setData(html);
+ } catch (e) {}
+
+ if (focus)
+ {
+ this.focus();
+ }
+ }
+ }
+
+ replaceHtml(find, replaceHtml) {
+ if (this.editor && this.__inited && 'wysiwyg' === this.editor.mode)
+ {
+ try {
+ this.editor.setData(
+ this.editor.getData().replace(find, replaceHtml));
+ } catch (e) {}
+ }
+ }
+
+ setPlain(plain, focus) {
+ if (this.editor && this.__inited)
+ {
+ this.modeToggle(false);
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
+ {
+ return this.editor.__plain.setRawData(plain);
+ }
+ else
+ {
+ try {
+ this.editor.setData(plain);
+ } catch (e) {}
+ }
+
+ if (focus)
+ {
+ this.focus();
+ }
+ }
+ }
+
+ init() {
+ if (this.$element && this.$element[0] && !this.editor)
+ {
+ const
+ initFunc = () => {
+
+ const
+ config = Globals.oHtmlEditorDefaultConfig,
+ language = Settings.settingsGet('Language'),
+ allowSource = !!Settings.settingsGet('AllowHtmlEditorSourceButton'),
+ biti = !!Settings.settingsGet('AllowHtmlEditorBitiButtons')
+ ;
+
+ 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';
+ }
+ }
+
+ config.enterMode = window.CKEDITOR.ENTER_BR;
+ config.shiftEnterMode = window.CKEDITOR.ENTER_P;
+
+ config.language = Globals.oHtmlEditorLangsMap[language] || 'en';
+ if (window.CKEDITOR.env)
+ {
+ window.CKEDITOR.env.isCompatible = true;
+ }
+
+ this.editor = window.CKEDITOR.appendTo(this.$element[0], config);
+
+ this.editor.on('key', (event) => {
+ if (event && event.data && 9 /* Tab */ === event.data.keyCode)
+ {
+ return false;
+ }
+ });
+
+ this.editor.on('blur', () => {
+ this.blurTrigger();
+ });
+
+ this.editor.on('mode', () => {
+ this.blurTrigger();
+ if (this.onModeChange)
+ {
+ this.onModeChange('plain' !== this.editor.mode);
+ }
+ });
+
+ this.editor.on('focus', () => {
+ this.focusTrigger();
+ });
+
+ 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))
+ {
+ var
+ id = event.data.dataTransfer.id,
+ imageId = `[img=${id}]`,
+ reader = new window.FileReader()
+ ;
+
+ reader.onloadend = () => {
+ if (reader.result)
+ {
+ this.replaceHtml(imageId, ``);
+ }
+ };
+
+ reader.readAsDataURL(file);
+
+ 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.__resizable = true;
+ this.__inited = true;
+
+ this.resize();
+
+ if (this.onReady)
+ {
+ this.onReady();
+ }
+
+ });
+ }
+ ;
+
+ if (window.CKEDITOR)
+ {
+ initFunc();
+ }
+ else
+ {
+ window.__initEditor = initFunc;
+ }
+ }
+ }
+
+ focus() {
+ if (this.editor)
+ {
+ try {
+ this.editor.focus();
+ } catch (e) {}
+ }
+ }
+
+ hasFocus() {
+ if (this.editor)
+ {
+ try {
+ return !!this.editor.focusManager.hasFocus;
+ } catch (e) {}
+ }
+
+ return false;
+ }
+
+ blur() {
+ if (this.editor)
+ {
+ try {
+ this.editor.focusManager.blur(true);
+ } catch (e) {}
+ }
+ }
+
+ resize() {
+ if (this.editor && this.__resizable)
+ {
+ try {
+ this.editor.resize(this.$element.width(), this.$element.innerHeight());
+ } catch (e) {}
+ }
+ }
+
+ setReadOnly(value) {
+ if (this.editor)
+ {
+ try {
+ this.editor.setReadOnly(!!value);
+ } catch (e) {}
+ }
+ }
+
+ clear(focus) {
+ this.setHtml('', focus);
+ }
+}
+
+export {HtmlEditor, HtmlEditor as default};
+module.exports = HtmlEditor;
diff --git a/dev/Common/Momentor.jsx b/dev/Common/Momentor.jsx
index fb19ffb68..182c9fdc9 100644
--- a/dev/Common/Momentor.jsx
+++ b/dev/Common/Momentor.jsx
@@ -4,11 +4,11 @@ import Translator from 'Common/Translator';
class Momentor
{
+ _moment = null;
+ _momentNow = 0;
+
constructor()
{
- this._moment = null;
- this._momentNow = 0;
-
this.updateMomentNow = _.debounce(() => {
this._moment = moment();
}, 500, true);
diff --git a/dev/Common/Plugins.jsx b/dev/Common/Plugins.jsx
index def0d1173..89f891656 100644
--- a/dev/Common/Plugins.jsx
+++ b/dev/Common/Plugins.jsx
@@ -6,11 +6,11 @@ import Settings from 'Storage/Settings';
class Plugins
{
- constructor() {
- this.oSimpleHooks = {};
- this.aUserViewModelsHooks = [];
- this.aAdminViewModelsHooks = [];
- }
+ oSimpleHooks = {};
+ aUserViewModelsHooks = [];
+ aAdminViewModelsHooks = [];
+
+ constructor() {}
/**
* @param {string} name
diff --git a/dev/Common/Selector.js b/dev/Common/Selector.js
deleted file mode 100644
index 623da8d3f..000000000
--- a/dev/Common/Selector.js
+++ /dev/null
@@ -1,801 +0,0 @@
-
-(function () {
-
- 'use strict';
-
- var
- _ = require('_'),
- $ = require('$'),
- ko = require('ko'),
- key = require('key'),
-
- Enums = require('Common/Enums'),
- Utils = require('Common/Utils')
- ;
-
- /**
- * @constructor
- * @param {koProperty} oKoList
- * @param {koProperty} oKoSelectedItem
- * @param {koProperty} oKoFocusedItem
- * @param {string} sItemSelector
- * @param {string} sItemSelectedSelector
- * @param {string} sItemCheckedSelector
- * @param {string} sItemFocusedSelector
- */
- function Selector(oKoList, oKoSelectedItem, oKoFocusedItem,
- sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
- {
- this.list = oKoList;
-
- this.listChecked = ko.computed(function () {
- return _.filter(this.list(), function (oItem) {
- return oItem.checked();
- });
- }, this).extend({'rateLimit': 0});
-
- this.isListChecked = ko.computed(function () {
- return 0 < this.listChecked().length;
- }, this);
-
- this.focusedItem = oKoFocusedItem || ko.observable(null);
- this.selectedItem = oKoSelectedItem || ko.observable(null);
- this.selectedItemUseCallback = true;
-
- this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
-
- this.listChecked.subscribe(function (aItems) {
- if (0 < aItems.length)
- {
- if (null === this.selectedItem())
- {
- if (this.selectedItem.valueHasMutated)
- {
- this.selectedItem.valueHasMutated();
- }
- }
- else
- {
- this.selectedItem(null);
- }
- }
- else if (this.autoSelect() && this.focusedItem())
- {
- this.selectedItem(this.focusedItem());
- }
- }, this);
-
- this.selectedItem.subscribe(function (oItem) {
-
- if (oItem)
- {
- if (this.isListChecked())
- {
- _.each(this.listChecked(), function (oSubItem) {
- oSubItem.checked(false);
- });
- }
-
- if (this.selectedItemUseCallback)
- {
- this.itemSelectedThrottle(oItem);
- }
- }
- else if (this.selectedItemUseCallback)
- {
- this.itemSelected(null);
- }
-
- }, this);
-
- this.selectedItem = this.selectedItem.extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.selected(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.selected(true);
- }
- }
- ]});
-
- this.focusedItem = this.focusedItem.extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.focused(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.focused(true);
- }
- }
- ]});
-
- this.iSelectNextHelper = 0;
- this.iFocusedNextHelper = 0;
- this.oContentVisible = null;
- this.oContentScrollable = null;
-
- this.sItemSelector = sItemSelector;
- this.sItemSelectedSelector = sItemSelectedSelector;
- this.sItemCheckedSelector = sItemCheckedSelector;
- this.sItemFocusedSelector = sItemFocusedSelector;
-
- this.sLastUid = '';
- this.oCallbacks = {};
-
- this.emptyFunction = function () {};
- this.emptyTrueFunction = function () { return true; };
-
- this.focusedItem.subscribe(function (oItem) {
- if (oItem)
- {
- this.sLastUid = this.getItemUid(oItem);
- }
- }, this);
-
- var
- aCache = [],
- aCheckedCache = [],
- mFocused = null,
- mSelected = null
- ;
-
- this.list.subscribe(function (aItems) {
-
- var self = this;
- if (Utils.isArray(aItems))
- {
- _.each(aItems, function (oItem) {
- if (oItem)
- {
- var sUid = self.getItemUid(oItem);
-
- aCache.push(sUid);
- if (oItem.checked())
- {
- aCheckedCache.push(sUid);
- }
- if (null === mFocused && oItem.focused())
- {
- mFocused = sUid;
- }
- if (null === mSelected && oItem.selected())
- {
- mSelected = sUid;
- }
- }
- });
- }
- }, this, 'beforeChange');
-
- this.list.subscribe(function (aItems) {
-
- var
- self = this,
- oTemp = null,
- bGetNext = false,
- aUids = [],
- mNextFocused = mFocused,
- bChecked = false,
- bSelected = false,
- iLen = 0
- ;
-
- this.selectedItemUseCallback = false;
-
- this.focusedItem(null);
- this.selectedItem(null);
-
- if (Utils.isArray(aItems))
- {
- iLen = aCheckedCache.length;
-
- _.each(aItems, function (oItem) {
-
- var sUid = self.getItemUid(oItem);
- aUids.push(sUid);
-
- if (null !== mFocused && mFocused === sUid)
- {
- self.focusedItem(oItem);
- mFocused = null;
- }
-
- if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache))
- {
- bChecked = true;
- oItem.checked(true);
- iLen--;
- }
-
- if (!bChecked && null !== mSelected && mSelected === sUid)
- {
- bSelected = true;
- self.selectedItem(oItem);
- mSelected = null;
- }
- });
-
- this.selectedItemUseCallback = true;
-
- if (!bChecked && !bSelected && this.autoSelect())
- {
- if (self.focusedItem())
- {
- self.selectedItem(self.focusedItem());
- }
- else if (0 < aItems.length)
- {
- if (null !== mNextFocused)
- {
- bGetNext = false;
- mNextFocused = _.find(aCache, function (sUid) {
- if (bGetNext && -1 < Utils.inArray(sUid, aUids))
- {
- return sUid;
- }
- else if (mNextFocused === sUid)
- {
- bGetNext = true;
- }
- return false;
- });
-
- if (mNextFocused)
- {
- oTemp = _.find(aItems, function (oItem) {
- return mNextFocused === self.getItemUid(oItem);
- });
- }
- }
-
- self.selectedItem(oTemp || null);
- self.focusedItem(self.selectedItem());
- }
- }
-
- if ((0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) && 0 < aItems.length && !self.focusedItem())
- {
- oTemp = null;
- if (0 !== this.iFocusedNextHelper)
- {
- oTemp = aItems[-1 === this.iFocusedNextHelper ? aItems.length - 1 : 0] || null;
- }
-
- if (!oTemp && 0 !== this.iSelectNextHelper)
- {
- oTemp = aItems[-1 === this.iSelectNextHelper ? aItems.length - 1 : 0] || null;
- }
-
- if (oTemp)
- {
- if (0 !== this.iSelectNextHelper)
- {
- self.selectedItem(oTemp || null);
- }
-
- self.focusedItem(oTemp || null);
-
- self.scrollToFocused();
-
- _.delay(function () {
- self.scrollToFocused();
- }, 100);
- }
-
- this.iSelectNextHelper = 0;
- this.iFocusedNextHelper = 0;
- }
- }
-
- aCache = [];
- aCheckedCache = [];
- mFocused = null;
- mSelected = null;
-
- }, this);
- }
-
- Selector.prototype.itemSelected = function (oItem)
- {
- if (this.isListChecked())
- {
- if (!oItem)
- {
- (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem || null);
- }
- }
- else
- {
- if (oItem)
- {
- (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem);
- }
- }
- };
-
- Selector.prototype.goDown = function (bForceSelect)
- {
- this.newSelectPosition(Enums.EventKeyCode.Down, false, bForceSelect);
- };
-
- Selector.prototype.goUp = function (bForceSelect)
- {
- this.newSelectPosition(Enums.EventKeyCode.Up, false, bForceSelect);
- };
-
- Selector.prototype.unselect = function ()
- {
- this.selectedItem(null);
- this.focusedItem(null);
- };
-
- Selector.prototype.init = function (oContentVisible, oContentScrollable, sKeyScope)
- {
- this.oContentVisible = oContentVisible;
- this.oContentScrollable = oContentScrollable;
-
- sKeyScope = sKeyScope || 'all';
-
- if (this.oContentVisible && this.oContentScrollable)
- {
- var
- self = this
- ;
-
- $(this.oContentVisible)
- .on('selectstart', function (oEvent) {
- if (oEvent && oEvent.preventDefault)
- {
- oEvent.preventDefault();
- }
- })
- .on('click', this.sItemSelector, function (oEvent) {
- self.actionClick(ko.dataFor(this), oEvent);
- })
- .on('click', this.sItemCheckedSelector, function (oEvent) {
- var oItem = ko.dataFor(this);
- if (oItem)
- {
- if (oEvent && oEvent.shiftKey)
- {
- self.actionClick(oItem, oEvent);
- }
- else
- {
- self.focusedItem(oItem);
- oItem.checked(!oItem.checked());
- }
- }
- })
- ;
-
- key('enter', sKeyScope, function () {
- if (self.focusedItem() && !self.focusedItem().selected())
- {
- self.actionClick(self.focusedItem());
- return false;
- }
-
- return true;
- });
-
- key('ctrl+up, command+up, ctrl+down, command+down', sKeyScope, function () {
- return false;
- });
-
- key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', sKeyScope, function (event, handler) {
- if (event && handler && handler.shortcut)
- {
- var iKey = 0;
- switch (handler.shortcut)
- {
- case 'up':
- case 'shift+up':
- iKey = Enums.EventKeyCode.Up;
- break;
- case 'down':
- case 'shift+down':
- iKey = Enums.EventKeyCode.Down;
- break;
- case 'insert':
- iKey = Enums.EventKeyCode.Insert;
- break;
- case 'space':
- iKey = Enums.EventKeyCode.Space;
- break;
- case 'home':
- iKey = Enums.EventKeyCode.Home;
- break;
- case 'end':
- iKey = Enums.EventKeyCode.End;
- break;
- case 'pageup':
- iKey = Enums.EventKeyCode.PageUp;
- break;
- case 'pagedown':
- iKey = Enums.EventKeyCode.PageDown;
- break;
- }
-
- if (0 < iKey)
- {
- self.newSelectPosition(iKey, key.shift);
- return false;
- }
- }
- });
- }
- };
-
- /**
- * @return {boolean}
- */
- Selector.prototype.autoSelect = function ()
- {
- return !!(this.oCallbacks['onAutoSelect'] || this.emptyTrueFunction)();
- };
-
- /**
- * @param {boolean}
- */
- Selector.prototype.doUpUpOrDownDown = function (bUp)
- {
- (this.oCallbacks['onUpUpOrDownDown'] || this.emptyTrueFunction)(!!bUp);
- };
-
- /**
- * @param {Object} oItem
- * @return {string}
- */
- Selector.prototype.getItemUid = function (oItem)
- {
- var
- sUid = '',
- fGetItemUidCallback = this.oCallbacks['onItemGetUid'] || null
- ;
-
- if (fGetItemUidCallback && oItem)
- {
- sUid = fGetItemUidCallback(oItem);
- }
-
- return sUid.toString();
- };
-
- /**
- * @param {number} iEventKeyCode
- * @param {boolean} bShiftKey
- * @param {boolean=} bForceSelect = false
- */
- Selector.prototype.newSelectPosition = function (iEventKeyCode, bShiftKey, bForceSelect)
- {
- var
- iIndex = 0,
- iPageStep = 10,
- bNext = false,
- bStop = false,
- oResult = null,
- aList = this.list(),
- iListLen = aList ? aList.length : 0,
- oFocused = this.focusedItem()
- ;
-
- if (0 < iListLen)
- {
- if (!oFocused)
- {
- if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode || Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.PageUp === iEventKeyCode)
- {
- oResult = aList[0];
- }
- else if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode || Enums.EventKeyCode.PageDown === iEventKeyCode)
- {
- oResult = aList[aList.length - 1];
- }
- }
- else if (oFocused)
- {
- if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- _.each(aList, function (oItem) {
- if (!bStop)
- {
- switch (iEventKeyCode) {
- case Enums.EventKeyCode.Up:
- if (oFocused === oItem)
- {
- bStop = true;
- }
- else
- {
- oResult = oItem;
- }
- break;
- case Enums.EventKeyCode.Down:
- case Enums.EventKeyCode.Insert:
- if (bNext)
- {
- oResult = oItem;
- bStop = true;
- }
- else if (oFocused === oItem)
- {
- bNext = true;
- }
- break;
- }
- }
- });
-
- if (!oResult && (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Up === iEventKeyCode))
- {
- this.doUpUpOrDownDown(Enums.EventKeyCode.Up === iEventKeyCode);
- }
- }
- else if (Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode)
- {
- if (Enums.EventKeyCode.Home === iEventKeyCode)
- {
- oResult = aList[0];
- }
- else if (Enums.EventKeyCode.End === iEventKeyCode)
- {
- oResult = aList[aList.length - 1];
- }
- }
- else if (Enums.EventKeyCode.PageDown === iEventKeyCode)
- {
- for (; iIndex < iListLen; iIndex++)
- {
- if (oFocused === aList[iIndex])
- {
- iIndex += iPageStep;
- iIndex = iListLen - 1 < iIndex ? iListLen - 1 : iIndex;
- oResult = aList[iIndex];
- break;
- }
- }
- }
- else if (Enums.EventKeyCode.PageUp === iEventKeyCode)
- {
- for (iIndex = iListLen; iIndex >= 0; iIndex--)
- {
- if (oFocused === aList[iIndex])
- {
- iIndex -= iPageStep;
- iIndex = 0 > iIndex ? 0 : iIndex;
- oResult = aList[iIndex];
- break;
- }
- }
- }
- }
- }
-
- if (oResult)
- {
- this.focusedItem(oResult);
-
- if (oFocused)
- {
- if (bShiftKey)
- {
- if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
- }
- else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
- }
-
- if ((this.autoSelect() || !!bForceSelect) &&
- !this.isListChecked() && Enums.EventKeyCode.Space !== iEventKeyCode)
- {
- this.selectedItem(oResult);
- }
-
- this.scrollToFocused();
- }
- else if (oFocused)
- {
- if (bShiftKey && (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode))
- {
- oFocused.checked(!oFocused.checked());
- }
- else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
-
- this.focusedItem(oFocused);
- }
- };
-
- /**
- * @return {boolean}
- */
- Selector.prototype.scrollToFocused = function ()
- {
- if (!this.oContentVisible || !this.oContentScrollable)
- {
- return false;
- }
-
- var
- iOffset = 20,
- aList = this.list(),
- oFocused = $(this.sItemFocusedSelector, this.oContentScrollable),
- oPos = oFocused.position(),
- iVisibleHeight = this.oContentVisible.height(),
- iFocusedHeight = oFocused.outerHeight()
- ;
-
- if (aList && aList[0] && aList[0].focused())
- {
- this.oContentScrollable.scrollTop(0);
-
- return true;
- }
- else if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
- {
- if (oPos.top < 0)
- {
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
- }
- else
- {
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
- }
-
- return true;
- }
-
- return false;
- };
-
- /**
- * @param {boolean=} bFast = false
- * @return {boolean}
- */
- Selector.prototype.scrollToTop = function (bFast)
- {
- if (!this.oContentVisible || !this.oContentScrollable)
- {
- return false;
- }
-
- if (bFast || 50 > this.oContentScrollable.scrollTop())
- {
- this.oContentScrollable.scrollTop(0);
- }
- else
- {
- this.oContentScrollable.stop().animate({'scrollTop': 0}, 200);
- }
-
- return true;
- };
-
- Selector.prototype.eventClickFunction = function (oItem, oEvent)
- {
- var
- sUid = this.getItemUid(oItem),
- iIndex = 0,
- iLength = 0,
- oListItem = null,
- sLineUid = '',
- bChangeRange = false,
- bIsInRange = false,
- aList = [],
- bChecked = false
- ;
-
- if (oEvent && oEvent.shiftKey)
- {
- if ('' !== sUid && '' !== this.sLastUid && sUid !== this.sLastUid)
- {
- aList = this.list();
- bChecked = oItem.checked();
-
- for (iIndex = 0, iLength = aList.length; iIndex < iLength; iIndex++)
- {
- oListItem = aList[iIndex];
- sLineUid = this.getItemUid(oListItem);
-
- bChangeRange = false;
- if (sLineUid === this.sLastUid || sLineUid === sUid)
- {
- bChangeRange = true;
- }
-
- if (bChangeRange)
- {
- bIsInRange = !bIsInRange;
- }
-
- if (bIsInRange || bChangeRange)
- {
- oListItem.checked(bChecked);
- }
- }
- }
- }
-
- this.sLastUid = '' === sUid ? '' : sUid;
- };
-
- /**
- * @param {Object} oItem
- * @param {Object=} oEvent
- */
- Selector.prototype.actionClick = function (oItem, oEvent)
- {
- if (oItem)
- {
- var
- bClick = true,
- sUid = this.getItemUid(oItem)
- ;
-
- if (oEvent)
- {
- if (oEvent.shiftKey && !(oEvent.ctrlKey || oEvent.metaKey) && !oEvent.altKey)
- {
- bClick = false;
- if ('' === this.sLastUid)
- {
- this.sLastUid = sUid;
- }
-
- oItem.checked(!oItem.checked());
- this.eventClickFunction(oItem, oEvent);
-
- this.focusedItem(oItem);
- }
- else if ((oEvent.ctrlKey || oEvent.metaKey) && !oEvent.shiftKey && !oEvent.altKey)
- {
- bClick = false;
- this.focusedItem(oItem);
-
- if (this.selectedItem() && oItem !== this.selectedItem())
- {
- this.selectedItem().checked(true);
- }
-
- oItem.checked(!oItem.checked());
- }
- }
-
- if (bClick)
- {
- this.selectMessageItem(oItem);
- }
- }
- };
-
- Selector.prototype.on = function (sEventName, fCallback)
- {
- this.oCallbacks[sEventName] = fCallback;
- };
-
- Selector.prototype.selectMessageItem = function (oMessageItem)
- {
- this.focusedItem(oMessageItem);
- this.selectedItem(oMessageItem);
-
- this.scrollToFocused();
- };
-
- module.exports = Selector;
-
-}());
\ No newline at end of file
diff --git a/dev/Common/Selector.jsx b/dev/Common/Selector.jsx
new file mode 100644
index 000000000..ed3cd4376
--- /dev/null
+++ b/dev/Common/Selector.jsx
@@ -0,0 +1,763 @@
+
+import {$, _, key} from 'common';
+import ko from 'ko';
+import {EventKeyCode} from 'Common/Enums';
+import Utils from 'Common/Utils';
+
+class Selector
+{
+ /**
+ * @constructor
+ * @param {koProperty} koList
+ * @param {koProperty} koSelectedItem
+ * @param {koProperty} koFocusedItem
+ * @param {string} sItemSelector
+ * @param {string} sItemSelectedSelector
+ * @param {string} sItemCheckedSelector
+ * @param {string} sItemFocusedSelector
+ */
+ constructor(koList, koSelectedItem, koFocusedItem,
+ sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
+ {
+ this.list = koList;
+
+ this.listChecked = ko.computed(() => {
+ return _.filter(this.list(), (item) => item.checked());
+ }, this).extend({'rateLimit': 0});
+
+ this.isListChecked = ko.computed(() => 0 < this.listChecked().length);
+
+ this.focusedItem = koFocusedItem || ko.observable(null);
+ this.selectedItem = koSelectedItem || ko.observable(null);
+ this.selectedItemUseCallback = true;
+
+ this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
+
+ this.listChecked.subscribe((items) => {
+ if (0 < items.length)
+ {
+ if (null === this.selectedItem())
+ {
+ if (this.selectedItem.valueHasMutated)
+ {
+ this.selectedItem.valueHasMutated();
+ }
+ }
+ else
+ {
+ this.selectedItem(null);
+ }
+ }
+ else if (this.autoSelect() && this.focusedItem())
+ {
+ this.selectedItem(this.focusedItem());
+ }
+ }, this);
+
+ this.selectedItem.subscribe((item) => {
+
+ if (item)
+ {
+ if (this.isListChecked())
+ {
+ _.each(this.listChecked(), (subItem) => {
+ subItem.checked(false);
+ });
+ }
+
+ if (this.selectedItemUseCallback)
+ {
+ this.itemSelectedThrottle(item);
+ }
+ }
+ else if (this.selectedItemUseCallback)
+ {
+ this.itemSelected(null);
+ }
+
+ }, this);
+
+ this.selectedItem = this.selectedItem.extend({'toggleSubscribe': [null,
+ (prev) => {
+ if (prev)
+ {
+ prev.selected(false);
+ }
+ }, (next) => {
+ if (next)
+ {
+ next.selected(true);
+ }
+ }
+ ]});
+
+ this.focusedItem = this.focusedItem.extend({'toggleSubscribe': [null,
+ (prev) => {
+ if (prev)
+ {
+ prev.focused(false);
+ }
+ }, (next) => {
+ if (next)
+ {
+ next.focused(true);
+ }
+ }
+ ]});
+
+ this.iSelectNextHelper = 0;
+ this.iFocusedNextHelper = 0;
+ this.oContentVisible = null;
+ this.oContentScrollable = null;
+
+ this.sItemSelector = sItemSelector;
+ this.sItemSelectedSelector = sItemSelectedSelector;
+ this.sItemCheckedSelector = sItemCheckedSelector;
+ this.sItemFocusedSelector = sItemFocusedSelector;
+
+ this.sLastUid = '';
+ this.oCallbacks = {};
+
+ this.emptyFunction = () => {};
+ this.emptyTrueFunction = () => true;
+
+ this.focusedItem.subscribe((item) => {
+ if (item)
+ {
+ this.sLastUid = this.getItemUid(item);
+ }
+ }, this);
+
+ let
+ aCache = [],
+ aCheckedCache = [],
+ mFocused = null,
+ mSelected = null
+ ;
+
+ this.list.subscribe((items) => {
+
+ if (Utils.isArray(items))
+ {
+ _.each(items, (item) => {
+ if (item)
+ {
+ const uid = this.getItemUid(item);
+
+ aCache.push(uid);
+ if (item.checked())
+ {
+ aCheckedCache.push(uid);
+ }
+ if (null === mFocused && item.focused())
+ {
+ mFocused = uid;
+ }
+ if (null === mSelected && item.selected())
+ {
+ mSelected = uid;
+ }
+ }
+ });
+ }
+ }, this, 'beforeChange');
+
+ this.list.subscribe((aItems) => {
+
+ var
+ oTemp = null,
+ bGetNext = false,
+ aUids = [],
+ mNextFocused = mFocused,
+ bChecked = false,
+ bSelected = false,
+ iLen = 0
+ ;
+
+ this.selectedItemUseCallback = false;
+
+ this.focusedItem(null);
+ this.selectedItem(null);
+
+ if (Utils.isArray(aItems))
+ {
+ iLen = aCheckedCache.length;
+
+ _.each(aItems, (oItem) => {
+
+ var sUid = this.getItemUid(oItem);
+ aUids.push(sUid);
+
+ if (null !== mFocused && mFocused === sUid)
+ {
+ this.focusedItem(oItem);
+ mFocused = null;
+ }
+
+ if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache))
+ {
+ bChecked = true;
+ oItem.checked(true);
+ iLen--;
+ }
+
+ if (!bChecked && null !== mSelected && mSelected === sUid)
+ {
+ bSelected = true;
+ this.selectedItem(oItem);
+ mSelected = null;
+ }
+ });
+
+ this.selectedItemUseCallback = true;
+
+ if (!bChecked && !bSelected && this.autoSelect())
+ {
+ if (this.focusedItem())
+ {
+ this.selectedItem(this.focusedItem());
+ }
+ else if (0 < aItems.length)
+ {
+ if (null !== mNextFocused)
+ {
+ bGetNext = false;
+ mNextFocused = _.find(aCache, (sUid) => {
+ if (bGetNext && -1 < Utils.inArray(sUid, aUids))
+ {
+ return sUid;
+ }
+ else if (mNextFocused === sUid)
+ {
+ bGetNext = true;
+ }
+ return false;
+ });
+
+ if (mNextFocused)
+ {
+ oTemp = _.find(aItems, (oItem) => mNextFocused === this.getItemUid(oItem));
+ }
+ }
+
+ this.selectedItem(oTemp || null);
+ this.focusedItem(this.selectedItem());
+ }
+ }
+
+ if ((0 !== this.iSelectNextHelper || 0 !== this.iFocusedNextHelper) && 0 < aItems.length && !this.focusedItem())
+ {
+ oTemp = null;
+ if (0 !== this.iFocusedNextHelper)
+ {
+ oTemp = aItems[-1 === this.iFocusedNextHelper ? aItems.length - 1 : 0] || null;
+ }
+
+ if (!oTemp && 0 !== this.iSelectNextHelper)
+ {
+ oTemp = aItems[-1 === this.iSelectNextHelper ? aItems.length - 1 : 0] || null;
+ }
+
+ if (oTemp)
+ {
+ if (0 !== this.iSelectNextHelper)
+ {
+ this.selectedItem(oTemp || null);
+ }
+
+ this.focusedItem(oTemp || null);
+
+ this.scrollToFocused();
+
+ _.delay(() => this.scrollToFocused(), 100);
+ }
+
+ this.iSelectNextHelper = 0;
+ this.iFocusedNextHelper = 0;
+ }
+ }
+
+ aCache = [];
+ aCheckedCache = [];
+ mFocused = null;
+ mSelected = null;
+
+ }, this);
+ }
+
+ itemSelected(item) {
+
+ if (this.isListChecked())
+ {
+ if (!item)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(item || null);
+ }
+ }
+ else
+ {
+ if (item)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(item);
+ }
+ }
+ }
+
+ /**
+ * @param {boolean} forceSelect
+ */
+ goDown(forceSelect) {
+ this.newSelectPosition(EventKeyCode.Down, false, forceSelect);
+ }
+
+ /**
+ * @param {boolean} forceSelect
+ */
+ goUp(forceSelect) {
+ this.newSelectPosition(EventKeyCode.Up, false, forceSelect);
+ }
+
+ unselect() {
+ this.selectedItem(null);
+ this.focusedItem(null);
+ }
+
+ init(contentVisible, contentScrollable, keyScope = 'all') {
+
+ this.oContentVisible = contentVisible;
+ this.oContentScrollable = contentScrollable;
+
+ if (this.oContentVisible && this.oContentScrollable)
+ {
+ $(this.oContentVisible)
+ .on('selectstart', (event) => {
+ if (event && event.preventDefault)
+ {
+ event.preventDefault();
+ }
+ })
+ .on('click', this.sItemSelector, (event) => {
+ this.actionClick(ko.dataFor(event.currentTarget), event);
+ })
+ .on('click', this.sItemCheckedSelector, (event) => {
+ const item = ko.dataFor(event.currentTarget);
+ if (item)
+ {
+ if (event && event.shiftKey)
+ {
+ this.actionClick(item, event);
+ }
+ else
+ {
+ this.focusedItem(item);
+ item.checked(!item.checked());
+ }
+ }
+ })
+ ;
+
+ key('enter', keyScope, () => {
+ if (this.focusedItem() && !this.focusedItem().selected())
+ {
+ this.actionClick(this.focusedItem());
+ return false;
+ }
+
+ return true;
+ });
+
+ 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)
+ {
+ let eventKey = 0;
+ switch (handler.shortcut)
+ {
+ case 'up':
+ case 'shift+up':
+ eventKey = EventKeyCode.Up;
+ break;
+ case 'down':
+ case 'shift+down':
+ eventKey = EventKeyCode.Down;
+ break;
+ case 'insert':
+ eventKey = EventKeyCode.Insert;
+ break;
+ case 'space':
+ eventKey = EventKeyCode.Space;
+ break;
+ case 'home':
+ eventKey = EventKeyCode.Home;
+ break;
+ case 'end':
+ eventKey = EventKeyCode.End;
+ break;
+ case 'pageup':
+ eventKey = EventKeyCode.PageUp;
+ break;
+ case 'pagedown':
+ eventKey = EventKeyCode.PageDown;
+ break;
+ }
+
+ if (0 < eventKey)
+ {
+ this.newSelectPosition(eventKey, key.shift);
+ return false;
+ }
+ }
+ });
+ }
+ }
+
+ /**
+ * @return {boolean}
+ */
+ autoSelect() {
+ return !!(this.oCallbacks['onAutoSelect'] || this.emptyTrueFunction)();
+ }
+
+ /**
+ * @param {boolean} up
+ */
+ doUpUpOrDownDown(up) {
+ (this.oCallbacks['onUpUpOrDownDown'] || this.emptyTrueFunction)(!!up);
+ }
+
+ /**
+ * @param {Object} oItem
+ * @return {string}
+ */
+ getItemUid(item) {
+
+ let uid = '';
+
+ const getItemUidCallback = this.oCallbacks['onItemGetUid'] || null;
+ if (getItemUidCallback && item)
+ {
+ uid = getItemUidCallback(item);
+ }
+
+ return uid.toString();
+ }
+
+ /**
+ * @param {number} iEventKeyCode
+ * @param {boolean} bShiftKey
+ * @param {boolean=} bForceSelect = false
+ */
+ newSelectPosition(iEventKeyCode, bShiftKey, bForceSelect) {
+
+ var
+ iIndex = 0,
+ iPageStep = 10,
+ bNext = false,
+ bStop = false,
+ oResult = null,
+ aList = this.list(),
+ iListLen = aList ? aList.length : 0,
+ oFocused = this.focusedItem()
+ ;
+
+ if (0 < iListLen)
+ {
+ if (!oFocused)
+ {
+ if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode || EventKeyCode.Home === iEventKeyCode || EventKeyCode.PageUp === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.End === iEventKeyCode || EventKeyCode.PageDown === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (oFocused)
+ {
+ if (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode || EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
+ {
+ _.each(aList, (item) => {
+ if (!bStop)
+ {
+ switch (iEventKeyCode) {
+ case EventKeyCode.Up:
+ if (oFocused === item)
+ {
+ bStop = true;
+ }
+ else
+ {
+ oResult = item;
+ }
+ break;
+ case EventKeyCode.Down:
+ case EventKeyCode.Insert:
+ if (bNext)
+ {
+ oResult = item;
+ bStop = true;
+ }
+ else if (oFocused === item)
+ {
+ bNext = true;
+ }
+ break;
+ }
+ }
+ });
+
+ if (!oResult && (EventKeyCode.Down === iEventKeyCode || EventKeyCode.Up === iEventKeyCode))
+ {
+ this.doUpUpOrDownDown(EventKeyCode.Up === iEventKeyCode);
+ }
+ }
+ else if (EventKeyCode.Home === iEventKeyCode || EventKeyCode.End === iEventKeyCode)
+ {
+ if (EventKeyCode.Home === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (EventKeyCode.End === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (EventKeyCode.PageDown === iEventKeyCode)
+ {
+ for (; iIndex < iListLen; iIndex++)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex += iPageStep;
+ iIndex = iListLen - 1 < iIndex ? iListLen - 1 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ else if (EventKeyCode.PageUp === iEventKeyCode)
+ {
+ for (iIndex = iListLen; iIndex >= 0; iIndex--)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex -= iPageStep;
+ iIndex = 0 > iIndex ? 0 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (oResult)
+ {
+ this.focusedItem(oResult);
+
+ if (oFocused)
+ {
+ if (bShiftKey)
+ {
+ if (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+ else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+
+ if ((this.autoSelect() || !!bForceSelect) &&
+ !this.isListChecked() && EventKeyCode.Space !== iEventKeyCode)
+ {
+ this.selectedItem(oResult);
+ }
+
+ this.scrollToFocused();
+ }
+ else if (oFocused)
+ {
+ if (bShiftKey && (EventKeyCode.Up === iEventKeyCode || EventKeyCode.Down === iEventKeyCode))
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ else if (EventKeyCode.Insert === iEventKeyCode || EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+
+ this.focusedItem(oFocused);
+ }
+ }
+
+ /**
+ * @return {boolean}
+ */
+ scrollToFocused() {
+
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ 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())
+ {
+ this.oContentScrollable.scrollTop(0);
+ return true;
+ }
+ else if (pos && (pos.top < 0 || pos.top + focusedHeight > visibleHeight))
+ {
+ this.oContentScrollable.scrollTop(pos.top < 0 ?
+ this.oContentScrollable.scrollTop() + pos.top - offset :
+ this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
+ );
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @param {boolean=} fast = false
+ * @return {boolean}
+ */
+ scrollToTop(fast = false) {
+
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ if (fast || 50 > this.oContentScrollable.scrollTop())
+ {
+ this.oContentScrollable.scrollTop(0);
+ }
+ else
+ {
+ this.oContentScrollable.stop().animate({'scrollTop': 0}, 200);
+ }
+
+ return true;
+ }
+
+ eventClickFunction(item, event) {
+
+ let
+ index = 0,
+ length = 0,
+ changeRange = false,
+ isInRange = false,
+ list = [],
+ checked = false,
+ listItem = null,
+ lineUid = ''
+ ;
+
+ const uid = this.getItemUid(item);
+ 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++)
+ {
+ listItem = list[index];
+ lineUid = this.getItemUid(listItem);
+
+ changeRange = false;
+ if (lineUid === this.sLastUid || lineUid === uid)
+ {
+ changeRange = true;
+ }
+
+ if (changeRange)
+ {
+ isInRange = !isInRange;
+ }
+
+ if (isInRange || changeRange)
+ {
+ listItem.checked(checked);
+ }
+ }
+ }
+ }
+
+ this.sLastUid = '' === uid ? '' : uid;
+ }
+
+ /**
+ * @param {Object} item
+ * @param {Object=} event
+ */
+ actionClick = function (item, event = null) {
+
+ if (item)
+ {
+ let click = true;
+ if (event)
+ {
+ if (event.shiftKey && !(event.ctrlKey || event.metaKey) && !event.altKey)
+ {
+ click = false;
+ if ('' === this.sLastUid)
+ {
+ this.sLastUid = this.getItemUid(item);
+ }
+
+ item.checked(!item.checked());
+ this.eventClickFunction(item, event);
+
+ this.focusedItem(item);
+ }
+ else if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey)
+ {
+ click = false;
+ this.focusedItem(item);
+
+ if (this.selectedItem() && item !== this.selectedItem())
+ {
+ this.selectedItem().checked(true);
+ }
+
+ item.checked(!item.checked());
+ }
+ }
+
+ if (click)
+ {
+ this.selectMessageItem(item);
+ }
+ }
+ }
+
+ on(eventName, callback) {
+ this.oCallbacks[eventName] = callback;
+ }
+
+ selectMessageItem(messageItem) {
+ this.focusedItem(messageItem);
+ this.selectedItem(messageItem);
+ this.scrollToFocused();
+ }
+}
+
+export {Selector, Selector as default};
+module.exports = Selector;
diff --git a/dev/Common/Translator.jsx b/dev/Common/Translator.jsx
index 81b991aa1..1cf3afa02 100644
--- a/dev/Common/Translator.jsx
+++ b/dev/Common/Translator.jsx
@@ -7,9 +7,11 @@ import Globals from 'Common/Globals';
class Translator
{
+ data = {};
+ notificationI18N = {};
+
constructor() {
this.data = window['rainloopI18N'] || {};
- this.notificationI18N = {};
this.trigger = ko.observable(false);
this.i18n = _.bind(this.i18n, this);
this.init();
@@ -185,7 +187,7 @@ class Translator
this.notificationI18N = this.notificationI18N || {};
- _.each(map, (item) => {
+ map.forEach((item) => {
this.notificationI18N[item[0]] = this.i18n(item[1]);
});
}
diff --git a/dev/Component/AbstracCheckbox.jsx b/dev/Component/AbstracCheckbox.jsx
index f77bb51d2..de08377ff 100644
--- a/dev/Component/AbstracCheckbox.jsx
+++ b/dev/Component/AbstracCheckbox.jsx
@@ -6,9 +6,9 @@ import {AbstractComponent} from 'Component/Abstract';
class AbstracCheckbox extends AbstractComponent
{
/**
- * @param {Object} params
+ * @param {Object} params = {}
*/
- constructor(params) {
+ constructor(params = {}) {
super();
diff --git a/dev/Component/AbstracRadio.jsx b/dev/Component/AbstracRadio.jsx
index a1f5de237..03cde5e5e 100644
--- a/dev/Component/AbstracRadio.jsx
+++ b/dev/Component/AbstracRadio.jsx
@@ -27,10 +27,7 @@ class AbstracRadio extends AbstractComponent
if (params.values)
{
this.values(_.map(params.values, (label, value) => {
- return {
- 'label': label,
- 'value': value
- };
+ return {'label': label, 'value': value};
}));
}
diff --git a/dev/Component/Abstract.jsx b/dev/Component/Abstract.jsx
index d1547ae2d..637f2cc6d 100644
--- a/dev/Component/Abstract.jsx
+++ b/dev/Component/Abstract.jsx
@@ -1,16 +1,16 @@
-import {_} from 'common';
+import {$} from 'common';
import ko from 'ko';
import Utils from 'Common/Utils';
class AbstractComponent
{
- constructor() {
- this.disposable = [];
- }
+ disposable = [];
+
+ constructor() {}
dispose() {
- _.each(this.disposable, (funcToDispose) => {
+ this.disposable.forEach((funcToDispose) => {
if (funcToDispose && funcToDispose.dispose)
{
funcToDispose.dispose();
@@ -21,10 +21,10 @@ class AbstractComponent
/**
* @param {*} ClassObject
- * @param {string} templateID
+ * @param {string} templateID = ''
* @return {Object}
*/
-const componentExportHelper = (ClassObject, templateID) => {
+const componentExportHelper = (ClassObject, templateID = '') => {
return {
template: templateID ? {element: templateID} : '',
viewModel: {
diff --git a/dev/Component/Script.jsx b/dev/Component/Script.jsx
index 3dfa6a576..65ef64b66 100644
--- a/dev/Component/Script.jsx
+++ b/dev/Component/Script.jsx
@@ -15,7 +15,7 @@ class ScriptComponent extends AbstractComponent
params.element[0] && params.element[0].outerHTML)
{
let script = params.element[0].outerHTML;
- script = script
+ script = !script ? '' : script
.replace(/